/* binarylab.jsx — BinaryTutor: the unsigned 8-bit binary-number bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just
   the FIGURE. compute = window.BenchFields.binary — the SAME function
   server/benches/binary.js calls, so client and server fields are identical by
   construction. Mirrors the gas-laws lab: controls → BenchFields.fn(state) → report + meters. */
(function () {
  const { useState, useMemo, useEffect } = React;
  const K = window.BenchKit, C = K.C, SVG_BG = K.SVG_BG;
  const TaskStrip = K.TaskStrip, StatMeter = K.StatMeter;
  const compute = (s) => window.BenchFields.binary(s);
  const IDX = [7, 6, 5, 4, 3, 2, 1, 0]; // MSB → LSB

  function BinaryFig({ task, setTask, tasks, report, event, done }) {
    const [bits, setBits] = useState({ bit7: false, bit6: false, bit5: false, bit4: false, bit3: false, bit2: false, bit1: false, bit0: false });
    const fld = useMemo(() => compute(bits), [bits]);
    useEffect(() => { report(fld); }, [bits]); // eslint-disable-line

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const flip = (i) => {
      const key = "bit" + i, next = { ...bits, [key]: !bits[key] };
      setBits(next);
      const nf = compute(next);
      event("toggled", `bit${i} (${Math.pow(2, i)}) = ${next[key] ? 1 : 0}`, { response: `value ${nf.value} ${nf.hex}` }, C.blue);
    };

    // eight toggle squares, MSB→LSB
    const CW = 56, GAP = 8, X0 = 60, Y0 = 70, SH = 70;

    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 }}>
          {IDX.map((i, k) => {
            const on = bits["bit" + i], x = X0 + k * (CW + GAP), pv = Math.pow(2, i);
            return (
              <g key={i} onClick={() => flip(i)} style={{ cursor: "pointer" }}>
                <rect x={x} y={Y0} width={CW} height={SH} rx="6" fill={on ? C.teal : C.panel} stroke={on ? C.teal : C.line} strokeWidth="2" />
                <text x={x + CW / 2} y={Y0 + 34} textAnchor="middle" fill={on ? "#06251c" : C.mute} fontSize="22" fontWeight="600" fontFamily="monospace">{on ? 1 : 0}</text>
                <text x={x + CW / 2} y={Y0 + 56} textAnchor="middle" fill={on ? "#06251c" : C.faint} fontSize="11" fontFamily="monospace">{pv}</text>
                <text x={x + CW / 2} y={Y0 - 8} textAnchor="middle" fill={C.faint} fontSize="10" fontFamily="monospace">bit{i}</text>
              </g>
            );
          })}
          <text x={300} y={200} textAnchor="middle" fill={C.ink} fontSize="22" fontWeight="600" fontFamily="monospace">value = {fld.value}</text>
          <text x={300} y={228} textAnchor="middle" fill={C.amber} fontSize="15" fontFamily="monospace">{fld.hex}  ·  {fld.bitsSet} bit{fld.bitsSet === 1 ? "" : "s"} set</text>
          <text x={300} y={252} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">value = Σ bitᵢ · 2ⁱ  (click a bit to flip)</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${C.line}`, color: C.mute, fontSize: 12.5, fontFamily: "monospace" }}>
          Unsigned 8-bit · bit7 is the MSB (128). value = {fld.value} = {fld.hex} · {fld.isEven ? "even" : "odd"}{fld.isPowerOfTwo ? " · power of two" : ""}.
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="value" v={fld.value} d={0} color={C.teal} />
          <StatMeter label="bits set" v={fld.bitsSet} d={0} color={C.blue} />
          <StatMeter label="hex" v={fld.hex} color={C.amber} />
          <StatMeter label="power of two" v={fld.isPowerOfTwo ? "yes" : "no"} color={fld.isPowerOfTwo ? C.teal : C.faint} />
        </div>
      </>
    );
  }

  window.BinaryTutor = K.makeTutor(BinaryFig, { moduleLabel: "Binary-number bench", benchId: "binary" });
})();
