// Main app
const { useState: useStateM, useEffect: useEffectM } = React;

const STATE_VERSION = 4;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "variant": "noir",
  "accent": "#ff5a5a",
  "scanlines": true,
  "grain": true,
  "taglineFormat": "serif",
  "blocking": "A"
}/*EDITMODE-END*/;

function App() {
  useConsoleEgg();
  useScrollReveal();
  useScrollSpy();

  const [state, setState] = useStateM(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("coc_state") || "null");
      if (saved && saved.__v === STATE_VERSION) return saved;
      return { ...TWEAK_DEFAULTS, __v: STATE_VERSION };
    } catch { return { ...TWEAK_DEFAULTS, __v: STATE_VERSION }; }
  });

  useEffectM(() => {
    localStorage.setItem("coc_state", JSON.stringify(state));
    document.documentElement.style.setProperty("--accent", state.accent);
    window.COC_STATE = state;
  }, [state]);

  // Also sync during render so children reading window.COC_STATE get fresh values on first paint
  if (typeof window !== "undefined") {
    window.COC_STATE = state;
    try { document.documentElement.style.setProperty("--accent", state.accent); } catch {}
  }

  // Sudo easter egg — type 'sudo' to flash the manifesto
  const [flash, setFlash] = useStateM(false);
  useEffectM(() => {
    let buf = "";
    const onKey = (e) => {
      if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA") return;
      buf = (buf + e.key.toLowerCase()).slice(-6);
      if (buf.endsWith("sudo")) {
        setFlash(true);
        setTimeout(() => setFlash(false), 3200);
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const Hero =
    state.variant === "dossier" ? window.HeroDossier :
    state.variant === "noir" ? window.HeroNoir :
    window.HeroTerminal;

  return (
    <div className={`coc-root variant-${state.variant} ${state.grain ? "has-grain" : ""} ${state.scanlines ? "has-scan" : ""}`}>
      <div className="coc-bg-grain" aria-hidden="true" />
      <Nav />
      <main id="top">
        <Hero />
        <Services />
        <About />
        <Clients />
        <Writing />
        <Contact />
      </main>
      <Footer />
      <Tweaks state={state} setState={setState} />

      {flash && (
        <div className="sudo-flash">
          <div className="sudo-flash-inner">
            <div className="sudo-k">// sudo access granted</div>
            <div className="sudo-v">my crime is that of curiosity.</div>
            <div className="sudo-k sudo-k-dim">— the hacker manifesto, 1986</div>
          </div>
        </div>
      )}
    </div>
  );
}

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