// SSE subscription helper. Returns an unsubscribe function.

export function subscribeSSE(
  onMessage: (type: string, payload: unknown) => void,
  onError?: (e: Event) => void,
): () => void {
  const tok = localStorage.getItem('c2s_token')
  const url = '/api/events/stream' + (tok ? `?token=${encodeURIComponent(tok)}` : '')
  const es = new EventSource(url)

  es.onmessage = (e) => {
    try {
      const env = JSON.parse(e.data) as { type: string; payload: unknown; timestamp: string }
      onMessage(env.type, env.payload)
    } catch (err) {
      console.error('SSE parse:', err)
    }
  }
  es.onerror = (e) => {
    if (onError) onError(e)
    // Browser will auto-reconnect; nothing to do
  }
  return () => es.close()
}
