/* powerserieslab.jsx — PowerSeriesTutor: the power-series convergence bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just the
   FIGURE. computeFields = window.BenchFields.powerseries — the SAME function
   server/benches/powerseries.js calls, so client and server fields are identical by construction.
   The learner moves the test point x across the radius R and adds terms N; a number line shows the
   convergence interval (−R, R) shaded, the test point inside or outside, and a bar comparing the
   partial sum to the closed-form limit 1/(1−x/R) as the geometric series Σ(x/R)ⁿ converges. */
(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.powerseries(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 PowerSeriesFig({ task, setTask, tasks, report, event, done }) {
    const [x, setX] = useState(2);
    const [R, setR] = useState(3);
    const [N, setN] = useState(20);
    const fld = useMemo(() => compute({ x, R, N }), [x, R, N]);
    useEffect(() => { report(fld); }, [x, R, N]); // eslint-disable-line

    // number line: the convergence interval (−R, R) shaded, the test point x inside/outside.
    const X0 = 60, X1 = 380, axisY = 150, plotW = X1 - X0;
    const span = 6;                              // x slider runs −6..6
    const xScale = plotW / (2 * span);           // px per unit, centred at the origin
    const cx0 = X0 + span * xScale;              // pixel of the origin (x = 0)
    const px = (v) => cx0 + v * xScale;          // value → pixel
    const inside = !!fld.withinRadius;
    const ptColor = inside ? C.teal : C.amber;

    // bar comparing partial sum to the closed-form limit (only meaningful inside the radius).
    const limit = inside ? 1 / (1 - x / R) : 0;
    const barTop = 210, barH = 18, barW = 230, barX = X1 + 36;
    const scale = Math.max(Math.abs(limit), Math.abs(fld.partialSum), 1);
    const pw = inside ? Math.max(0, Math.min(1, fld.partialSum / scale)) * barW : 0;
    const lw = inside ? Math.max(0, Math.min(1, limit / scale)) * barW : 0;

    const t = tasks.find((q) => q.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 }}>
          {/* convergence interval (−R, R) shaded teal */}
          <rect x={px(-R).toFixed(1)} y={axisY - 16} width={Math.max(0.6, (px(R) - px(-R))).toFixed(1)} height="32" fill={C.teal} fillOpacity="0.18" />
          {/* the number line */}
          <line x1={X0} y1={axisY} x2={X1 + 4} y2={axisY} stroke={C.faint} strokeWidth="1.2" />
          {/* origin tick */}
          <line x1={px(0)} y1={axisY - 6} x2={px(0)} y2={axisY + 6} stroke={C.faint} strokeWidth="1" />
          <text x={px(0)} y={axisY + 22} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="middle">0</text>
          {/* ±R ticks */}
          <line x1={px(-R)} y1={axisY - 10} x2={px(-R)} y2={axisY + 10} stroke={C.teal} strokeWidth="1.6" />
          <line x1={px(R)} y1={axisY - 10} x2={px(R)} y2={axisY + 10} stroke={C.teal} strokeWidth="1.6" />
          <text x={px(-R)} y={axisY + 24} fill={C.teal} fontSize="10" fontFamily="monospace" textAnchor="middle">−R = {fmt(-R)}</text>
          <text x={px(R)} y={axisY + 24} fill={C.teal} fontSize="10" fontFamily="monospace" textAnchor="middle">R = {fmt(R)}</text>
          {/* the test point x */}
          <circle cx={px(x)} cy={axisY} r="6" fill={ptColor} stroke={C.line} strokeWidth="1" />
          <text x={px(x)} y={axisY - 14} fill={ptColor} fontSize="11" fontFamily="monospace" textAnchor="middle">x = {fmt(x)}</text>
          {/* readout panel on the right */}
          <text x={X1 + 36} y={40} fill={C.mute} fontSize="12" fontFamily="monospace">Σ (x/R)ⁿ · ratio test</text>
          <text x={X1 + 36} y={66} fill={ptColor} fontSize="13" fontFamily="monospace">ρ = |x|/R = {fmt(fld.ratio)}</text>
          <text x={X1 + 36} y={88} fill={C.blue} fontSize="13" fontFamily="monospace">partial sum = {fmt(fld.partialSum)}</text>
          <text x={X1 + 36} y={110} fill={okColor} fontSize="13" fontFamily="monospace">tail gap = {fmt(fld.tailGap)}</text>
          {/* bars: partial sum vs the closed-form limit */}
          <text x={barX} y={barTop - 8} fill={C.mute} fontSize="11" fontFamily="monospace">partial vs limit</text>
          <rect x={barX} y={barTop} width={Math.max(0.6, pw).toFixed(1)} height={barH} rx="2" fill={C.blue} fillOpacity="0.8" />
          <rect x={barX} y={barTop + barH + 5} width={Math.max(0.6, lw).toFixed(1)} height={barH} rx="2" fill={C.teal} fillOpacity="0.8" />
          <text x={barX + 4} y={barTop + 13} fill={C.bg || "#000"} fontSize="10" fontFamily="monospace">Σ</text>
          <text x={barX + 4} y={barTop + barH + 18} fill={C.bg || "#000"} fontSize="10" fontFamily="monospace">L</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.amber, fontSize: 12.5 }}>
          ρ = |x|/R = {fmt(fld.ratio)} — {inside ? <K.T>inside the radius</K.T> : <K.T>outside the radius</K.T>}. {fld.converged ? <>⚑ <K.T>Converged — the partial sum has closed onto the limit 1/(1−x/R).</K.T></> : (inside ? <K.T>Inside, but not converged yet — add terms (raise N) to shrink the tail gap.</K.T> : <K.T>Divergent — |x| ≥ R, so the series blows up. Bring x inside the radius.</K.T>)}
        </div>
        <Slider label="test point x" value={x} set={setX} min={-6} max={6} step={0.25} unit="" color={C.gold} onUp={() => event("adjusted", `Set x = ${fmt(x)}`, { response: `ratio ${fmt(fld.ratio)}` }, C.gold)} />
        <Slider label="radius R" value={R} set={setR} min={1} max={5} step={0.5} unit="" color={C.teal} onUp={() => event("adjusted", `Set R = ${fmt(R)}`, { response: `ratio ${fmt(fld.ratio)}` }, C.teal)} />
        <Slider label="terms N" value={N} set={(v) => setN(Math.round(v))} min={0} max={40} step={1} unit="" color={C.blue} onUp={() => event("adjusted", `Set N = ${fmt(Math.round(N))}`, { response: `tail gap ${fmt(fld.tailGap)}` }, C.blue)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="ratio ρ" v={fld.ratio} d={3} color={ptColor} />
          <StatMeter label="radius R" v={fld.radius} d={2} color={C.teal} />
          <StatMeter label="partial sum" v={fld.partialSum} d={3} color={C.blue} />
          <StatMeter label="tail gap" v={fld.tailGap} d={3} color={okColor} />
        </div>
      </>
    );
  }

  window.PowerSeriesTutor = K.makeTutor(PowerSeriesFig, { moduleLabel: "Power Series Convergence bench", benchId: "powerseries" });
})();
