/* ============================================================
   Eval Pulse — app shell
   ============================================================ */
function App({ data }) {
  const [theme, setTheme] = useState(() => localStorage.getItem("ep-theme") || "light");
  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    localStorage.setItem("ep-theme", theme);
  }, [theme]);

  // data.js fetches from Supabase asynchronously; render a calm placeholder
  // until the first payload lands (usually <300ms).
  if (!data) {
    return (
      <div className="app">
        <div style={{ padding: "96px 0", textAlign: "center", color: "var(--text-2)", fontSize: 15 }}>
          Loading live data…
        </div>
      </div>
    );
  }

  let updated = "";
  try { updated = new Date(data.as_of).toLocaleString(); } catch (e) { updated = ""; }

  return (
    <div className="app">
      <Header data={data} theme={theme} onToggle={() => setTheme(t => t === "dark" ? "light" : "dark")} />
      <Hero data={data} />
      <TrendSection />
      <Highlights items={data.highlights} />
      <div className="grid-2 align-start">
        <Graders items={data.graders} />
        <Domains items={data.domains} />
      </div>
      <Regression reg={data.regression} />
      <footer className="foot reveal" style={{ "--i": 7 }}>
        Eval Pulse · {data.customer} · live · updated {updated}
      </footer>
    </div>
  );
}

/* Root owns the data state. It seeds from window.DATA if data.js already
   resolved, and re-renders whenever data.js fires "data-ready" — both on
   first load and on each 5-minute auto-refresh. */
function Root() {
  const [data, setData] = useState(window.DATA || null);
  useEffect(() => {
    const onReady = () => setData(window.DATA);
    document.addEventListener("data-ready", onReady);
    if (window.DATA) setData(window.DATA); // covers the event firing before mount
    return () => document.removeEventListener("data-ready", onReady);
  }, []);
  return <App data={data} />;
}

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

/* Fail-safe: once the entrance animation has had time to play (or be
   skipped by a paused clock), force all reveal elements visible. */
setTimeout(() => document.body.classList.add("reveal-ready"), 1000);
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "hidden") document.body.classList.add("reveal-ready");
});
