"use client";

import { useSyncExternalStore } from "react";
import HomeCockpit from "./HomeCockpit";
import HomeDashboard from "./HomeDashboard";
import WelcomeModal from "./WelcomeModal";
import { DEFAULT_HOME_LAYOUT, readHomeLayout, subscribeHomeLayout } from "@/lib/homeLayout";
import { useHomeBroadcast } from "@/lib/useHomeBroadcast";

// Home — the / route. Picks the saved home layout (Cockpit is the default,
// Classic is the original HomeDashboard) and hosts the shared remote-driven
// layer (broadcast payload + welcome-video modal) so BOTH layouts get it
// without duplicating fetches. The TopBar toggle flips layouts live through
// the homeLayout store subscription.
export default function Home() {
  // useSyncExternalStore: server snapshot = the default, client snapshot = the
  // saved preference. Worst case is a one-frame swap on hydration, never a
  // hydration mismatch.
  const layout = useSyncExternalStore(subscribeHomeLayout, readHomeLayout, () => DEFAULT_HOME_LAYOUT);
  const { bc, welcomeOpen, openWelcome, dismissWelcome } = useHomeBroadcast();

  return (
    <>
      {layout === "classic"
        ? <HomeDashboard bc={bc} onWatchIntro={openWelcome} />
        : <HomeCockpit bc={bc} onWatchIntro={openWelcome} />}
      <WelcomeModal open={welcomeOpen} video={bc?.welcomeVideo ?? null} onClose={dismissWelcome} />
    </>
  );
}
