/* visuals7.jsx — Diode: the one-way valve.
   A check-valve / flap in a pipe that only lets water flow one direction.
   Forward = open & flowing; reverse = flap slams shut, no flow.
   Plus a matching circuit scene with a diode symbol + LED.            */

/* ─── DiodeWaterScene ────────────────────────────────────────────────────
   Barrel → pipe with a hinged flap (check valve) → outlet.
   `forward` true  → flap pushed open, water flows.
   `forward` false → pressure holds flap shut, no flow.
   ───────────────────────────────────────────────────────────────────────── */
function DiodeWaterScene({ voltage = 6, forward = true, height = 360, showLabels = true }) {
  const W = 820, H = 460;
  const open = forward && voltage > 0.3;
  const I = open ? voltage / 3 : 0;
  const period = flowPeriod(Math.max(0.05, I));
  const fill = fillRatio(voltage);

  const barrelCx = 110, barrelTop = 70, barrelBot = 360;
  const rimRx = 62, midRx = 80;
  const pipeY = 270;
  const pipeStart = barrelCx + 60;
  const pipeEnd = W - 80;
  const baseH = 32;

  // valve seat near middle
  const valveX = (pipeStart + pipeEnd) / 2;
  const seatTopY = pipeY - baseH;
  const seatBotY = pipeY + baseH;

  // flap hinges at top of pipe; swings down-right when open, vertical (shut) when closed
  const hingeX = valveX - 4, hingeY = seatTopY + 2;
  const flapLen = baseH * 2 - 4;
  const openAngle = open ? 58 : 0;   // degrees from vertical

  // direction arrows showing intended flow
  const dirX = forward ? 1 : -1;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={height}
         preserveAspectRatio="xMidYMid meet" style={{ display: "block", maxHeight: height }}>
      {renderBarrel({ cx: barrelCx, top: barrelTop, bot: barrelBot, rimRx, midRx, fill, idSuffix: "dw" })}

      {/* pipe segments before/after the valve */}
      {renderPipe({ pipeStart, pipeEnd: valveX - 14, pipeY, baseH, constrictions: [],
                    current: I, period, idSuffix: "dw-pre", showOutletCap: false })}
      {renderPipe({ pipeStart: valveX + 14, pipeEnd, pipeY, baseH, constrictions: [],
                    current: I, period, idSuffix: "dw-post" })}

      {/* valve seat (a notch the flap seals against) */}
      <line x1={valveX} y1={seatBotY} x2={valveX} y2={seatBotY - 10}
            stroke="var(--ink)" strokeWidth="3" strokeLinecap="round" />

      {/* the flap */}
      <g transform={`translate(${hingeX} ${hingeY}) rotate(${dirX > 0 ? openAngle : -openAngle * (open?0:1)})`}
         style={{ transition: "transform 260ms cubic-bezier(.3,.8,.3,1)" }}>
        <rect x={-5} y={0} width={10} height={flapLen} rx={3}
              fill={open ? "var(--water-soft)" : "var(--ink-soft)"}
              stroke="var(--ink)" strokeWidth="2"
              style={{ transition: "fill 200ms ease" }} />
        {/* hinge pin */}
        <circle cx={0} cy={0} r={4} fill="var(--ink)" />
      </g>

      {/* "blocked" splash when reverse */}
      {!open && voltage > 0.3 && (
        <g opacity="0.8">
          <text x={valveX - 60} y={pipeY + 4} fontFamily="IBM Plex Mono, monospace"
                fontSize="29.5" fill="var(--current)" textAnchor="middle">⊘</text>
        </g>
      )}

      {/* outlet droplets when flowing */}
      {open && I > 0.1 && renderOutletDroplets({ pipeEnd, pipeY, baseH, current: I, period })}

      {showLabels && (
        <g fontFamily="IBM Plex Mono, monospace" letterSpacing="0.1em">
          <text x={barrelCx - midRx + 6} y={barrelTop - 22} fontSize="27" fill="var(--water)">
            PRESSURE · {voltage.toFixed(1)}V
          </text>
          <text x={valveX} y={pipeY + baseH + 40} textAnchor="middle" fontSize="24.5"
                fill={open ? "var(--water)" : "var(--current)"}
                style={{ transition: "fill 200ms ease" }}>
            {open ? "VALVE OPEN · flows" : "VALVE SHUT · blocked"}
          </text>
          <text x={valveX} y={pipeY - baseH - 26} textAnchor="middle" fontSize="21.5"
                fill="var(--ink-faint)">
            {forward ? "trying to flow  →" : "←  trying to flow"}
          </text>
        </g>
      )}
    </svg>
  );
}

/* ─── DiodeCircuitScene ──────────────────────────────────────────────────
   Battery → diode (triangle+bar) → resistor → LED → back.
   forward = diode passes, LED lights. reverse = diode blocks, dark.
   ───────────────────────────────────────────────────────────────────────── */
function DiodeCircuitScene({ voltage = 6, forward = true, height = 360, showLabels = true }) {
  const W = 820, H = 460;
  const conducts = forward && voltage > 0.7;
  const I = conducts ? (voltage - 0.7) / 3 : 0;
  const period = flowPeriod(Math.max(0.05, I));
  const flowing = I > 0.05;

  const L = 130, R = 690, T = 130, B = 360;
  const batCx = L, batCy = (T + B) / 2, batHalfH = 32;
  const diodeCx = 330, diodeCy = T;
  const resCx = 520, resCy = T;
  const bulbCx = R, bulbCy = (T + B) / 2, bulbR = 30;

  const wirePath = `
    M ${L} ${batCy - batHalfH}
    L ${L} ${T}
    L ${diodeCx - 34} ${T}
    M ${diodeCx + 34} ${T}
    L ${resCx - 45} ${T}
    M ${resCx + 45} ${T}
    L ${R} ${T}
    L ${R} ${bulbCy - bulbR}
    M ${R} ${bulbCy + bulbR}
    L ${R} ${B}
    L ${L} ${B}
    L ${L} ${batCy + batHalfH}
  `;
  const loopPath = `
    M ${L} ${batCy - batHalfH}
    L ${L} ${T} L ${R} ${T} L ${R} ${B} L ${L} ${B}
    L ${L} ${batCy + batHalfH} L ${L} ${batCy - batHalfH} Z`;

  const power = voltage * I;
  const glow = Math.max(0, Math.min(1, power / 14));

  // Diode triangle points the direction it allows current (anode→cathode).
  // forward: points right (toward bulb). reverse: we still draw it pointing
  // right but the battery is "pushing" against it.
  const triDir = 1;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={height}
         preserveAspectRatio="xMidYMid meet" style={{ display: "block", maxHeight: height }}>
      <path d={wirePath} fill="none" stroke="var(--current-faint)" strokeWidth="9"
            strokeLinecap="round" opacity={flowing ? 0.5 : 0}
            style={{ transition: "opacity 200ms ease" }} />
      <path d={wirePath} fill="none" stroke="var(--ink)" strokeWidth="2.5" strokeLinecap="round" />

      {flowing && renderElectrons({ path: loopPath, period, flowing: true, count: 6 })}

      {renderBatterySymbol({ cx: batCx, cy: batCy, halfH: batHalfH, voltage, showLabel: showLabels })}

      {/* diode symbol: triangle + cathode bar */}
      <g>
        <polygon
          points={`${diodeCx - 16},${diodeCy - 16} ${diodeCx - 16},${diodeCy + 16} ${diodeCx + 16},${diodeCy}`}
          fill={conducts ? "var(--current)" : "var(--bg-card)"}
          stroke="var(--ink)" strokeWidth="2.5"
          style={{ transition: "fill 200ms ease" }} />
        <line x1={diodeCx + 16} y1={diodeCy - 16} x2={diodeCx + 16} y2={diodeCy + 16}
              stroke="var(--ink)" strokeWidth="3" />
        {showLabels && (
          <text x={diodeCx} y={diodeCy - 26} textAnchor="middle"
                fontFamily="IBM Plex Mono, monospace" fontSize="17.5"
                fill={conducts ? "var(--current)" : "var(--ink-faint)"}
                letterSpacing="0.1em" style={{ transition: "fill 200ms ease" }}>
            DIODE · {conducts ? "ON" : "OFF"}
          </text>
        )}
        {/* "blocked" mark when reverse */}
        {!conducts && voltage > 0.7 && (
          <text x={diodeCx} y={diodeCy + 42} textAnchor="middle"
                fontFamily="IBM Plex Mono, monospace" fontSize="21.5" fill="var(--current)">⊘ blocked</text>
        )}
      </g>

      {renderResistorSymbol({ cx: resCx, cy: resCy, w: 90, h: 30, r: 3,
                              label: showLabels && "R" })}
      {renderBulbSymbol({ cx: bulbCx, cy: bulbCy, r: bulbR, glowOpacity: glow, flowing,
                          label: showLabels && (flowing ? "LIT" : "DARK") })}

      {showLabels && (
        <text x={(L + R) / 2} y={B + 30}
              fontFamily="IBM Plex Mono, monospace" fontSize="20.5"
              fill={flowing ? "var(--current)" : "var(--ink-faint)"}
              textAnchor="middle" letterSpacing="0.1em"
              style={{ transition: "fill 200ms ease" }}>
          {forward ? `FORWARD · I = ${I.toFixed(2)}A` : "REVERSE · I = 0 A"}
        </text>
      )}
    </svg>
  );
}

Object.assign(window, { DiodeWaterScene, DiodeCircuitScene });
