'use client'
import { useEffect } from 'react'
import { useEngineStore } from '@/store/engineStore'

// SSE is disabled in the static build — replaced with plain HTTP polling.
// EventSource('/api/stream') would always fail (404) since there is no
// streaming route in the FastAPI-served static build, causing permanent
// ENGINE OFFLINE display. Polling /api/stats every 5s works in all modes.
const BASE = 'http://localhost:8000'

export function useSSE() {
  const setStats  = useEngineStore((s) => s.setStats)
  const setOffline = useEngineStore((s) => s.setOffline)

  useEffect(() => {
    let alive = true

    const poll = async () => {
      try {
        const res = await fetch(`${BASE}/api/stats`)
        if (!res.ok) throw new Error('not ok')
        const data = await res.json()
        if (alive) setStats(data)   // also clears isOffline via store
      } catch {
        if (alive) setOffline(true)
      }
    }

    poll()                              // immediate on mount
    const id = setInterval(poll, 5000)  // then every 5 s

    return () => {
      alive = false
      clearInterval(id)
    }
  }, [setStats, setOffline])
}
