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

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

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "A",
  "headline": "Build a one-person content studio that produces like a *ten-person team.*",
  "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>

      <div style={row}>
        <span style={{ fontSize: 13 }}>Hero variant</span>
        <div style={{ display: "flex", gap: 4 }}>
          {["A", "B"].map(v => (
            <button key={v} onClick={() => setT({ heroVariant: v })} style={{
              padding: "6px 12px", borderRadius: 999, cursor: "pointer",
              border: "1px solid var(--border)",
              background: tweaks.heroVariant === v ? "var(--orange)" : "var(--white)",
              color: tweaks.heroVariant === v ? "#fff" : "var(--ink)",
              fontFamily: "var(--font-mono)", fontSize: 11,
            }}>{v === "A" ? "Outnumbered" : "Studio · Split"}</button>
          ))}
        </div>
      </div>

      <div style={{ ...row, flexDirection: "column", alignItems: "stretch" }}>
        <span style={{ fontSize: 13, marginBottom: 6 }}>Hero headline</span>
        <textarea value={tweaks.headline} onChange={e => setT({ headline: e.target.value })}
          style={{
            width: "100%", minHeight: 62, resize: "vertical",
            padding: 10, borderRadius: 12, border: "1px solid var(--border)",
            fontFamily: "var(--font-body)", fontSize: 13, color: "var(--ink)",
            background: "var(--snow)",
          }} />
        <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 6 }}>Applies to variant A only</div>
      </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 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 = () => formRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });

  // Hero A with a custom headline from Tweaks — matches window.HeroA design.
  // Wrap the phrase to emphasize in *asterisks* in the tweak string.
  // Fallback: auto-italicize the last significant word if no markers found.
  const HeroAPatched = () => {
    const raw = tweaks.headline || "";
    const hasMarkers = /\*[^*]+\*/.test(raw);

    let rendered;
    if (hasMarkers) {
      // Split on *...* groups, italicize the captured content.
      const parts = raw.split(/(\*[^*]+\*)/);
      rendered = parts.map((p, i) =>
        p.startsWith("*") && p.endsWith("*") && p.length > 2
          ? <em key={i}>{p.slice(1, -1)}</em>
          : <span key={i}>{p}</span>
      );
    } else {
      const words = raw.split(/(\s+)/);
      const lastIdx = (() => {
        for (let i = words.length - 1; i >= 0; i--) {
          const w = words[i].replace(/[^\w']/g, "");
          if (w.length > 2) return i;
        }
        return -1;
      })();
      rendered = words.map((w, i) => i === lastIdx
        ? <em key={i}>{w}</em>
        : <span key={i}>{w}</span>
      );
    }

    return (
      <header className="scs-hero-a" style={{ position: "relative", overflow: "hidden", padding: "80px 32px 40px", textAlign: "center" }}>
        <window.MeshBg variant="warm" />
        <div style={{ position: "relative", maxWidth: 1000, margin: "0 auto" }}>
          <h1 style={{
            fontSize: "clamp(40px, 4.8vw, 72px)",
            lineHeight: 1.1, letterSpacing: "-0.03em",
            margin: "0 auto 28px", maxWidth: 900,
          }}>
            {rendered}
          </h1>
          <p className="scs-hero-a-p" style={{ fontSize: 22, lineHeight: 1.5, color: "var(--ink-light)",
                      maxWidth: 680, margin: "0 auto 40px", fontWeight: 400 }}>
            Ten years ago, marketing a solo business meant a blog and a newsletter.
            Today, it's nine formats, four platforms, and a schedule that never stops.
            <br /><br />
            <span style={{ color: "var(--ink)", fontWeight: 700 }}>
              We're building you a way out.
            </span>
          </p>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
            <window.WaitlistForm variant="light" size="lg" align="center" />
            <span style={{
              fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--muted)",
              letterSpacing: "0.12em", textTransform: "uppercase",
            }}>No spam · One email when doors open</span>
          </div>
        </div>
        <window.SpecialistTicker />
      </header>
    );
  };

  return (
    <div>
      <window.NavBar onJoin={onJoin} />
      {tweaks.showCountdownStrip && <window.CountdownStrip />}
      {tweaks.heroVariant === "A"
        ? <HeroAPatched />
        : <window.HeroB onJoin={onJoin} />}
      <window.ProblemActs />
      <window.OutputShowcase />
      <window.TheTen />
      <window.HowItWorks />
      <window.PeekSection />
      {tweaks.showReactions && <window.Reactions />}
      <window.WaitlistCTA formRef={formRef} />
      <window.SCSFooter />

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

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