import { useEffect, useRef } from 'preact/hooks';
import type { SSEEvent } from '../types/index.js';

export function useSSE(
  url: string | null,
  onEvent: (event: SSEEvent) => void,
  onClose?: () => void,
): { close: () => void } {
  const esRef = useRef<EventSource | null>(null);
  const onEventRef = useRef(onEvent);
  onEventRef.current = onEvent;
  const onCloseRef = useRef(onClose);
  onCloseRef.current = onClose;

  useEffect(() => {
    if (!url) return;

    const es = new EventSource(url);
    esRef.current = es;

    es.onmessage = (e: MessageEvent) => {
      try {
        const event = JSON.parse(e.data as string) as SSEEvent;
        onEventRef.current(event);

        if (event.stage === 'complete' || event.status === 'error') {
          es.close();
          esRef.current = null;
        }
      } catch {
        // ignore parse errors
      }
    };

    es.onerror = () => {
      es.close();
      esRef.current = null;
      onCloseRef.current?.();
    };

    return () => {
      es.close();
      esRef.current = null;
    };
  }, [url]);

  return {
    close: () => {
      esRef.current?.close();
      esRef.current = null;
    },
  };
}
