/* hardyweinberglab.jsx — HardyWeinbergTutor: the Hardy–Weinberg equilibrium bench.
   Built on window.BenchKit (harness) + window.BenchFields (shared field math), so this
   file is just the FIGURE. computeFields = window.BenchFields.hardyWeinberg — the SAME
   function server/benches/hardyweinberg.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.hardyWeinberg(s);

  function Slider({ label, value, set, min, max, step, color, onUp }) {
    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: 64, textAlign: "right" }}>{value}</span>
      </div>
    );
  }

  function HardyFig({ task, setTask, tasks, report, event, done }) {
    const [p, setP] = useState(0.3);
    const fld = useMemo(() => compute({ p }), [p]);
    useEffect(() => { report(fld); }, [p]); // eslint-disable-line

    // stacked area of p² / 2pq / q² as p sweeps 0→1, with current p marked.
    const PX0 = 70, PX1 = 530, PY0 = 50, PY1 = 250;
    const x = (pp) => PX0 + pp * (PX1 - PX0);
    const y = (frac) => PY1 - frac * (PY1 - PY0);
    const aaPts = [], domPts = []; // aa = q² area; AA boundary = top of p²
    const STEPS = 50;
    for (let i = 0; i <= STEPS; i++) {
      const pp = i / STEPS, qq = 1 - pp;
      aaPts.push(`${x(pp).toFixed(1)},${y(qq * qq).toFixed(1)}`);       // q² band (bottom)
      domPts.push(`${x(pp).toFixed(1)},${y(qq * qq + 2 * pp * qq).toFixed(1)}`); // q² + 2pq (top of het band)
    }
    // closed polygons for the three stacked bands.
    const base = `${x(1).toFixed(1)},${y(0).toFixed(1)} ${x(0).toFixed(1)},${y(0).toFixed(1)}`;
    const aaPoly = aaPts.join(" ") + " " + base;
    const hetPoly = domPts.join(" ") + " " + aaPts.slice().reverse().join(" ");
    const topPts = [`${x(0).toFixed(1)},${y(1).toFixed(1)}`, `${x(1).toFixed(1)},${y(1).toFixed(1)}`];
    const aaTop = `${x(1).toFixed(1)},${y(1).toFixed(1)} ${x(0).toFixed(1)},${y(1).toFixed(1)}`;
    const domPoly = domPts.join(" ") + " " + aaTop; // p² band fills to the top (total = 1)
    const cx = x(p);
    const t = tasks.find((z) => z.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 }}>
          {/* stacked bands: aa (bottom), Aa (middle), AA (top) */}
          <polygon points={aaPoly} fill={C.gold} fillOpacity="0.45" />
          <polygon points={hetPoly} fill={C.amber} fillOpacity="0.45" />
          <polygon points={domPoly} fill={C.blue} fillOpacity="0.4" />
          {/* band labels */}
          <text x={PX0 + 8} y={y(0.06)} fill={C.gold} fontSize="11" fontFamily="monospace">aa = q²</text>
          <text x={(PX0 + PX1) / 2 - 20} y={y(0.5)} fill={C.amber} fontSize="11" fontFamily="monospace">Aa = 2pq</text>
          <text x={PX1 - 70} y={y(0.94)} fill={C.blue} fontSize="11" fontFamily="monospace">AA = p²</text>
          {/* axes */}
          <line x1={PX0} y1={PY1} x2={PX1} y2={PY1} stroke={C.faint} strokeWidth="1.5" />
          <line x1={PX0} y1={PY0} x2={PX0} y2={PY1} stroke={C.faint} strokeWidth="1.5" />
          <text x={PX0} y={PY1 + 16} textAnchor="start" fill={C.faint} fontSize="10" fontFamily="monospace">p = 0</text>
          <text x={PX1} y={PY1 + 16} textAnchor="end" fill={C.faint} fontSize="10" fontFamily="monospace">p = 1</text>
          {/* current p marker */}
          <line x1={cx} y1={PY0} x2={cx} y2={PY1} stroke={C.ink} strokeWidth="1.5" />
          <circle cx={cx} cy={PY0} r={4} fill={C.ink} />
          <text x={cx} y={PY0 - 8} textAnchor="middle" fill={C.ink} fontSize="11" fontFamily="monospace">p = {fmt(p, 2)}</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 }}>
          p² + 2pq + q² = 1. {fld.hetMax ? "▸ p = 0.5: heterozygotes (2pq) are maximal." : fld.recessiveRare ? "▸ recessive phenotype is rare (q² ≤ 0.04)." : "Slide p to reshape the genotype frequencies."}
        </div>
        <Slider label="dominant freq p" value={p} set={setP} min={0} max={1} step={0.01} color={C.blue} onUp={() => event("adjusted", `Set p = ${fmt(p, 2)}`, { response: `Aa ${fmt(fld.freqAa, 2)}` }, C.blue)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(5,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="p" v={fld.p} d={2} color={C.blue} />
          <StatMeter label="q" v={fld.q} d={2} color={C.crimson} />
          <StatMeter label="AA = p²" v={fld.freqAA} d={2} color={C.blue} />
          <StatMeter label="Aa = 2pq" v={fld.freqAa} d={2} color={C.amber} />
          <StatMeter label="aa = q²" v={fld.freqaa} d={2} color={C.gold} />
        </div>
      </>
    );
  }

  window.HardyWeinbergTutor = K.makeTutor(HardyFig, { moduleLabel: "Hardy–Weinberg bench", benchId: "hardyweinberg" });
})();
