import { create } from 'zustand';
import { devtools } from 'zustand/middleware';

/**
 * sentinelStore — showroom session state + alert queue
 */
interface SentinelAlert {
  id: string;
  matchedName?: string;
  matchedPersonId?: string;
  confidence?: number;
  zone: string;
  timestamp: Date;
}

interface SentinelStore {
  // Live session
  isShowroomActive: boolean;
  currentSessionId: string | null;
  currentSessionDuration: string;
  // Alerts
  pendingAlert: SentinelAlert | null;
  alertCount: number;
  // AI rail
  hasInsights: boolean;
  // Actions
  setPendingAlert: (alert: SentinelAlert) => void;
  clearPendingAlert: () => void;
  setShowroomActive: (active: boolean, sessionId?: string) => void;
  setSessionDuration: (duration: string) => void;
  setHasInsights: (has: boolean) => void;
  incrementAlertCount: () => void;
  clearAlerts: () => void;
}

export const useSentinelStore = create<SentinelStore>()(
  devtools(
    (set, get) => ({
      isShowroomActive: false,
      currentSessionId: null,
      currentSessionDuration: '00:00',
      pendingAlert: null,
      alertCount: 0,
      hasInsights: false,

      setPendingAlert: (alert) =>
        set(
          { pendingAlert: alert, alertCount: get().alertCount + 1 },
          false,
          'sentinel/setPendingAlert'
        ),

      clearPendingAlert: () =>
        set({ pendingAlert: null }, false, 'sentinel/clearPendingAlert'),

      setShowroomActive: (active, sessionId) =>
        set(
          { isShowroomActive: active, currentSessionId: sessionId ?? null },
          false,
          'sentinel/setShowroomActive'
        ),

      setSessionDuration: (duration) =>
        set({ currentSessionDuration: duration }, false, 'sentinel/setDuration'),

      setHasInsights: (has) =>
        set({ hasInsights: has }, false, 'sentinel/setHasInsights'),

      incrementAlertCount: () =>
        set({ alertCount: get().alertCount + 1 }, false, 'sentinel/incrementAlert'),

      clearAlerts: () =>
        set({ alertCount: 0 }, false, 'sentinel/clearAlerts'),
    }),
    { name: 'SentinelStore' }
  )
);
