"use client";

import { useCallback, useEffect, useState } from "react";
import { WELCOME_SEEN_KEY, type BroadcastPayload } from "@/lib/homeBroadcast";

export interface HomeBroadcastState {
  bc: BroadcastPayload | null;
  welcomeOpen: boolean;
  openWelcome: () => void;
  dismissWelcome: () => void;
}

// useHomeBroadcast — the remote-driven layer shared by BOTH home layouts
// (Classic + Cockpit): one broadcast fetch per visit plus the welcome-video
// modal state. Lives in the <Home/> wrapper so switching layouts never
// re-fetches the payload or re-decides whether to show the modal.
export function useHomeBroadcast(): HomeBroadcastState {
  const [bc, setBc] = useState<BroadcastPayload | null>(null);
  const [welcomeOpen, setWelcomeOpen] = useState(false);

  // Remote-driven content — fetched once per visit via our server route.
  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const r = await fetch("/api/home/broadcast", { cache: "no-store" });
        const j: BroadcastPayload = await r.json();
        if (cancelled || !j || typeof j !== "object") return;
        setBc(j);
        const v = j.welcomeVideo;
        if (v?.show) {
          try {
            if (localStorage.getItem(WELCOME_SEEN_KEY) !== String(v.version)) setWelcomeOpen(true);
          } catch { /* private mode: just show it */ setWelcomeOpen(true); }
        }
      } catch { /* offline: strip + modal simply stay hidden */ }
    })();
    return () => { cancelled = true; };
  }, []);

  const openWelcome = useCallback(() => setWelcomeOpen(true), []);

  const dismissWelcome = useCallback(() => {
    setWelcomeOpen(false);
    const version = bc?.welcomeVideo?.version;
    if (version !== undefined) {
      try { localStorage.setItem(WELCOME_SEEN_KEY, String(version)); } catch { /* private mode */ }
    }
  }, [bc]);

  return { bc, welcomeOpen, openWelcome, dismissWelcome };
}
