/* build-page.jsx — /build page: hero, why-build grid, get-involved, video playlist.
   Reuses Nav/Footer/Reveal + global CSS vars. Every section covers the full viewport. */

const BUILD_RAIN = (() => {
  const chars = "0123456789ABCDEFabcdef$%&/\\xz+=<>";
  let s = 71237; const rnd = () => (s = (s * 16807) % 2147483647) / 2147483647;
  let out = ""; for (let i = 0; i < 1800; i++) { out += chars[(rnd() * chars.length) | 0]; if (i % 64 === 63) out += "\n"; }
  return out;
})();

function CodeRain({ opacity = 0.05 }) {
  return (
    <div aria-hidden="true" style={{ position: "absolute", inset: 0, fontFamily: "var(--mono)", fontSize: 12,
      lineHeight: 1.55, color: `rgba(255,255,255,${opacity})`, whiteSpace: "pre-wrap", wordBreak: "break-all",
      overflow: "hidden", pointerEvents: "none", padding: 16, userSelect: "none" }}>{BUILD_RAIN}</div>
  );
}

const BP_SECTION = { position: "relative", minHeight: "100vh", overflow: "hidden", display: "flex",
  flexDirection: "column", justifyContent: "center", padding: "clamp(80px,12vh,150px) 0",
  borderTop: "1px solid var(--line)" };
const BP_INNER = { width: "100%", maxWidth: 1680, margin: "0 auto", padding: "0 clamp(20px,5vw,72px)" };
const BP_EYE = { display: "flex", alignItems: "center", gap: 14, fontFamily: "var(--mono)", fontSize: 12,
  letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--green)" };
const BP_DASH = <span style={{ width: 28, height: 1, background: "var(--green)", display: "inline-block" }} />;
const BP_H = { fontFamily: "var(--display)", fontWeight: 800, textTransform: "uppercase", letterSpacing: "-0.025em",
  lineHeight: 1.0, margin: "18px 0 0" };

/* ---- Apply modal (triggered from hero CTA) ---- */
function ApplyModal({ onClose }) {
  const [name, setName] = useState("");
  const [githubId, setGithubId] = useState("");
  const [whatBuilding, setWhatBuilding] = useState("");
  const [status, setStatus] = useState("idle"); // idle | sending | sent | error
  const [err, setErr] = useState(null);
  const busy = status === "sending" || status === "sent";

  const fieldStyle = {
    width: "100%", background: "#111", border: "1px solid var(--line)", borderRadius: 0,
    padding: "12px 14px", fontFamily: "var(--body)", fontSize: 15, color: "var(--text)",
    outline: "none", transition: "border-color .18s",
  };
  const labelStyle = { fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.22em",
    textTransform: "uppercase", color: "var(--faint)" };

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [onClose]);

  async function onSubmit(e) {
    e.preventDefault();
    if (!githubId.trim() || !whatBuilding.trim() || busy) return;
    setStatus("sending"); setErr(null);
    try {
      const res = await fetch("/rfp/api/contact", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, contact: githubId, message: whatBuilding, idea: "Application" }),
      });
      if (!res.ok) { const d = await res.json().catch(() => ({})); throw new Error(d.error || "Something went wrong."); }
      setStatus("sent");
    } catch (e2) { setStatus("error"); setErr(e2.message || "Something went wrong."); }
  }

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 100,
      background: "rgba(3,6,14,0.84)", backdropFilter: "blur(8px)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: "clamp(16px,4vw,48px)" }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: "100%", maxWidth: 560,
        background: "linear-gradient(165deg,#181818 0%,#141414 50%,#0e0b0a 100%)",
        border: "1px solid var(--line)", borderTop: "2px solid var(--green)",
        padding: "clamp(24px,3vw,40px)", position: "relative" }}>
        <button onClick={onClose} style={{ position: "absolute", top: 14, right: 14, background: "none", border: "none",
          cursor: "pointer", fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.18em",
          color: "var(--faint)", padding: "4px 8px" }}>ESC ✕</button>
        <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.22em",
          textTransform: "uppercase", color: "var(--green)", marginBottom: 14 }}>— Apply</div>
        {status === "sent" ? (
          <div>
            <h2 style={{ fontFamily: "var(--display)", fontWeight: 800, textTransform: "uppercase",
              fontSize: "clamp(22px,3vw,38px)", letterSpacing: "-0.02em", lineHeight: 1.05,
              background: "linear-gradient(178deg,#fffdf1 0%,#ffcdb6 100%)", WebkitBackgroundClip: "text",
              backgroundClip: "text", WebkitTextFillColor: "transparent", color: "transparent", margin: 0 }}>
              You're in.
            </h2>
            <p style={{ fontFamily: "var(--body)", fontSize: 15, color: "var(--dim)", lineHeight: 1.6, marginTop: 14 }}>
              We'll be in touch. Book a call if you'd like to talk sooner.
            </p>
            <a href="https://cal.com/adithyadinesh" target="_blank" rel="noreferrer"
              className="btn btn-ghost" style={{ display: "inline-flex", alignItems: "center", gap: 8, marginTop: 22 }}>
              Book a call <span className="arrow">→</span>
            </a>
          </div>
        ) : (
          <form onSubmit={onSubmit} style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <h2 style={{ fontFamily: "var(--display)", fontWeight: 800, textTransform: "uppercase",
              fontSize: "clamp(18px,2.2vw,28px)", letterSpacing: "-0.02em", lineHeight: 1.1, margin: "0 0 4px",
              background: "linear-gradient(178deg,#fffdf1 0%,#f4ece8 55%,#ffcdb6 100%)", WebkitBackgroundClip: "text",
              backgroundClip: "text", WebkitTextFillColor: "transparent", color: "transparent" }}>
              Start your application.
            </h2>
            <label style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <span style={labelStyle}>Name <span style={{ color: "var(--faint)", letterSpacing: 0 }}>(optional)</span></span>
              <input type="text" value={name} disabled={busy} onChange={(e) => setName(e.target.value)}
                placeholder="Your name"
                onFocus={(e) => (e.target.style.borderColor = "var(--green)")}
                onBlur={(e) => (e.target.style.borderColor = "var(--line)")}
                style={fieldStyle} />
            </label>
            <label style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <span style={labelStyle}>GitHub username <span style={{ color: "var(--green)" }}>*</span></span>
              <input type="text" required value={githubId} disabled={busy} onChange={(e) => setGithubId(e.target.value)}
                placeholder="your-github-handle"
                onFocus={(e) => (e.target.style.borderColor = "var(--green)")}
                onBlur={(e) => (e.target.style.borderColor = "var(--line)")}
                style={fieldStyle} />
            </label>
            <label style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              <span style={labelStyle}>What are you looking to build <span style={{ color: "var(--green)" }}>*</span></span>
              <textarea required value={whatBuilding} disabled={busy} rows={4}
                onChange={(e) => setWhatBuilding(e.target.value)} placeholder="Describe your idea…"
                onFocus={(e) => (e.target.style.borderColor = "var(--green)")}
                onBlur={(e) => (e.target.style.borderColor = "var(--line)")}
                style={{ ...fieldStyle, resize: "vertical" }} />
            </label>
            <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 14, marginTop: 4 }}>
              <button type="submit" className="btn btn-orange"
                disabled={busy || !githubId.trim() || !whatBuilding.trim()}
                style={{ opacity: busy || !githubId.trim() || !whatBuilding.trim() ? 0.5 : 1, cursor: "pointer" }}>
                {status === "sending" ? "Sending…" : "Submit"} <span className="arrow">→</span>
              </button>
              {status === "error" && err && (
                <span style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--green)" }}>{err}</span>
              )}
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

/* ---- Hero ---- */
function BuildHero() {
  return (
    <header id="build-top" style={{ ...BP_SECTION, alignItems: "center", textAlign: "center", borderTop: "none" }}>
      {/* (removed bg.mp4 — distracting face imagery; CodeRain + gradient carry it) */}
      <CodeRain opacity={0.06} />
      <div style={{ position: "absolute", inset: 0, zIndex: 1,
        background: "radial-gradient(ellipse 75% 60% at 50% 50%, rgba(197, 52, 0,0.18), transparent 60%), radial-gradient(ellipse at 50% 50%, rgba(13,13,13,0.5) 25%, var(--bg) 82%)" }} />
      <div style={{ ...BP_INNER, position: "relative", zIndex: 2, display: "flex", flexDirection: "column", alignItems: "center" }}>
        <Reveal><div style={BP_EYE}>{BP_DASH} Build privacy</div></Reveal>
        <Reveal delay={0.06} style={{ width: "100%" }}>
          <h1 style={{ ...BP_H, fontSize: "clamp(22px,6.4vw,78px)", maxWidth: "min(92vw,1120px)", marginInline: "auto", textAlign: "center", marginTop: 18,
            background: "linear-gradient(178deg,#fffdf1 0%,#f4ece8 55%,#ffcdb6 100%)", WebkitBackgroundClip: "text",
            backgroundClip: "text", WebkitTextFillColor: "transparent", color: "transparent" }}>
            Add privacy to your stack.
          </h1>
        </Reveal>
        <Reveal delay={0.14}>
          <p style={{ fontFamily: "var(--body)", fontSize: "clamp(14px,1.15vw,17px)", color: "var(--dim)", lineHeight: 1.65,
            maxWidth: 640, margin: "26px auto 0" }}>
            STRK20 brings shielded balances, private transfers, and private app flows to ERC-20 assets on Starknet. Build on existing liquidity and existing wallets, with a built-in compliance path.
          </p>
        </Reveal>
        <Reveal delay={0.2}>
          <div style={{ display: "flex", gap: 14, marginTop: 36, flexWrap: "wrap", justifyContent: "center" }}>
            <a href="https://cal.com/adithyadinesh" target="_blank" rel="noreferrer" className="btn btn-orange">
              Get in touch <span className="arrow">→</span>
            </a>
            <a href="/rfp" className="btn btn-ghost">Browse RFPs</a>
          </div>
        </Reveal>
      </div>
    </header>
  );
}

/* ---- Why build (6 cards) ---- */
const BP_WHY = [
  { n: "01", t: "Protocol-level privacy", d: "Built into the protocol, not bolted on at the app layer. Every shielded asset shares one unified privacy pool, so the anonymity set grows with total system usage." },
  { n: "02", t: "Anonymous DeFi on existing liquidity", d: "Anonymous swaps run on existing AMMs (Ekubo, AVNU). No unshield-swap-reshield, no fragmented liquidity. The AMM never sees the swap came from the privacy pool." },
  { n: "03", t: "Multi-call composability", d: "Unshield, swap across AMMs, flash-loan, repay, and reshield inside one private transaction. The first multi-call support inside a privacy system." },
  { n: "04", t: "No new wallets", d: "Existing Starknet wallets via native account abstraction: multisig, hardware, social recovery. One viewing key derived from the user's signing key." },
  { n: "05", t: "Compliance-first", d: "Per-user viewing keys, wallet-level screening (Elliptic / TRM / Chainalysis). Confidential by default, scoped lawful disclosure when required." },
  { n: "06", t: "Built on Cairo", d: "Both the smart contract and the proving language, what makes atomic, composable privacy possible. Fork it to Rust and the result would not be provable." },
];
function WhyBuild() {
  return (
    <section id="why-build" style={{ ...BP_SECTION,
      background: "radial-gradient(ellipse 55% 65% at 92% -6%, rgba(197, 52, 0,0.10), transparent 55%), var(--bg)" }}>
      <div style={BP_INNER}>
        <Reveal><div style={BP_EYE}>{BP_DASH} Why build on strk20</div></Reveal>
        <Reveal delay={0.05}><h2 style={{ ...BP_H, fontSize: "clamp(26px,3.4vw,52px)", maxWidth: 900 }}>Privacy as infrastructure, not an integration.</h2></Reveal>
        <Reveal delay={0.1}>
          <div className="why-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16, marginTop: "clamp(28px,4vh,52px)" }}>
            {BP_WHY.map((c) => (
              <div key={c.n} className="why-card" style={{ display: "flex", flexDirection: "column",
                minHeight: "clamp(240px,30vh,320px)", padding: "clamp(26px,2.4vw,40px)", borderRadius: 0,
                background: "linear-gradient(165deg, #181818 0%, #141414 48%, #100c0a 100%)",
                border: "1px solid var(--line)", transition: "transform .2s, background .2s, border-color .2s" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <span style={{ fontFamily: "var(--mono)", fontSize: 12, letterSpacing: "0.1em", color: "var(--faint)" }}>{c.n}</span>
                  <span style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--green)" }}>[ ]</span>
                </div>
                <h3 style={{ fontFamily: "var(--body)", fontWeight: 600, fontSize: "clamp(19px,1.6vw,26px)", color: "#fff",
                  margin: "clamp(22px,2.4vw,34px) 0 0", letterSpacing: "-0.01em", lineHeight: 1.12 }}>{c.t}</h3>
                <p style={{ fontFamily: "var(--body)", fontSize: "clamp(14px,0.95vw,15px)", lineHeight: 1.62,
                  color: "var(--dim)", margin: "14px 0 0" }}>{c.d}</p>
              </div>
            ))}
          </div>
        </Reveal>
      </div>
      <style>{`
        .why-card:hover{transform:translateY(-3px);background:#181210;border-color:rgba(197, 52, 0,0.5);}
        @media(max-width:900px){.why-grid{grid-template-columns:1fr!important;}}
      `}</style>
    </section>
  );
}

/* ---- Builder resources (external docs / examples) ---- */
const BP_RESOURCES = [
  { t: "STRK20 by Example", d: "Learn the protocol through simple, runnable examples: privacy pools, notes and nullifiers, viewing keys, the wallet API, helper contracts, and SDK flows.",
    cta: "strk20-by-example.org", href: "https://strk20-by-example.org/" },
];
function BuilderResources() {
  // Compact strip (not full-viewport like BP_SECTION) — one row of resource
  // cards; the 3-col grid leaves room for future entries.
  return (
    <section id="resources" style={{ position: "relative", overflow: "hidden", borderTop: "1px solid var(--line)",
      padding: "clamp(56px,9vh,110px) 0", background: "var(--bg)" }}>
      <div style={BP_INNER}>
        <Reveal><div style={BP_EYE}>{BP_DASH} Builder resources</div></Reveal>
        <Reveal delay={0.05}>
          <div className="res-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16, marginTop: "clamp(24px,3vh,40px)" }}>
            {BP_RESOURCES.map((r) => (
              <a key={r.t} href={r.href} target="_blank" rel="noreferrer" className="res-card"
                style={{ display: "flex", flexDirection: "column", padding: "clamp(26px,2.4vw,40px)", borderRadius: 0,
                  background: "linear-gradient(165deg, #181818 0%, #141414 48%, #100c0a 100%)",
                  border: "1px solid var(--line)", borderTop: "2px solid var(--green)",
                  transition: "transform .2s, border-color .2s", textDecoration: "none" }}>
                <h3 style={{ fontFamily: "var(--body)", fontWeight: 600, fontSize: "clamp(19px,1.6vw,26px)", color: "#fff",
                  margin: 0, letterSpacing: "-0.01em", lineHeight: 1.12 }}>{r.t}</h3>
                <p style={{ fontFamily: "var(--body)", fontSize: "clamp(14px,0.95vw,15px)", lineHeight: 1.62,
                  color: "var(--dim)", margin: "14px 0 0" }}>{r.d}</p>
                <div style={{ marginTop: "auto", paddingTop: "clamp(20px,2vw,28px)", display: "flex", alignItems: "center", gap: 9,
                  fontFamily: "var(--mono)", fontSize: 12.5, letterSpacing: "0.04em", textTransform: "uppercase",
                  fontWeight: 600, color: "var(--text)" }}>
                  {r.cta} <span className="res-arrow" style={{ color: "var(--green)", transition: "transform .2s", display: "inline-block" }}>→</span>
                </div>
              </a>
            ))}
          </div>
        </Reveal>
      </div>
      <style>{`
        .res-card:hover{transform:translateY(-3px);border-color:rgba(197,52,0,0.5);}
        .res-card:hover .res-arrow{transform:translateX(5px);}
        @media(max-width:900px){.res-grid{grid-template-columns:1fr!important;}}
      `}</style>
    </section>
  );
}

/* ---- Get involved (3 cards) ---- */
const BP_WAYS = [
  { n: "01", t: "Proof of Privacy Incubator", d: "Proof is a focused accelerator for high-potential teams building with STRK20: eight weeks of mentorship, milestone-based support, investor preparation, and a demo day designed to turn early privacy ideas into credible company-building evidence.",
    cta: "Apply to the cohort", href: "https://proof.starknet.io", ext: true },
  { n: "02", t: "Request for Startups", d: "Defined problem statements for specific builds: private payroll, lending, identity, and more. Clear signals of what's worth building.",
    cta: "Browse open requests", href: "/rfp", ext: false },
  { n: "03", t: "SDK access", d: "Self-serve track for teams ready to ship. Get the SDK, docs, and protocol access to start building privately today.",
    cta: "Request SDK access", href: "https://cal.com/adithyadinesh", ext: true },
];
function GetInvolved() {
  return (
    <section id="get-involved" style={{ ...BP_SECTION,
      background: "radial-gradient(ellipse 60% 70% at 90% -8%, rgba(197, 52, 0,0.10), transparent 55%), var(--bg)" }}>
      <div style={BP_INNER}>
        <Reveal><div style={BP_EYE}>{BP_DASH} Get involved</div></Reveal>
        <Reveal delay={0.05}><h2 style={{ ...BP_H, fontSize: "clamp(26px,3.4vw,52px)", maxWidth: 760 }}>Three ways in, one place to apply.</h2></Reveal>
        <Reveal delay={0.1}>
          <div className="ways-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: "clamp(16px,1.4vw,22px)", marginTop: "clamp(28px,4vh,52px)" }}>
            {BP_WAYS.map((c) => (
              <a key={c.n} href={c.href} {...(c.ext ? { target: "_blank", rel: "noreferrer" } : {})}
                className="gi-card" style={{ display: "flex", flexDirection: "column", minHeight: "clamp(300px,40vh,400px)",
                  padding: "clamp(28px,2.3vw,40px)", borderRadius: 0,
                  background: "linear-gradient(165deg, #181818 0%, #141414 48%, #100c0a 100%)",
                  border: "1px solid var(--line)", borderTop: "2px solid var(--green)",
                  transition: "transform .24s ease, box-shadow .24s ease, border-color .24s ease", textDecoration: "none" }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                  <span style={{ fontFamily: "var(--mono)", fontSize: 13, letterSpacing: "0.08em", color: "var(--green)" }}>{c.n}</span>
                  <span className="gi-dot" style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--green)" }} />
                </div>
                <h3 style={{ fontFamily: "var(--body)", fontWeight: 600, fontSize: "clamp(22px,2vw,30px)", color: "#fff",
                  margin: "clamp(26px,3vw,40px) 0 0", letterSpacing: "-0.015em", lineHeight: 1.1 }}>{c.t}</h3>
                <p style={{ fontFamily: "var(--body)", fontSize: 15, lineHeight: 1.62, color: "var(--dim)", margin: "14px 0 0" }}>{c.d}</p>
                <div style={{ marginTop: "auto", paddingTop: "clamp(20px,2vw,28px)", display: "flex", alignItems: "center", gap: 9,
                  borderTop: "1px solid var(--line)", fontFamily: "var(--mono)", fontSize: 12.5, letterSpacing: "0.04em",
                  textTransform: "uppercase", fontWeight: 600, color: "var(--text)" }}>
                  {c.cta} <span className="gi-arrow" style={{ color: "var(--green)", transition: "transform .24s ease", display: "inline-block" }}>→</span>
                </div>
              </a>
            ))}
          </div>
        </Reveal>
      </div>
      <style>{`
        .gi-card:hover{transform:translateY(-6px);border-color:rgba(197,52,0,0.5);box-shadow:0 40px 70px -30px rgba(0,0,0,0.7);}
        .gi-card:hover .gi-arrow{transform:translateX(5px);}
        @media(max-width:900px){.ways-grid{grid-template-columns:1fr!important;}.gi-card{min-height:0!important;}}
      `}</style>
    </section>
  );
}

/* ---- Playlists (Build + Users tabs) ---- */
const BP_PLAYLISTS = {
  ELI5: [
    { n: "01", t: "What is shielding?", video: "uploads/pl-shielding.mp4" },
    { n: "02", t: "Public vs private mode", video: "uploads/pl-modes.mp4" },
    { n: "03", t: "Anonymous swaps explained", video: "uploads/pl-swaps.mp4" },
    { n: "04", t: "Multi-call private transactions", video: "uploads/pl-multicall.mp4" },
  ],
  Users: [
    { n: "01", t: "How to get a Ready or Xverse wallet", video: "uploads/pl-wallet.mp4" },
    { n: "02", t: "How to bridge assets to Starknet", video: "uploads/pl-bridge.mp4" },
    { n: "03", t: "How to shield and unshield assets", video: "uploads/pl-shield-unshield.mp4" },
    { n: "04", t: "How to transfer privately", video: "uploads/pl-transfer.mp4" },
    { n: "05", t: "How to swap privately", video: "uploads/pl-private-swap.mp4" },
    { n: "06", t: "How to earn yield privately", soon: true, disabled: true },
  ],
};
const BP_TABS = ["ELI5", "Users"];

function Playlists() {
  // Default to the "Users" genre — that's where the wallet/how-to videos live,
  // so clicking "Tutorials" lands people on the user-facing playlist first.
  const [tab, setTab] = useState("Users");
  const [idx, setIdx] = useState(0);
  const [playing, setPlaying] = useState(false);
  const list = BP_PLAYLISTS[tab];
  const ep = list[idx] || list[0];
  const canPlay = !!ep.video && !ep.soon;
  const selectTab = (t) => { if (t !== tab) { setTab(t); setIdx(0); setPlaying(false); } };
  const selectEp = (i, e) => { if (!e.disabled) { setIdx(i); setPlaying(false); } };

  return (
    <section id="playlists" style={{ ...BP_SECTION }}>
      <div style={BP_INNER}>
        <Reveal><div style={BP_EYE}>{BP_DASH} Playlists</div></Reveal>
        <Reveal delay={0.05}><h2 style={{ ...BP_H, fontSize: "clamp(26px,3.4vw,52px)", maxWidth: 620 }}>Privacy, explained simply.</h2></Reveal>

        <Reveal delay={0.08}>
          <div style={{ display: "flex", gap: 8, marginTop: "clamp(20px,3vh,30px)" }}>
            {BP_TABS.map((t) => (
              <button key={t} onClick={() => selectTab(t)} style={{ fontFamily: "var(--mono)", fontSize: 12,
                letterSpacing: "0.12em", textTransform: "uppercase", padding: "9px 20px", cursor: "pointer", borderRadius: 0,
                background: tab === t ? "var(--green)" : "transparent", color: tab === t ? "#fff" : "var(--dim)",
                border: tab === t ? "1px solid var(--green)" : "1px solid var(--line)",
                transition: "background .2s, color .2s, border-color .2s" }}>{t}</button>
            ))}
          </div>
        </Reveal>

        <Reveal delay={0.12}>
          <div className="pl-grid" style={{ display: "grid", gridTemplateColumns: "1.35fr 1fr", gap: 24, marginTop: "clamp(18px,2.6vh,28px)", alignItems: "stretch" }}>
            {/* player / coming-soon panel */}
            <div style={{ position: "relative", border: "1px solid var(--line)", borderRadius: 10, overflow: "hidden", aspectRatio: "16 / 10", background: "#0a0a0a" }}>
              {canPlay && playing ? (
                <video key={ep.video} src={ep.video} controls autoPlay playsInline
                  style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "contain", background: "#000" }} />
              ) : canPlay ? (
                <button onClick={() => setPlaying(true)} style={{ position: "absolute", inset: 0, border: "none", background: "none", cursor: "pointer", width: "100%", height: "100%", padding: 0 }}>
                  <video key={ep.video + "-prev"} src={ep.video} muted loop autoPlay playsInline preload="metadata"
                    style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", opacity: 0.55 }} />
                  <CodeRain opacity={0.04} />
                  <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(8,8,8,0.85) 0%, rgba(8,8,8,0.15) 55%, transparent 100%), radial-gradient(ellipse at 50% 45%, rgba(197, 52, 0,0.12), transparent 60%)" }} />
                  <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center" }}>
                    <span className="pl-play" style={{ width: 76, height: 58, borderRadius: 8, border: "1px solid rgba(255,255,255,0.6)",
                      display: "grid", placeItems: "center", color: "#fff", fontSize: 16, background: "rgba(197, 52, 0,0.22)",
                      backdropFilter: "blur(4px)", transition: "transform .2s, background .2s" }}>▶</span>
                  </div>
                  <div style={{ position: "absolute", left: "clamp(20px,3vw,36px)", bottom: "clamp(20px,3vw,36px)", textAlign: "left" }}>
                    <div style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.16em", color: "var(--green)" }}>[ EPISODE {ep.n} ]</div>
                    <div style={{ fontFamily: "var(--display)", fontWeight: 800, textTransform: "uppercase", fontSize: "clamp(20px,2vw,30px)", color: "#fff", marginTop: 8 }}>{ep.t}</div>
                  </div>
                </button>
              ) : (
                <div style={{ position: "absolute", inset: 0 }}>
                  <CodeRain opacity={0.05} />
                  <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse at 50% 45%, rgba(197, 52, 0,0.1), transparent 62%)" }} />
                  <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center", textAlign: "center", padding: 24 }}>
                    <span style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.22em", color: "var(--green)", border: "1px solid rgba(197, 52, 0,0.5)", borderRadius: 999, padding: "5px 14px" }}>COMING SOON</span>
                    <div style={{ fontFamily: "var(--display)", fontWeight: 800, textTransform: "uppercase", fontSize: "clamp(19px,2.2vw,30px)", color: "#fff", marginTop: 18, maxWidth: 440, lineHeight: 1.12 }}>{ep.t}</div>
                    {ep.disabled ? <div style={{ fontFamily: "var(--body)", fontSize: 13.5, color: "var(--faint)", marginTop: 12, maxWidth: 360 }}>Not yet possible on Starknet.</div> : null}
                  </div>
                </div>
              )}
            </div>
            {/* episode list */}
            <div style={{ border: "1px solid var(--line)", borderRadius: 10, overflow: "hidden", display: "flex", flexDirection: "column" }}>
              {list.map((e, i) => {
                const active = i === idx;
                return (
                  <button key={e.n} onClick={() => selectEp(i, e)} disabled={e.disabled} style={{ flex: 1, display: "flex", alignItems: "center", gap: 14,
                    textAlign: "left", padding: "clamp(12px,1.4vh,18px) clamp(16px,2vw,26px)", cursor: e.disabled ? "not-allowed" : "pointer",
                    opacity: e.disabled ? 0.42 : 1,
                    background: active ? "rgba(197, 52, 0,0.1)" : "transparent",
                    borderTop: i ? "1px solid var(--line)" : "none", borderLeft: active ? "2px solid var(--green)" : "2px solid transparent", borderRight: "none", borderBottom: "none" }}>
                    <span style={{ fontFamily: "var(--mono)", fontSize: 13, color: active ? "var(--green)" : "var(--faint)" }}>{e.n}</span>
                    <span style={{ fontFamily: "var(--mono)", fontSize: "clamp(12px,0.95vw,14px)", color: active ? "var(--text)" : "var(--dim)", flex: 1, lineHeight: 1.3 }}>{e.t}</span>
                    {e.soon
                      ? <span style={{ fontFamily: "var(--mono)", fontSize: 8.5, letterSpacing: "0.14em", color: "var(--green)", border: "1px solid rgba(197, 52, 0,0.4)", borderRadius: 999, padding: "3px 7px", whiteSpace: "nowrap" }}>SOON</span>
                      : (active ? <span style={{ color: "var(--green)", fontSize: 11 }}>▶</span> : null)}
                  </button>
                );
              })}
            </div>
          </div>
        </Reveal>
      </div>
      <style>{`
        .pl-grid button:hover .pl-play{transform:scale(1.08);background:rgba(197, 52, 0,0.4);}
        @media(max-width:860px){.pl-grid{grid-template-columns:1fr!important;}}
      `}</style>
    </section>
  );
}

/* ---- Tell us what you're building (contact form → /rfp/api/contact) ---- */
function BuildContact() {
  const [message, setMessage] = useState("");
  const [name, setName] = useState("");
  const [contact, setContact] = useState("");
  const [status, setStatus] = useState("idle"); // idle | sending | sent | error
  const [err, setErr] = useState(null);
  const busy = status === "sending" || status === "sent";

  const fieldStyle = {
    width: "100%", background: "#111", border: "1px solid var(--line)", borderRadius: 0,
    padding: "12px 14px", fontFamily: "var(--body)", fontSize: 15, color: "var(--text)",
    outline: "none", transition: "border-color .18s",
  };
  const labelStyle = { fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.22em",
    textTransform: "uppercase", color: "var(--faint)" };

  async function onSubmit(e) {
    e.preventDefault();
    if (!message.trim() || !contact.trim() || busy) return;
    setStatus("sending"); setErr(null);
    try {
      const res = await fetch("/rfp/api/contact", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message, name, contact, idea: "Build inquiry" }),
      });
      if (!res.ok) { const d = await res.json().catch(() => ({})); throw new Error(d.error || "Something went wrong."); }
      setStatus("sent");
    } catch (e2) { setStatus("error"); setErr(e2.message || "Something went wrong."); }
  }

  return (
    <section id="build-contact" style={{ ...BP_SECTION }}>
      <div aria-hidden="true" style={{ position: "absolute", inset: 0, zIndex: 0,
        background: "radial-gradient(ellipse 55% 60% at 12% 110%, rgba(197, 52, 0,0.1), transparent 55%)" }} />
      <CodeRain opacity={0.04} />
      <div style={{ ...BP_INNER, position: "relative", zIndex: 1, maxWidth: 760 }}>
        <Reveal><div style={BP_EYE}>{BP_DASH} Tell us what you're building</div></Reveal>
        <Reveal delay={0.05}><h2 style={{ ...BP_H, fontSize: "clamp(26px,3.4vw,52px)", maxWidth: 620 }}>Have an idea? Send it our way.</h2></Reveal>
        <Reveal delay={0.1}>
          <p style={{ fontFamily: "var(--body)", fontSize: "clamp(14px,1.1vw,16px)", color: "var(--dim)",
            lineHeight: 1.65, maxWidth: 560, margin: "20px 0 0" }}>
            An early concept, a question, or a half-formed pitch. No commitment. It comes straight to our inbox and a human gets back to you.
          </p>
        </Reveal>
        <Reveal delay={0.14}>
          <div style={{ marginTop: "clamp(28px,4vh,44px)", border: "1px solid var(--line)",
            background: "linear-gradient(165deg, #161616 0%, #121212 50%, #0e0b0a 100%)", padding: "clamp(24px,3vw,40px)" }}>
            {status === "sent" ? (
              <div style={{ display: "flex", gap: 14, alignItems: "flex-start", border: "1px solid rgba(197, 52, 0,0.4)",
                background: "rgba(197, 52, 0,0.05)", padding: "18px 20px" }}>
                <span style={{ width: 7, height: 7, background: "var(--green)", marginTop: 6, flexShrink: 0 }} />
                <div>
                  <div style={{ fontFamily: "var(--mono)", fontSize: 13, letterSpacing: "0.08em", textTransform: "uppercase", color: "#fff" }}>Message sent</div>
                  <div style={{ fontFamily: "var(--body)", fontSize: 14, color: "var(--dim)", marginTop: 6 }}>Thanks for reaching out. We'll get back to you soon.</div>
                </div>
              </div>
            ) : (
              <form onSubmit={onSubmit} style={{ display: "flex", flexDirection: "column", gap: 20 }}>
                <label style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  <span style={labelStyle}>What are you building <span style={{ color: "var(--green)" }}>*</span></span>
                  <textarea required value={message} disabled={busy} rows={4}
                    onChange={(e) => setMessage(e.target.value)} placeholder="What's on your mind?"
                    onFocus={(e) => (e.target.style.borderColor = "var(--green)")}
                    onBlur={(e) => (e.target.style.borderColor = "var(--line)")}
                    style={{ ...fieldStyle, resize: "vertical" }} />
                </label>
                <div className="bc-row" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20 }}>
                  <label style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                    <span style={labelStyle}>Name <span style={{ color: "var(--faint)", letterSpacing: 0 }}>(optional)</span></span>
                    <input type="text" value={name} disabled={busy} onChange={(e) => setName(e.target.value)} placeholder="Your name"
                      onFocus={(e) => (e.target.style.borderColor = "var(--green)")}
                      onBlur={(e) => (e.target.style.borderColor = "var(--line)")} style={fieldStyle} />
                  </label>
                  <label style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                    <span style={labelStyle}>Email / TG / X <span style={{ color: "var(--green)" }}>*</span></span>
                    <input type="text" required value={contact} disabled={busy} onChange={(e) => setContact(e.target.value)} placeholder="So we can reply"
                      onFocus={(e) => (e.target.style.borderColor = "var(--green)")}
                      onBlur={(e) => (e.target.style.borderColor = "var(--line)")} style={fieldStyle} />
                  </label>
                </div>
                <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: 16, marginTop: 4 }}>
                  <button type="submit" className="btn btn-orange"
                    disabled={busy || !message.trim() || !contact.trim()}
                    style={{ opacity: busy || !message.trim() || !contact.trim() ? 0.5 : 1, cursor: "pointer" }}>
                    {status === "sending" ? "Sending…" : "Send message"} <span className="arrow">→</span>
                  </button>
                  <a href="https://cal.com/adithyadinesh" target="_blank" rel="noreferrer" className="btn btn-ghost">
                    Book a call with us instead
                  </a>
                  {status === "error" && err && (
                    <span style={{ fontFamily: "var(--mono)", fontSize: 12, color: "var(--green)" }}>{err}</span>
                  )}
                </div>
              </form>
            )}
          </div>
        </Reveal>
      </div>
      <style>{`@media(max-width:680px){.bc-row{grid-template-columns:1fr!important;}}`}</style>
    </section>
  );
}

/* ---- Get involved: WebGL scroll sequence (3 stages); falls back to the static cards ---- */
function webglOK() {
  try {
    const c = document.createElement("canvas");
    return !!(window.WebGLRenderingContext && (c.getContext("webgl") || c.getContext("experimental-webgl")));
  } catch (e) { return false; }
}
const giActiveStep = (p) => (p < 0.40 ? 0 : p < 0.72 ? 1 : 2);

function GetInvolvedScroll() {
  const sectionRef = useRef(null);
  const canvasRef = useRef(null);
  const instRef = useRef(null);
  const p = useScrollProgress(sectionRef);
  const step = giActiveStep(p);

  useEffect(() => {
    if (!canvasRef.current || !window.IncubatorScene) return;
    const inst = new window.IncubatorScene(canvasRef.current);
    instRef.current = inst;
    const update = () => { isNear(canvasRef.current, 120) ? inst.start() : inst.stop(); };
    update();
    const off = onViewportChange(update);
    return () => { off(); inst.destroy(); instRef.current = null; };
  }, []);
  useEffect(() => { if (instRef.current) instRef.current.setProgress(p); }, [p]);

  return (
    <section id="get-involved" ref={sectionRef} style={{ height: "360vh", position: "relative", borderTop: "1px solid var(--line)" }}>
      <div style={{ position: "sticky", top: 0, height: "100vh", overflow: "hidden",
        background: "radial-gradient(ellipse 60% 70% at 90% -8%, rgba(197, 52, 0,0.10), transparent 55%), var(--bg)" }}>
        <canvas ref={canvasRef} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", zIndex: 0 }} />
        <div aria-hidden="true" style={{ position: "absolute", inset: 0, zIndex: 1,
          background: "linear-gradient(90deg, rgba(13,13,13,0.92) 0%, rgba(13,13,13,0.45) 24%, transparent 40%, transparent 60%, rgba(13,13,13,0.45) 76%, rgba(13,13,13,0.92) 100%)" }} />

        <div style={{ position: "absolute", top: 0, bottom: 0, left: 0, width: 2, background: "var(--line)", zIndex: 3 }}>
          <div style={{ position: "absolute", top: 0, left: 0, width: "100%", height: `${p * 100}%`,
            background: "linear-gradient(var(--green),var(--orange))", boxShadow: "0 0 12px var(--green-glow)" }} />
        </div>

        {/* LEFT — section heading */}
        <div className="gi-left" style={{ position: "absolute", left: 0, top: "50%", transform: "translateY(-50%)", zIndex: 4, ...BP_INNER, pointerEvents: "none" }}>
          <div className="gi-left-in" style={{ maxWidth: 400 }}>
            <div style={BP_EYE}>{BP_DASH} Get involved</div>
            <h2 style={{ ...BP_H, fontSize: "clamp(26px,3vw,46px)", marginTop: 16 }}>Three ways in, one place to apply.</h2>
          </div>
        </div>

        {/* RIGHT — per-stage copy + CTA */}
        <div className="gi-right" style={{ position: "absolute", right: 0, top: "50%", transform: "translateY(-50%)", zIndex: 4, ...BP_INNER }}>
          <div className="gi-copy" style={{ position: "relative", maxWidth: 400, minHeight: 250, marginLeft: "auto" }}>
            {BP_WAYS.map((c, i) => {
              const on = i === step;
              return (
                <div key={c.n} className="gi-stage" style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "flex-end", textAlign: "right",
                  opacity: on ? 1 : 0, transform: on ? "translateY(0)" : "translateY(16px)",
                  transition: "opacity .5s ease, transform .5s ease", pointerEvents: on ? "auto" : "none" }}>
                  <span style={{ fontFamily: "var(--mono)", fontSize: 13, letterSpacing: "0.08em", color: "var(--green)" }}>{c.n}</span>
                  <h3 style={{ fontFamily: "var(--body)", fontWeight: 600, fontSize: "clamp(24px,2.2vw,34px)", color: "#fff",
                    margin: "12px 0 0", letterSpacing: "-0.015em", lineHeight: 1.08 }}>{c.t}</h3>
                  <p style={{ fontFamily: "var(--body)", fontSize: "clamp(14px,1.05vw,16px)", lineHeight: 1.62, color: "var(--dim)", margin: "14px 0 0" }}>{c.d}</p>
                  <a href={c.href} {...(c.ext ? { target: "_blank", rel: "noreferrer" } : {})} className="btn btn-orange" style={{ marginTop: 24 }}>
                    {c.cta} <span className="arrow">→</span>
                  </a>
                </div>
              );
            })}
          </div>
        </div>

        <div style={{ position: "absolute", bottom: 40, left: "50%", transform: "translateX(-50%)", display: "flex", gap: 10, zIndex: 4 }}>
          {BP_WAYS.map((_, i) => (
            <div key={i} style={{ width: i === step ? 26 : 8, height: 4, borderRadius: 2,
              background: i === step ? "var(--green)" : "var(--ghost)", transition: "all .4s" }} />
          ))}
        </div>
      </div>
      <style>{`
        @media(max-width:900px){
          .gi-left{top:clamp(48px,8vh,84px)!important;transform:none!important;}
          .gi-left-in{max-width:none!important;text-align:center;}
          .gi-left-in>div:first-child{justify-content:center;}
          .gi-right{top:auto!important;bottom:clamp(72px,11vh,130px)!important;transform:none!important;}
          .gi-copy{margin:0 auto!important;max-width:560px!important;min-height:190px!important;}
          .gi-stage{align-items:center!important;text-align:center!important;}
        }
      `}</style>
    </section>
  );
}

function GetInvolvedSection() {
  const [mode] = useState(() => {
    const reduced = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduced || !window.THREE || !window.IncubatorScene || !webglOK()) return "static";
    return "scroll";
  });
  return mode === "scroll" ? <GetInvolvedScroll /> : <GetInvolved />;
}

function BuildPage() {
  return (
    <React.Fragment>
      <Nav />
      <BuildHero />
      <LogoTicker label="Build alongside the Starknet ecosystem" />
      <GetInvolvedSection />
      <WhyBuild />
      <BuilderResources />
      <Playlists />
      <BuildContact />
      <Footer />
    </React.Fragment>
  );
}

window.BuildPage = BuildPage;
window.Playlists = Playlists;
