/* newtonlab.jsx — NewtonTutor: the Newton's-method bench. Built on window.BenchKit (harness) +
   window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.newton — the SAME function server/benches/newton.js calls,
   so client and server fields are identical by construction. The learner sets the number c, the
   start x0 and the iteration count n; the figure draws the parabola y = x²−c and the Newton
   tangent-step staircase from x0 toward the root √c, making the residual shrink visible as the
   error roughly squares each step (quadratic convergence). */
(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.newton(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 NewtonFig({ task, setTask, tasks, report, event, done }) {
    const [c, setC] = useState(9);
    const [x0, setX0] = useState(5);
    const [n, setN] = useState(3);
    const fld = useMemo(() => compute({ c, x0, n }), [c, x0, n]);
    useEffect(() => { report(fld); }, [c, x0, n]); // eslint-disable-line

    // plot: parabola y = x²−c, the x-axis, the root √c, and the tangent-step staircase from x0.
    const X0 = 60, X1 = 380, plotW = X1 - X0;
    const cc = Math.max(0.01, c);
    const root = Math.sqrt(cc);
    const xMax = Math.max(6.5, x0 + 0.5, root + 0.5);   // x-range [0, xMax]
    const xScale = plotW / xMax;
    // y-range: f spans from -c (at x=0) up to f(xMax). Map with 0 near vertical mid-top.
    const yLo = -cc, yHi = xMax * xMax - cc;
    const yTop = 30, yBot = 250, plotH = yBot - yTop;
    const yScale = plotH / (yHi - yLo || 1);
    const px = (x) => X0 + x * xScale;
    const py = (y) => yBot - (y - yLo) * yScale;
    const axisY = py(0);

    // the parabola y = x²−c
    let curve = "";
    const steps = 60;
    for (let i = 0; i <= steps; i++) {
      const x = (i / steps) * xMax, y = x * x - cc;
      curve += (i === 0 ? "M " : "L ") + px(x).toFixed(1) + " " + py(y).toFixed(1) + " ";
    }

    // Newton tangent-step staircase: iterate inline for drawing (up to n steps).
    const ni = Math.max(0, Math.round(n));
    const iterates = [x0];
    let xk = x0;
    for (let i = 0; i < ni; i++) {
      if (xk === 0) break;
      const next = xk - (xk * xk - cc) / (2 * xk);
      iterates.push(next);
      xk = next;
    }
    const segs = [];
    const pts = [];
    for (let i = 0; i < iterates.length; i++) {
      const x = iterates[i], fx = x * x - cc;
      // tangent segment from (x, f(x)) down to (x_{i+1}, 0)
      if (i < iterates.length - 1) {
        segs.push(<line key={"t" + i} x1={px(x).toFixed(1)} y1={py(fx).toFixed(1)} x2={px(iterates[i + 1]).toFixed(1)} y2={axisY.toFixed(1)} stroke={C.vermilion || C.amber} strokeWidth="1.4" />);
        // vertical drop from x-axis up to the curve at the next iterate (the "staircase" riser)
        const xn = iterates[i + 1], fxn = xn * xn - cc;
        segs.push(<line key={"v" + i} x1={px(xn).toFixed(1)} y1={axisY.toFixed(1)} x2={px(xn).toFixed(1)} y2={py(fxn).toFixed(1)} stroke={C.faint} strokeWidth="0.8" strokeDasharray="3 3" />);
      }
      pts.push(<circle key={"p" + i} cx={px(x).toFixed(1)} cy={py(fx).toFixed(1)} r="2.6" fill={i === iterates.length - 1 ? C.teal : C.blue} />);
    }

    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 }}>
          {/* x-axis */}
          <line x1={X0} y1={axisY} x2={X1 + 4} y2={axisY} stroke={C.faint} strokeWidth="1.2" />
          {/* the parabola y = x²−c */}
          <path d={curve} fill="none" stroke={C.gold} strokeWidth="2" />
          {/* the tangent-step staircase */}
          {segs}
          {pts}
          {/* the exact root √c marked on the x-axis */}
          <line x1={px(root).toFixed(1)} y1={(axisY - 8).toFixed(1)} x2={px(root).toFixed(1)} y2={(axisY + 8).toFixed(1)} stroke={C.teal} strokeWidth="1.6" />
          <text x={px(root)} y={axisY + 24} fill={C.teal} fontSize="10" fontFamily="monospace" textAnchor="middle">√c = {fmt(root)}</text>
          {/* start label */}
          <text x={px(x0)} y={axisY - 12} fill={C.blue} fontSize="10" fontFamily="monospace" textAnchor="middle">x0 = {fmt(x0)}</text>
          {/* readout panel on the right */}
          <text x={X1 + 36} y={40} fill={C.mute} fontSize="12" fontFamily="monospace">f(x) = x²−c, c = {fmt(cc)}</text>
          <text x={X1 + 36} y={66} fill={C.blue} fontSize="13" fontFamily="monospace">estimate xₙ = {fmt(fld.estimate)}</text>
          <text x={X1 + 36} y={88} fill={C.teal} fontSize="13" fontFamily="monospace">root √c = {fmt(fld.rootExact)}</text>
          <text x={X1 + 36} y={110} fill={okColor} fontSize="13" fontFamily="monospace">residual = {fmt(fld.residual)}</text>
          <text x={X1 + 36} y={132} fill={C.mute} fontSize="12" fontFamily="monospace">{fld.iterations} iterations</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 }}>
          Estimate xₙ = {fmt(fld.estimate)} with residual |f(xₙ)| = {fmt(fld.residual)} (target root √c = {fmt(fld.rootExact)}). {fld.converged ? <>⚑ <K.T>Converged — the estimate has snapped onto the root.</K.T></> : <K.T>Not converged yet — add iterations (raise n) to shrink the residual.</K.T>}
        </div>
        <Slider label="number c" value={c} set={(v) => setC(Math.round(v))} min={1} max={20} step={1} unit="" color={C.gold} onUp={() => event("adjusted", `Set c = ${fmt(Math.round(c))}`, { response: `root ${fmt(fld.rootExact)}` }, C.gold)} />
        <Slider label="start x0" value={x0} set={setX0} min={0.5} max={6} step={0.5} unit="" color={C.blue} onUp={() => event("adjusted", `Set x0 = ${fmt(x0)}`, { response: `estimate ${fmt(fld.estimate)}` }, C.blue)} />
        <Slider label="iterations n" value={n} set={(v) => setN(Math.round(v))} min={0} max={8} step={1} unit="" color={C.teal} onUp={() => event("adjusted", `Set n = ${fmt(Math.round(n))}`, { response: `residual ${fmt(fld.residual)}` }, C.teal)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="estimate" v={fld.estimate} d={3} color={C.blue} />
          <StatMeter label="residual" v={fld.residual} d={4} color={okColor} />
          <StatMeter label="error to root" v={fld.errorToRoot} d={4} color={C.teal} />
          <StatMeter label="iterations" v={fld.iterations} d={0} color={C.amber} />
        </div>
      </>
    );
  }

  window.NewtonTutor = K.makeTutor(NewtonFig, { moduleLabel: "Newton's Method bench", benchId: "newton" });
})();
