/* punnettlab.jsx — PunnettTutor: the monohybrid Punnett-square bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is
   just the FIGURE. computeFields = window.BenchFields.punnett — the SAME function
   server/benches/punnett.js calls, so client and server fields are identical by
   construction. Follows the gaslawslab.jsx single-figure template. */
(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.punnett(s);

  const GENOTYPES = ["AA", "Aa", "aa"];
  const ALLELES = { AA: ["A", "A"], Aa: ["A", "a"], aa: ["a", "a"] };
  const isDom = (g) => g.indexOf("A") >= 0; // AA or Aa show the dominant trait

  function EnumRow({ label, value, set, options, onPick }) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 9 }}>
        <span style={{ fontSize: 12, color: C.mute, width: 116 }}>{label}</span>
        <div style={{ display: "flex", gap: 6, flex: 1 }}>
          {options.map((o) => {
            const on = o === value;
            return (
              <button key={o} onClick={() => { set(o); onPick && onPick(o); }}
                style={{ flex: 1, padding: "6px 0", borderRadius: 6, cursor: "pointer",
                  fontFamily: "monospace", fontSize: 13, fontWeight: on ? 600 : 400,
                  background: on ? C.teal : C.panel2, color: on ? "#06251c" : C.mute,
                  border: `1px solid ${on ? C.teal : C.line}` }}>{o}</button>
            );
          })}
        </div>
      </div>
    );
  }

  function PunnettFig({ task, setTask, tasks, report, event, done }) {
    const [parent1, setParent1] = useState("Aa");
    const [parent2, setParent2] = useState("aa");
    const fld = useMemo(() => compute({ parent1, parent2 }), [parent1, parent2]);
    useEffect(() => { report(fld); }, [parent1, parent2]); // eslint-disable-line

    const g1 = ALLELES[parent1], g2 = ALLELES[parent2];
    // 2×2 grid: rows = parent1 gametes (top axis), cols = parent2 gametes (left axis).
    const X0 = 230, Y0 = 70, CELL = 90;
    const cells = [];
    for (let r = 0; r < 2; r++) {
      for (let c = 0; c < 2; c++) {
        const geno = [g1[c], g2[r]].sort().join(""); // sorted → AA / Aa / aa
        cells.push({ r, c, geno, dom: isDom(geno) });
      }
    }
    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 + CELL} y={36} textAnchor="middle" fill={C.mute} fontSize="12" fontFamily="monospace">Parent 1: {parent1}</text>
          <text x={X0 - 30} y={Y0 + CELL + 6} textAnchor="middle" fill={C.mute} fontSize="12" fontFamily="monospace" transform={`rotate(-90 ${X0 - 30} ${Y0 + CELL + 6})`}>Parent 2: {parent2}</text>
          {/* gamete headers along the top (parent1) */}
          {[0, 1].map((c) => (
            <text key={"top" + c} x={X0 + c * CELL + CELL / 2} y={Y0 - 10} textAnchor="middle" fill={C.amber} fontSize="15" fontFamily="monospace">{g1[c]}</text>
          ))}
          {/* gamete headers along the left (parent2) */}
          {[0, 1].map((r) => (
            <text key={"left" + r} x={X0 - 16} y={Y0 + r * CELL + CELL / 2 + 5} textAnchor="middle" fill={C.blue} fontSize="15" fontFamily="monospace">{g2[r]}</text>
          ))}
          {/* the four offspring cells */}
          {cells.map((cell, i) => (
            <g key={i}>
              <rect x={X0 + cell.c * CELL} y={Y0 + cell.r * CELL} width={CELL} height={CELL}
                fill={cell.dom ? C.teal : C.crimson} fillOpacity="0.16"
                stroke={C.faint} strokeWidth="1.5" />
              <text x={X0 + cell.c * CELL + CELL / 2} y={Y0 + cell.r * CELL + CELL / 2 + 7}
                textAnchor="middle" fill={C.ink} fontSize="22" fontFamily="monospace">{cell.geno}</text>
            </g>
          ))}
          <text x={X0 + CELL} y={Y0 + 2 * CELL + 28} textAnchor="middle" fill={C.mute} fontSize="12" fontFamily="monospace">
            dominant = AA + Aa = {fmt(fld.fracDominant * 100, 0)}% · recessive = {fmt(fld.fracRecessive * 100, 0)}%
          </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 }}>
          Each parent passes ONE allele at random. {fld.is3to1 ? "▸ classic 3:1 phenotype ratio." : fld.allDominant ? "▸ every offspring shows the dominant trait." : "Pick parent genotypes to shape the offspring ratios."}
        </div>
        <EnumRow label="Parent 1" value={parent1} set={setParent1} options={GENOTYPES}
          onPick={(o) => event("crossed", `Parent 1 = ${o}`, { response: `${fmt(fld.fracDominant * 100, 0)}% dominant` }, C.amber)} />
        <EnumRow label="Parent 2" value={parent2} set={setParent2} options={GENOTYPES}
          onPick={(o) => event("crossed", `Parent 2 = ${o}`, { response: `${fmt(fld.fracDominant * 100, 0)}% dominant` }, C.blue)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(5,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="% dominant" v={fld.fracDominant * 100} d={0} unit="%" color={C.teal} />
          <StatMeter label="% recessive" v={fld.fracRecessive * 100} d={0} unit="%" color={C.crimson} />
          <StatMeter label="AA" v={fld.fracAA} d={2} color={C.blue} />
          <StatMeter label="Aa" v={fld.fracAa} d={2} color={C.amber} />
          <StatMeter label="aa" v={fld.fracaa} d={2} color={C.gold} />
        </div>
      </>
    );
  }

  window.PunnettTutor = K.makeTutor(PunnettFig, { moduleLabel: "Punnett-square bench", benchId: "punnett" });
})();
