'use client'
// Single WebSocket hook. One connection per active deployment; auto-reconnect
// on close. Pushed events accumulate into the caller-provided state.
import { useEffect, useRef, useState } from 'react'

export type WsEvent = {
  deploymentId: string
  kind: 'progress' | 'log' | 'status'
  state?: string
  stage?: string
  line?: string
  at: number
  backfill?: boolean
}

export function useDeploymentWS(deploymentId: string | null) {
  const [events, setEvents] = useState<WsEvent[]>([])
  const [state, setState] = useState<string>('QUEUED')
  const wsRef = useRef<WebSocket | null>(null)

  useEffect(() => {
    if (!deploymentId) return
    setEvents([])
    setState('QUEUED')

    const proto = window.location.protocol === 'https:' ? 'wss' : 'ws'
    // Slice-2: the WS endpoint is mounted at the dashboard's
    // basePath. NEXT_PUBLIC_BASE_PATH is baked in at build time.
    const base = (process.env.NEXT_PUBLIC_BASE_PATH ?? '').replace(/\/$/, '')
    const url = `${proto}://${window.location.host}${base}/ws/deployments/${deploymentId}`
    const ws = new WebSocket(url)
    wsRef.current = ws

    ws.onmessage = (ev) => {
      try {
        const e: WsEvent = JSON.parse(ev.data)
        if (e.kind === 'status' && e.state) setState(e.state)
        if (e.kind === 'log' || e.kind === 'progress' || e.kind === 'status') {
          setEvents((prev) => [...prev, e].slice(-2000)) // ponytail: cap memory
        }
      } catch {
        // ponytail: drop malformed frames; would-be 3am pain otherwise
      }
    }
    // ponytail: no onclose handler — just let it die. Refresh = resubscribe.
    return () => ws.close()
  }, [deploymentId])

  return { events, state }
}
