"use client";

import { useQueryClient } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
import { useEffect } from "react";

export function EventsBridge() {
  const { data: session, status } = useSession();
  const queryClient = useQueryClient();

  useEffect(() => {
    if (status !== "authenticated" || !session) return;
    if (typeof window === "undefined" || !("EventSource" in window)) return;

    let closed = false;
    let es: EventSource | null = null;

    const connect = () => {
      if (closed) return;
      es = new EventSource("/api/events");

      es.addEventListener("status", (e: MessageEvent) => {
        try {
          queryClient.setQueryData(["status"], JSON.parse(e.data));
        } catch {}
      });
      es.addEventListener("chat", (e: MessageEvent) => {
        try {
          queryClient.setQueryData(["chat"], JSON.parse(e.data));
        } catch {}
      });

      es.onerror = () => {
        // Browser auto-retries, but if the server closed after the 10m cap
        // we want a clean reconnect rather than tight reconnect loops.
        if (closed) return;
        es?.close();
        es = null;
        setTimeout(connect, 3000);
      };
    };

    connect();
    return () => {
      closed = true;
      es?.close();
    };
  }, [status, session, queryClient]);

  return null;
}
