/* dihybridlab.jsx — DihybridTutor: the dihybrid-cross bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.dihybrid — the SAME function server/benches/dihybrid.js
   calls, so client and server fields are identical by construction. The two-gene sibling of
   punnettlab.jsx; 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.dihybrid(s);

  const GENOTYPES = ["AaBb", "AABB", "aabb", "AaBB", "AABb", "Aabb", "aaBb"];
  // Four gametes for a 2-gene genotype "XxYy": each gene contributes one of its two alleles.
  const gametes = (g) => {
    const a = [g[0], g[1]], b = [g[2], g[3]];
    const out = [];
    for (let i = 0; i < 2; i++) for (let j = 0; j < 2; j++) out.push(a[i] + b[j]);
    return out; // 4 gametes
  };
  // Phenotype class of an offspring genotype string (two A alleles + two B alleles, any order).
  const phenoClass = (geno) => {
    const domA = geno.indexOf("A") >= 0;     // A_ vs aa
    const domB = geno.indexOf("B") >= 0;     // B_ vs bb
    if (domA && domB) return 9;              // both dominant
    if (domA && !domB) return "3a";          // A_bb
    if (!domA && domB) return "3b";          // aaB_
    return 1;                                // aabb
  };
  const CLASS_COLOR = (cls) => cls === 9 ? C.teal : cls === "3a" ? C.amber : cls === "3b" ? C.blue : C.crimson;

  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, flexWrap: "wrap" }}>
          {options.map((o) => {
            const on = o === value;
            return (
              <button key={o} onClick={() => { set(o); onPick && onPick(o); }}
                style={{ flex: "1 0 auto", padding: "6px 8px", 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 DihybridFig({ task, setTask, tasks, report, event, done }) {
    const [parent1, setParent1] = useState("AaBb");
    const [parent2, setParent2] = useState("AaBb");
    const fld = useMemo(() => compute({ parent1, parent2 }), [parent1, parent2]);
    useEffect(() => { report(fld); }, [parent1, parent2]); // eslint-disable-line

    const g1 = gametes(parent1), g2 = gametes(parent2); // top axis = p1, left axis = p2
    // 4×4 grid of offspring; each cell combines a p1 gamete (col) and a p2 gamete (row).
    const X0 = 250, Y0 = 56, CELL = 52;
    const sortGeno = (s) => {
      const a = [s[0], s[2]].filter((x) => x.toLowerCase() === "a").sort((x, y) => (x === "A" ? -1 : 1)).join("");
      const b = [s[1], s[3]].filter((x) => x.toLowerCase() === "b").sort((x, y) => (x === "B" ? -1 : 1)).join("");
      return a + b; // e.g. "AaBb"
    };
    const cells = [];
    for (let r = 0; r < 4; r++) {
      for (let c = 0; c < 4; c++) {
        const raw = g1[c] + g2[r];            // 2 A-locus alleles + 2 B-locus alleles interleaved
        const geno = sortGeno(g1[c][0] + g2[r][0] + g1[c][1] + g2[r][1]);
        cells.push({ r, c, geno, cls: phenoClass(raw) });
      }
    }
    const t = tasks.find((x) => x.id === task) || tasks[0];

    // 9:3:3:1 fraction bars
    const bars = [
      { key: "frac9", label: "both dom (9)", v: fld.frac9, color: C.teal },
      { key: "frac3a", label: "A_bb (3)", v: fld.frac3a, color: C.amber },
      { key: "frac3b", label: "aaB_ (3)", v: fld.frac3b, color: C.blue },
      { key: "frac1", label: "aabb (1)", v: fld.frac1, color: C.crimson },
    ];
    const BX = 30, BY = 70, BW = 180, ROW = 40;

    return (
      <>
        <TaskStrip tasks={tasks} cur={task} setCur={setTask} done={done} goal={t && t.goal} />
        <svg viewBox="0 0 600 340" style={{ width: "100%", background: SVG_BG, border: `1px solid ${C.line}`, borderRadius: 8 }}>
          {/* phenotype-fraction bars on the left */}
          <text x={BX} y={BY - 14} fill={C.mute} fontSize="11" fontFamily="monospace">phenotype fractions</text>
          {bars.map((b, i) => (
            <g key={b.key}>
              <text x={BX} y={BY + i * ROW + 11} fill={C.mute} fontSize="10.5" fontFamily="monospace">{b.label}</text>
              <rect x={BX} y={BY + i * ROW + 16} width={BW} height={12} fill={C.panel2} stroke={C.line} strokeWidth="0.75" rx="2" />
              <rect x={BX} y={BY + i * ROW + 16} width={Math.max(0, b.v) * BW} height={12} fill={b.color} opacity="0.85" rx="2" />
              <text x={BX + BW + 6} y={BY + i * ROW + 26} fill={b.color} fontSize="11" fontFamily="monospace">{fmt(b.v * 100, 0)}%</text>
            </g>
          ))}

          {/* axis labels */}
          <text x={X0 + 2 * CELL} y={28} textAnchor="middle" fill={C.mute} fontSize="12" fontFamily="monospace">Parent 1: {parent1}</text>
          <text x={X0 - 34} y={Y0 + 2 * CELL} textAnchor="middle" fill={C.mute} fontSize="12" fontFamily="monospace" transform={`rotate(-90 ${X0 - 34} ${Y0 + 2 * CELL})`}>Parent 2: {parent2}</text>
          {/* gamete headers along the top (parent1) */}
          {g1.map((gm, c) => (
            <text key={"top" + c} x={X0 + c * CELL + CELL / 2} y={Y0 - 8} textAnchor="middle" fill={C.amber} fontSize="12" fontFamily="monospace">{gm}</text>
          ))}
          {/* gamete headers along the left (parent2) */}
          {g2.map((gm, r) => (
            <text key={"left" + r} x={X0 - 16} y={Y0 + r * CELL + CELL / 2 + 4} textAnchor="middle" fill={C.blue} fontSize="12" fontFamily="monospace">{gm}</text>
          ))}
          {/* the 16 offspring cells, shaded by phenotype class */}
          {cells.map((cell, i) => (
            <g key={i}>
              <rect x={X0 + cell.c * CELL} y={Y0 + cell.r * CELL} width={CELL} height={CELL}
                fill={CLASS_COLOR(cell.cls)} fillOpacity="0.18" stroke={C.faint} strokeWidth="1" />
              <text x={X0 + cell.c * CELL + CELL / 2} y={Y0 + cell.r * CELL + CELL / 2 + 4}
                textAnchor="middle" fill={C.ink} fontSize="12" fontFamily="monospace">{cell.geno}</text>
            </g>
          ))}
          <text x={X0 + 2 * CELL} y={Y0 + 4 * CELL + 22} textAnchor="middle" fill={C.mute} fontSize="11.5" fontFamily="monospace">
            {fld.is9331 ? "▸ classic 9:3:3:1 ratio" : fld.allDominant ? "▸ all offspring show both dominant traits" : "ratio: " + fmt(fld.frac9 * 16, 1) + " : " + fmt(fld.frac3a * 16, 1) + " : " + fmt(fld.frac3b * 16, 1) + " : " + fmt(fld.frac1 * 16, 1)}
          </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 per gene at random; the two genes assort independently. {fld.is9331 ? "▸ classic 9:3:3:1 phenotype ratio." : fld.allDominant ? "▸ every offspring shows both dominant traits." : "Pick parent genotypes to shape the offspring classes."}
        </div>
        <EnumRow label="Parent 1" value={parent1} set={setParent1} options={GENOTYPES}
          onPick={(o) => event("crossed", `Parent 1 = ${o}`, { response: `${fmt(fld.frac9 * 100, 0)}% both-dominant` }, C.amber)} />
        <EnumRow label="Parent 2" value={parent2} set={setParent2} options={GENOTYPES}
          onPick={(o) => event("crossed", `Parent 2 = ${o}`, { response: `${fmt(fld.frac9 * 100, 0)}% both-dominant` }, C.blue)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="both dom (9)" v={fld.frac9 * 100} d={0} unit="%" color={C.teal} />
          <StatMeter label="A_bb (3)" v={fld.frac3a * 100} d={0} unit="%" color={C.amber} />
          <StatMeter label="aaB_ (3)" v={fld.frac3b * 100} d={0} unit="%" color={C.blue} />
          <StatMeter label="aabb (1)" v={fld.frac1 * 100} d={0} unit="%" color={C.crimson} />
        </div>
      </>
    );
  }

  window.DihybridTutor = K.makeTutor(DihybridFig, { moduleLabel: "Dihybrid cross bench", benchId: "dihybrid" });
})();
