import { create } from 'zustand'

/**
 * Tracks the live connection state and emergency mode flag.
 *
 * States:
 *   'online'     — server reachable, SSE connected, normal operation
 *   'lost'       — server unreachable, modal shown (Wait / Emergency)
 *   'emergency'  — user chose emergency mode, working from IndexedDB snapshot
 */
const useConnectionStore = create((set, get) => ({
  status: 'online',       // 'online' | 'lost' | 'emergency'
  lostAt: null,           // Date when connection was lost

  setLost: () => {
    if (get().status === 'online') {
      set({ status: 'lost', lostAt: new Date() })
    }
  },

  setOnline: () => set({ status: 'online', lostAt: null }),

  enterEmergency: () => set({ status: 'emergency' }),

  // Called when server comes back while in emergency mode — triggers sync then go online
  exitEmergency: () => set({ status: 'online', lostAt: null }),

  isOnline:    () => get().status === 'online',
  isLost:      () => get().status === 'lost',
  isEmergency: () => get().status === 'emergency',
}))

export default useConnectionStore
