import { useEffect } from 'react';

export function useSSE(onMessage: (data: any) => void) {
  useEffect(() => {
    const eventSource = new EventSource('/api/notify');

    eventSource.onmessage = (event) => {
      try {
        const parsed = JSON.parse(event.data);
        onMessage(parsed);
      } catch (err) {
        console.error('Invalid SSE data', err);
      }
    };

    eventSource.onerror = () => {
      eventSource.close();
    };

    return () => {
      eventSource.close();
    };
  }, [onMessage]);
}
