/* secantlab.jsx — SecantTutor: the definition-of-the-derivative bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE. computeFields
   = window.BenchFields.secant — the SAME function server/benches/secant.js calls, so client and
   server fields are identical by construction. On f(x) = x³ the learner sets a base point x0 and a
   step h; the secant through (x0,f(x0)) and (x0+h,f(x0+h)) pivots into the tangent as h→0. */
(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.secant(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 SecantFig({ task, setTask, tasks, report, event, done }) {
    const [x0, setX0] = useState(1);
    const [h, setH] = useState(1);
    const fld = useMemo(() => compute({ x0, h }), [x0, h]);
    useEffect(() => { report(fld); }, [x0, h]); // eslint-disable-line

    const X0 = 60, X1 = 560, Y0 = 30, Y1 = 270;
    const XMIN = -2.4, XMAX = 2.4, YMIN = -9, YMAX = 9;
    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 f = (x) => x * x * x;

    const pts = [];
    for (let i = 0; i <= 120; i++) { const x = XMIN + (i / 120) * (XMAX - XMIN); pts.push(`${sx(x).toFixed(1)},${sy(f(x)).toFixed(1)}`); }

    // the two points + secant; the tangent at x0 (slope 3x0²) spanning ±1.1 in x.
    const ax = x0, ay = f(x0), bx = x0 + h, by = f(bx);
    const tanL = -1.1, tanR = 1.1;
    const tyL = ay + fld.tangentSlope * tanL, tyR = ay + fld.tangentSlope * tanR;
    // secant extended a touch beyond the two points for readability
    const sSlope = fld.secantSlope, sL = Math.min(0, h) - 0.4, sR = Math.max(0, h) + 0.4;
    const syL = ay + sSlope * sL, syR = ay + sSlope * sR;

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const secColor = 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" />
          {/* the curve */}
          <polyline points={pts.join(" ")} fill="none" stroke={C.blue} strokeWidth="2" />
          {/* tangent at x0 (dashed) */}
          <line x1={sx(ax + tanL)} y1={sy(tyL)} x2={sx(ax + tanR)} y2={sy(tyR)} stroke={C.faint} strokeWidth="1.5" strokeDasharray="5 4" />
          {/* secant line */}
          <line x1={sx(ax + sL)} y1={sy(syL)} x2={sx(ax + sR)} y2={sy(syR)} stroke={secColor} strokeWidth="2.5" />
          {/* the two points */}
          <circle cx={sx(ax)} cy={sy(ay)} r={5} fill={C.crimson} stroke={C.ink} strokeWidth="1" />
          <circle cx={sx(bx)} cy={sy(by)} r={5} fill={secColor} stroke={C.ink} strokeWidth="1" />
          <text x={sx(ax) + 8} y={sy(ay) + 16} fill={C.crimson} fontSize="11" fontFamily="monospace">x₀ = {fmt(x0)}</text>
          <text x={X0 + 4} y={Y0 + 14} fill={secColor} fontSize="11" fontFamily="monospace">secant = {fmt(fld.secantSlope)} · tangent = {fmt(fld.tangentSlope)} · gap = {fmt(fld.error)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${secColor}`, color: secColor, fontSize: 12.5 }}>
          {fld.converged
            ? <><K.T>The secant matches the tangent</K.T> — f'(x₀) = {fmt(fld.tangentSlope)}.</>
            : <><K.T>Shrink |h| toward 0</K.T> — the secant slope {fmt(fld.secantSlope)} is closing on the tangent {fmt(fld.tangentSlope)}.</>}
        </div>
        <Slider label="base point x₀" value={x0} set={setX0} min={-2} max={2} step={0.1} unit="" color={C.crimson} onUp={() => event("adjusted", `Set x₀ = ${fmt(x0)}`, { response: `f'(x₀) ${fmt(fld.tangentSlope)}` }, C.crimson)} />
        <Slider label="step h" value={h} set={setH} min={-2} max={2} step={0.02} unit="" color={C.teal} onUp={() => event("adjusted", `Set h = ${fmt(h)}`, { response: `gap ${fmt(fld.error)}` }, C.teal)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="secant slope" v={fld.secantSlope} d={2} color={secColor} />
          <StatMeter label="tangent f'(x₀)" v={fld.tangentSlope} d={2} color={C.blue} />
          <StatMeter label="gap |Δ|" v={fld.error} d={3} color={C.amber} />
          <StatMeter label="converged?" v={fld.converged ? 1 : 0} d={0} color={fld.converged ? C.teal : C.crimson} />
        </div>
      </>
    );
  }

  window.SecantTutor = K.makeTutor(SecantFig, { moduleLabel: "Definition of the Derivative bench", benchId: "secant" });
})();
