/* global React */

/* Background circuit schematic — a public CD4060 timer / LED-flasher
   reference design, traced into vector form with all text labels
   stripped. Recolored copper via CSS, rendered very faint, and tiled
   vertically to fill the page band. */

// All elements stroke="currentColor" fill="none" so the parent's
// `color: var(--copper)` controls the tint.

// Animated "current flow" path. Computes its own length on mount so
// the pulse moves at a constant physical speed regardless of route
// length — that's what makes two routes sharing an initial segment
// look like one pulse that splits at the junction.
function FlowPath({ d, speed = 110, delay = 0 }) {
  const ref = React.useRef(null);

  React.useEffect(() => {
    const path = ref.current;
    if (!path) return;

    const length = path.getTotalLength();
    const dashLen = 26;
    const gapLen = length + 60;
    const cycle = dashLen + gapLen;
    const durationMs = (cycle / speed) * 1000;

    path.style.strokeDasharray = `${dashLen} ${gapLen}`;

    const animation = path.animate(
      [
        { strokeDashoffset: 0 },
        { strokeDashoffset: -cycle },
      ],
      {
        duration: durationMs,
        iterations: Infinity,
        delay: delay * 1000,
        easing: 'linear',
      },
    );

    return () => animation.cancel();
  }, [d, speed, delay]);

  return <path ref={ref} className="circuit-flow" d={d} />;
}

// Schematic primitives ------------------------------------------------------

// Horizontal resistor, body 24 wide, 40 total with leads.
// dir='v' rotates to vertical orientation.
function R({ x, y, dir = 'h' }) {
  const t = dir === 'v' ? `translate(${x},${y}) rotate(90)` : `translate(${x},${y})`;
  return (
    <g transform={t}>
      <path d="M0 0 L8 0 M32 0 L40 0" />
      <rect x="8" y="-4" width="24" height="8" />
    </g>
  );
}

// Potentiometer — resistor with arrow tap from above.
function Pot({ x, y, dir = 'h' }) {
  const t = dir === 'v' ? `translate(${x},${y}) rotate(90)` : `translate(${x},${y})`;
  return (
    <g transform={t}>
      <path d="M0 0 L8 0 M32 0 L40 0" />
      <rect x="8" y="-4" width="24" height="8" />
      <path d="M20 -14 L20 -4" />
      <path d="M16 -8 L20 -4 L24 -8" />
    </g>
  );
}

// Ceramic (non-polarized) capacitor — two parallel plates.
function CapC({ x, y, dir = 'h' }) {
  const t = dir === 'v' ? `translate(${x},${y}) rotate(90)` : `translate(${x},${y})`;
  return (
    <g transform={t}>
      <path d="M0 0 L14 0 M20 0 L34 0" />
      <path d="M14 -7 L14 7" />
      <path d="M20 -7 L20 7" />
    </g>
  );
}

// Electrolytic capacitor — flat plate + curved plate.
function CapE({ x, y, dir = 'h' }) {
  const t = dir === 'v' ? `translate(${x},${y}) rotate(90)` : `translate(${x},${y})`;
  return (
    <g transform={t}>
      <path d="M0 0 L14 0 M22 0 L36 0" />
      <path d="M14 -8 L14 8" />
      <path d="M22 -8 Q28 0 22 8" />
    </g>
  );
}

// Diode — anode on the (untransformed) left, cathode on the right.
// dir rotates: 'right' default, 'down' 90, 'left' 180, 'up' 270.
const ROT = { right: 0, down: 90, left: 180, up: 270 };
function Diode({ x, y, dir = 'right' }) {
  return (
    <g transform={`translate(${x},${y}) rotate(${ROT[dir]})`}>
      <path d="M0 0 L8 0 M22 0 L30 0" />
      <path d="M8 -6 L8 6 L22 0 Z" />
      <path d="M22 -6 L22 6" />
    </g>
  );
}

// Zener diode — like diode but with bent cathode bar.
function Zener({ x, y, dir = 'right' }) {
  return (
    <g transform={`translate(${x},${y}) rotate(${ROT[dir]})`}>
      <path d="M0 0 L8 0 M22 0 L30 0" />
      <path d="M8 -6 L8 6 L22 0 Z" />
      <path d="M18 -6 L22 -6 L22 6 L26 6" />
    </g>
  );
}

// LED — diode with two outward light arrows.
function LED({ x, y, dir = 'right' }) {
  return (
    <g transform={`translate(${x},${y}) rotate(${ROT[dir]})`}>
      <path d="M0 0 L8 0 M22 0 L30 0" />
      <path d="M8 -6 L8 6 L22 0 Z" />
      <path d="M22 -6 L22 6" />
      <path d="M14 -10 L20 -16 M17 -16 L20 -16 L20 -13" />
      <path d="M18 -8 L24 -14 M21 -14 L24 -14 L24 -11" />
    </g>
  );
}

// NPN transistor — base on left, collector up, emitter down with arrow OUT.
function NPN({ x, y }) {
  return (
    <g transform={`translate(${x},${y})`}>
      <circle cx="0" cy="0" r="14" />
      <path d="M-14 0 L-4 0" />
      <path d="M-4 -8 L-4 8" />
      <path d="M-4 -3 L10 -11 L10 -20" />
      <path d="M-4 3 L10 11 L10 20" />
      <path d="M3 11 L10 11 L10 4" />
    </g>
  );
}

// PNP transistor — base on left, emitter arrow points IN toward base.
function PNP({ x, y }) {
  return (
    <g transform={`translate(${x},${y})`}>
      <circle cx="0" cy="0" r="14" />
      <path d="M-14 0 L-4 0" />
      <path d="M-4 -8 L-4 8" />
      <path d="M-4 -3 L10 -11 L10 -20" />
      <path d="M-4 3 L10 11 L10 20" />
      <path d="M0 4 L-4 8 L2 9" />
    </g>
  );
}

// IC chip — rectangle with notch and pin marks.
function IC({ x, y, w = 70, h = 130, pins = 8 }) {
  const half = pins / 2;
  const pinSpacing = (h - 20) / (half - 1);
  const pinYs = Array.from({ length: half }, (_, i) => 10 + i * pinSpacing);
  return (
    <g transform={`translate(${x},${y})`}>
      <rect x="0" y="0" width={w} height={h} />
      <path d={`M${w / 2 - 5} 0 A5 5 0 0 0 ${w / 2 + 5} 0`} />
      {pinYs.map((py, i) => (
        <React.Fragment key={i}>
          <path d={`M-6 ${py} L0 ${py}`} />
          <path d={`M${w} ${py} L${w + 6} ${py}`} />
        </React.Fragment>
      ))}
    </g>
  );
}

// Transformer — two coils with three humps each, parallel core lines.
function Transformer({ x, y }) {
  return (
    <g transform={`translate(${x},${y})`}>
      {/* Primary coil humps face right */}
      <path d="M0 0 a8 8 0 0 1 0 16 a8 8 0 0 1 0 16 a8 8 0 0 1 0 16" />
      {/* Secondary coil humps face left */}
      <path d="M30 0 a8 8 0 0 0 0 16 a8 8 0 0 0 0 16 a8 8 0 0 0 0 16" />
      {/* Core */}
      <path d="M11 -4 L11 52" />
      <path d="M19 -4 L19 52" />
      {/* Primary leads (left side) */}
      <path d="M0 0 L0 -12 L-16 -12" />
      <path d="M0 48 L0 60 L-16 60" />
      {/* Secondary leads (right side) */}
      <path d="M30 0 L30 -12 L46 -12" />
      <path d="M30 48 L30 60 L46 60" />
    </g>
  );
}

// Bridge rectifier — square outline with 4 diode marks inside, AC on
// top/bottom corners, DC on left/right corners.
function Bridge({ x, y, size = 50 }) {
  const s = size;
  const m = s / 2;
  return (
    <g transform={`translate(${x},${y})`}>
      {/* outer diamond */}
      <path d={`M0 ${-m} L${m} 0 L0 ${m} L${-m} 0 Z`} />
      {/* 4 small diode triangles inside, oriented toward + output (right) */}
      {/* top-left arm: anode top, cathode toward right (output) */}
      <path d={`M${-m / 2 - 3} ${-m / 2 + 3} L${-m / 2 + 3} ${-m / 2 - 3} L${-m / 2 + 5} ${-m / 2 + 5} Z`} />
      {/* top-right arm */}
      <path d={`M${m / 2 + 3} ${-m / 2 + 3} L${m / 2 - 3} ${-m / 2 - 3} L${m / 2 - 5} ${-m / 2 + 5} Z`} />
      {/* bottom-right arm */}
      <path d={`M${m / 2 + 3} ${m / 2 - 3} L${m / 2 - 3} ${m / 2 + 3} L${m / 2 - 5} ${m / 2 - 5} Z`} />
      {/* bottom-left arm */}
      <path d={`M${-m / 2 - 3} ${m / 2 - 3} L${-m / 2 + 3} ${m / 2 + 3} L${-m / 2 + 5} ${m / 2 - 5} Z`} />
    </g>
  );
}

// Ground symbol — stacked horizontal lines.
function Ground({ x, y }) {
  return (
    <g transform={`translate(${x},${y})`}>
      <path d="M0 0 L0 6" />
      <path d="M-9 6 L9 6" />
      <path d="M-6 10 L6 10" />
      <path d="M-3 14 L3 14" />
    </g>
  );
}

// SPST switch — two terminals, one open contact lever.
function SwitchSym({ x, y }) {
  return (
    <g transform={`translate(${x},${y})`}>
      <path d="M0 0 L8 0" />
      <circle cx="10" cy="0" r="1.5" />
      <circle cx="30" cy="0" r="1.5" />
      <path d="M10 0 L26 -8" />
      <path d="M32 0 L40 0" />
    </g>
  );
}

// Single schematic instance ------------------------------------------------

function Schematic() {
  return (
    <>
      <g
        className="circuit-traces"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinecap="round"
        strokeLinejoin="round"
        vectorEffect="non-scaling-stroke"
      >
      {/* === Rails === */}
      <path d="M210 30 L755 30" /> {/* top rail */}
      <path d="M165 360 L755 360" /> {/* ground rail */}

      {/* === Left: transformer + bridge + C1 + ground === */}
      <Transformer x={50} y={150} />
      {/* AC primary leads continue off the left edge (no source drawn) */}
      <path d="M34 138 L20 138" />
      <path d="M34 210 L20 210" />
      {/* secondary into bridge AC corners (top and bottom of diamond) */}
      <path d="M96 138 L130 138 L130 155 L150 155" />
      <path d="M96 210 L130 210 L130 205 L150 205" />

      <Bridge x={165} y={180} />
      {/* DC outputs: + on right of diamond → up to top rail; − on left → down to ground */}
      <path d="M190 180 L210 180 L210 30" />
      <path d="M140 180 L120 180 L120 360" />

      {/* C1 electrolytic, vertical, across DC */}
      <CapE x={230} y={240} dir="v" />
      <path d="M230 240 L230 220 L210 220" />
      <path d="M230 276 L230 360" />

      <Ground x={120} y={360} />

      {/* === VD5 freewheel on top rail (cathode toward left) === */}
      <Diode x={250} y={30} dir="left" />

      {/* === R1 horizontal, R2 vertical, V1 NPN === */}
      <path d="M210 60 L260 60" /> {/* small bus to R1 */}
      <R x={260} y={60} />
      <path d="M300 60 L320 60 L320 90" />

      <R x={335} y={75} dir="v" /> {/* R2 vertical between rails */}
      <path d="M335 30 L335 75" />
      <path d="M335 115 L335 150" />
      <path d="M310 150 L360 150" />

      <NPN x={335} y={170} />
      <path d="M321 170 L310 170 L310 150" /> {/* base from R1 path */}
      <path d="M345 150 L345 30" /> {/* collector up to top rail */}
      <path d="M345 190 L345 360" /> {/* emitter down to ground rail */}

      {/* === C2 across top rail to IC supply === */}
      <CapC x={400} y={50} dir="v" />
      <path d="M400 30 L400 50" />
      <path d="M400 84 L400 110" />

      {/* === IC1 (CD4060) center === */}
      <IC x={460} y={110} w={70} h={130} pins={8} />
      {/* VDD (pin 16) — top-left pin → C2 / top rail */}
      <path d="M454 120 L420 120 L420 110" />
      <path d="M420 110 L400 110" />
      <path d="M420 110 L420 30" />
      {/* Vss (pin 8) — bottom-left → ground */}
      <path d="M454 230 L440 230 L440 360" />
      {/* pin 10 → RP1 tap */}
      <path d="M454 140 L440 140" />
      {/* pin 11 → R3/R4 network bottom */}
      <path d="M454 200 L440 200 L440 285" />
      {/* pin 12 (reset) → right-side wire down to V2 area */}
      <path d="M530 130 L555 130" />
      {/* pin Q14 (pin 3) → V2 base */}
      <path d="M530 195 L555 195 L555 225 L560 225" />
      {/* pin 9 */}
      <path d="M454 165 L420 165" />
      <path d="M530 160 L545 160" />

      {/* === RP1 + R3 timing network for CD4060 === */}
      <Pot x={360} y={140} />
      <R x={400} y={170} />
      <path d="M360 140 L355 140 L355 170 L400 170" />
      <path d="M400 140 L440 140" />
      <path d="M440 170 L420 170" />

      {/* === C3 across timing network === */}
      <CapC x={345} y={105} />
      <path d="M345 105 L335 105 L335 140" />
      <path d="M379 105 L395 105 L395 140" />

      {/* === R4 bottom + VD6 + VD7 toward ground === */}
      <R x={365} y={285} />
      <path d="M365 285 L350 285 L350 200" />
      <path d="M405 285 L420 285" />

      <Diode x={355} y={310} dir="down" />
      <path d="M355 310 L355 295" />
      <path d="M355 340 L355 360" />

      <Diode x={490} y={310} dir="down" />
      <path d="M490 310 L490 295" />
      <path d="M490 340 L490 360" />
      <path d="M490 295 L460 295 L460 240" />

      {/* === R5 vertical, right of IC, to ground rail === */}
      <R x={555} y={275} dir="v" />
      <path d="M555 255 L555 240" />
      <path d="M555 295 L555 360" />

      {/* === Right block: VD8, V2, R6, V3, VZ, R8, R7, LED, S1 === */}
      <Diode x={555} y={120} dir="down" />
      <path d="M555 120 L555 100" />
      <path d="M555 150 L555 195" />

      <PNP x={580} y={225} />
      <path d="M566 225 L555 225" /> {/* base */}
      <path d="M590 205 L590 30" /> {/* collector to top rail */}
      <path d="M590 245 L590 360" /> {/* emitter to ground side network */}

      <SwitchSym x={580} y={30} />
      <path d="M620 30 L620 30" />

      <R x={620} y={55} dir="v" /> {/* R6 1k */}
      <path d="M620 30 L620 55" />
      <path d="M620 95 L620 135" />

      <PNP x={645} y={140} />
      <path d="M631 140 L620 140 L620 135" />
      <path d="M655 120 L655 70" />
      <path d="M655 160 L655 220" />

      <Zener x={660} y={45} dir="down" />
      <path d="M660 45 L660 30" />
      <path d="M660 75 L660 70" />
      <path d="M660 70 L685 70" />

      <R x={685} y={30} /> {/* R8 horizontal */}
      <path d="M685 30 L685 70" />
      <path d="M725 30 L725 30" />

      <R x={705} y={240} dir="v" /> {/* R7 vertical */}
      <path d="M705 220 L705 240" />
      <path d="M705 280 L705 300" />

      <LED x={705} y={315} dir="down" />
      <path d="M705 315 L705 300" />
      <path d="M705 345 L705 360" />

      {/* small vertical bus joins on right */}
      <path d="M655 220 L705 220" />
      <path d="M590 80 L655 80" />

      {/* === Inter-tile connectors === */}
      {/* Vertical stubs at the top and bottom edges, placed
          symmetrically around the viewBox center (380) so they survive
          a horizontal mirror transform and still meet edge-to-edge
          between any pair of variant tiles. */}
      <path d="M260 0 L260 30" />
      <path d="M380 0 L380 30" />
      <path d="M500 0 L500 30" />
      <path d="M260 360 L260 420" />
      <path d="M380 360 L380 420" />
      <path d="M500 360 L500 420" />
      </g>
      {/* === Current flow routes === */}
      {/* Both routes start at the V+ rail entry and share the rail
          segment from x=210 to x=345 — pulses coincide there, then
          split at the V1 collector junction. */}
      <g className="circuit-flow-group">
        {/* Route A1: V+ → V1 → ground rail */}
        <FlowPath d="M210 30 L345 30 L345 360 L500 360" />
        {/* Route A2: V+ → IC supply → through IC body → ground rail */}
        <FlowPath d="M210 30 L420 30 L420 120 L454 120 L454 230 L440 230 L440 360 L300 360" />
      </g>
    </>
  );
}

// Second schematic — a 3-stage discrete NPN amplifier chain with input
// pot and output LED. Deliberately different topology from the CD4060
// one above so adjacent tiles don't read as repeats.
function SchematicB() {
  return (
    <>
      <g
        className="circuit-traces"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinecap="round"
        strokeLinejoin="round"
        vectorEffect="non-scaling-stroke"
      >
      {/* === Rails === */}
      <path d="M60 30 L700 30" />
      <path d="M60 360 L700 360" />

      {/* === Power bypass electrolytic === */}
      <CapE x={110} y={100} dir="v" />
      <path d="M110 30 L110 100" />
      <path d="M110 136 L110 360" />

      {/* === Input pot === */}
      <Pot x={170} y={80} dir="v" />
      <path d="M170 30 L170 80" />
      <path d="M170 120 L170 200" />

      {/* === Stage 1: R1 + Q1, coupling C1 to next stage === */}
      <R x={270} y={80} dir="v" />
      <path d="M270 30 L270 80" />
      <path d="M270 120 L270 220" />

      <NPN x={260} y={240} />
      <path d="M170 200 L246 200 L246 240" />
      <path d="M270 260 L270 360" />

      <CapC x={300} y={180} />
      <path d="M270 180 L300 180" />
      <path d="M334 180 L380 180" />

      {/* === Stage 2: R2 base bias, R3 collector pull-up, Q2 === */}
      <R x={380} y={80} dir="v" />
      <path d="M380 30 L380 80" />
      <path d="M380 120 L380 240" />

      <R x={450} y={80} dir="v" />
      <path d="M450 30 L450 80" />
      <path d="M450 120 L450 220" />

      <NPN x={440} y={240} />
      <path d="M380 240 L426 240" />
      <path d="M450 260 L450 360" />

      <CapC x={480} y={180} />
      <path d="M450 180 L480 180" />
      <path d="M514 180 L560 180" />

      {/* === Stage 3: R4 base bias, output Q3 with LED on collector === */}
      <R x={560} y={80} dir="v" />
      <path d="M560 30 L560 80" />
      <path d="M560 120 L560 240" />

      <NPN x={620} y={240} />
      <path d="M560 240 L606 240" />
      <path d="M630 260 L630 360" />

      <R x={630} y={60} dir="v" />
      <path d="M630 30 L630 60" />
      <path d="M630 100 L630 130" />

      <LED x={630} y={140} dir="down" />
      <path d="M630 170 L630 220" />

      {/* === Two small ceramic decoupling caps near rails === */}
      <CapC x={680} y={50} dir="v" />
      <path d="M680 30 L680 50" />
      <path d="M680 84 L680 360" />

      {/* === Inter-tile connectors — same symmetric set as Schematic A === */}
      <path d="M260 0 L260 30" />
      <path d="M380 0 L380 30" />
      <path d="M500 0 L500 30" />
      <path d="M260 360 L260 420" />
      <path d="M380 360 L380 420" />
      <path d="M500 360 L500 420" />
      </g>
      {/* === Current flow routes === */}
      {/* Both start at left rail entry, share x=60→170, then split at
          the pot junction: one drops down through Q1's stage, the other
          continues right to the Q3 output stage. */}
      <g className="circuit-flow-group">
        {/* Route B1: V+ → pot → Q1 → ground rail */}
        <FlowPath d="M60 30 L170 30 L170 240 L270 240 L270 360 L500 360" />
        {/* Route B2: V+ → far right → R5/LED/Q3 → ground rail */}
        <FlowPath d="M60 30 L630 30 L630 360 L500 360" />
      </g>
    </>
  );
}

// Background layer ---------------------------------------------------------

function CircuitBg() {
  // Four variants cycle: original A, original B, A mirrored, B mirrored.
  // With ~3-4 visible tiles in the band, the same schematic never
  // appears twice. Connector stubs are at horizontally symmetric
  // x-positions so the mirror flip still aligns edge-to-edge.
  const TILES = 8;
  const VARIANTS = [
    { use: 'A', flip: false },
    { use: 'B', flip: false },
    { use: 'A', flip: true },
    { use: 'B', flip: true },
  ];
  return (
    <div className="circuit-bg" aria-hidden="true">
      {Array.from({ length: TILES }).map((_, i) => {
        const v = VARIANTS[i % VARIANTS.length];
        const Inner = v.use === 'A' ? Schematic : SchematicB;
        return (
          <svg
            key={i}
            className="circuit-tile"
            viewBox="0 0 760 420"
            preserveAspectRatio="xMidYMid meet"
          >
            {v.flip ? (
              <g transform="translate(760, 0) scale(-1, 1)">
                <Inner />
              </g>
            ) : (
              <Inner />
            )}
          </svg>
        );
      })}
    </div>
  );
}

window.CircuitBg = CircuitBg;
