// App.jsx — orchestrates the pre-launch page, with Tweaks support.

const { useState: useAppSt, useEffect: useAppEf, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "showCountdownStrip": false,
  "showReactions": true
}/*EDITMODE-END*/;

function TweaksPanel({ open, tweaks, setT, onClose }) {
  if (!open) return null;
  const row = { display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 0", borderBottom: "1px solid var(--border)", gap: 12 };
  return (
    <div style={{
      position: "fixed", bottom: 24, right: 24, zIndex: 100,
      width: 320, background: "var(--white)",
      border: "1px solid var(--border)", borderRadius: 20,
      boxShadow: "var(--shadow-lg)", padding: 20,
      fontFamily: "var(--font-body)",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 20 }}>Tweaks</div>
        <button onClick={onClose} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--muted)", fontSize: 20 }}>×</button>
      </div>

      {[["showCountdownStrip", "Countdown strip (under nav)"],
        ["showReactions", "Reactions section"]].map(([k, l]) => (
        <div key={k} style={row}>
          <span style={{ fontSize: 13 }}>{l}</span>
          <button onClick={() => setT({ [k]: !tweaks[k] })} style={{
            width: 40, height: 22, borderRadius: 999,
            background: tweaks[k] ? "var(--orange)" : "var(--cloud)",
            border: "none", cursor: "pointer", position: "relative",
          }}>
            <span style={{
              position: "absolute", top: 2, left: tweaks[k] ? 20 : 2,
              width: 18, height: 18, borderRadius: "50%",
              background: "#fff", transition: "left 0.15s",
            }} />
          </button>
        </div>
      ))}
    </div>
  );
}

function App() {
  const [tweaks, setTweaks] = useAppSt(TWEAK_DEFAULTS);
  const [editMode, setEditMode] = useAppSt(false);
  const formRef = useRef(null);
  const phase = window.SCS_PHASE || {};
  const isPostCohort = phase.mode === "post-cohort";

  const setT = (patch) => {
    const next = { ...tweaks, ...patch };
    setTweaks(next);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: patch }, "*");
  };

  useAppEf(() => {
    const onMsg = (e) => {
      if (e.data?.type === "__activate_edit_mode") setEditMode(true);
      if (e.data?.type === "__deactivate_edit_mode") setEditMode(false);
    };
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

  // Scroll-reveal observer — adds .is-visible to any .scs-reveal element
  // as it enters the viewport. Respects prefers-reduced-motion via CSS.
  useAppEf(() => {
    if (typeof window === "undefined" || !("IntersectionObserver" in window)) return;
    const io = new IntersectionObserver((entries) => {
      for (const entry of entries) {
        if (entry.isIntersecting) {
          entry.target.classList.add("is-visible");
          io.unobserve(entry.target);
        }
      }
    }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });

    let raf = 0;
    const attach = () => {
      document.querySelectorAll(".scs-reveal:not(.is-visible)").forEach(el => io.observe(el));
    };
    // Initial attach after paint, then a few re-scans for late-mounted nodes.
    raf = requestAnimationFrame(attach);
    const t1 = setTimeout(attach, 400);
    const t2 = setTimeout(attach, 1200);

    return () => {
      cancelAnimationFrame(raf);
      clearTimeout(t1);
      clearTimeout(t2);
      io.disconnect();
    };
  }, []);

  const onJoin = () => {
    const el = document.getElementById("pricing");
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
    else formRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });
  };

  return (
    <div>
      <window.NavBar onJoin={onJoin} />
      <window.AnnouncementStrip />
      {tweaks.showCountdownStrip && <window.CountdownStrip />}
      <window.HeroIndieChat />
      <window.ProblemActs />
      <window.ZoomDemoReactions />
      <section style={{
        padding: "16px 0 48px", background: "var(--white)",
        position: "relative", overflow: "hidden",
      }}>
        <window.SpecialistTicker />
      </section>
      <window.ProductDemoSection />
      <window.OutputShowcase />
      <window.TheTen />
      <window.HowItWorks />
      <window.FeaturesSection />
      {tweaks.showReactions && <window.Reactions />}
      <window.WhoItsFor />
      <window.FounderStory />
      {!isPostCohort && <window.CohortBenefits />}
      <window.PricingSection />
      <window.ComparisonSection />
      <window.FAQ />
      <window.FinalCTA formRef={formRef} />
      <window.SCSFooter />

      <window.FloatingBuyButton />

      <TweaksPanel open={editMode} tweaks={tweaks} setT={setT} onClose={() => setEditMode(false)} />
    </div>
  );
}

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