/* enzymeslab.jsx — EnzymesTutor: the Michaelis–Menten enzyme-kinetics bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just
   the FIGURE. compute = window.BenchFields.enzymes — the SAME function server/benches/enzymes.js
   calls, so client and server fields are identical by construction. Follows the gaslawslab.jsx
   TEMPLATE: 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.enzymes(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 EnzymesFig({ task, setTask, tasks, report, event, done }) {
    const [subConc, setSubConc] = useState(5);
    const [Vmax, setVmax] = useState(100);
    const [Km, setKm] = useState(5);
    const fld = useMemo(() => compute({ subConc, Vmax, Km }), [subConc, Vmax, Km]);
    useEffect(() => { report(fld); }, [subConc, Vmax, Km]); // eslint-disable-line

    // plot: [S] on x (0..20 mM), v on y (0..Vmax). Curve v = Vmax·[S]/(Km+[S]).
    const X0 = 70, X1 = 540, AY0 = 50, AY1 = 250;
    const SMAX = 20;
    const sx = (s) => X0 + (s / SMAX) * (X1 - X0);
    const vy = (v) => AY1 - (v / Vmax) * (AY1 - AY0);
    let curve = "";
    for (let i = 0; i <= 80; i++) {
      const s = (i / 80) * SMAX;
      const v = Vmax * s / (Km + s);
      curve += `${i === 0 ? "M" : "L"}${sx(s).toFixed(1)},${vy(v).toFixed(1)} `;
    }
    const t = tasks.find((x) => x.id === task) || tasks[0];
    const rate = fld.rate;
    const ptX = sx(Math.min(subConc, SMAX)), ptY = vy(rate);
    const halfX = sx(Math.min(Km, SMAX)), halfY = vy(Vmax / 2);

    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 */}
          <line x1={X0} y1={AY0} x2={X0} y2={AY1} stroke={C.faint} strokeWidth="1.5" />
          <line x1={X0} y1={AY1} x2={X1} y2={AY1} stroke={C.faint} strokeWidth="1.5" />
          <text x={X0 - 8} y={AY0 + 4} textAnchor="end" fill={C.mute} fontSize="11" fontFamily="monospace">v</text>
          <text x={X1} y={AY1 + 16} textAnchor="end" fill={C.mute} fontSize="11" fontFamily="monospace">[S] (mM)</text>
          {/* Vmax asymptote */}
          <line x1={X0} y1={vy(Vmax)} x2={X1} y2={vy(Vmax)} stroke={C.crimson} strokeWidth="1.2" strokeDasharray="5 4" opacity="0.7" />
          <text x={X1 - 4} y={vy(Vmax) - 5} textAnchor="end" fill={C.crimson} fontSize="11" fontFamily="monospace">Vmax = {fmt(Vmax)}</text>
          {/* half-Vmax line + Km marker */}
          <line x1={X0} y1={halfY} x2={halfX} y2={halfY} stroke={C.mute} strokeWidth="1" strokeDasharray="3 3" opacity="0.6" />
          <line x1={halfX} y1={halfY} x2={halfX} y2={AY1} stroke={C.mute} strokeWidth="1" strokeDasharray="3 3" opacity="0.6" />
          <circle cx={halfX} cy={halfY} r={4} fill="none" stroke={C.gold} strokeWidth="1.5" />
          <text x={halfX + 6} y={AY1 - 6} fill={C.gold} fontSize="11" fontFamily="monospace">Km = {fmt(Km)}</text>
          {/* the Michaelis–Menten curve */}
          <path d={curve} fill="none" stroke={C.teal} strokeWidth="2.5" />
          {/* current operating point */}
          <line x1={ptX} y1={ptY} x2={ptX} y2={AY1} stroke={C.blue} strokeWidth="1" strokeDasharray="2 3" opacity="0.6" />
          <circle cx={ptX} cy={ptY} r={5} fill={C.blue} />
          <text x={(X0 + X1) / 2} y={AY0 - 4} textAnchor="middle" fill={C.ink} fontSize="13" fontFamily="monospace">v = {fmt(rate)} µmol/min · {Math.round(fld.fracVmax * 100)}% of Vmax</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.isSaturated ? C.crimson : C.line}`, color: fld.isSaturated ? C.crimson : C.mute, fontSize: 12.5 }}>
          v = Vmax·[S]/(Km + [S]) = {fmt(rate)} µmol/min. {fld.atHalfVmax ? "✓ [S] = Km → exactly ½Vmax." : fld.isSaturated ? "⚠ saturated: near Vmax, ↑[S] barely helps." : "Raise [S] toward/over Km to climb the curve."}
        </div>
        <Slider label="substrate [S]" value={subConc} set={setSubConc} min={0.1} max={20} step={0.1} unit="mM" color={C.blue} onUp={() => event("adjusted", `Set [S] = ${fmt(subConc)} mM`, { response: `v ${fmt(fld.rate)} µmol/min` }, C.blue)} />
        <Slider label="Vmax" value={Vmax} set={setVmax} min={1} max={100} step={1} unit="µmol/min" color={C.crimson} onUp={() => event("adjusted", `Set Vmax = ${fmt(Vmax)} µmol/min`, { response: `v ${fmt(fld.rate)} µmol/min` }, C.crimson)} />
        <Slider label="Km" value={Km} set={setKm} min={0.5} max={10} step={0.5} unit="mM" color={C.gold} onUp={() => event("adjusted", `Set Km = ${fmt(Km)} mM`, { response: `v ${fmt(fld.rate)} µmol/min` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="rate v" v={fld.rate} d={2} unit="µmol/min" color={fld.isSaturated ? C.crimson : C.teal} />
          <StatMeter label="fraction of Vmax" v={fld.fracVmax} d={2} color={C.gold} />
          <StatMeter label="substrate [S]" v={fld.subConc} d={2} unit="mM" color={C.blue} />
          <StatMeter label="Km" v={fld.km} d={2} unit="mM" color={C.amber} />
        </div>
      </>
    );
  }

  window.EnzymesTutor = K.makeTutor(EnzymesFig, { moduleLabel: "Enzyme kinetics bench", benchId: "enzymes" });
})();
