/* lineintegrallab.jsx — LineIntegralTutor: the line-integral (work) bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just the
   FIGURE. computeFields = window.BenchFields.lineintegral — the SAME function
   server/benches/lineintegral.js calls, so client and server fields are identical by construction.
   The learner sets the arc (radius R, span θmax) and the number of segments n; the work of the
   shear field F = (y, 0) along the circular arc r(θ) = (R cosθ, R sinθ) is read off a midpoint
   Riemann sum as it converges onto the exact work −R²(θmax/2 − sin(2θmax)/4). */
(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.lineintegral(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 }}><K.T>{label}</K.T></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 LineIntegralFig({ task, setTask, tasks, report, event, done }) {
    const [R, setR] = useState(2);
    const [thMax, setThMax] = useState(150);
    const [n, setN] = useState(4);
    const fld = useMemo(() => compute({ R, thMax, n }), [R, thMax, n]);
    useEffect(() => { report(fld); }, [R, thMax, n]); // eslint-disable-line

    // centred axes on the left; the circular arc r(θ)=(R cosθ, R sinθ), θ:0→θmax.
    const cx = 150, cy = 150, pxPerUnit = 34; // px per unit radius
    const rPx = Math.max(0.5, R) * pxPerUnit;
    const thR = (Math.max(1, thMax) * Math.PI) / 180;
    const ni = Math.max(1, Math.round(n));
    // SVG y grows downward → negate the y of each point.
    const pt = (th) => [cx + rPx * Math.cos(th), cy - rPx * Math.sin(th)];

    // sampled polyline along the arc
    const SAMP = 64;
    let arc = "";
    for (let i = 0; i <= SAMP; i++) {
      const [px, py] = pt((i / SAMP) * thR);
      arc += `${i === 0 ? "M" : "L"} ${px.toFixed(1)} ${py.toFixed(1)} `;
    }
    // n segment-division dots along the arc
    const dots = [];
    for (let i = 0; i <= ni; i++) {
      const [px, py] = pt((i / ni) * thR);
      dots.push(<circle key={`d${i}`} cx={px.toFixed(1)} cy={py.toFixed(1)} r="2.6" fill={C.blue} stroke={C.line} strokeWidth="0.6" />);
    }
    // a few field arrows F=(y,0): horizontal, length ∝ y = R sinθ (sampled at segment midpoints)
    const NARROW = Math.min(ni, 7);
    const arrows = [];
    const aScale = 26; // px per unit of y
    for (let i = 0; i < NARROW; i++) {
      const th = ((i + 0.5) / NARROW) * thR;
      const [px, py] = pt(th);
      const y = R * Math.sin(th);          // F = (y, 0)
      const len = y * aScale;              // horizontal arrow length ∝ y
      const ex = px + len;
      arrows.push(<line key={`a${i}`} x1={px.toFixed(1)} y1={py.toFixed(1)} x2={ex.toFixed(1)} y2={py.toFixed(1)} stroke={C.gold} strokeWidth="1.6" markerEnd="url(#li-arrow)" />);
    }

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const okColor = fld.converged ? C.teal : C.amber;
    const RX = 320; // right-side readout x

    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="li-arrow" markerWidth="7" markerHeight="7" refX="5.5" refY="3" orient="auto" markerUnits="userSpaceOnUse">
              <path d="M0,0 L6,3 L0,6 Z" fill={C.gold} />
            </marker>
          </defs>
          {/* centred axes */}
          <line x1={cx - 100} y1={cy} x2={cx + 100} y2={cy} stroke={C.faint} strokeWidth="1" strokeDasharray="4 3" />
          <line x1={cx} y1={cy - 100} x2={cx} y2={cy + 100} stroke={C.faint} strokeWidth="1" strokeDasharray="4 3" />
          {/* the circular arc */}
          <path d={arc} fill="none" stroke={C.teal} strokeWidth="2.2" />
          {/* field arrows F=(y,0) */}
          {arrows}
          {/* segment-division dots */}
          {dots}
          <text x={cx} y={cy + 116} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="middle">F = (y, 0) along r(θ), θ: 0 → {fld.spanDeg}°</text>
          {/* readout panel on the right */}
          <text x={RX} y={40} fill={C.mute} fontSize="12" fontFamily="monospace">work ∫_C F·dr along arc</text>
          <text x={RX} y={66} fill={C.blue} fontSize="13" fontFamily="monospace">Riemann sum = {fmt(fld.riemann)}</text>
          <text x={RX} y={88} fill={C.teal} fontSize="13" fontFamily="monospace">exact work = {fmt(fld.work)}</text>
          <text x={RX} y={110} fill={okColor} fontSize="13" fontFamily="monospace">error = {fmt(fld.error)}</text>
          <text x={RX} y={132} fill={C.mute} fontSize="12" fontFamily="monospace">{fld.nSeg} segments · {fld.spanDeg}°</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.converged ? C.teal : C.line}`, color: fld.converged ? C.teal : C.mute, fontSize: 12.5 }}>
          Midpoint Riemann sum = {fmt(fld.riemann)} vs exact work −R²(θmax/2 − sin(2θmax)/4) = {fmt(fld.work)}. {fld.converged ? <>⚑ <K.T>Converged — the Riemann sum has closed onto the exact work.</K.T></> : <K.T>Not converged yet — add segments (raise n) to shrink the error.</K.T>}
        </div>
        <Slider label="arc radius R" value={R} set={setR} min={1} max={3} step={0.5} unit="" color={C.teal} onUp={() => event("adjusted", `Set R = ${fmt(R)}`, { response: `work ${fmt(fld.work)}` }, C.teal)} />
        <Slider label="span θmax" value={thMax} set={(v) => setThMax(Math.round(v))} min={30} max={330} step={15} unit="°" color={C.gold} onUp={() => event("adjusted", `Set θmax = ${fmt(Math.round(thMax))}°`, { response: `work ${fmt(fld.work)}` }, C.gold)} />
        <Slider label="segments n" value={n} set={(v) => setN(Math.round(v))} min={1} max={60} step={1} unit="" color={C.blue} onUp={() => event("adjusted", `Set n = ${fmt(Math.round(n))}`, { response: `error ${fmt(fld.error)}` }, C.blue)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="exact work" v={fld.work} d={3} color={C.teal} />
          <StatMeter label="Riemann sum" v={fld.riemann} d={3} color={C.blue} />
          <StatMeter label="error" v={fld.error} d={3} color={okColor} />
          <StatMeter label="# segments" v={fld.nSeg} d={0} color={C.amber} />
        </div>
      </>
    );
  }

  window.LineIntegralTutor = K.makeTutor(LineIntegralFig, { moduleLabel: "Line Integral bench", benchId: "lineintegral" });
})();
