/* ============================================================
   ROOT APP
   ============================================================ */
const { useState: useS, useEffect: useE, useRef: useR } = React;
const LS_KEY = "ucc_overlay_state_v2";

function loadState() {
  try {
    const raw = localStorage.getItem(LS_KEY);
    if (raw) return { ...window.UCC_DEFAULT, ...JSON.parse(raw) };
  } catch (e) {}
  return window.UCC_DEFAULT;
}

function App() {
  const [state, setState] = useS(loadState);
  const [dockOpen, setDockOpen] = useS(false);
  const [liveTick, setLiveTick] = useS(0);
  const [clock, setClock] = useS(
    state.intermission.clockMin * 60 + state.intermission.clockSec
  );

  // persist
  useE(() => {
    try { localStorage.setItem(LS_KEY, JSON.stringify(state)); } catch (e) {}
  }, [state]);

  // theme on stage
  // viewport scaling
  const scaleRef = useR(null);
  useE(() => {
    const fit = () => {
      const s = Math.min(window.innerWidth / 1920, window.innerHeight / 1080);
      if (scaleRef.current) scaleRef.current.style.transform = `scale(${s})`;
    };
    fit();
    window.addEventListener("resize", fit);
    return () => window.removeEventListener("resize", fit);
  }, []);

  // intermission countdown
  const im = state.intermission;
  useE(() => {
    if (!state.visible.intermission) return;
    setClock(im.clockMin * 60 + im.clockSec);
    const t = setInterval(() => {
      setClock((c) => (c > 0 ? c - 1 : 0));
    }, 1000);
    return () => clearInterval(t);
  }, [state.visible.intermission, im.clockMin, im.clockSec]);

  // simulate live run
  const simulate = () => setLiveTick((n) => n + 1);

  const v = state.visible;

  return (
    <>
      <div id="viewport">
        <div id="stageScale" ref={scaleRef}>
          <div className="stage" data-theme={state.theme}>
            <div className="feed">
              <image-slot id="ucc-feed" shape="rect" placeholder="Drop program feed still (optional)"></image-slot>
            </div>

            <Bug s={state.bug} vis={v.bug} />
            <RunReadout s={state.run} disc={state.discipline} vis={v.run} liveTick={liveTick} />
            <Standings s={state.standings} vis={v.standings} />
            <UpNext s={state.upnext} vis={v.upnext} />
            <LowerThird s={state.lower} vis={v.lower} />
            <DragMatchup s={state.matchup} vis={v.matchup} />
            <Ticker s={state.ticker} spon={state.sponsor} vis={v.ticker} sponVis={v.sponsor} />
            <Intermission s={im} vis={v.intermission} clock={clock} />
          </div>
        </div>
      </div>

      {!dockOpen && (
        <button id="dockToggle" onClick={() => setDockOpen(true)}>
          <i></i> Producer Control
        </button>
      )}
      <Dock state={state} setState={setState} open={dockOpen} setOpen={setDockOpen} onSimulate={simulate} />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
