/* molaritylab.jsx — MolarityTutor: the molarity & dilution bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.molarity — the SAME function server/benches/molarity.js
   calls, so client and server fields are identical by construction. Mirrors gaslawslab.jsx:
   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.molarity(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 MolarityFig({ task, setTask, tasks, report, event, done }) {
    const [stockConc, setStockConc] = useState(2);
    const [stockVol, setStockVol] = useState(50);
    const [waterAdded, setWaterAdded] = useState(50);
    const fld = useMemo(() => compute({ stockConc, stockVol, waterAdded }), [stockConc, stockVol, waterAdded]);
    useEffect(() => { report(fld); }, [stockConc, stockVol, waterAdded]); // eslint-disable-line

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

    // beaker geometry: three beakers across the canvas. Fill height ∝ volume (vs 500 mL max),
    // color opacity ∝ concentration (vs 5 M max). Stock + water → final (combined volume, diluted).
    const beaker = (cx, w, h, vol, conc, maxVol, isWater) => {
      const bx = cx - w / 2, by = 30, bh = 200;
      const fillFrac = Math.min(1, vol / maxVol);
      const fh = fillFrac * (bh - 10);
      const fy = by + (bh - fh);
      const op = isWater ? 0.18 : (0.12 + Math.min(1, conc / 5) * 0.78);
      const col = isWater ? C.blue : C.teal;
      return (
        <g>
          <rect x={bx} y={by} width={w} height={bh} fill="none" stroke={C.faint} strokeWidth="1.5" rx="4" />
          <rect x={bx + 2} y={fy} width={w - 4} height={fh} fill={col} opacity={op} rx="2" />
        </g>
      );
    };

    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 }}>
          {/* stock beaker */}
          {beaker(110, 90, 200, stockVol, stockConc, 200, false)}
          <text x={110} y={252} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">stock</text>
          <text x={110} y={268} textAnchor="middle" fill={C.teal} fontSize="11" fontFamily="monospace">{fmt(stockConc)} M · {fmt(stockVol)} mL</text>
          {/* water beaker */}
          {beaker(300, 90, 200, waterAdded, 0, 500, true)}
          <text x={300} y={252} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">water</text>
          <text x={300} y={268} textAnchor="middle" fill={C.blue} fontSize="11" fontFamily="monospace">+{fmt(waterAdded)} mL</text>
          {/* plus / arrow */}
          <text x={205} y={140} textAnchor="middle" fill={C.mute} fontSize="20" fontFamily="monospace">+</text>
          <text x={400} y={140} textAnchor="middle" fill={C.mute} fontSize="20" fontFamily="monospace">→</text>
          {/* final beaker */}
          {beaker(500, 110, 200, fld.finalVol, fld.finalConc, 700, false)}
          <text x={500} y={252} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">diluted</text>
          <text x={500} y={268} textAnchor="middle" fill={C.ink} fontSize="12" fontFamily="monospace">C₂ = {fmt(fld.finalConc)} M</text>
          <text x={500} y={20} textAnchor="middle" fill={C.amber} fontSize="11" fontFamily="monospace">{fmt(fld.finalVol)} mL · {fmt(fld.dilutionFactor)}×</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.isDilute ? C.teal : C.line}`, color: fld.isDilute ? C.teal : C.mute, fontSize: 12.5 }}>
          C₁V₁ = C₂V₂ · C₂ = {fmt(stockConc)}×{fmt(stockVol)}/{fmt(fld.finalVol)} = {fmt(fld.finalConc)} M. {fld.isDilute ? "Dilute (< 1 M)." : "Add water (↑) to dilute below 1 M."}
        </div>
        <Slider label="stock conc C₁" value={stockConc} set={setStockConc} min={0.1} max={5} step={0.1} unit="M" color={C.teal} onUp={() => event("adjusted", `Set C₁ = ${fmt(stockConc)} M`, { response: `C₂ ${fmt(fld.finalConc)} M` }, C.teal)} />
        <Slider label="stock vol V₁" value={stockVol} set={setStockVol} min={10} max={200} step={5} unit="mL" color={C.gold} onUp={() => event("adjusted", `Set V₁ = ${fmt(stockVol)} mL`, { response: `C₂ ${fmt(fld.finalConc)} M` }, C.gold)} />
        <Slider label="water added" value={waterAdded} set={setWaterAdded} min={0} max={500} step={5} unit="mL" color={C.blue} onUp={() => event("adjusted", `Added ${fmt(waterAdded)} mL water`, { response: `C₂ ${fmt(fld.finalConc)} M` }, C.blue)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="final conc C₂" v={fld.finalConc} d={3} unit="M" color={fld.isDilute ? C.teal : C.amber} />
          <StatMeter label="moles solute" v={fld.moles} d={3} unit="mol" color={C.blue} />
          <StatMeter label="dilution factor" v={fld.dilutionFactor} d={2} unit="×" color={C.gold} />
          <StatMeter label="final vol" v={fld.finalVol} d={1} unit="mL" color={C.crimson} />
        </div>
      </>
    );
  }

  window.MolarityTutor = K.makeTutor(MolarityFig, { moduleLabel: "Molarity & dilution bench", benchId: "molarity" });
})();
