/* equilibriumlab.jsx — EquilibriumTutor: the reaction-quotient (Q vs K) bench for A + B ⇌ C.
   Built on window.BenchKit (harness) + window.BenchFields (shared field math), so this file is
   just the FIGURE. compute = window.BenchFields.equilibrium — the SAME function
   server/benches/equilibrium.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.equilibrium(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 EquilibriumFig({ task, setTask, tasks, report, event, done }) {
    const [concA, setConcA] = useState(1);
    const [concB, setConcB] = useState(1);
    const [concC, setConcC] = useState(2);
    const fld = useMemo(() => compute({ concA, concB, concC }), [concA, concB, concC]);
    useEffect(() => { report(fld); }, [concA, concB, concC]); // eslint-disable-line

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const Q = fld.Q, Keq = fld.Keq;
    const dir = fld.atEquilibrium ? "rest" : fld.shiftsForward ? "fwd" : "rev";
    const dirCol = fld.atEquilibrium ? C.teal : fld.shiftsForward ? C.blue : C.crimson;

    // three concentration bars; max 10 M for [C], 5 M for A/B → normalize to bar height.
    const bars = [
      { k: "[A]", v: concA, max: 5, col: C.amber },
      { k: "[B]", v: concB, max: 5, col: C.gold },
      { k: "[C]", v: concC, max: 10, col: C.teal },
    ];
    const BY0 = 60, BY1 = 240, BX = [70, 150, 230], BW = 50;
    // gauge: Q on a log-ish scale 0..10 mapped to an angle; K=4 marked.
    const GX = 440, GY = 200, GR = 90;
    const ang = (q) => Math.PI - Math.min(1, q / 10) * Math.PI; // 0→left(π), 10→right(0)
    const qA = ang(Q), kA = ang(Keq);

    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={70} y={36} fill={C.mute} fontSize="12" fontFamily="monospace">A + B ⇌ C</text>
          {/* concentration bars */}
          {bars.map((b, i) => {
            const h = Math.max(2, Math.min(1, b.v / b.max) * (BY1 - BY0));
            return (
              <g key={b.k}>
                <rect x={BX[i]} y={BY1 - h} width={BW} height={h} fill={b.col} opacity="0.7" rx="2" />
                <line x1={BX[i]} y1={BY1} x2={BX[i] + BW} y2={BY1} stroke={C.faint} strokeWidth="1" />
                <text x={BX[i] + BW / 2} y={BY1 + 16} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">{b.k}</text>
                <text x={BX[i] + BW / 2} y={BY1 - h - 6} textAnchor="middle" fill={b.col} fontSize="11" fontFamily="monospace">{fmt(b.v)}</text>
              </g>
            );
          })}
          {/* Q vs K gauge */}
          <path d={`M${GX - GR} ${GY} A${GR} ${GR} 0 0 1 ${GX + GR} ${GY}`} fill="none" stroke={C.faint} strokeWidth="2" />
          {/* K marker (fixed) */}
          <line x1={GX} y1={GY} x2={GX + GR * Math.cos(kA)} y2={GY - GR * Math.sin(kA)} stroke={C.mute} strokeWidth="2" strokeDasharray="4 3" />
          <text x={GX + (GR + 12) * Math.cos(kA)} y={GY - (GR + 12) * Math.sin(kA)} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">K=4</text>
          {/* Q needle */}
          <line x1={GX} y1={GY} x2={GX + GR * Math.cos(qA)} y2={GY - GR * Math.sin(qA)} stroke={dirCol} strokeWidth="3" />
          <circle cx={GX} cy={GY} r={4} fill={dirCol} />
          <text x={GX} y={GY + 26} textAnchor="middle" fill={dirCol} fontSize="13" fontFamily="monospace">Q = {fmt(Q)}</text>
          <text x={GX} y={GY + 42} textAnchor="middle" fill={dirCol} fontSize="11" fontFamily="monospace">{fld.atEquilibrium ? "at equilibrium" : fld.shiftsForward ? "→ shifts forward" : "← shifts reverse"}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${dirCol}`, color: dirCol, fontSize: 12.5 }}>
          Q = [C]/([A]·[B]) = {fmt(Q)} vs K = {Keq}. {fld.atEquilibrium ? "✓ Q = K — the reaction rests." : fld.shiftsForward ? "Q < K — shifts forward to make more C." : "Q > K — shifts reverse to consume C."}
        </div>
        <Slider label="[A]" value={concA} set={setConcA} min={0.1} max={5} step={0.1} unit="M" color={C.amber} onUp={() => event("adjusted", `Set [A] = ${fmt(concA)} M`, { response: `Q ${fmt(fld.Q)}` }, C.amber)} />
        <Slider label="[B]" value={concB} set={setConcB} min={0.1} max={5} step={0.1} unit="M" color={C.gold} onUp={() => event("adjusted", `Set [B] = ${fmt(concB)} M`, { response: `Q ${fmt(fld.Q)}` }, C.gold)} />
        <Slider label="[C]" value={concC} set={setConcC} min={0.1} max={10} step={0.1} unit="M" color={C.teal} onUp={() => event("adjusted", `Set [C] = ${fmt(concC)} M`, { response: `Q ${fmt(fld.Q)}` }, C.teal)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="Q" v={fld.Q} d={2} color={dirCol} />
          <StatMeter label="Keq" v={fld.Keq} d={0} color={C.mute} />
          <StatMeter label="shift" v={dir === "rest" ? "rest" : dir === "fwd" ? "forward" : "reverse"} color={dirCol} />
          <StatMeter label="[C]" v={fld.concC} d={1} unit="M" color={C.teal} />
        </div>
      </>
    );
  }

  window.EquilibriumTutor = K.makeTutor(EquilibriumFig, { moduleLabel: "Equilibrium (Q vs K) bench", benchId: "equilibrium" });
})();
