/* limitslab.jsx — LimitsTutor: the limits & continuity bench. Built on window.BenchKit (harness) +
   window.BenchFields (shared field math), so this file is just the FIGURE. computeFields =
   window.BenchFields.limits — the SAME function server/benches/limits.js calls, so client and server
   fields are identical by construction. The learner tunes the left limit, the jump to the right
   branch, and a hole offsetting f(c) at a fixed point c = 1. */
(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.limits(s);
  const CX = 1; // the fixed point of interest c

  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: 140 }}><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: 56, textAlign: "right" }}>{value}{unit ? ` ${unit}` : ""}</span>
      </div>
    );
  }

  function LimitsFig({ task, setTask, tasks, report, event, done }) {
    const [baseLevel, setBaseLevel] = useState(1);
    const [jump, setJump] = useState(2);
    const [hole, setHole] = useState(0);
    const fld = useMemo(() => compute({ baseLevel, jump, hole }), [baseLevel, jump, hole]);
    useEffect(() => { report(fld); }, [baseLevel, jump, hole]); // eslint-disable-line

    const X0 = 60, X1 = 560, Y0 = 30, Y1 = 270;
    const XMIN = -1.5, XMAX = 3.5, YMIN = -6, YMAX = 6;
    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 M = 1; // branch slope
    const yL = (x) => fld.leftLimit + M * (x - CX);   // left branch
    const yR = (x) => fld.rightLimit + M * (x - CX);  // right branch

    const leftPts = [], rightPts = [];
    for (let i = 0; i <= 60; i++) { const x = XMIN + (i / 60) * (CX - XMIN); leftPts.push(`${sx(x).toFixed(1)},${sy(yL(x)).toFixed(1)}`); }
    for (let i = 0; i <= 60; i++) { const x = CX + (i / 60) * (XMAX - CX); rightPts.push(`${sx(x).toFixed(1)},${sy(yR(x)).toFixed(1)}`); }

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const stateColor = fld.continuous ? C.teal : (fld.limitExists ? C.amber : C.crimson);
    const stateText = fld.continuous ? "continuous at c" : (fld.limitExists ? "removable hole — limit exists, not continuous" : "jump — the two-sided limit does not exist");

    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 line x = c */}
          <line x1={sx(CX)} y1={Y0} x2={sx(CX)} y2={Y1} stroke={C.line} strokeWidth="1" strokeDasharray="3 4" />
          <text x={sx(CX) + 4} y={Y1 - 4} fill={C.faint} fontSize="10" fontFamily="monospace">x = c = 1</text>
          {/* branches */}
          <polyline points={leftPts.join(" ")} fill="none" stroke={C.blue} strokeWidth="2.5" />
          <polyline points={rightPts.join(" ")} fill="none" stroke={C.blue} strokeWidth="2.5" />
          {/* open circles at each branch's endpoint (the one-sided limits) */}
          <circle cx={sx(CX)} cy={sy(fld.leftLimit)} r={5} fill={SVG_BG} stroke={C.blue} strokeWidth="2" />
          <circle cx={sx(CX)} cy={sy(fld.rightLimit)} r={5} fill={SVG_BG} stroke={C.blue} strokeWidth="2" />
          {/* the defined value f(c): a filled dot */}
          <circle cx={sx(CX)} cy={sy(fld.fAtC)} r={5.5} fill={stateColor} stroke={C.ink} strokeWidth="1" />
          <text x={sx(CX) + 9} y={sy(fld.fAtC) + 4} fill={stateColor} fontSize="12" fontFamily="monospace">f(c) = {fmt(fld.fAtC)}</text>
          <text x={X0 + 4} y={Y0 + 14} fill={C.mute} fontSize="11" fontFamily="monospace">lim⁻ = {fmt(fld.leftLimit)} · lim⁺ = {fmt(fld.rightLimit)} · gap = {fmt(fld.gap)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${stateColor}`, color: stateColor, fontSize: 12.5 }}>
          {fld.limitExists ? <><K.T>The two-sided limit exists</K.T> (left = right).</> : <><K.T>No two-sided limit</K.T> — left ≠ right.</>} <K.T>{stateText}</K.T>
        </div>
        <Slider label="left limit (base)" value={baseLevel} set={setBaseLevel} min={-3} max={3} step={0.5} unit="" color={C.blue} onUp={() => event("adjusted", `Set left limit = ${fmt(baseLevel)}`, { response: `lim ${fmt(fld.leftLimit)}` }, C.blue)} />
        <Slider label="jump (right − left)" value={jump} set={setJump} min={-4} max={4} step={0.5} unit="" color={C.crimson} onUp={() => event("adjusted", `Set jump = ${fmt(jump)}`, { response: `limitExists ${fld.limitExists}` }, C.crimson)} />
        <Slider label="hole (f(c) − limit)" value={hole} set={setHole} min={-4} max={4} step={0.5} unit="" color={C.amber} onUp={() => event("adjusted", `Set hole = ${fmt(hole)}`, { response: `continuous ${fld.continuous}` }, C.amber)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="lim⁻ (left)" v={fld.leftLimit} d={2} color={C.blue} />
          <StatMeter label="lim⁺ (right)" v={fld.rightLimit} d={2} color={C.blue} />
          <StatMeter label="limit exists?" v={fld.limitExists ? 1 : 0} d={0} color={fld.limitExists ? C.teal : C.crimson} />
          <StatMeter label="continuous?" v={fld.continuous ? 1 : 0} d={0} color={fld.continuous ? C.teal : C.crimson} />
        </div>
      </>
    );
  }

  window.LimitsTutor = K.makeTutor(LimitsFig, { moduleLabel: "Limits & Continuity bench", benchId: "limits" });
})();
