/* cryptographylab.jsx — CryptographyTutor: the Caesar-cipher bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   compute = window.BenchFields.cryptography — the SAME function server/benches/cryptography.js
   calls, so client and server fields are identical by construction. Mirrors gaslawslab.jsx:
   sliders → BenchFields.fn(state) → report + meters. */
(function () {
  const { useState, useMemo, useEffect } = React;
  const K = window.BenchKit, C = K.C, SVG_BG = K.SVG_BG, fmt = K.fmt;
  const TaskStrip = K.TaskStrip, StatMeter = K.StatMeter;
  const compute = (s) => window.BenchFields.cryptography(s);
  const L = (v) => String.fromCharCode(65 + ((v % 26) + 26) % 26);

  function Slider({ label, value, set, min, max, step, unit, color, onUp, suffix }) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 9 }}>
        <span style={{ fontSize: 12, color: C.mute, width: 116 }}>{label}</span>
        <input type="range" min={min} max={max} step={step} value={value} onChange={(e) => set(parseFloat(e.target.value))} onPointerUp={onUp} style={{ flex: 1 }} />
        <span style={{ color: color || C.amber, width: 72, textAlign: "right" }}>{value}{unit ? ` ${unit}` : ""}{suffix != null ? ` (${suffix})` : ""}</span>
      </div>
    );
  }

  function CryptographyFig({ task, setTask, tasks, report, event, done }) {
    const [plainValue, setPlainValue] = useState(0);
    const [shift, setShift] = useState(3);
    const fld = useMemo(() => compute({ plainValue, shift }), [plainValue, shift]);
    useEffect(() => { report(fld); }, [plainValue, shift]); // eslint-disable-line

    const cipher = fld.shiftedValue;
    // two alphabet rows: outer A–Z (plaintext), inner rotated by the shift (ciphertext).
    const X0 = 30, X1 = 570, n = 26;
    const cw = (X1 - X0) / n;
    const ROW0 = 96, ROW1 = 168, cellH = 30;
    const cellX = (i) => X0 + i * cw + cw / 2;
    const t = tasks.find((x) => x.id === task) || tasks[0];

    return (
      <>
        <TaskStrip tasks={tasks} cur={task} setCur={setTask} done={done} goal={t && t.goal} />
        <svg viewBox="0 0 600 300" style={{ width: "100%", background: SVG_BG, border: `1px solid ${C.line}`, borderRadius: 8 }}>
          <text x={X0} y={ROW0 - 18} fill={C.mute} fontSize="11" fontFamily="monospace">plaintext  A–Z</text>
          <text x={X0} y={ROW1 + cellH + 18} fill={C.mute} fontSize="11" fontFamily="monospace">ciphertext  (shift {shift})</text>
          {Array.from({ length: n }).map((_, i) => {
            const isPlain = i === plainValue;
            const out = ((i + shift) % 26);
            const isCipher = i === cipher; // inner cell index i holds letter (i+shift) mod 26; highlight the one under the plaintext column
            return (
              <g key={i}>
                {/* outer / plaintext row: cell i shows letter i */}
                <rect x={X0 + i * cw} y={ROW0} width={cw - 1.5} height={cellH} rx="2"
                  fill={isPlain ? C.teal : C.panel} opacity={isPlain ? 0.9 : 0.5} stroke={C.line} strokeWidth="1" />
                <text x={cellX(i)} y={ROW0 + cellH / 2 + 4} textAnchor="middle" fontSize="12" fontFamily="monospace"
                  fill={isPlain ? "#fff" : C.mute}>{L(i)}</text>
                {/* inner / ciphertext row: column i sits under plaintext i and shows the mapped letter (i+shift) */}
                <rect x={X0 + i * cw} y={ROW1} width={cw - 1.5} height={cellH} rx="2"
                  fill={isPlain ? C.gold : C.panel} opacity={isPlain ? 0.9 : 0.5} stroke={C.line} strokeWidth="1" />
                <text x={cellX(i)} y={ROW1 + cellH / 2 + 4} textAnchor="middle" fontSize="12" fontFamily="monospace"
                  fill={isPlain ? "#23262d" : C.mute}>{L(out)}</text>
              </g>
            );
          })}
          {/* mapping arrow from plaintext cell to its ciphertext cell */}
          <line x1={cellX(plainValue)} y1={ROW0 + cellH} x2={cellX(plainValue)} y2={ROW1} stroke={C.crimson} strokeWidth="2" markerEnd="url(#cryArrow)" />
          <defs>
            <marker id="cryArrow" markerWidth="8" markerHeight="8" refX="4" refY="4" orient="auto">
              <path d="M0,0 L8,4 L0,8 Z" fill={C.crimson} />
            </marker>
          </defs>
          <text x={300} y={ROW1 + cellH + 56} textAnchor="middle" fill={C.ink} fontSize="14" fontFamily="monospace">
            {L(plainValue)} + {shift} = {L(cipher)}   ·   c = (p + k) mod 26
          </text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.isIdentity ? C.crimson : C.line}`, color: fld.isIdentity ? C.crimson : C.mute, fontSize: 12.5 }}>
          {L(plainValue)} → {L(cipher)} · decrypts back to {L(fld.recovered)}. {fld.isIdentity ? "⚠ shift 0 is the identity — no encryption." : (fld.wrapsAround ? "↻ this shift wraps past Z." : `keyspace ${fld.keyspace} — only 25 useful keys.`)}
        </div>
        <Slider label="plaintext p" value={plainValue} set={setPlainValue} min={0} max={25} step={1} suffix={L(plainValue)} color={C.teal} onUp={() => event("adjusted", `Set plaintext = ${L(plainValue)}`, { response: `cipher ${L(fld.shiftedValue)}` }, C.teal)} />
        <Slider label="shift key k" value={shift} set={setShift} min={0} max={25} step={1} suffix={`→ ${L((plainValue + shift) % 26)}`} color={C.gold} onUp={() => event("adjusted", `Set shift = ${shift}`, { response: `cipher ${L(fld.shiftedValue)}` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="ciphertext" v={`${fld.shiftedValue} (${L(fld.shiftedValue)})`} color={C.gold} />
          <StatMeter label="shift k" v={fld.shift} d={0} color={C.crimson} />
          <StatMeter label="keyspace" v={fld.keyspace} d={0} color={C.blue} />
        </div>
      </>
    );
  }

  window.CryptographyTutor = K.makeTutor(CryptographyFig, { moduleLabel: "Caesar cipher bench", benchId: "cryptography" });
})();
