/* taylorlab.jsx — TaylorTutor: the Taylor / Maclaurin bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.taylor — the SAME function server/benches/taylor.js
   calls, so client and server fields are identical by construction. The learner picks an
   evaluation point x and raises the degree n; the degree-n Maclaurin polynomial Pₙ(x) is
   plotted against the true curve y = eˣ so the closing error gap is visible. */
(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.taylor(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 TaylorFig({ task, setTask, tasks, report, event, done }) {
    const [xEval, setXEval] = useState(1);
    const [n, setN] = useState(1);
    const fld = useMemo(() => compute({ xEval, n }), [xEval, n]);
    useEffect(() => { report(fld); }, [xEval, n]); // eslint-disable-line

    // plot window: x ∈ [-3,3], y ∈ [0,16] (eˣ on [-3,3] tops out near 20; clamp for the plot).
    const X0 = 60, X1 = 560, Y0 = 30, Y1 = 270;
    const XMIN = -3, XMAX = 3, YMIN = 0, YMAX = 16;
    const sx = (x) => X0 + ((x - XMIN) / (XMAX - XMIN)) * (X1 - X0);
    const sy = (y) => Y1 - ((Math.max(YMIN, Math.min(YMAX, y)) - YMIN) / (YMAX - YMIN)) * (Y1 - Y0);
    const ex = (x) => Math.exp(x);
    // degree-n Maclaurin polynomial Pₙ(x) = Σ_{k=0}^n xᵏ/k!, computed here for plotting.
    const poly = (x) => { let term = 1, sum = 1; for (let k = 1; k <= n; k++) { term *= x / k; sum += term; } return sum; };

    // sample the true curve and the polynomial
    const tp = [], pp = [];
    for (let i = 0; i <= 120; i++) { const x = XMIN + (i / 120) * (XMAX - XMIN); tp.push(`${sx(x).toFixed(1)},${sy(ex(x)).toFixed(1)}`); pp.push(`${sx(x).toFixed(1)},${sy(poly(x)).toFixed(1)}`); }
    const trueCurve = tp.join(" "), polyCurve = pp.join(" ");

    // the evaluation point: vertical line + the two values (approx vs exact) and the error gap.
    const px = sx(xEval), pyA = sy(fld.approx), pyE = sy(fld.exact);

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const statusColor = 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 }}>
          {/* axes */}
          <line x1={X0} y1={sy(0)} x2={X1} y2={sy(0)} stroke={C.faint} strokeWidth="1" />
          <line x1={sx(0)} y1={Y0} x2={sx(0)} y2={Y1} stroke={C.faint} strokeWidth="1" />
          <text x={X1 - 6} y={sy(0) - 5} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="end">x</text>
          {/* evaluation-point vertical line */}
          <line x1={px} y1={Y0} x2={px} y2={Y1} stroke={C.line} strokeWidth="1" strokeDasharray="3 4" />
          {/* true curve y = eˣ */}
          <polyline points={trueCurve} fill="none" stroke={C.blue} strokeWidth="2" />
          {/* degree-n Maclaurin polynomial */}
          <polyline points={polyCurve} fill="none" stroke={statusColor} strokeWidth="2" strokeDasharray="6 4" />
          {/* error gap at the evaluation point */}
          <line x1={px} y1={pyA} x2={px} y2={pyE} stroke={C.crimson} strokeWidth="2.5" />
          <circle cx={px} cy={pyE} r={5} fill={C.blue} stroke={C.ink} strokeWidth="1" />
          <circle cx={px} cy={pyA} r={5} fill={statusColor} stroke={C.ink} strokeWidth="1" />
          <text x={px + 9} y={pyE - 6} fill={C.blue} fontSize="12" fontFamily="monospace">eˣ = {fmt(fld.exact)}</text>
          <text x={px + 9} y={pyA + 14} fill={statusColor} fontSize="12" fontFamily="monospace">Pₙ(x) = {fmt(fld.approx)}</text>
          <text x={X0 + 4} y={Y0 + 14} fill={C.mute} fontSize="11" fontFamily="monospace">Pₙ(x) = Σ xᵏ/k! · x = {fmt(xEval)} · n = {n} · error = {fmt(fld.error)}</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 }}>
          P{n}(x) = {fmt(fld.approx)} vs eˣ = {fmt(fld.exact)}, error = {fmt(fld.error)} (Lagrange bound ≤ {fmt(fld.remainderBound)}). {fld.converged ? <>⚑ <K.T>converged — the polynomial matches eˣ to tolerance.</K.T></> : <K.T>Raise the degree n to shrink the error.</K.T>}
        </div>
        <Slider label="evaluate at x" value={xEval} set={setXEval} min={-3} max={3} step={0.25} unit="" color={C.teal} onUp={() => event("adjusted", `Evaluate at x = ${fmt(xEval)}`, { response: `error ${fmt(fld.error)}` }, C.teal)} />
        <Slider label="degree n" value={n} set={setN} min={0} max={12} step={1} unit="" color={C.gold} onUp={() => event("adjusted", `Set degree n = ${n}`, { response: `error ${fmt(fld.error)}` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="Pₙ(x) approx" v={fld.approx} d={3} color={statusColor} />
          <StatMeter label="eˣ exact" v={fld.exact} d={3} color={C.blue} />
          <StatMeter label="error" v={fld.error} d={3} color={fld.converged ? C.teal : C.crimson} />
          <StatMeter label="nTerms" v={fld.nTerms} d={0} color={C.amber} />
        </div>
      </>
    );
  }

  window.TaylorTutor = K.makeTutor(TaylorFig, { moduleLabel: "Taylor / Maclaurin bench", benchId: "taylor" });
})();
