// Zustand store for app-level shared state (persisted to sessionStorage).
// No provider needed — import useAppStore or useAppContext anywhere.

import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';

interface AppState {
  currentUser: { id: string; firstName: string; lastName: string; email: string; role: string; departmentId: string; avatar?: string } | null;
  setCurrentUser: (value: { id: string; firstName: string; lastName: string; email: string; role: string; departmentId: string; avatar?: string } | null) => void;
  selectedJobId: string | null;
  setSelectedJobId: (value: string | null) => void;
  unreadNotificationCount: number;
  setUnreadNotificationCount: (value: number) => void;
  jobFilters: { status?: string[]; priority?: string[]; assigneeId?: string; departmentId?: string; jobTypeId?: string; dateRange?: [string, string]; search?: string };
  setJobFilters: (value: { status?: string[]; priority?: string[]; assigneeId?: string; departmentId?: string; jobTypeId?: string; dateRange?: [string, string]; search?: string }) => void;
  sessionId: string;
  clearSession: () => void;
}

const useAppStore = create<AppState>()((
  persist(
    (set) => ({
    sessionId: crypto.randomUUID(),
    currentUser: null,
    selectedJobId: null,
    unreadNotificationCount: 0,
    jobFilters: {},
    setCurrentUser: (value) => set({ currentUser: value }),
    setSelectedJobId: (value) => set({ selectedJobId: value }),
    setUnreadNotificationCount: (value) => set({ unreadNotificationCount: value }),
    setJobFilters: (value) => set({ jobFilters: value }),
    clearSession: () => set({ sessionId: crypto.randomUUID(), currentUser: null, selectedJobId: null, unreadNotificationCount: 0, jobFilters: {} }),
    }),
    {
      name: 'job_management_system_session',
      storage: createJSONStorage(() => sessionStorage),
    },
  )
));

// Convenience alias — pages import useAppContext.
const useAppContext = useAppStore;

export { useAppStore, useAppContext };
