/* gaslawslab.jsx — GasLawsTutor: the ideal-gas piston bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.gasLaws — the SAME function server/benches/gaslaws.js
   calls, so client and server fields are identical by construction. This is the TEMPLATE
   every "extra" single-figure lab follows: sliders → BenchFields.fn(state) → report + meters. */
(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.gasLaws(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 GasFig({ task, setTask, tasks, report, event, done }) {
    const [moles, setMoles] = useState(1);
    const [tempK, setTempK] = useState(300);
    const [volumeL, setVolumeL] = useState(24.6);
    const fld = useMemo(() => compute({ moles, tempK, volumeL }), [moles, tempK, volumeL]);
    useEffect(() => { report(fld); }, [moles, tempK, volumeL]); // eslint-disable-line

    // piston: cylinder 0..50 L maps to x; particles ∝ moles; jitter ∝ temperature.
    const X0 = 70, X1 = 540, AY0 = 60, AY1 = 250;
    const pistonX = X0 + (volumeL / 50) * (X1 - X0);
    const nDots = Math.max(4, Math.round(moles * 9));
    const heat = Math.min(1, (tempK - 100) / 900);
    const dots = [];
    for (let i = 0; i < nDots; i++) {
      const gx = X0 + 14 + ((i * 53) % Math.max(1, pistonX - X0 - 28));
      const gy = AY0 + 14 + ((i * 37) % (AY1 - AY0 - 28));
      dots.push({ x: gx, y: gy });
    }
    const t = tasks.find((x) => x.id === task) || tasks[0];
    const press = fld.pressure;

    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 }}>
          {/* cylinder */}
          <rect x={X0} y={AY0} width={X1 - X0} height={AY1 - AY0} fill="none" stroke={C.faint} strokeWidth="1.5" rx="4" />
          {/* gas region */}
          <rect x={X0} y={AY0} width={pistonX - X0} height={AY1 - AY0} fill={C.teal} opacity={0.06 + heat * 0.12} />
          {dots.map((d, i) => <circle key={i} cx={d.x} cy={d.y} r={3} fill={heat > 0.6 ? C.crimson : C.teal} opacity="0.85" />)}
          {/* piston */}
          <rect x={pistonX} y={AY0 - 6} width={14} height={AY1 - AY0 + 12} fill={C.gold} opacity="0.85" />
          <line x1={pistonX + 14} y1={(AY0 + AY1) / 2} x2={X1 + 30} y2={(AY0 + AY1) / 2} stroke={C.gold} strokeWidth="4" />
          <text x={X0 + 6} y={AY0 - 8} fill={C.mute} fontSize="11" fontFamily="monospace">V = {fmt(volumeL)} L · T = {Math.round(tempK)} K · n = {fmt(moles)} mol</text>
          <text x={(X0 + pistonX) / 2} y={(AY0 + AY1) / 2 + 4} textAnchor="middle" fill={C.ink} fontSize="13" fontFamily="monospace">P = {fmt(press)} atm</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${press > 8 ? C.crimson : C.line}`, color: press > 8 ? C.crimson : C.mute, fontSize: 12.5 }}>
          PV = nRT · P = nRT/V = {fmt(press)} atm. {press > 8 ? "⚠ very high pressure." : "Compress (↓V) or heat (↑T) to raise pressure."}
        </div>
        <Slider label="amount n" value={moles} set={setMoles} min={0.1} max={5} step={0.1} unit="mol" color={C.blue} onUp={() => event("adjusted", `Set n = ${fmt(moles)} mol`, { response: `P ${fmt(fld.pressure)} atm` }, C.blue)} />
        <Slider label="temperature T" value={tempK} set={setTempK} min={100} max={1000} step={5} unit="K" color={C.crimson} onUp={() => event("adjusted", `Set T = ${Math.round(tempK)} K`, { response: `P ${fmt(fld.pressure)} atm` }, C.crimson)} />
        <Slider label="volume V" value={volumeL} set={setVolumeL} min={1} max={50} step={0.1} unit="L" color={C.gold} onUp={() => event("adjusted", `Set V = ${fmt(volumeL)} L`, { response: `P ${fmt(fld.pressure)} atm` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="pressure P" v={fld.pressure} d={2} unit="atm" color={press > 8 ? C.crimson : C.teal} />
          <StatMeter label="nRT" v={fld.nRT} unit="L·atm" color={C.blue} />
          <StatMeter label="P·V" v={fld.pvProduct} unit="L·atm" color={C.amber} />
          <StatMeter label="T" v={fld.tempK} d={0} unit="K" color={C.crimson} />
        </div>
      </>
    );
  }

  window.GasLawsTutor = K.makeTutor(GasFig, { moduleLabel: "Gas-laws bench", benchId: "gaslaws" });
})();
