// 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; name: string; role: 'administrator' | 'doctor' | 'nurse' | 'receptionist' | 'billing_officer'; department?: string } | null;
  setCurrentUser: (value: { id: string; name: string; role: 'administrator' | 'doctor' | 'nurse' | 'receptionist' | 'billing_officer'; department?: string } | null) => void;
  selectedPatientId: string | null;
  setSelectedPatientId: (value: string | null) => void;
  notifications: { id: string; message: string; type: string; read: boolean; timestamp: string }[];
  setNotifications: (value: { id: string; message: string; type: string; read: boolean; timestamp: string }[]) => void;
  sessionId: string;
  clearSession: () => void;
}

const useAppStore = create<AppState>()((
  persist(
    (set) => ({
    sessionId: crypto.randomUUID(),
    currentUser: null,
    selectedPatientId: null,
    notifications: [],
    setCurrentUser: (value) => set({ currentUser: value }),
    setSelectedPatientId: (value) => set({ selectedPatientId: value }),
    setNotifications: (value) => set({ notifications: value }),
    clearSession: () => set({ sessionId: crypto.randomUUID(), currentUser: null, selectedPatientId: null, notifications: [] }),
    }),
    {
      name: 'healthcare_management_system_session',
      storage: createJSONStorage(() => sessionStorage),
    },
  )
));

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

export { useAppStore, useAppContext };
