/* ============================================================
   APP — frame, nav, page-turn, theme toggle, tweaks
   ============================================================ */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "typePair": "chakra",
  "accent": "#d3232c"
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [section, setSection] = useState(() => localStorage.getItem("tc_section") || "home");
  const [prev, setPrev] = useState(null);
  const [turnKey, setTurnKey] = useState(0);
  const [leafH, setLeafH] = useState(0);
  const [projectsReady, setProjectsReady] = useState(false);
  const flipping = useRef(false);
  const pageRef = useRef(null);
  const projTimer = useRef(null);

  // Boot→grid handoff lives HERE (App never remounts), so the Projects
  // terminal can restart/remount freely without ever stranding the grid.
  const startProjBoot = () => {
    setProjectsReady(false);
    if (projTimer.current) clearTimeout(projTimer.current);
    projTimer.current = setTimeout(() => setProjectsReady(true), 2400);
  };
  // direct-load case (e.g. refresh while on Projects)
  useEffect(() => { if (section === "projects") startProjBoot(); /* eslint-disable-next-line */ }, []);

  // apply type + accent to root
  useEffect(() => { document.documentElement.setAttribute("data-type", t.typePair || "chakra"); }, [t.typePair]);
  useEffect(() => {
    const r = document.documentElement.style;
    r.setProperty("--accent", t.accent);
    r.setProperty("--accent-bright", t.accent);
  }, [t.accent]);
  useEffect(() => { localStorage.setItem("tc_section", section); }, [section]);
  useEffect(() => { const b = document.getElementById("boot"); if (b) b.remove(); }, []);

  const cur = SECTIONS.find(s => s.id === section) || SECTIONS[0];
  const prv = prev ? SECTIONS.find(s => s.id === prev) : null;

  const navTo = (id) => {
    if (id === section || flipping.current) return;
    flipping.current = true;
    if (id === "projects") startProjBoot();
    setLeafH(pageRef.current ? pageRef.current.offsetHeight : 0);
    setPrev(section);
    setSection(id);
    setTurnKey(k => k + 1);
    document.querySelector(".stage").scrollTo({ top: 0, behavior: "auto" });
    setTimeout(endTurn, 950); // guaranteed cleanup if animationend is missed
  };

  const onBodyClick = (e) => {
    const el = e.target.closest("[data-go]");
    if (el) navTo(el.getAttribute("data-go"));
  };

  const endTurn = () => { setPrev(null); flipping.current = false; };

  const CurComp = cur.Comp, PrvComp = prv ? prv.Comp : null;

  return (
    <div className="stage">
      <div className="doc-frame">
        {/* persistent header */}
        <div className="doc-header">
          <div className="brand">
            <div className="cog"></div>
            <div className="who"><b>T. Chandra</b><span>ENGINEERING LOGBOOK</span></div>
          </div>
          <div className="nav">
            {SECTIONS.map(s => (
              <button key={s.id} className={"nav-item" + (s.id === section ? " on" : "")} onClick={() => navTo(s.id)}>
                <span className="idx">{s.idx}</span>
                <span className="lbl">{s.label}</span>
              </button>
            ))}
          </div>
        </div>

        {/* turning area */}
        <div className="leaf-stage" onClick={onBodyClick}>
          <div ref={pageRef} className="settling" key={section} style={{ position: "relative", zIndex: 1 }}>
            <CurComp t={t} ready={projectsReady} />
          </div>
          {prv && (
            <div className="flip-leaf" key={turnKey} style={{ height: leafH || undefined }} onAnimationEnd={endTurn}>
              <div className="face front" style={{ height: leafH || undefined }}><PrvComp t={t} leaf ready /></div>
              <div className="face back sheet-grid"></div>
              <div className="shade"></div>
            </div>
          )}
        </div>
      </div>

      {/* tweaks */}
      <TweaksPanel>
        <TweakSection label="Type & Color" />
        <TweakRadio label="Typeface" value={t.typePair} options={["chakra", "editorial"]}
          onChange={(v) => setTweak("typePair", v)} />
        <TweakColor label="Accent" value={t.accent}
          options={["#1f6fc4", "#2f8be0", "#0e8a86", "#d3232c"]}
          onChange={(v) => setTweak("accent", v)} />
      </TweaksPanel>
    </div>
  );
}

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