/* thermochemlab.jsx — ThermochemTutor: the reaction-enthalpy bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is
   just the FIGURE. compute = window.BenchFields.thermochem — the SAME function
   server/benches/thermochem.js calls, so client and server fields are identical by
   construction. Mirrors gaslawslab.jsx (the single-figure lab 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.thermochem(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 ThermochemFig({ task, setTask, tasks, report, event, done }) {
    const [hfReactants, setHfReactants] = useState(0);
    const [hfProducts, setHfProducts] = useState(-200);
    const [moles, setMoles] = useState(1);
    const fld = useMemo(() => compute({ hfReactants, hfProducts, moles }), [hfReactants, hfProducts, moles]);
    useEffect(() => { report(fld); }, [hfReactants, hfProducts, moles]); // eslint-disable-line

    // energy diagram: enthalpy (kJ) -500..500 maps to y (high enthalpy = high on plot).
    const X0 = 80, X1 = 540, AY0 = 50, AY1 = 250;
    const yFor = (h) => AY1 - ((h + 500) / 1000) * (AY1 - AY0);
    const yR = yFor(hfReactants), yP = yFor(hfProducts);
    const xR0 = X0 + 20, xR1 = X0 + 160;          // reactants level (left)
    const xP0 = X1 - 160, xP1 = X1 - 20;          // products level (right)
    const arrowX = (xR1 + xP0) / 2;
    const exo = fld.isExothermic;
    const arrowColor = exo ? C.teal : C.crimson;
    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 }}>
          {/* axes: reaction coordinate (x) and enthalpy (y) */}
          <line x1={X0} y1={AY0 - 6} x2={X0} y2={AY1 + 16} stroke={C.faint} strokeWidth="1.5" />
          <line x1={X0} y1={AY1 + 16} x2={X1 + 10} y2={AY1 + 16} stroke={C.faint} strokeWidth="1.5" />
          <text x={X0 - 6} y={AY0 - 10} fill={C.mute} fontSize="11" textAnchor="end" fontFamily="monospace">H (kJ)</text>
          <text x={X1 + 10} y={AY1 + 30} fill={C.mute} fontSize="11" textAnchor="end" fontFamily="monospace">reaction coordinate →</text>
          {/* reactants level */}
          <line x1={xR0} y1={yR} x2={xR1} y2={yR} stroke={C.blue} strokeWidth="3.5" />
          <text x={xR0} y={yR - 8} fill={C.blue} fontSize="12" fontFamily="monospace">reactants {fmt(hfReactants)}</text>
          {/* products level */}
          <line x1={xP0} y1={yP} x2={xP1} y2={yP} stroke={C.gold} strokeWidth="3.5" />
          <text x={xP1} y={yP - 8} fill={C.gold} fontSize="12" textAnchor="end" fontFamily="monospace">products {fmt(hfProducts)}</text>
          {/* connectors from each level toward the ΔH arrow */}
          <line x1={xR1} y1={yR} x2={arrowX} y2={yR} stroke={C.faint} strokeWidth="1" strokeDasharray="3 3" />
          <line x1={xP0} y1={yP} x2={arrowX} y2={yP} stroke={C.faint} strokeWidth="1" strokeDasharray="3 3" />
          {/* ΔH arrow (down = exothermic, up = endothermic) */}
          <line x1={arrowX} y1={yR} x2={arrowX} y2={yP} stroke={arrowColor} strokeWidth="2.5" />
          <polygon points={`${arrowX - 5},${yP - (yP > yR ? 9 : -9)} ${arrowX + 5},${yP - (yP > yR ? 9 : -9)} ${arrowX},${yP}`} fill={arrowColor} />
          <text x={arrowX + 8} y={(yR + yP) / 2 + 4} fill={arrowColor} fontSize="13" fontFamily="monospace">ΔH = {fmt(fld.deltaH)} kJ</text>
          <text x={(X0 + X1) / 2} y={AY0 - 14} textAnchor="middle" fill={exo ? C.teal : C.crimson} fontSize="13" fontFamily="monospace">{exo ? "exothermic ▼" : "endothermic ▲"}</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 }}>
          ΔH = ΣHf(products) − ΣHf(reactants) = {fmt(fld.deltaH)} kJ · {exo ? `releases ${fmt(fld.energyReleased)} kJ/mol (exothermic)` : `absorbs ${fmt(-fld.energyReleased)} kJ/mol (endothermic)`} · total q = {fmt(fld.totalEnergy)} kJ.
        </div>
        <Slider label="ΣΔHf reactants" value={hfReactants} set={setHfReactants} min={-500} max={500} step={10} unit="kJ" color={C.blue} onUp={() => event("adjusted", `Set ΣΔHf(reactants) = ${fmt(hfReactants)} kJ`, { response: `ΔH ${fmt(fld.deltaH)} kJ` }, C.blue)} />
        <Slider label="ΣΔHf products" value={hfProducts} set={setHfProducts} min={-500} max={500} step={10} unit="kJ" color={C.gold} onUp={() => event("adjusted", `Set ΣΔHf(products) = ${fmt(hfProducts)} kJ`, { response: `ΔH ${fmt(fld.deltaH)} kJ` }, C.gold)} />
        <Slider label="moles reacted" value={moles} set={setMoles} min={0.5} max={10} step={0.5} unit="mol" color={C.crimson} onUp={() => event("adjusted", `Set moles = ${fmt(moles)} mol`, { response: `q ${fmt(fld.totalEnergy)} kJ` }, C.crimson)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="ΔH" v={fld.deltaH} d={1} unit="kJ" color={exo ? C.teal : C.crimson} />
          <StatMeter label="energy released" v={fld.energyReleased} d={1} unit="kJ" color={C.teal} />
          <StatMeter label="total energy q" v={fld.totalEnergy} d={1} unit="kJ" color={C.amber} />
          <StatMeter label="moles" v={fld.moles} d={1} unit="mol" color={C.blue} />
        </div>
      </>
    );
  }

  window.ThermochemTutor = K.makeTutor(ThermochemFig, { moduleLabel: "Thermochemistry bench", benchId: "thermochem" });
})();
