/* kit.jsx — "Take it off the screen" offer page.
   Two-track monetization that respects the free-course ethic:
     • START NOW (zero inventory): a name-your-price PDF guide, a pre-order
       printed book, and a parts list with affiliate links to real retailers.
       Earns commission + builds an email list from day one.
     • COMING SOON (waitlist): the assembled Beacon kit + a classroom pack.
   The course itself never goes behind a paywall.
   Shared globals come from shared.jsx; keep all names kit*-prefixed.

   ── TO GO LIVE: swap these placeholders for your real links ──────────────
   STORE.pdf / STORE.print → your Gumroad / Lulu / Stripe product URLs.
   RETAILERS[].url        → your affiliate-tagged deep links.
   Leave a URL as "" to route that action through the email modal instead. */

const { useState, useEffect } = React;

const STORE = {
  pdf: "",     // e.g. "https://yourname.gumroad.com/l/field-guide" — empty = email-capture flow
  print: "",   // e.g. "https://www.lulu.com/..." — empty = pre-order email flow
};

const RETAILERS = [
  { name: "Adafruit", note: "Curated and beginner-friendly. Their Parts Pal covers most of this list.", url: "https://www.adafruit.com" },
  { name: "SparkFun", note: "Famous for plain-English tutorials alongside the parts.", url: "https://www.sparkfun.com" },
  { name: "DigiKey", note: "Every exact component, shipped worldwide. Best for precise values.", url: "https://www.digikey.com" },
  { name: "Amazon", note: "Fastest option — a single breadboard starter kit covers nearly everything.", url: "https://www.amazon.com/s?k=electronics+breadboard+starter+kit" },
];

/* exploded line-art of the finished Beacon — drawn from styles.css tokens only */
function KitBeaconArt() {
  return (
    <div className="kit-art">
      <div className="label">The Beacon · what you build</div>
      <svg viewBox="0 0 420 300" role="img" aria-label="Exploded view of the Beacon: three LEDs, a 555 timer, a transistor, resistors and a 9-volt battery on a breadboard.">
        {/* breadboard slab */}
        <rect x="40" y="120" width="340" height="120" rx="8" fill="var(--bg-deeper)" stroke="var(--rule-strong)" strokeWidth="1.5" />
        {Array.from({ length: 17 }).map((_, i) => (
          <g key={i}>
            <circle cx={58 + i * 19} cy={150} r="2" fill="var(--ink-faint)" opacity="0.5" />
            <circle cx={58 + i * 19} cy={172} r="2" fill="var(--ink-faint)" opacity="0.5" />
            <circle cx={58 + i * 19} cy={194} r="2" fill="var(--ink-faint)" opacity="0.5" />
            <circle cx={58 + i * 19} cy={216} r="2" fill="var(--ink-faint)" opacity="0.5" />
          </g>
        ))}
        <line x1="50" y1="135" x2="370" y2="135" stroke="var(--current)" strokeWidth="1" opacity="0.5" />
        <line x1="50" y1="231" x2="370" y2="231" stroke="var(--water)" strokeWidth="1" opacity="0.5" />

        {/* three LEDs up top, glowing */}
        {[150, 210, 270].map((x, i) => (
          <g key={x}>
            <circle cx={x} cy="58" r="17" fill="var(--current-faint)" className="pulse-glow" style={{ animationDelay: `${i * 0.25}s` }} />
            <circle cx={x} cy="58" r="10" fill="var(--current)" />
            <circle cx={x} cy="54" r="3" fill="var(--current-soft)" opacity="0.9" />
            <line x1={x} y1="68" x2={x} y2="120" stroke="var(--ink-faint)" strokeWidth="1.5" />
          </g>
        ))}
        <line x1="150" y1="58" x2="270" y2="58" stroke="var(--current)" strokeWidth="1" opacity="0.35" strokeDasharray="3 5" />

        {/* 555 timer chip */}
        <rect x="92" y="158" width="64" height="48" rx="4" fill="var(--ink)" />
        <text x="124" y="186" textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="11" fill="var(--bg-card)">555</text>
        <circle cx="100" cy="166" r="2.4" fill="var(--bg-card)" opacity="0.6" />

        {/* transistor */}
        <path d="M250 160 a16 16 0 0 1 16 16 a16 16 0 0 1 -16 16 z" fill="var(--water)" opacity="0.85" />
        <text x="244" y="182" textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="9" fill="var(--ink)">Q</text>

        {/* resistor */}
        <rect x="180" y="170" width="46" height="13" rx="6" fill="var(--bg-card)" stroke="var(--current)" strokeWidth="1.4" />
        <rect x="190" y="170" width="4" height="13" fill="var(--current)" /><rect x="200" y="170" width="4" height="13" fill="var(--ink)" /><rect x="210" y="170" width="4" height="13" fill="var(--current-deep)" />

        {/* capacitor */}
        <circle cx="300" cy="178" r="13" fill="var(--bg-card)" stroke="var(--water)" strokeWidth="1.5" />
        <text x="300" y="182" textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="9" fill="var(--water)">C</text>

        {/* 9V battery */}
        <rect x="322" y="156" width="46" height="74" rx="6" fill="var(--bg-card)" stroke="var(--rule-strong)" strokeWidth="1.5" />
        <rect x="332" y="148" width="10" height="9" rx="2" fill="var(--current)" />
        <rect x="348" y="148" width="10" height="9" rx="2" fill="var(--ink)" />
        <text x="345" y="198" textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="13" fill="var(--ink)">9V</text>

        <text x="40" y="270" fontFamily="IBM Plex Mono, monospace" fontSize="10" letterSpacing="0.12em" fill="var(--ink-faint)">FLASHING SIGNAL BEACON · ~14 mA · RUNS ALL NIGHT</text>
      </svg>
    </div>
  );
}

const KIT_BOM = [
  { q: "×1", n: "Solderless breadboard", d: "400 tie-points" },
  { q: "×3", n: "Red LEDs", d: "5 mm, 2 V drop" },
  { q: "×1", n: "555 timer IC", d: "the blink engine" },
  { q: "×1", n: "NPN transistor", d: "2N3904 switch" },
  { q: "×1", n: "Signal diode", d: "1N4148" },
  { q: "×20", n: "Resistor assortment", d: "120 Ω – 10 kΩ, ¼ W" },
  { q: "×4", n: "Capacitors", d: "0.1 µF & 10 µF" },
  { q: "×2", n: "Pushbuttons", d: "tactile, for switch logic" },
  { q: "×1", n: "9 V battery + clip", d: "powers it all" },
  { q: "×1", n: "Jumper wire pack", d: "pre-cut, tidy" },
  { q: "×1", n: "Light sensor (LDR)", d: "auto-on at dusk" },
  { q: "×1", n: "Quick-start card", d: "links back to the course" },
];

/* one modal, three jobs: email me the PDF / pre-order the book / join a waitlist.
   `kind` drives the copy; nothing is stored until the user hits send. */
const MODAL_COPY = {
  pdf:      { kick: "Get the guide", cta: "Email me the guide",
              done: (e) => <>We’ll email a copy to <strong style={{ color: "var(--ink)" }}>{e}</strong> too. It’s ready to read right now — open it below, then hit <span className="mono">⌘P</span> to save your own PDF. Name-your-price, so it’s yours even at $0.</> },
  preorder: { kick: "Pre-order", cta: "Notify me at launch",
              done: (e) => <>You're first in line. We'll email <strong style={{ color: "var(--ink)" }}>{e}</strong> the moment the printed guide is ready to order.</> },
  waitlist: { kick: "Reserve", cta: "Notify me",
              done: (e) => <>You're on the list. We'll email <strong style={{ color: "var(--ink)" }}>{e}</strong> when it ships. Until then, every circuit is yours to design on screen — free.</> },
};

function KitWaitlist({ open, onClose }) {
  const [email, setEmail] = useState("");
  const [done, setDone] = useState(false);
  useEffect(() => { if (open) { setDone(false); setEmail(""); } }, [open]);
  if (!open) return null;
  const c = MODAL_COPY[open.kind] || MODAL_COPY.waitlist;
  const submit = () => { if (email.trim()) setDone(true); };
  return (
    <div className="wl-scrim" onClick={onClose}>
      <div className="wl-card" style={{ position: "relative" }} onClick={(e) => e.stopPropagation()}>
        {!done ? (
          <>
            <div className="wl-kick">{c.kick} · {open.flag}</div>
            <h3>{open.title}</h3>
            <p>{open.blurb}{open.kind === "waitlist" ? " Drop an email and we’ll tell you the moment it ships — no account, no spam, one message." : " No account, no spam — one email."}</p>
            <div className="wl-row">
              <input type="email" placeholder="you@email.com" value={email}
                     onChange={(e) => setEmail(e.target.value)}
                     onKeyDown={(e) => e.key === "Enter" && submit()} autoFocus />
              <button className="cta cta-primary" onClick={submit}>{c.cta}</button>
            </div>
            <p className="wl-fine">We store nothing until you hit send. The course stays 100% free either way.</p>
          </>
        ) : (
          <>
            <div className="wl-done">
              <span className="tick">✓</span>
              <h3 style={{ margin: 0 }}>{open.kind === "pdf" ? "On its way." : "You’re in."}</h3>
            </div>
            <p style={{ marginTop: 14 }}>{c.done(email)}</p>
            {open.kind === "pdf" ? (
              <>
                <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 18 }}>
                  <a className="cta cta-primary" href="field-guide-l1.html" target="_blank" rel="noopener">Level 1 · The Water Rules →</a>
                  <a className="cta cta-secondary" href="field-guide-l2.html" target="_blank" rel="noopener">Level 2 · The Parts Catalog →</a>
                  <a className="cta cta-secondary" href="field-guide-l3.html" target="_blank" rel="noopener">Level 3 · The Build →</a>
                </div>
                <div style={{ display: "flex", gap: 12, marginTop: 14, flexWrap: "wrap", alignItems: "center" }}>
                  <a href="field-guide.html" target="_blank" rel="noopener" style={{ fontFamily: "'IBM Plex Mono', monospace", fontSize: 12, color: "var(--ink-soft)", border: "none" }}>or the complete edition (all three in one) →</a>
                  <button className="wl-x" style={{ marginTop: 0, marginLeft: "auto" }} onClick={onClose}>Close</button>
                </div>
              </>
            ) : (
              <button className="wl-x" onClick={onClose}>Close</button>
            )}
          </>
        )}
      </div>
    </div>
  );
}

function KitApp() {
  const [t, setTweak] = useTweaks({ theme: "paper", audience: "adult" });
  useCrossChapterPersistence(t, setTweak);
  useEffect(() => { document.body.setAttribute("data-theme", t.theme); }, [t.theme]);
  const kids = t.audience === "kids";
  const [modal, setModal] = useState(null);

  // open the email modal, OR follow a real store link if one is configured
  const act = (offer) => {
    if (offer.link) { window.open(offer.link, "_blank", "noopener"); return; }
    setModal(offer);
  };

  const guides = [
    {
      kicker: "Read it anywhere",
      title: <>The Field Guide <em>PDFs</em></>,
      sub: kids
        ? "Three little books — one for each level. Read just the one you're on, on any screen."
        : "Three per-level volumes — the Water Rules, the Parts Catalog, and the Build. Each a focused, beautifully typeset PDF, yours to keep and print.",
      price: "Free", per: "name your price · 3 volumes",
      items: ["One slim PDF per level", "Read just the level you're on", "Reads on phone, tablet, desktop", { t: "Pay $0 — or tip if it helped", muted: false }],
      cta: "Get the PDFs", foot: "Instant · name-your-price",
      flag: "Field Guide PDFs", kind: "pdf", link: STORE.pdf,
      blurb: kids ? "Three little books, one per level." : "Three per-level volumes — yours to keep.",
    },
    {
      kicker: "Read it on paper",
      title: <>The <em>Printed</em> Field Guide</>,
      sub: kids
        ? "A real book you can flip through and scribble in, with all the pictures on nice paper."
        : "A ~180-page printed book with margins built for notes. The PDF is included the day it ships.",
      price: "35", per: "ships worldwide · PDF included",
      items: ["Lay-flat softcover", "Every diagram, print-resolution", "Notes margins on each spread", { t: "PDF bundled in", muted: false }],
      cta: "Pre-order the book", foot: "First print run · Q3 2026",
      flag: "Printed Guide", kind: "preorder", link: STORE.print,
      blurb: "The printed field guide — the whole course as a book.",
      featured: true,
    },
  ];

  const future = [
    {
      kicker: "Build it on your desk",
      title: <>The <em>Beacon</em> Kit</>,
      sub: kids
        ? "A box with everything to build your very own flashing beacon for real — the lights, the chip, the battery, all of it."
        : "Every part you sized on screen, kitted into one box. Nothing to solder — it's all solderless. Build the exact Beacon you engineered.",
      price: "39", per: "kit · everything included",
      items: ["All 12 parts (full list below)", "Maps 1:1 onto every Level 2 build", "Quick-start card → the course", { t: "Field-guide PDF bundled in", muted: false }],
      cta: "Join the waitlist", foot: "First run ships Q3 2026",
      flag: "Beacon Kit", kind: "waitlist",
      blurb: "The complete Beacon kit — every part, one box.",
      featured: true,
    },
    {
      kicker: "Teach the room",
      title: <>The <em>Classroom</em> Pack</>,
      sub: kids
        ? "A big set for a whole class or club — enough kits and books for everyone to build together."
        : "Ten kits, ten guides, and a teacher sheet that maps each chapter to a 45-minute lesson. For clubs, classrooms, and makerspaces.",
      price: "480", per: "10 seats · invoiced",
      items: ["10 Beacon kits + 10 guides", "Lesson-by-lesson teacher sheet", "Printable worksheets & answer keys", { t: "Volume pricing past 30 seats", muted: true }],
      cta: "Request a quote", foot: "POs welcome",
      flag: "Classroom Pack", kind: "waitlist",
      blurb: "Ten kits, ten guides, and a teacher sheet for the room.",
    },
  ];

  const OfferCard = (o) => (
    <div key={o.flag} className={"offer" + (o.featured ? " featured" : "")}>
      {o.featured && <span className="offer-flag">{o.flagText || "Most popular"}</span>}
      <div className="offer-kicker">{o.kicker}</div>
      <h2>{o.title}</h2>
      <p className="offer-sub">{o.sub}</p>
      <div className="offer-price">
        {/^\d/.test(o.price)
          ? <span className="amt"><span className="cur">$</span>{o.price}</span>
          : <span className="amt" style={{ fontSize: 38 }}>{o.price}</span>}
        <span className="per">{o.per}</span>
      </div>
      <ul className="offer-list">
        {o.items.map((it, i) => {
          const obj = typeof it === "string" ? { t: it } : it;
          return <li key={i} className={obj.muted ? "muted" : ""}><span className="dot"></span><span>{obj.t}</span></li>;
        })}
      </ul>
      <div className="offer-cta">
        <a className={"cta " + (o.featured ? "cta-primary" : "cta-secondary")}
           onClick={() => act(o)} style={{ cursor: "pointer" }}>{o.cta}</a>
        <span className="offer-foot">{o.foot}</span>
      </div>
    </div>
  );

  return (
    <>
      <TopBar audience={t.audience} setAudience={(v) => setTweak("audience", v)} />
      <main className="home">
        {/* hero */}
        <section className="kit-hero">
          <div>
            <div className="badges" style={{ display: "flex", gap: "8px 14px", marginBottom: 14, fontFamily: "'IBM Plex Mono', monospace", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-faint)" }}>
              <a href="map.html" style={{ border: "none", color: "var(--ink-soft)" }}>← Course map</a>
              <span>·</span><span>Take it off the screen</span>
            </div>
            <h1>
              {kids ? <>You built it on screen.<br/>Now build it <em>for real</em>.</>
                    : <>You designed it on screen.<br/>Now hold it in your <em>hands</em>.</>}
            </h1>
            <p className="lede" style={{ color: "var(--ink-soft)" }}>
              {kids
                ? <>The whole course is free, forever. When you're ready to build the Beacon for real, grab the parts today — or wait for the ready-made box.</>
                : <>Every chapter quietly engineers one device: <em>the Beacon</em>. The lessons stay free forever. Two ways to make it real — grab the parts and the guide <em>today</em>, or reserve the ready-made kit.</>}
            </p>
            <div className="home-cta-row" style={{ marginTop: 28, display: "flex", gap: 12, flexWrap: "wrap" }}>
              <a className="cta cta-primary" href="#parts">{kids ? "Get the parts now →" : "Start today · get the parts →"}</a>
              <a className="cta cta-secondary" href="#guide">Read the field guide</a>
            </div>
          </div>
          <KitBeaconArt />
        </section>

        {/* ── TRACK A · start today ── */}
        <section id="guide" style={{ borderTop: "1px solid var(--rule)" }}>
          <div className="track-head">
            <span className="track-badge now">● Available now</span>
            <h2>Start today — no waiting.</h2>
          </div>
          <p className="track-sub">
            {kids
              ? "Two things you can get right now: the guide to read, and the parts to build with."
              : "Everything here ships (or downloads) the moment you ask. Zero back-order — read the guide and gather the parts this week."}
          </p>
          <div className="kit-grid two">
            {guides.map(OfferCard)}
          </div>

          {/* direct per-level PDF strip — grab one volume without the email step */}
          <div className="fg-vol-strip">
            {[
              { n: "1", t: "The Water Rules", d: kids ? "the rules of flow" : "ch 1–5 · the rules of flow", href: "field-guide-l1.html" },
              { n: "2", t: "The Parts Catalog", d: kids ? "the real parts" : "ch 6–10 · the real components", href: "field-guide-l2.html" },
              { n: "3", t: "The Build", d: kids ? "build it for real" : "breadboard, Beacon & projects", href: "field-guide-l3.html" },
            ].map((v) => (
              <a key={v.n} className="fg-vol" href={v.href} target="_blank" rel="noopener">
                <span className="fg-vol-n">Level {v.n}</span>
                <span className="fg-vol-t">{v.t}</span>
                <span className="fg-vol-d">{v.d}</span>
                <span className="fg-vol-go">Open PDF →</span>
              </a>
            ))}
          </div>
          <p className="track-sub" style={{ marginTop: 12, fontSize: 13.5 }}>
            {kids
              ? "Each one is free — open it, then print or save it however you like."
              : "Each volume is free and name-your-price. Open it in a new tab, then hit "}
            {!kids && <span className="mono">⌘P</span>}{!kids && " to save your own PDF."}
          </p>
        </section>

        {/* parts / affiliate */}
        <section id="parts" style={{ padding: "8px 0 0" }}>
          <div className="track-head" style={{ marginTop: 30 }}>
            <h2 style={{ fontSize: "clamp(26px, 3.2vw, 38px)" }}>Source the parts yourself.</h2>
          </div>
          <p className="track-sub">
            {kids
              ? "Here's the shopping list for the Beacon. Pick a shop below — a grown-up can help you order."
              : "The Beacon needs just twelve common parts (a few dollars total). Pick a retailer and gather them — each stocks everything on this list."}
          </p>

          <div className="retailers">
            {RETAILERS.map((r) => (
              <div key={r.name} className="retailer">
                <span className="r-name">{r.name}</span>
                <span className="r-note">{r.note}</span>
                <a className="cta cta-secondary" href={r.url} target="_blank" rel="noopener">Shop {r.name} →</a>
              </div>
            ))}
          </div>
          <p className="aff-note">
            <strong>A note on these links:</strong> some are affiliate links — buy through them and the course earns a small commission, at no extra cost to you. It's one of the ways the lessons stay free. The exact part numbers also live on the <a href="about.html">About &amp; safety</a> page.
          </p>

          {/* BOM strip */}
          <div className="kit-bom" style={{ padding: "26px 0 8px" }}>
            <div className="home-curriculum-header" style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap", gap: 14, margin: "8px 0 18px" }}>
              <h3 style={{ fontFamily: "Newsreader, serif", fontWeight: 400, fontSize: "clamp(22px, 2.6vw, 30px)", margin: 0 }}>The shopping list</h3>
              <span className="eyebrow">12 parts · enough for every Level 2 build</span>
            </div>
            <div className="kit-bom-grid">
              {KIT_BOM.map((b) => (
                <div key={b.n} className="kit-bom-cell">
                  <div className="q">{b.q}</div>
                  <div className="n">{b.n}</div>
                  <div className="d">{b.d}</div>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* ── TRACK B · coming soon ── */}
        <section style={{ padding: "8px 0 0", borderTop: "1px solid var(--rule)", marginTop: 30 }}>
          <div className="track-head">
            <span className="track-badge soon">◷ In the works</span>
            <h2>Or wait for the ready-made box.</h2>
          </div>
          <p className="track-sub">
            {kids
              ? "Don't want to shop for parts? We're putting together a box with everything inside. Add your email and we'll tell you when it's ready."
              : "If you'd rather not gather parts, we're assembling a kitted box — every component counted and packed. Reserve a spot and we'll email you at launch. No charge until it ships."}
          </p>
          <div className="kit-grid two">
            {future.map(OfferCard)}
          </div>
        </section>

        {/* free-forever reassurance */}
        <section style={{ padding: "30px 0 8px" }}>
          <div className="kit-free">
            <span className="free-badge">Always free</span>
            <div>
              <h3>The course never goes behind a paywall.</h3>
              <p>
                {kids
                  ? <>Every lesson, every animation, every puzzle stays free for everyone. The guide and the kit are just for people who want to build it with their hands — you never have to buy anything to learn.</>
                  : <>Every lesson, simulation, quiz, and capstone stays free for everyone, no sign-in required. The guide, parts, and kit exist for the moment you want to leave the screen — they fund the work without ever gating it. Nothing you’ve learned is locked.</>}
              </p>
            </div>
          </div>
        </section>

        {/* closing line */}
        <section style={{ padding: "30px 0 10px", borderTop: "1px solid var(--rule)", marginTop: 24 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", flexWrap: "wrap", gap: 16 }}>
            <div>
              <div className="eyebrow" style={{ color: "var(--current)", marginBottom: 8 }}>One device, the whole way through</div>
              <h2 style={{ fontFamily: "Newsreader, serif", fontWeight: 400, fontSize: "clamp(26px, 3.6vw, 44px)", margin: 0, maxWidth: "14em" }}>
                Learn it, design it, hold it.
              </h2>
            </div>
            <a className="cta cta-primary" href="#parts">Get started →</a>
          </div>
        </section>

        <footer className="home-footer">
          <span>Fath<span style={{ color: "var(--current)" }}>ohm</span> · A field guide</span>
          <span style={{ display: "flex", gap: 22 }}>
            <a href="map.html">Course map</a>
            <a href="projects.html">Projects</a>
            <a href="about.html">About</a>
          </span>
        </footer>
      </main>

      <KitWaitlist open={modal} onClose={() => setModal(null)} />
      <TweaksPanel title="Tweaks"><CommonTweaks t={t} setTweak={setTweak} /></TweaksPanel>
      <GlossaryFab />
    </>
  );
}

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