/* ============================================================================
   APP — the single hydrated island. State machine:
   entry → (diagnose) → rebuild sweep → landing → (re-diagnose) → entry.
   Owns the --accent swap and the signature "rewiring" moment.
   ============================================================================ */
const { useState: useStateA, useEffect: useEffectA, useRef: useRefA } = React;

function RebuildOverlay({ accent }) {
  return React.createElement(
    "div",
    { className: "rebuild-overlay", style: { "--accent": accent } },
    React.createElement("div", { className: "rebuild-sweep" }),
    React.createElement("div", { className: "rebuild-grid" }),
    React.createElement(
      "div",
      { className: "rebuild-label mono" },
      React.createElement("span", { className: "rb-dot" }),
      "Rewiring the platform…"
    )
  );
}

function App() {
  const { LABS, DEFAULT_ACCENT } = window.TALYA_DATA;
  const [phase, setPhase] = useStateA("entry"); // entry | rebuilding | landing
  const [problem, setProblem] = useStateA(null);
  const [labKey, setLabKey] = useStateA(null);
  const [pains, setPains] = useStateA([]);
  const [accent, setAccent] = useStateA(DEFAULT_ACCENT);

  function onDiagnose(pKey, lKey, painKeys) {
    setProblem(pKey);
    setLabKey(lKey);
    setPains(painKeys || []);
    const newAccent = LABS[lKey].accent;
    if (window.prefersReduced()) {
      setAccent(newAccent);
      setPhase("landing");
      window.scrollTo(0, 0);
      return;
    }
    setPhase("rebuilding");
    // swap accent partway through the sweep so the new color "arrives"
    setTimeout(() => setAccent(newAccent), 280);
    setTimeout(() => { setPhase("landing"); window.scrollTo(0, 0); }, 760);
  }

  function onRediagnose() {
    window.scrollTo(0, 0);
    setPhase("entry");
    setProblem(null);
    setLabKey(null);
    setTimeout(() => setAccent(DEFAULT_ACCENT), 60);
  }

  function onGoToLab(lKey) {
    const { PROBLEMS } = window.TALYA_DATA;
    onDiagnose(problem || PROBLEMS[0].key, lKey, pains);
  }

  const lab = labKey ? LABS[labKey] : null;

  return React.createElement(
    "div",
    { className: "app", style: { "--accent": accent } },
    React.createElement(AmbientBackground, { accent }),
    phase === "entry"
      ? React.createElement(EntryExperience, { onDiagnose })
      : React.createElement(Landing, { problem, lab, pains, onRediagnose, onGoToLab }),
    phase === "rebuilding" && React.createElement(RebuildOverlay, { accent }),
    React.createElement("div", { className: "accent-flash", "data-on": phase === "rebuilding" })
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(React.createElement(App));
