import { useEffect, useRef } from "react";
import { toast } from "sonner";

type State = "idle" | "connecting" | "open" | "reconnecting" | "closed";

/**
 * Emits toast notifications on WebSocket connection lifecycle changes.
 * - "reconnecting" (after we've been open) → warning toast with attempt #
 * - "open" (after a reconnect) → success toast confirming stream is live
 * - "closed" → error toast that the feed dropped
 * Skips the initial "connecting → open" handshake so the first page load
 * doesn't spam the user.
 */
export function useConnectionToasts(
  label: string,
  connection: { state: State; attempt: number },
) {
  const prev = useRef<State>("idle");
  const hasOpened = useRef(false);
  const toastId = useRef<string | number | null>(null);

  useEffect(() => {
    const s = connection.state;
    const p = prev.current;
    if (s === p) return;

    if (s === "reconnecting" && hasOpened.current) {
      toastId.current = toast.warning(`${label} reconnecting…`, {
        id: toastId.current ?? undefined,
        description: connection.attempt > 1 ? `Attempt #${connection.attempt}` : undefined,
      });
    } else if (s === "open") {
      if (hasOpened.current) {
        toastId.current = toast.success(`${label} live`, {
          id: toastId.current ?? undefined,
          description: "Realtime stream restored",
        });
      }
      hasOpened.current = true;
    } else if (s === "closed" && hasOpened.current) {
      toastId.current = toast.error(`${label} offline`, {
        id: toastId.current ?? undefined,
        description: "We'll keep retrying in the background",
      });
    }
    prev.current = s;
  }, [connection.state, connection.attempt, label]);
}
