/* coulomblab.jsx — CoulombTutor: the two-point-charges bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.coulomb — the SAME function server/benches/coulomb.js
   calls, so client and server fields are identical by construction. Mirrors the gas-laws
   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.coulomb(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 CoulombFig({ task, setTask, tasks, report, event, done }) {
    const [q1, setQ1] = useState(2);
    const [q2, setQ2] = useState(3);
    const [distance, setDistance] = useState(10);
    const fld = useMemo(() => compute({ q1, q2, distance }), [q1, q2, distance]);
    useEffect(() => { report(fld); }, [q1, q2, distance]); // eslint-disable-line

    // layout: two spheres on a horizontal axis; gap ∝ r (1..50 cm), radius ∝ |q|.
    const CY = 150, X0 = 110, X1 = 490;
    const cx1 = X0, cx2 = X0 + (distance / 50) * (X1 - X0);
    const rad = (q) => 12 + Math.min(28, Math.abs(q) * 2.4);
    const r1 = rad(q1), r2 = rad(q2);
    const colorOf = (q) => (q >= 0 ? C.crimson : C.blue);
    const signOf = (q) => (q >= 0 ? "+" : "−");

    // force arrows: length ∝ log-scaled |force|, clamped; direction = attractive→inward.
    const mag = Math.abs(fld.force);
    const aLen = mag <= 0 ? 0 : Math.min(70, 14 + 18 * Math.log10(1 + mag * 4));
    const attract = fld.isAttractive;
    // left charge arrow: attractive points right (+), repulsive points left (−).
    const dir = attract ? 1 : -1;
    const lTip = cx1 - r1 + dir * aLen * -1; // left sphere: inward=+x means toward right
    const lFrom = cx1 - r1, lTo = cx1 - r1 - dir * aLen;
    const rFrom = cx2 + r2, rTo = cx2 + r2 + dir * aLen;

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const arrowCol = attract ? C.teal : C.crimson;

    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 }}>
          <defs>
            <marker id="coulArrow" markerWidth="9" markerHeight="9" refX="7" refY="4.5" orient="auto">
              <path d="M0,0 L9,4.5 L0,9 Z" fill={arrowCol} />
            </marker>
          </defs>
          {/* axis */}
          <line x1={40} y1={CY} x2={560} y2={CY} stroke={C.faint} strokeWidth="1" strokeDasharray="3 4" />
          {/* separation bracket */}
          <line x1={cx1} y1={CY + 56} x2={cx2} y2={CY + 56} stroke={C.mute} strokeWidth="1" />
          <text x={(cx1 + cx2) / 2} y={CY + 72} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">r = {Math.round(distance)} cm</text>
          {/* force arrows */}
          {mag > 0 && <line x1={lFrom} y1={CY} x2={lTo} y2={CY} stroke={arrowCol} strokeWidth="3" markerEnd="url(#coulArrow)" />}
          {mag > 0 && <line x1={rFrom} y1={CY} x2={rTo} y2={CY} stroke={arrowCol} strokeWidth="3" markerEnd="url(#coulArrow)" />}
          {/* charge spheres */}
          <circle cx={cx1} cy={CY} r={r1} fill={colorOf(q1)} opacity="0.9" stroke={C.ink} strokeWidth="1" />
          <circle cx={cx2} cy={CY} r={r2} fill={colorOf(q2)} opacity="0.9" stroke={C.ink} strokeWidth="1" />
          <text x={cx1} y={CY + 5} textAnchor="middle" fill={C.ink} fontSize="16" fontWeight="bold" fontFamily="monospace">{signOf(q1)}</text>
          <text x={cx2} y={CY + 5} textAnchor="middle" fill={C.ink} fontSize="16" fontWeight="bold" fontFamily="monospace">{signOf(q2)}</text>
          <text x={cx1} y={CY - r1 - 8} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">q₁ {fmt(q1)} µC</text>
          <text x={cx2} y={CY - r2 - 8} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">q₂ {fmt(q2)} µC</text>
          <text x={300} y={36} textAnchor="middle" fill={attract ? C.teal : C.crimson} fontSize="13" fontFamily="monospace">
            {attract ? "ATTRACTIVE" : "REPULSIVE"} · |F| = {fmt(mag)} N
          </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 }}>
          F = k·q₁q₂/r² = {fmt(fld.force)} N (signed: + repels, − attracts). {attract ? "Opposite signs ⇒ they pull together." : "Like signs ⇒ they push apart."} Separate them (↑r) to weaken F as 1/r².
        </div>
        <Slider label="charge q₁" value={q1} set={setQ1} min={-10} max={10} step={0.5} unit="µC" color={colorOf(q1)} onUp={() => event("adjusted", `Set q₁ = ${fmt(q1)} µC`, { response: `F ${fmt(fld.force)} N` }, colorOf(q1))} />
        <Slider label="charge q₂" value={q2} set={setQ2} min={-10} max={10} step={0.5} unit="µC" color={colorOf(q2)} onUp={() => event("adjusted", `Set q₂ = ${fmt(q2)} µC`, { response: `F ${fmt(fld.force)} N` }, colorOf(q2))} />
        <Slider label="separation r" value={distance} set={setDistance} min={1} max={50} step={1} unit="cm" color={C.gold} onUp={() => event("adjusted", `Set r = ${Math.round(distance)} cm`, { response: `F ${fmt(fld.force)} N` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="force F" v={fld.force} d={2} unit="N" color={attract ? C.teal : C.crimson} />
          <StatMeter label="field E" v={fld.fieldE} d={0} unit="N/C" color={C.blue} />
          <StatMeter label="potential V" v={fld.potential} d={0} unit="V" color={C.amber} />
          <StatMeter label="separation r" v={fld.distance} d={0} unit="cm" color={C.gold} />
        </div>
      </>
    );
  }

  window.CoulombTutor = K.makeTutor(CoulombFig, { moduleLabel: "Coulomb bench", benchId: "coulomb" });
})();
