/* project-sequencer-data.jsx — "The Sequencer" build descriptor.
   A 555 clock feeds a 4017 decade counter that walks a light down a row.
   Sets window.PROJECT_BUILD for projectkit.jsx. Names pk-prefixed (SQ_ for build data). */

const pkOhm = (r) => r >= 1000 ? `${(r / 1000).toFixed(r % 1000 ? 1 : 0)} kΩ` : `${r} Ω`;
const pkFar = (c) => c >= 1e-6 ? `${(c * 1e6).toFixed(c * 1e6 % 1 ? 1 : 0)} µF` : `${(c * 1e9).toFixed(0)} nF`;
const pkMA  = (a) => `${a.toFixed(a < 10 ? 1 : 0)} mA`;
const pkHz  = (f) => `${f.toFixed(1)} Hz`;

const SQ_VB = 9, SQ_VF = 2;

const SQ_STAGES = [
  {
    id: "clock", n: 1, schem: "clock", part: "ic555",
    title: "The Heartbeat", teaches: "555 as a clock",
    tagline: "One steady pulse per step — set the tempo.",
    intro: {
      adult: "A sequencer needs a metronome: a 555 astable ticking out one pulse per step. Too fast and the chase blurs; too slow and it crawls. With R1 = 10 kΩ and R2 = 47 kΩ, pick the timing capacitor for a brisk 2.5–7 steps a second.",
      kids: "Every chase needs a beat — a chip that goes tick, tick, tick. Each tick moves the light one step. Pick the timing bucket so it ticks a few times a second: lively, but easy to follow.",
    },
    spec: "Clock rate between 2.5 Hz and 7 Hz — one tick per step.",
    givens: ["R1 = 10 kΩ", "R2 = 47 kΩ", "f = 1.44 ÷ ((R1 + 2·R2)·C)", "Each tick = one step"],
    explain: "The 555 astable is a self-running clock. f = 1.44 ÷ ((R_1 + 2·R_2)·C): a bigger timing capacitor slows the tick. Every rising edge advances the counter one position.",
    picks: [{
      id: "C", label: "Timing capacitor", unit: "F",
      hint: "Bigger C → slower tick. Aim for a few steps per second.",
      options: [1e-6, 2.2e-6, 4.7e-6, 1e-5].map(c => ({ label: pkFar(c), value: c })),
    }],
    check: (v) => {
      const f = 1.44 / ((10000 + 2 * 47000) * v.C);
      const ok = f >= 2.5 && f <= 7;
      return {
        ok,
        headline: `Tick ≈ ${pkHz(f)}`,
        formula: `f = 1.44 ÷ ((10 kΩ + 2×47 kΩ) × ${pkFar(v.C)}) = ${pkHz(f)}`,
        lines: [{ k: "Target", v: "2.5 – 7 Hz" }, { k: "Your rate", v: pkHz(f), ok }],
        note: {
          adult: ok ? "A lively, readable tempo — the light steps along at a satisfying pace." : f > 7 ? "Too fast — the steps blur into a flicker. Use a bigger capacitor." : "Sluggish — it crawls between steps. Use a smaller capacitor.",
          kids: ok ? "Just right — a fun, easy-to-watch pace!" : f > 7 ? "Too fast to follow — bigger bucket." : "Too slow and sleepy — smaller bucket.",
        },
      };
    },
  },
  {
    id: "count", n: 2, schem: "counter", part: "ic4017",
    title: "Walk the Row", teaches: "Decade counter",
    tagline: "A counter lights one LED per tick — set the loop length.",
    intro: {
      adult: "A 4017 decade counter has ten outputs; each clock pulse moves the single 'high' output one step along. You're using five LEDs (outputs 0–4). To loop cleanly after five, tie the counter's RESET to the next output up — so the sixth pulse snaps it back to the start.",
      kids: "The counter chip has ten outputs, and each tick turns on the next one in line. You're using five lights. To make it jump back to the start after five, connect the RESET to the output right after your last light.",
    },
    spec: "Loop after exactly 5 steps: wire RESET to the output just past your last LED.",
    givens: ["5 LEDs on outputs Q0–Q4", "Each pulse advances one output", "RESET snaps the count to Q0", "Tie RESET to the output after the last LED"],
    explain: "The 4017 lights Q0, Q1, Q2… in turn, one per clock pulse. Driving its RESET pin high forces it back to Q0. Tie RESET to Q5 and the count runs 0,1,2,3,4 then resets — a clean five-step loop.",
    picks: [{
      id: "reset", label: "Tie RESET to…", hint: "Five LEDs sit on Q0–Q4. Which output should snap it back?",
      options: [{ label: "Q4", value: "Q4" }, { label: "Q5", value: "Q5" }, { label: "Q6", value: "Q6" }],
    }],
    check: (v) => {
      const ok = v.reset === "Q5";
      return {
        ok,
        headline: ok ? "Clean 5-step loop" : v.reset === "Q4" ? "Loops one step short" : "Adds a blank beat",
        formula: `RESET ← ${v.reset} · count runs 0…${v.reset === "Q4" ? "3" : v.reset === "Q5" ? "4" : "5"} then restarts`,
        lines: [
          { k: "LEDs used", v: "Q0 – Q4 (5)" },
          { k: "RESET tied to", v: v.reset, ok },
        ],
        note: {
          adult: ok ? "Right — RESET on Q5 lets all five light, then the sixth pulse snaps back to Q0. A perfect loop." : v.reset === "Q4" ? "RESET on Q4 fires before your fifth LED ever lights — the last one stays dark. Move RESET up to Q5." : "RESET on Q6 counts to an unused output first, so every loop has a dark 'gap' beat. Tie it to Q5 instead.",
          kids: ok ? "All five light up, then it jumps back — perfect!" : v.reset === "Q4" ? "The last light never gets a turn. Move RESET up one." : "There's an extra dark beat each time. Move RESET down one.",
        },
      };
    },
  },
  {
    id: "leds", n: 3, schem: "chase-leds", part: "led3",
    title: "Light the Row", teaches: "Gentle current limiting",
    tagline: "One shared resistor — sized for the counter's modest drive.",
    intro: {
      adult: "Only one LED is ever lit at a time, so a single resistor on the common return limits whichever one is on. But a 4017 output can only source a few milliamps cleanly — push it like a raw LED and the chip sags. Size the resistor for a gentle 4–8 mA.",
      kids: "Only one light is on at any moment, so a single resistor can protect them all. But the counter chip is delicate — it can't push hard. Pick a resistor that keeps the light gentle, not greedy.",
    },
    spec: "Per-LED current 4–8 mA (the 4017 can't source much more).",
    givens: ["Supply = 9 V", "Each LED drops 2 V", "Only one LED lit at a time", "I = (9 − 2) ÷ R, keep it 4–8 mA"],
    explain: "Ohm's law again: I = (9 − 2) ÷ R. A raw LED loves 15 mA, but a logic-chip output can't deliver that without its voltage drooping — so you deliberately run these dimmer, around 4–8 mA.",
    picks: [{
      id: "R", label: "Shared resistor", unit: "Ω",
      hint: "Bigger R → gentler current. Aim 4–8 mA, not 15.",
      options: [470, 1000, 1500, 2200].map(r => ({ label: pkOhm(r), value: r })),
    }],
    check: (v) => {
      const I = (SQ_VB - SQ_VF) / v.R * 1000;
      const ok = I >= 4 && I <= 8;
      return {
        ok,
        headline: `Per-LED current ≈ ${pkMA(I)}`,
        formula: `I = (9 V − 2 V) ÷ ${pkOhm(v.R)} = ${pkMA(I)}`,
        lines: [{ k: "Target", v: "4 – 8 mA" }, { k: "Your current", v: pkMA(I), ok }],
        note: {
          adult: ok ? "Gentle and bright enough — the 4017 drives it cleanly without its output sagging." : I > 8 ? "Too greedy for a counter output — the chip's voltage droops and the chase dims unevenly. Bigger resistor." : "Quite dim — fine, but you've left brightness on the table. A slightly smaller resistor lifts it.",
          kids: ok ? "Bright enough, and easy on the chip!" : I > 8 ? "Too greedy — the chip can't keep up. Bigger resistor." : "A little dim — try a smaller resistor.",
        },
      };
    },
  },
  {
    id: "bounce", n: 4, schem: "bounce", part: "diode", final: true,
    title: "Make It Sweep", teaches: "Sequencing with diodes",
    tagline: "Fold the count back for a scanner that runs both ways.",
    intro: {
      adult: "A bare counter only chases one way — 1,2,3,4,5, jump. To sweep back like a scanner, let the counter run past five and use diodes to OR the upper outputs (6,7,8) back onto LEDs 4,3,2. Reset at Q8 and the light runs 1→5→1 in a loop. The diodes combine outputs without letting them back-feed each other.",
      kids: "On its own the light only runs one way, then jumps back. To make it bounce — out and back, like a robot's eye — let the counter keep going and use diodes to send the extra steps back through the middle lights. Then reset later so it loops smoothly.",
    },
    spec: "A back-and-forth sweep: fold the count with diodes and reset at Q8.",
    givens: ["Straight chase: RESET at Q5", "5 out + 3 back = 8 steps", "Diodes OR Q6,Q7,Q8 onto LEDs 4,3,2", "Diodes block back-feed between outputs"],
    explain: "A diode passes current one way only, so several outputs can drive one LED through diodes without shorting to each other. Sending outputs 6,7,8 back to the middle LEDs and resetting at Q8 makes the lit dot travel out and back — a scanner.",
    picks: [{
      id: "mode", label: "How should each pass end?", hint: "One way snaps back; the other folds the count to sweep.",
      options: [{ label: "Reset at Q5 — one-way chase", value: "straight" }, { label: "Diode-fold, reset at Q8 — bounce", value: "bounce" }],
    }],
    check: (v) => {
      const ok = v.mode === "bounce";
      return {
        ok,
        headline: ok ? "Scanner sweep — runs both ways" : "One-way chase only",
        formula: ok ? "Q6,Q7,Q8 →(diodes)→ LEDs 4,3,2 · RESET ← Q8 · dot runs 1→5→1" : "RESET ← Q5 · dot runs 1→5, jump to 1",
        lines: [
          { k: "Goal", v: "back-and-forth sweep" },
          { k: "Your wiring", v: ok ? "diode-fold, reset Q8" : "reset Q5 (one-way)", ok },
        ],
        note: {
          adult: ok ? "That's the classic scanner: the lit dot glides out to 5 and back to 1, forever. The diodes let three extra outputs reuse the middle LEDs without shorting together." : "A one-way chase works, but it snaps back with a visible jump. Fold the upper outputs through diodes and reset at Q8 for the smooth bounce.",
          kids: ok ? "It sweeps out and back like a robot's eye — the Sequencer is ALIVE! 🎉" : "This one just jumps back each time. Use the diode trick to make it bounce smoothly.",
        },
      };
    },
  },
];

window.PROJECT_BUILD = {
  id: "sequencer", name: "The Sequencer", em: "Sequencer", kicker: "Project 03 · patterns",
  hero: {
    adult: "Take the 555's beat and put it to work. A decade counter walks a single lit dot down a row of LEDs, one step per tick — and a handful of diodes fold the count over so it sweeps back like a scanner. Pure timing and logic, the most satisfying 'it does something!' build.",
    kids: "Make lights chase each other in a row! A counter chip moves the light one step every beat, and a few diodes make it sweep out and back like a robot's eye. Set the speed, the loop, and the bounce yourself.",
  },
  stages: SQ_STAGES,
  learned: {
    clock:  ["A 555 astable makes a steady clock: f = 1.44 ÷ ((R_1 + 2·R_2)·C).", "Each clock pulse is one step of the sequence."],
    count:  ["A decade counter lights one output per pulse, in turn.", "Tie RESET to the output after your last LED to set the loop length."],
    leds:   ["A counter output sources only a few mA — keep LED current gentle.", "One shared resistor limits whichever LED is lit (only one is on at a time)."],
    bounce: ["Diodes can OR several outputs onto one LED without back-feeding.", "Folding the back half of the count over makes a back-and-forth sweep."],
  },
  finale: {
    adult: "Four stages — a clock you tuned, a counter looped to length, gently-driven LEDs, and a diode fold that makes it sweep — and you've built a scanner from a chip and a beat. Sequencing, from scratch.",
    kids: "You built a row of lights that sweeps back and forth all by itself! A beat, a counter, and a clever diode trick — that's how patterns and displays are made.",
  },
  bench: {
    adult: "You've specified every value. Wire it on the breadboard in this order — the 555 clock first, then the counter and its reset, the LED row, and finally the bounce diodes:",
    kids: "You have the plan. Build it for real — the beat chip first, then the counter, then the lights, then the bounce diodes.",
  },
  specFoot: "Supply 9 V · red LEDs Vf 2 V · 555 clock → 4017 counter · every value meets its target spec.",
};
