/* linearizationlab.jsx — LinearizationTutor: the tangent line / linear approximation bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just the
   FIGURE. computeFields = window.BenchFields.linearization — the SAME function
   server/benches/linearization.js calls, so client and server fields are identical by construction.
   The learner sets the center a and the evaluation point x; the tangent line to f(x) = √x at a tracks
   the curve near a and drifts away as |x−a| grows, making the approximation error 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.linearization(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 LinearizationFig({ task, setTask, tasks, report, event, done }) {
    const [a, setA] = useState(4);
    const [x, setX] = useState(6);
    const fld = useMemo(() => compute({ a, x }), [a, x]);
    useEffect(() => { report(fld); }, [a, x]); // eslint-disable-line

    // plot y = √x over the domain [0,9]; tangent line at a; evaluation point x with an error bar.
    const X0 = 60, X1 = 380, baseY = 250, plotW = X1 - X0;
    const XMAX = 9, YMAX = 3;                    // √9 = 3
    const xScale = plotW / XMAX, yScale = (baseY - 40) / YMAX;
    const px = (xv) => X0 + xv * xScale;
    const py = (yv) => baseY - yv * yScale;

    const aa = Math.max(0.25, a), xx = Math.max(0, x);
    const slope = 1 / (2 * Math.sqrt(aa));
    const L = (xv) => Math.sqrt(aa) + slope * (xv - aa);  // tangent line value
    // the curve y = √x as a polyline
    let curve = "";
    for (let i = 0; i <= 90; i++) { const xv = (i / 90) * XMAX; curve += `${i ? "L" : "M"} ${px(xv).toFixed(1)} ${py(Math.sqrt(xv)).toFixed(1)} `; }
    // the tangent line across the domain
    const tan = `M ${px(0)} ${py(L(0))} L ${px(XMAX)} ${py(L(XMAX))}`;

    const t = tasks.find((q) => q.id === task) || tasks[0];
    const okColor = fld.withinTol ? 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={baseY} x2={X1 + 4} y2={baseY} stroke={C.faint} strokeWidth="1.2" />
          <line x1={X0} y1={baseY} x2={X0} y2={36} stroke={C.faint} strokeWidth="1.2" />
          {/* the curve y = √x */}
          <path d={curve} fill="none" stroke={C.gold} strokeWidth="2" />
          {/* the tangent line at a */}
          <path d={tan} fill="none" stroke={C.blue} strokeWidth="2" strokeDasharray="5 3" />
          {/* the center a */}
          <circle cx={px(aa)} cy={py(Math.sqrt(aa))} r="4" fill={C.teal} />
          <text x={px(aa)} y={baseY + 16} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="middle">a = {fmt(aa)}</text>
          {/* the evaluation point x: curve value, line value and the error bar between them */}
          <line x1={px(xx)} y1={py(fld.fExact)} x2={px(xx)} y2={py(fld.fApprox)} stroke={okColor} strokeWidth="3" />
          <circle cx={px(xx)} cy={py(fld.fExact)} r="3.5" fill={C.gold} />
          <circle cx={px(xx)} cy={py(fld.fApprox)} r="3.5" fill={C.blue} />
          <text x={px(xx)} y={baseY + 16} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="middle">x = {fmt(xx)}</text>
          {/* readout panel on the right */}
          <text x={X1 + 36} y={40} fill={C.mute} fontSize="12" fontFamily="monospace">L(x) ≈ √x near a</text>
          <text x={X1 + 36} y={66} fill={C.blue} fontSize="13" fontFamily="monospace">tangent L(x) = {fmt(fld.fApprox)}</text>
          <text x={X1 + 36} y={88} fill={C.gold} fontSize="13" fontFamily="monospace">true √x = {fmt(fld.fExact)}</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">slope = {fmt(fld.slope)}</text>
          <text x={X1 + 36} y={154} fill={C.mute} fontSize="12" fontFamily="monospace">dx = {fmt(fld.dx)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.withinTol ? C.teal : C.line}`, color: fld.withinTol ? C.teal : C.mute, fontSize: 12.5 }}>
          Tangent value L(x) = {fmt(fld.fApprox)} vs true √x = {fmt(fld.fExact)} at distance dx = {fmt(fld.dx)}. {fld.withinTol ? <>⚑ <K.T>Within tolerance — the tangent line closely tracks the curve here.</K.T></> : <K.T>Off the curve — move x toward the center a to shrink the error.</K.T>}
        </div>
        <Slider label="center a" value={a} set={setA} min={0.25} max={9} step={0.25} unit="" color={C.teal} onUp={() => event("adjusted", `Set a = ${fmt(a)}`, { response: `slope ${fmt(fld.slope)}` }, C.teal)} />
        <Slider label="evaluate at x" value={x} set={setX} min={0} max={9} step={0.25} unit="" color={C.gold} onUp={() => event("adjusted", `Set x = ${fmt(x)}`, { response: `error ${fmt(fld.error)}` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="tangent L(x)" v={fld.fApprox} d={3} color={C.blue} />
          <StatMeter label="true √x" v={fld.fExact} d={3} color={C.gold} />
          <StatMeter label="error" v={fld.error} d={3} color={okColor} />
          <StatMeter label="slope" v={fld.slope} d={3} color={C.teal} />
        </div>
      </>
    );
  }

  window.LinearizationTutor = K.makeTutor(LinearizationFig, { moduleLabel: "Tangent Line / Linear Approximation bench", benchId: "linearization" });
})();
