import { create } from 'zustand'

/**
 * Tracks the live connection state and emergency mode flag.
 *
 * States:
 *   'online'        — server reachable, SSE connected, normal operation
 *   'reconnecting'  — connection blip detected; 5-second grace before showing full modal
 *   'lost'          — grace period expired, modal shown (Wait / Emergency)
 *   'emergency'     — user chose emergency mode, working from IndexedDB snapshot
 */

const GRACE_MS = 5_000

const useConnectionStore = create((set, get) => ({
  status: 'online',       // 'online' | 'reconnecting' | 'lost' | 'emergency'
  lostAt: null,
  _graceTimer: null,

  setLost: () => {
    const { status, _graceTimer } = get()
    // Already lost or in emergency — no-op
    if (status === 'lost' || status === 'emergency') return
    // Already in grace period — don't restart the timer
    if (status === 'reconnecting') return

    // Start grace period
    const timer = setTimeout(() => {
      // Only escalate if we're still in reconnecting (not recovered in the meantime)
      if (get().status === 'reconnecting') {
        set({ status: 'lost', _graceTimer: null })
      }
    }, GRACE_MS)

    set({ status: 'reconnecting', lostAt: new Date(), _graceTimer: timer })
  },

  setOnline: () => {
    const { _graceTimer } = get()
    if (_graceTimer) clearTimeout(_graceTimer)
    set({ status: 'online', lostAt: null, _graceTimer: null })
  },

  enterEmergency: () => {
    const { _graceTimer } = get()
    if (_graceTimer) clearTimeout(_graceTimer)
    set({ status: 'emergency', _graceTimer: null })
  },

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

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

export default useConnectionStore
