/* projects.jsx — the Project Shelf. A catalog of buildable devices.
   The Beacon is live (links to its design bench); the rest are in development
   with a notify-me capture. Same free-course ethic: building is the paid layer
   (kits + per-project PDFs), the lessons stay free.
   Shared globals from shared.jsx. All names prj*-prefixed. */

const { useState: prjUseState, useEffect: prjUseEffect } = React;

/* ── line-art thumbnails, tokens only ───────────────────────────────────── */
function PrjThumbBeacon() {
  return (
    <svg viewBox="0 0 120 96" className="prj-thumb-svg" role="img" aria-label="Beacon: a glowing lamp throwing rings of light">
      {[26, 18, 10].map((r, i) => (
        <circle key={r} cx="60" cy="40" r={r + 16} fill="none" stroke="var(--current)" strokeWidth="1.5"
                opacity={0.12 + i * 0.06} className="prj-pulse" style={{ animationDelay: `${i * 0.3}s` }} />
      ))}
      <circle cx="60" cy="40" r="12" fill="var(--current)" />
      <circle cx="56" cy="36" r="3.5" fill="var(--current-soft)" opacity="0.9" />
      <line x1="60" y1="52" x2="60" y2="78" stroke="var(--ink-faint)" strokeWidth="2" />
      <rect x="44" y="78" width="32" height="8" rx="2" fill="var(--ink-faint)" />
    </svg>
  );
}
function PrjThumbSpinner() {
  return (
    <svg viewBox="0 0 120 96" className="prj-thumb-svg" role="img" aria-label="Spinner: a motor rotor">
      <circle cx="60" cy="48" r="30" fill="none" stroke="var(--rule-strong)" strokeWidth="2" />
      <g className="prj-spin" style={{ transformOrigin: "60px 48px" }}>
        {[0, 120, 240].map((a) => (
          <ellipse key={a} cx="60" cy="48" rx="7" ry="26" fill="var(--water)" opacity="0.8"
                   transform={`rotate(${a} 60 48)`} />
        ))}
        <circle cx="60" cy="48" r="7" fill="var(--ink)" />
      </g>
    </svg>
  );
}
function PrjThumbSequencer() {
  return (
    <svg viewBox="0 0 120 96" className="prj-thumb-svg" role="img" aria-label="Sequencer: a chasing row of lights">
      {[0, 1, 2, 3, 4].map((i) => (
        <circle key={i} cx={24 + i * 18} cy="48" r="8" fill="var(--current)"
                className="prj-chase" style={{ animationDelay: `${i * 0.22}s` }} />
      ))}
    </svg>
  );
}
function PrjThumbLamp() {
  return (
    <svg viewBox="0 0 120 96" className="prj-thumb-svg" role="img" aria-label="Mood lamp: a bulb with a fade">
      <defs>
        <linearGradient id="prjFade" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--current)" />
          <stop offset="100%" stopColor="var(--water)" />
        </linearGradient>
      </defs>
      <path d="M60 18 a22 22 0 0 1 14 39 c-3 3-4 6-4 10 h-20 c0-4-1-7-4-10 a22 22 0 0 1 14-39 z" fill="url(#prjFade)" opacity="0.85" />
      <rect x="50" y="70" width="20" height="7" rx="2" fill="var(--ink-faint)" />
      <rect x="53" y="79" width="14" height="5" rx="2" fill="var(--ink-faint)" />
    </svg>
  );
}
function PrjThumbBuzzer() {
  return (
    <svg viewBox="0 0 120 96" className="prj-thumb-svg" role="img" aria-label="Buzzer: a speaker with sound">
      <path d="M30 38 h14 l18 -14 v48 l-18 -14 h-14 z" fill="var(--ink)" />
      {[10, 18, 26].map((r, i) => (
        <path key={r} d={`M70 ${48 - r} a${r} ${r} 0 0 1 0 ${r * 2}`} fill="none" stroke="var(--current)"
              strokeWidth="2.4" opacity={0.85 - i * 0.22} strokeLinecap="round" />
      ))}
    </svg>
  );
}

const PRJ_THUMBS = {
  beacon: PrjThumbBeacon, spinner: PrjThumbSpinner, sequencer: PrjThumbSequencer,
  lamp: PrjThumbLamp, buzzer: PrjThumbBuzzer,
};

/* ── the catalog ────────────────────────────────────────────────────────── */
const PRJ_LIST = [
  {
    id: "beacon", thumb: "beacon", status: "live",
    name: "The Beacon", kicker: "Project 01 · the flagship",
    tagline: { adult: "A flashing signal light you engineer part by part.", kids: "A blinking signal light you build piece by piece." },
    blurb: {
      adult: "The course project. Across seven stages you light an LED, size it safely, branch it into three, fade it with a capacitor, drive it with a transistor, protect it with a diode, and give it a 555 heartbeat.",
      kids: "Build a real blinking beacon! Start with one light and add a part each stage until it flashes all on its own.",
    },
    teaches: ["Ohm's law", "Series & parallel", "Power", "Capacitor fade", "Transistor", "555 timer"],
    diff: 2, time: "7 stages", parts: 12,
    href: "project.html",
  },
  {
    id: "spinner", thumb: "spinner", status: "live", href: "project-spinner.html",
    name: "The Spinner", kicker: "Project 02 · motion",
    tagline: { adult: "Make a motor turn — and dial its speed.", kids: "Make a motor spin, and make it go faster or slower!" },
    blurb: {
      adult: "Your first moving output. Drive a small DC motor with a transistor, tame the back-kick with a flyback diode, and set the speed with a 555 running PWM — the inductor and diode chapters, made physical.",
      kids: "Spin a real motor! Learn how a tiny signal makes a big motor turn, and how to speed it up or slow it down.",
    },
    teaches: ["Transistor as switch", "Flyback diode", "Inductors", "PWM speed control"],
    diff: 3, time: "~5 stages", parts: 9,
  },
  {
    id: "sequencer", thumb: "sequencer", status: "live", href: "project-sequencer.html",
    name: "The Sequencer", kicker: "Project 03 · patterns",
    tagline: { adult: "A chasing row of lights — the classic.", kids: "A row of lights that runs back and forth, like a robot's eye." },
    blurb: {
      adult: "Take the 555 from the Beacon and feed its beat into a counter that walks the light down a row. Pure logic and timing — the most satisfying first 'it does something!' build.",
      kids: "Make lights chase each other in a row! It uses the same blinking trick as the Beacon, but moves the light along step by step.",
    },
    teaches: ["555 as a clock", "Counters & logic", "Sequencing"],
    diff: 2, time: "~4 stages", parts: 8,
  },
  {
    id: "lamp", thumb: "lamp", status: "live", href: "project-lamp.html",
    name: "The Mood Lamp", kicker: "Project 04 · light",
    tagline: { adult: "A smooth fade you can dial by hand.", kids: "A lamp that glows brighter and dimmer, however you like." },
    blurb: {
      adult: "Swap the blink for a slow breath. A capacitor smooths the 555's output into a gentle ramp, a potentiometer sets the level, and a transistor drives a bright LED — your first analog-feeling control.",
      kids: "A lamp you can fade up and down with a knob. Learn how to turn a sharp on-off into a soft, smooth glow.",
    },
    teaches: ["Smoothing with capacitors", "Potentiometers", "Transistor driver"],
    diff: 1, time: "~3 stages", parts: 7,
  },
  {
    id: "buzzer", thumb: "buzzer", status: "live", href: "project-buzzer.html",
    name: "The Buzzer", kicker: "Project 05 · sound",
    tagline: { adult: "Make a sound — the 555 as a tone.", kids: "Make beeps and tones you can actually hear!" },
    blurb: {
      adult: "Run the 555 fast enough and the blink becomes a pitch. Drive a piezo, change the resistor to change the note, and you've built the front half of every synth and alarm.",
      kids: "Turn the blinking chip up so fast it makes a sound! Change a part and the beep gets higher or lower.",
    },
    teaches: ["Frequency & pitch", "555 at audio speed", "Piezo output"],
    diff: 1, time: "~3 stages", parts: 6,
  },
];

const prjDots = (n) => "●●●".slice(0, n) + "○○○".slice(0, 3 - n);
const PRJ_DIFF_LABEL = { 1: "Gentle", 2: "Moderate", 3: "Spicy" };

/* notify-me modal for in-development projects */
function PrjNotify({ open, onClose }) {
  const [email, setEmail] = prjUseState("");
  const [done, setDone] = prjUseState(false);
  prjUseEffect(() => { if (open) { setDone(false); setEmail(""); } }, [open]);
  if (!open) return null;
  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">In development · {open.name}</div>
            <h3>{open.name}</h3>
            <p>This build is on the bench now. Drop an email and we'll tell you the moment <strong style={{ color: "var(--ink)" }}>{open.name}</strong> goes live — its design page, parts list, and kit. No account, no spam, one message.</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}>Notify me</button>
            </div>
            <p className="wl-fine">We store nothing until you hit send. Every lesson stays 100% free.</p>
          </>
        ) : (
          <>
            <div className="wl-done"><span className="tick">✓</span><h3 style={{ margin: 0 }}>You're in.</h3></div>
            <p style={{ marginTop: 14 }}>We'll email <strong style={{ color: "var(--ink)" }}>{email}</strong> the moment {open.name} is ready to build. Until then, the whole course is yours on screen — free.</p>
            <button className="wl-x" onClick={onClose}>Close</button>
          </>
        )}
      </div>
    </div>
  );
}

function PrjCard({ p, kids, onNotify }) {
  const Thumb = PRJ_THUMBS[p.thumb];
  const live = p.status === "live";
  return (
    <div className={"prj-card" + (live ? " live" : "")}>
      <div className="prj-thumb"><Thumb /></div>
      <div className="prj-body">
        <div className="prj-head">
          <span className="prj-kicker">{p.kicker}</span>
          <span className={"prj-status " + p.status}>{live ? "● Live" : "◷ In development"}</span>
        </div>
        <h3 className="prj-name">{p.name}</h3>
        <p className="prj-tag">{kids ? p.tagline.kids : p.tagline.adult}</p>
        <p className="prj-blurb">{kids ? p.blurb.kids : p.blurb.adult}</p>

        <div className="prj-meta">
          <span><i className="prj-dots">{prjDots(p.diff)}</i>{PRJ_DIFF_LABEL[p.diff]}</span>
          <span>{p.time}</span>
          <span>{p.parts} parts</span>
        </div>

        <div className="prj-teaches">
          {(kids ? p.teaches.slice(0, 3) : p.teaches).map((t) => <span key={t} className="prj-chip">{t}</span>)}
        </div>

        <div className="prj-cta">
          {live ? (
            <>
              <a className="cta cta-primary" href={p.href}>{kids ? "Build it →" : "Open the build bench →"}</a>
              <a className="cta cta-secondary" href="get-the-kit.html#parts">Get the parts</a>
            </>
          ) : (
            <a className="cta cta-secondary" onClick={() => onNotify(p)} style={{ cursor: "pointer" }}>Notify me when it's ready</a>
          )}
        </div>
      </div>
    </div>
  );
}

function ProjectsApp() {
  const [t, setTweak] = useTweaks({ theme: "paper", audience: "adult" });
  useCrossChapterPersistence(t, setTweak);
  prjUseEffect(() => { document.body.setAttribute("data-theme", t.theme); }, [t.theme]);
  const kids = t.audience === "kids";
  const [notify, setNotify] = prjUseState(null);

  const live = PRJ_LIST.filter((p) => p.status === "live");
  const soon = PRJ_LIST.filter((p) => p.status === "soon");

  return (
    <>
      <TopBar audience={t.audience} setAudience={(v) => setTweak("audience", v)} />
      <main className="home">
        {/* hero */}
        <section className="prj-hero">
          <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>The project shelf</span>
          </div>
          <h1>{kids ? <>Pick a thing<br/>to <em>build</em>.</> : <>One bench.<br/>A shelf of <em>things to build</em>.</>}</h1>
          <p className="lede" style={{ color: "var(--ink-soft)", maxWidth: "44em" }}>
            {kids
              ? <>Every project uses the same parts and the same breadboard you already know. Start with the Beacon — then make a motor spin, lights chase, or a buzzer beep.</>
              : <>Each project is a self-contained build on the same breadboard and the same handful of parts — one new idea apiece. Every one is live: pick real component values and the page checks your math. The lessons stay free; kits and per-project guides are how the work gets funded.</>}
          </p>
        </section>

        {/* live */}
        <section style={{ borderTop: "1px solid var(--rule)", paddingTop: 28 }}>
          <div className="track-head"><span className="track-badge now">● Build it now</span><h2>Live on the bench.</h2></div>
          <div className="prj-grid">{live.map((p) => <PrjCard key={p.id} p={p} kids={kids} onNotify={setNotify} />)}</div>
        </section>

        {/* coming soon */}
        {soon.length > 0 && (
        <section style={{ borderTop: "1px solid var(--rule)", marginTop: 34, paddingTop: 28 }}>
          <div className="track-head"><span className="track-badge soon">◷ On the bench</span><h2>In development.</h2></div>
          <p className="track-sub">
            {kids ? "These are being built right now. Tap one to get an email when it's ready." : "Each reuses the Beacon's parts and adds one new trick. Reserve a spot and we'll email you the moment it goes live — no charge, ever, to learn it."}
          </p>
          <div className="prj-grid">{soon.map((p) => <PrjCard key={p.id} p={p} kids={kids} onNotify={setNotify} />)}</div>
        </section>
        )}

        {/* free-forever reassurance */}
        <section style={{ padding: "34px 0 8px" }}>
          <div className="kit-free">
            <span className="free-badge">Always free</span>
            <div>
              <h3>The lessons never go behind a paywall.</h3>
              <p>{kids
                ? <>Every project's design bench is free to play with on screen. Kits and printed guides are just for building it for real — you never have to buy anything to learn.</>
                : <>Every project's interactive design bench is free, no sign-in. The parts kits and per-project build cards exist for the moment you leave the screen — they fund the work without ever gating it.</>}
              </p>
            </div>
          </div>
        </section>

        <footer className="home-footer">
          <span>Fath<span style={{ color: "var(--current)" }}>ohm</span> · The project shelf</span>
          <span style={{ display: "flex", gap: 22 }}>
            <a href="map.html">Course map</a>
            <a href="get-the-kit.html">Store</a>
            <a href="about.html">About</a>
          </span>
        </footer>
      </main>

      <PrjNotify open={notify} onClose={() => setNotify(null)} />
      <TweaksPanel title="Tweaks"><CommonTweaks t={t} setTweak={setTweak} /></TweaksPanel>
      <GlossaryFab />
    </>
  );
}

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