/* stoichiometrylab.jsx — StoichiometryTutor: the 2A + B → 2C reaction bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just
   the FIGURE. compute = window.BenchFields.stoichiometry — the SAME function
   server/benches/stoichiometry.js calls, so client and server fields are identical by
   construction. Follows the single-figure lab TEMPLATE (gaslawslab.jsx). */
(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.stoichiometry(s);

  function Slider({ label, value, set, min, max, step, unit, 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}{unit ? ` ${unit}` : ""}</span>
      </div>
    );
  }

  function StoichiometryFig({ task, setTask, tasks, report, event, done }) {
    const [molA, setMolA] = useState(4);
    const [molB, setMolB] = useState(3);
    const [actualYield, setActualYield] = useState(3);
    const fld = useMemo(() => compute({ molA, molB, actualYield }), [molA, molB, actualYield]);
    useEffect(() => { report(fld); }, [molA, molB, actualYield]); // eslint-disable-line

    const t = tasks.find((x) => x.id === task) || tasks[0];

    // three stacks of "moles": A, B, C(theoretical). Heights ∝ moles, capped to plot area.
    const MAXMOL = 10, PLOT_Y0 = 40, PLOT_Y1 = 240, PLOT_H = PLOT_Y1 - PLOT_Y0;
    const h = (m) => Math.max(2, Math.min(1, m / MAXMOL) * PLOT_H);
    const theo = fld.theoreticalYield;
    const limA = fld.limitingIsA;
    const stacks = [
      { x: 100, m: molA, label: "A", color: limA ? C.crimson : C.teal, lim: limA },
      { x: 230, m: molB, label: "B", color: !limA ? C.crimson : C.blue, lim: !limA },
      { x: 360, m: theo, label: "C (theo)", color: C.gold, lim: false },
    ];
    const W = 64;

    // theoretical vs actual yield mini-bars (right panel)
    const YX = 470, YW = 90, ymax = Math.max(theo, actualYield, 1);
    const yh = (m) => Math.max(2, (m / ymax) * PLOT_H);

    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={20} y={24} fill={C.mute} fontSize="12" fontFamily="monospace">2A + B → 2C · limiting: {limA ? "A" : "B"} · theo {fmt(theo)} mol C</text>
          {/* baseline */}
          <line x1={60} y1={PLOT_Y1} x2={420} y2={PLOT_Y1} stroke={C.faint} strokeWidth="1.5" />
          {stacks.map((s, i) => (
            <g key={i}>
              <rect x={s.x} y={PLOT_Y1 - h(s.m)} width={W} height={h(s.m)} fill={s.color} opacity={s.lim ? 0.9 : 0.6} stroke={s.lim ? C.crimson : "none"} strokeWidth={s.lim ? 2 : 0} rx="3" />
              <text x={s.x + W / 2} y={PLOT_Y1 + 16} textAnchor="middle" fill={C.ink} fontSize="12" fontFamily="monospace">{s.label}</text>
              <text x={s.x + W / 2} y={PLOT_Y1 - h(s.m) - 6} textAnchor="middle" fill={s.color} fontSize="11" fontFamily="monospace">{fmt(s.m)}</text>
              {s.lim ? <text x={s.x + W / 2} y={PLOT_Y0 - 6} textAnchor="middle" fill={C.crimson} fontSize="10" fontFamily="monospace">limiting</text> : null}
            </g>
          ))}
          {/* excess marker on the non-limiting reactant */}
          <text x={260} y={PLOT_Y0 + 6} textAnchor="middle" fill={C.mute} fontSize="10" fontFamily="monospace">excess {fmt(fld.excessMoles)} mol</text>
          {/* theoretical vs actual yield bars */}
          <line x1={YX - 6} y1={PLOT_Y1} x2={YX + 2 * YW + 10} y2={PLOT_Y1} stroke={C.faint} strokeWidth="1.5" />
          <rect x={YX} y={PLOT_Y1 - yh(theo)} width={YW / 2} height={yh(theo)} fill={C.gold} opacity="0.5" rx="2" />
          <rect x={YX + YW / 2 + 8} y={PLOT_Y1 - yh(actualYield)} width={YW / 2} height={yh(actualYield)} fill={C.teal} opacity="0.85" rx="2" />
          <text x={YX + YW / 4} y={PLOT_Y1 + 16} textAnchor="middle" fill={C.mute} fontSize="10" fontFamily="monospace">theo</text>
          <text x={YX + YW / 2 + 8 + YW / 4} y={PLOT_Y1 + 16} textAnchor="middle" fill={C.mute} fontSize="10" fontFamily="monospace">actual</text>
          <text x={YX + YW / 2 + 4} y={PLOT_Y0 - 6} textAnchor="middle" fill={C.ink} fontSize="11" fontFamily="monospace">{fmt(fld.percentYield)}%</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.isComplete ? C.teal : C.line}`, color: C.mute, fontSize: 12.5 }}>
          theoretical yield = 2·min(molA/2, molB/1) = {fmt(theo)} mol C. {limA ? "A" : "B"} is limiting; {fmt(fld.excessMoles)} mol of the other is left over. {fld.isComplete ? "✓ reached theoretical yield." : "Raise the actual yield toward theoretical to lift % yield."}
        </div>
        <Slider label="moles of A" value={molA} set={setMolA} min={0.5} max={10} step={0.5} unit="mol" color={C.teal} onUp={() => event("adjusted", `Set A = ${fmt(molA)} mol`, { response: `theo ${fmt(fld.theoreticalYield)} mol C` }, C.teal)} />
        <Slider label="moles of B" value={molB} set={setMolB} min={0.5} max={10} step={0.5} unit="mol" color={C.blue} onUp={() => event("adjusted", `Set B = ${fmt(molB)} mol`, { response: `limiting ${fld.limitingIsA ? "A" : "B"}` }, C.blue)} />
        <Slider label="actual yield" value={actualYield} set={setActualYield} min={0} max={20} step={0.5} unit="mol" color={C.gold} onUp={() => event("adjusted", `Set actual yield = ${fmt(actualYield)} mol`, { response: `${fmt(fld.percentYield)}% yield` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="theoretical yield" v={fld.theoreticalYield} unit="mol C" color={C.gold} />
          <StatMeter label="% yield" v={fld.percentYield} d={0} unit="%" color={fld.percentYield >= 90 ? C.teal : C.blue} />
          <StatMeter label="excess" v={fld.excessMoles} unit="mol" color={C.mute} />
          <StatMeter label="actual yield" v={fld.actualYield} unit="mol C" color={C.teal} />
        </div>
      </>
    );
  }

  window.StoichiometryTutor = K.makeTutor(StoichiometryFig, { moduleLabel: "Stoichiometry bench", benchId: "stoichiometry" });
})();
