/* quadraticlab.jsx — QuadraticTutor: the parabola y = ax² + bx + c bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is
   just the FIGURE. compute = window.BenchFields.quadratic — the SAME function
   server/benches/quadratic.js calls, so client and server fields are identical by
   construction. Follows the single-figure lab TEMPLATE (gaslawslab.jsx):
   sliders → BenchFields.fn(state) → report + meters. */
(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.quadratic(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 }}>{label}</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 QuadraticFig({ task, setTask, tasks, report, event, done }) {
    const [a, setA] = useState(1);
    const [b, setB] = useState(-5);
    const [c, setC] = useState(6);
    const fld = useMemo(() => compute({ a, b, c }), [a, b, c]);
    useEffect(() => { report(fld); }, [a, b, c]); // eslint-disable-line

    // graph window: x ∈ [-8,8], y ∈ [-10,10] mapped to the SVG stage.
    const X0 = 60, X1 = 560, AY0 = 30, AY1 = 270;
    const xMin = -8, xMax = 8, yMin = -10, yMax = 10;
    const sx = (x) => X0 + ((x - xMin) / (xMax - xMin)) * (X1 - X0);
    const sy = (y) => AY1 - ((y - yMin) / (yMax - yMin)) * (AY1 - AY0);
    const yOf = (x) => a * x * x + b * x + c;

    // sample the parabola across the window.
    let path = "";
    for (let i = 0; i <= 200; i++) {
      const x = xMin + (i / 200) * (xMax - xMin);
      const py = Math.max(yMin - 5, Math.min(yMax + 5, yOf(x)));
      path += (i === 0 ? "M" : "L") + sx(x).toFixed(1) + " " + sy(py).toFixed(1) + " ";
    }

    // roots (x-intercepts) when real.
    const roots = [];
    if (fld.hasRealRoots && fld.discriminant >= 0) {
      const sq = Math.sqrt(Math.max(0, fld.discriminant));
      const aa = a || 1e-9;
      roots.push((-b + sq) / (2 * aa));
      if (fld.rootCount === 2) roots.push((-b - sq) / (2 * aa));
    }

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const dPos = fld.discriminant > 0, dZero = Math.abs(fld.discriminant) <= 0.2;

    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.5" />
          <line x1={sx(0)} y1={AY0} x2={sx(0)} y2={AY1} stroke={C.faint} strokeWidth="1.5" />
          <text x={X1 - 8} y={sy(0) - 6} fill={C.mute} fontSize="10" fontFamily="monospace">x</text>
          <text x={sx(0) + 6} y={AY0 + 12} fill={C.mute} fontSize="10" fontFamily="monospace">y</text>
          {/* axis of symmetry */}
          {isFinite(fld.vertexX) && Math.abs(fld.vertexX) <= xMax ? (
            <line x1={sx(fld.vertexX)} y1={AY0} x2={sx(fld.vertexX)} y2={AY1} stroke={C.gold} strokeWidth="0.8" strokeDasharray="3 4" opacity="0.6" />
          ) : null}
          {/* the parabola */}
          <path d={path} fill="none" stroke={C.teal} strokeWidth="2.4" />
          {/* roots (x-intercepts) */}
          {roots.map((rx, i) => Math.abs(rx) <= xMax ? (
            <circle key={i} cx={sx(rx)} cy={sy(0)} r={5} fill={C.crimson} stroke={SVG_BG} strokeWidth="1.5" />
          ) : null)}
          {/* vertex */}
          {isFinite(fld.vertexX) && Math.abs(fld.vertexX) <= xMax && fld.vertexY >= yMin - 5 && fld.vertexY <= yMax + 5 ? (
            <>
              <circle cx={sx(fld.vertexX)} cy={sy(fld.vertexY)} r={5} fill={C.amber} stroke={SVG_BG} strokeWidth="1.5" />
              <text x={sx(fld.vertexX) + 8} y={sy(fld.vertexY) - 6} fill={C.amber} fontSize="11" fontFamily="monospace">({fmt(fld.vertexX)}, {fmt(fld.vertexY)})</text>
            </>
          ) : null}
          <text x={X0 + 6} y={AY0 + 14} fill={C.ink} fontSize="12" fontFamily="monospace">y = {fmt(a)}x² + {fmt(b)}x + {fmt(c)}</text>
          <text x={X0 + 6} y={AY1 - 8} fill={dPos ? C.teal : dZero ? C.gold : C.crimson} fontSize="12" fontFamily="monospace">Δ = b² − 4ac = {fmt(fld.discriminant)} · {fld.rootCount} root{fld.rootCount === 1 ? "" : "s"} · opens {fld.opensUp ? "up" : "down"}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${C.line}`, color: C.mute, fontSize: 12.5 }}>
          y = ax² + bx + c · Δ = {fmt(fld.discriminant)} ⇒ {fld.rootCount === 2 ? "two real roots." : fld.rootCount === 1 ? "one (double) root." : "no real roots (Δ < 0)."} Vertex at x = −b/2a = {fmt(fld.vertexX)}.
        </div>
        <Slider label="coefficient a" value={a} set={setA} min={-3} max={3} step={0.1} unit="" color={C.blue} onUp={() => event("adjusted", `Set a = ${fmt(a)}`, { response: `Δ ${fmt(fld.discriminant)}, ${fld.rootCount} roots` }, C.blue)} />
        <Slider label="coefficient b" value={b} set={setB} min={-10} max={10} step={0.5} unit="" color={C.crimson} onUp={() => event("adjusted", `Set b = ${fmt(b)}`, { response: `Δ ${fmt(fld.discriminant)}, ${fld.rootCount} roots` }, C.crimson)} />
        <Slider label="coefficient c" value={c} set={setC} min={-10} max={10} step={0.5} unit="" color={C.gold} onUp={() => event("adjusted", `Set c = ${fmt(c)}`, { response: `Δ ${fmt(fld.discriminant)}, ${fld.rootCount} roots` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="discriminant Δ" v={fld.discriminant} d={2} color={dPos ? C.teal : dZero ? C.gold : C.crimson} />
          <StatMeter label="vertex x" v={fld.vertexX} d={2} color={C.amber} />
          <StatMeter label="vertex y" v={fld.vertexY} d={2} color={C.amber} />
          <StatMeter label="real roots" v={fld.rootCount} d={0} color={C.blue} />
        </div>
      </>
    );
  }

  window.QuadraticTutor = K.makeTutor(QuadraticFig, { moduleLabel: "Quadratic functions bench", benchId: "quadratic" });
})();
