/* arclengthlab.jsx — ArcLengthTutor: the arc-length bench. Built on window.BenchKit (harness) +
   window.BenchFields (shared field math), so this file is just the FIGURE. computeFields =
   window.BenchFields.arclength — the SAME function server/benches/arclength.js calls, so client and
   server fields are identical by construction. The learner sets the interval [a,b] and the number of
   chords n; an inscribed polygon of n straight chords following the curve y = x²/2 makes the polygon
   length visible as it converges up to the exact arc length L = ∫√(1+(f′)²) dx. */
(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.arclength(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 ArcLengthFig({ task, setTask, tasks, report, event, done }) {
    const [a, setA] = useState(0);
    const [b, setB] = useState(3);
    const [n, setN] = useState(4);
    const fld = useMemo(() => compute({ a, b, n }), [a, b, n]);
    useEffect(() => { report(fld); }, [a, b, n]); // eslint-disable-line

    // plot the curve y = x²/2 over the visible range and the inscribed polygon of n chords over [a,b].
    const X0 = 60, X1 = 380, baseY = 270, plotW = X1 - X0, plotH = 220;
    const f = (x) => x * x / 2;
    const aa = Math.max(-2, a), bb = Math.max(aa + 0.1, b);
    const ni = Math.max(1, Math.round(n));
    // visible x range: a little padding around [a,b], anchored sensibly.
    const xLo = Math.min(aa, 0) - 0.2, xHi = bb + 0.2;
    const yHi = Math.max(f(xLo), f(xHi), 0.5);            // top of the plot (max curve height)
    const xScale = plotW / (xHi - xLo || 1);
    const yScale = plotH / (yHi || 1);
    const PX = (x) => X0 + (x - xLo) * xScale;
    const PY = (y) => baseY - y * yScale;

    // the smooth curve y = x²/2 across the visible range
    let curve = "";
    const STEPS = 80;
    for (let i = 0; i <= STEPS; i++) {
      const x = xLo + (i / STEPS) * (xHi - xLo);
      curve += (i ? " L " : "M ") + PX(x).toFixed(1) + " " + PY(f(x)).toFixed(1);
    }
    // the inscribed polygon: n straight chords over [a,b] (recompute chord vertices inline)
    const dx = (bb - aa) / ni;
    let poly = "";
    const dots = [];
    for (let i = 0; i <= ni; i++) {
      const x = aa + i * dx, px = PX(x), py = PY(f(x));
      poly += (i ? " L " : "M ") + px.toFixed(1) + " " + py.toFixed(1);
      dots.push(<circle key={i} cx={px.toFixed(1)} cy={py.toFixed(1)} r="2.6" fill={C.amber} />);
    }

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const okColor = fld.converged ? C.teal : C.amber;

    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 }}>
          {/* axis */}
          <line x1={X0} y1={baseY} x2={X1 + 4} y2={baseY} stroke={C.faint} strokeWidth="1.2" />
          {/* the smooth arc y = x²/2 */}
          <path d={curve} fill="none" stroke={C.gold} strokeWidth="2" />
          {/* the inscribed polygon of n chords */}
          <path d={poly} fill="none" stroke={C.blue} strokeWidth="1.8" />
          {dots}
          {/* bound labels */}
          <text x={PX(aa)} y={baseY + 16} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="middle">a = {fmt(aa)}</text>
          <text x={PX(bb)} y={baseY + 16} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="middle">b = {fmt(bb)}</text>
          {/* readout panel on the right */}
          <text x={X1 + 36} y={40} fill={C.mute} fontSize="12" fontFamily="monospace">arc length of y = x²/2</text>
          <text x={X1 + 36} y={66} fill={C.blue} fontSize="13" fontFamily="monospace">polygon = {fmt(fld.polygon)}</text>
          <text x={X1 + 36} y={88} fill={C.teal} fontSize="13" fontFamily="monospace">exact L = {fmt(fld.length)}</text>
          <text x={X1 + 36} y={110} fill={okColor} fontSize="13" fontFamily="monospace">error = {fmt(fld.error)}</text>
          <text x={X1 + 36} y={132} fill={C.mute} fontSize="12" fontFamily="monospace">{fld.nSeg} chords</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 }}>
          Inscribed-polygon length = {fmt(fld.polygon)} vs exact arc length L = ∫√(1+x²) dx = {fmt(fld.length)}. {fld.converged ? <>⚑ <K.T>Converged — the polygon has closed onto the arc.</K.T></> : <K.T>Not converged yet — add chords (raise n) to shrink the error.</K.T>}
        </div>
        <Slider label="left a" value={a} set={setA} min={-2} max={2} step={0.5} unit="" color={C.teal} onUp={() => event("adjusted", `Set a = ${fmt(a)}`, { response: `length ${fmt(fld.length)}` }, C.teal)} />
        <Slider label="right b" value={b} set={setB} min={1} max={4} step={0.5} unit="" color={C.gold} onUp={() => event("adjusted", `Set b = ${fmt(b)}`, { response: `length ${fmt(fld.length)}` }, C.gold)} />
        <Slider label="chords 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 length" v={fld.length} d={2} color={C.teal} />
          <StatMeter label="polygon" v={fld.polygon} d={2} color={C.blue} />
          <StatMeter label="error" v={fld.error} d={3} color={okColor} />
          <StatMeter label="# chords" v={fld.nSeg} d={0} color={C.amber} />
        </div>
      </>
    );
  }

  window.ArcLengthTutor = K.makeTutor(ArcLengthFig, { moduleLabel: "Arc Length bench", benchId: "arclength" });
})();
