/* implicitlab.jsx — ImplicitTutor: the implicit-differentiation bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.implicit — the SAME function server/benches/implicit.js calls,
   so client and server fields are identical by construction. A point rides the ellipse
   x²/A²+y²/B²=1 at angle t; the tangent line through it has the implicit slope
   dy/dx = −(B²x)/(A²y), undefined (vertical) at the left/right vertices and zero (horizontal) at
   the top/bottom. The point, the tangent line and the tangent type all update live. */
(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.implicit(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 ImplicitFig({ task, setTask, tasks, report, event, done }) {
    const [A, setA] = useState(3);
    const [B, setB] = useState(2);
    const [t, setT] = useState(45);
    const fld = useMemo(() => compute({ A, B, t }), [A, B, t]);
    useEffect(() => { report(fld); }, [A, B, t]); // eslint-disable-line

    // ellipse centered at left; world→screen
    const cx0 = 175, cy0 = 150, S = 30;          // origin px + px-per-unit
    const sx = (wx) => cx0 + wx * S, sy = (wy) => cy0 - wy * S;
    const px = sx(fld.xPt), py = sy(fld.yPt);

    // sampled ellipse polyline
    const N = 96;
    let pts = "";
    for (let i = 0; i <= N; i++) {
      const th = (i / N) * 2 * Math.PI;
      pts += `${sx(A * Math.cos(th)).toFixed(1)},${sy(B * Math.sin(th)).toFixed(1)} `;
    }

    // tangent line through the point with slope dydx; clamp drawing near vertical
    const L = 60; // half-length in px
    const vert = fld.tangentVert || Math.abs(fld.dydx) >= 999;
    let t1x, t1y, t2x, t2y;
    if (vert) { t1x = px; t1y = py - L; t2x = px; t2y = py + L; }
    else {
      const m = fld.dydx; // screen slope is −m (y flips)
      const dx = L / Math.sqrt(1 + m * m);
      t1x = px - dx; t1y = py + m * dx; // sy flips sign → +m*dx
      t2x = px + dx; t2y = py - m * dx;
    }
    const hot = fld.tangentHoriz || fld.tangentVert;
    const tanColor = fld.tangentHoriz ? C.teal : fld.tangentVert ? C.gold : C.amber;

    const tk = tasks.find((q) => q.id === task) || tasks[0];

    return (
      <>
        <TaskStrip tasks={tasks} cur={task} setCur={setTask} done={done} goal={tk && tk.goal} />
        <svg viewBox="0 0 600 300" style={{ width: "100%", background: SVG_BG, border: `1px solid ${C.line}`, borderRadius: 8 }}>
          <defs>
            <marker id="imp-t" markerWidth="9" markerHeight="9" refX="6" refY="3" orient="auto"><path d="M0,0 L6,3 L0,6 Z" fill={tanColor} /></marker>
          </defs>
          {/* axes */}
          <line x1={cx0 - 4.4 * S} y1={cy0} x2={cx0 + 4.4 * S} y2={cy0} stroke={C.faint} strokeWidth="1" />
          <line x1={cx0} y1={cy0 - 4.4 * S} x2={cx0} y2={cy0 + 4.4 * S} stroke={C.faint} strokeWidth="1" />
          {/* ellipse */}
          <polyline points={pts.trim()} fill="none" stroke={C.line} strokeWidth="1.6" />
          {/* tangent line */}
          <line x1={t1x} y1={t1y} x2={t2x} y2={t2y} stroke={tanColor} strokeWidth="2.5" markerEnd="url(#imp-t)" />
          {/* the point */}
          <circle cx={px} cy={py} r="4.5" fill={C.gold} stroke={C.bg} strokeWidth="1" />
          {/* readout panel */}
          <text x="372" y="40" fill={C.mute} fontSize="12" fontFamily="monospace">x²/A² + y²/B² = 1</text>
          <text x="372" y="64" fill={C.gold} fontSize="13" fontFamily="monospace">(x, y) = ({fmt(fld.xPt)}, {fmt(fld.yPt)})</text>
          <text x="372" y="86" fill={tanColor} fontSize="13" fontFamily="monospace">dy/dx = {fld.tangentVert ? "∞ (vertical)" : fmt(fld.dydx)}</text>
          <text x="372" y="108" fill={C.teal} fontSize="13" fontFamily="monospace">x²/A²+y²/B² = {fmt(fld.ellipseCheck)}</text>
          <text x="372" y="132" fill={C.mute} fontSize="11" fontFamily="monospace">{fld.tangentHoriz ? "horizontal tangent (x=0)" : fld.tangentVert ? "vertical tangent (y=0)" : "oblique tangent"}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${hot ? tanColor : C.line}`, color: hot ? tanColor : C.mute, fontSize: 12.5 }}>
          Implicit slope dy/dx = {fld.tangentVert ? "∞" : fmt(fld.dydx)}. {fld.tangentHoriz ? <>⚑ <K.T>Horizontal tangent at the top/bottom — here x=0 so dy/dx=0.</K.T></> : fld.tangentVert ? <>⚑ <K.T>Vertical tangent at a vertex — here y=0 so the slope is undefined.</K.T></> : <K.T>Move the point t toward a vertex (vertical) or the top/bottom (horizontal).</K.T>}
        </div>
        <Slider label="semi-axis A" value={A} set={setA} min={1} max={4} step={0.5} unit="" color={C.blue} onUp={() => event("adjusted", `Set A = ${fmt(A)}`, { response: `dydx ${fmt(fld.dydx)}` }, C.blue)} />
        <Slider label="semi-axis B" value={B} set={setB} min={1} max={4} step={0.5} unit="" color={C.teal} onUp={() => event("adjusted", `Set B = ${fmt(B)}`, { response: `dydx ${fmt(fld.dydx)}` }, C.teal)} />
        <Slider label="point angle t" value={t} set={(v) => setT(Math.round(v))} min={0} max={360} step={5} unit="°" color={C.gold} onUp={() => event("adjusted", `Set t = ${Math.round(t)}°`, { response: `dydx ${fmt(fld.dydx)}` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="x" v={fld.xPt} d={2} color={C.gold} />
          <StatMeter label="y" v={fld.yPt} d={2} color={C.teal} />
          <StatMeter label="dy/dx" v={fld.dydx} d={2} color={tanColor} />
          <StatMeter label="x²/A²+y²/B²" v={fld.ellipseCheck} d={2} color={C.blue} />
        </div>
      </>
    );
  }

  window.ImplicitTutor = K.makeTutor(ImplicitFig, { moduleLabel: "Implicit Differentiation bench", benchId: "implicit" });
})();
