/* systemslab.jsx — SystemsTutor: the systems-of-equations bench. Two lines on one graph.
   Built on window.BenchKit (harness) + window.BenchFields (shared field math), so this file
   is just the FIGURE. compute = window.BenchFields.systems — the SAME function
   server/benches/systems.js calls, so client and server fields are identical by construction. */
(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.systems(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 SystemsFig({ task, setTask, tasks, report, event, done }) {
    const [m1, setM1] = useState(1);
    const [b1, setB1] = useState(0);
    const [m2, setM2] = useState(-1);
    const [b2, setB2] = useState(4);
    const fld = useMemo(() => compute({ m1, b1, m2, b2 }), [m1, b1, m2, b2]);
    useEffect(() => { report(fld); }, [m1, b1, m2, b2]); // eslint-disable-line

    // graph: x,y both in [-10,10] mapped into a 600x300 SVG box.
    const GX0 = 60, GX1 = 560, GY0 = 30, GY1 = 270;
    const DOM = 10; // x,y range ±10
    const sx = (x) => GX0 + ((x + DOM) / (2 * DOM)) * (GX1 - GX0);
    const sy = (y) => GY1 - ((y + DOM) / (2 * DOM)) * (GY1 - GY0);
    const lineEnds = (m, b) => `${sx(-DOM)},${sy(m * -DOM + b)} ${sx(DOM)},${sy(m * DOM + b)}`;

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const solType = fld.sameLine ? "same line · infinitely many solutions"
      : fld.parallel ? "parallel · no solution"
      : "one solution";
    const typeColor = fld.sameLine ? C.amber : fld.parallel ? C.crimson : C.teal;
    const inView = fld.hasSolution && Math.abs(fld.solX) <= DOM && Math.abs(fld.solY) <= DOM;

    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={GX0} y1={sy(0)} x2={GX1} y2={sy(0)} stroke={C.faint} strokeWidth="1" />
          <line x1={sx(0)} y1={GY0} x2={sx(0)} y2={GY1} stroke={C.faint} strokeWidth="1" />
          <text x={GX1 - 4} y={sy(0) - 5} textAnchor="end" fill={C.faint} fontSize="10" fontFamily="monospace">x</text>
          <text x={sx(0) + 5} y={GY0 + 10} fill={C.faint} fontSize="10" fontFamily="monospace">y</text>
          {/* line 1 */}
          <polyline points={lineEnds(m1, b1)} fill="none" stroke={C.blue} strokeWidth="2.5" />
          <text x={GX0 + 6} y={GY0 + 14} fill={C.blue} fontSize="11" fontFamily="monospace">y = {fmt(m1)}x + {fmt(b1)}</text>
          {/* line 2 */}
          <polyline points={lineEnds(m2, b2)} fill="none" stroke={C.amber} strokeWidth="2.5" opacity={fld.sameLine ? 0.55 : 1} strokeDasharray={fld.sameLine ? "6 5" : "none"} />
          <text x={GX0 + 6} y={GY0 + 30} fill={C.amber} fontSize="11" fontFamily="monospace">y = {fmt(m2)}x + {fmt(b2)}</text>
          {/* intersection */}
          {inView ? (
            <>
              <circle cx={sx(fld.solX)} cy={sy(fld.solY)} r={5} fill={C.teal} stroke={SVG_BG} strokeWidth="1.5" />
              <text x={sx(fld.solX) + 8} y={sy(fld.solY) - 8} fill={C.teal} fontSize="12" fontFamily="monospace">({fmt(fld.solX)}, {fmt(fld.solY)})</text>
            </>
          ) : null}
          <text x={GX1 - 6} y={GY1 - 8} textAnchor="end" fill={typeColor} fontSize="12" fontFamily="monospace">{solType}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${typeColor}`, color: typeColor, fontSize: 12.5 }}>
          {fld.hasSolution
            ? `Distinct slopes ⇒ the lines cross at (${fmt(fld.solX)}, ${fmt(fld.solY)}) — one solution.`
            : fld.parallel
              ? "Equal slopes, different intercepts ⇒ parallel lines, no solution."
              : "Equal slopes AND equal intercepts ⇒ the same line, infinitely many solutions."}
        </div>
        <Slider label="m₁ (slope 1)" value={m1} set={setM1} min={-5} max={5} step={0.5} color={C.blue} onUp={() => event("adjusted", `Set m₁ = ${fmt(m1)}`, { response: solType }, C.blue)} />
        <Slider label="b₁ (intercept 1)" value={b1} set={setB1} min={-10} max={10} step={1} color={C.blue} onUp={() => event("adjusted", `Set b₁ = ${fmt(b1)}`, { response: solType }, C.blue)} />
        <Slider label="m₂ (slope 2)" value={m2} set={setM2} min={-5} max={5} step={0.5} color={C.amber} onUp={() => event("adjusted", `Set m₂ = ${fmt(m2)}`, { response: solType }, C.amber)} />
        <Slider label="b₂ (intercept 2)" value={b2} set={setB2} min={-10} max={10} step={1} color={C.amber} onUp={() => event("adjusted", `Set b₂ = ${fmt(b2)}`, { response: solType }, C.amber)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="solution x" v={fld.hasSolution ? fld.solX : "—"} d={2} color={C.teal} />
          <StatMeter label="solution y" v={fld.hasSolution ? fld.solY : "—"} d={2} color={C.teal} />
          <StatMeter label="slope Δ" v={fmt(m1 - m2)} color={C.blue} />
          <StatMeter label="intercept Δ" v={fmt(b1 - b2)} color={C.amber} />
        </div>
        <div style={{ marginTop: 8, fontSize: 12, color: typeColor, fontFamily: "monospace" }}>
          solution type: {solType}
        </div>
      </>
    );
  }

  window.SystemsTutor = K.makeTutor(SystemsFig, { moduleLabel: "Systems of equations bench", benchId: "systems" });
})();
