const { useEffect, useState } = React;

function App() {
  const [tweaks, setTweaks] = useState(window.__TWEAKS__);
  const [tweaksOn, setTweaksOn] = useState(false);
  const [showNewsletter, setShowNewsletter] = useState(false);

  useEffect(() => {
    // Always show popup after 30s (clear any stale dismissed flag on fresh load)
    sessionStorage.removeItem("nl_dismissed");
    const t = setTimeout(() => setShowNewsletter(true), 30000);
    return () => clearTimeout(t);
  }, []);

  useEffect(() => {
    const root = document.documentElement;
    const p = PALETTES[tweaks.palette] || PALETTES["ink-citron"];
    root.style.setProperty("--bg", p.bg);
    root.style.setProperty("--fg", p.fg);
    root.style.setProperty("--fg-mute", p.fgMute);
    root.style.setProperty("--rule", p.rule);
    root.style.setProperty("--rule-2", p.rule2);
    root.style.setProperty("--accent", p.accent);
    root.style.setProperty("--accent-ink", p.accentInk);
    root.style.setProperty("--card", p.card);

    const tp = TYPE_PAIRS[tweaks.type] || TYPE_PAIRS["bricolage-grotesk"];
    root.style.setProperty("--display", tp.display);
    root.style.setProperty("--sans", tp.sans);

    try { window.parent.postMessage({ type: "__edit_mode_set_keys", edits: tweaks }, "*"); } catch (e) {}
  }, [tweaks]);

  useEffect(() => {
    const onMsg = (e) => {
      if (!e.data || typeof e.data !== "object") return;
      if (e.data.type === "__activate_edit_mode") setTweaksOn(true);
      if (e.data.type === "__deactivate_edit_mode") setTweaksOn(false);
    };
    window.addEventListener("message", onMsg);
    try { window.parent.postMessage({ type: "__edit_mode_available" }, "*"); } catch (e) {}
    return () => window.removeEventListener("message", onMsg);
  }, []);

  const Hero = tweaks.hero === "calculator" ? HeroCalculator
             : tweaks.hero === "stack" ? HeroStack
             : HeroManifesto;

  return (
    <>
      <Nav />
      <Hero />
      <Ticker />
      <Problem />
      <Method />
      <Program />
      <FAQ />
      <Call />
      <Footer />
      <TweaksPanel
        tweaks={tweaks} setTweaks={setTweaks}
        visible={tweaksOn} onClose={() => setTweaksOn(false)}
      />
      {showNewsletter && (
        <NewsletterPopup onClose={() => setShowNewsletter(false)} />
      )}
    </>
  );
}

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