/* areabetweenlab.jsx — AreaBetweenTutor: the area-between-curves bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.areabetween — the SAME function server/benches/areabetween.js
   calls, so client and server fields are identical by construction. The learner tunes a line
   y = mx + b across the parabola y = x²; the shaded region between the intersections makes the
   enclosed area visible. */
(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.areabetween(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 AreaBetweenFig({ task, setTask, tasks, report, event, done }) {
    const [m, setM] = useState(1);
    const [b, setB] = useState(2);
    const fld = useMemo(() => compute({ m, b }), [m, b]);
    useEffect(() => { report(fld); }, [m, b]); // eslint-disable-line

    // plot window: x ∈ [-4,4], y ∈ [-2,16]; map math coords → svg px.
    const X0 = 60, X1 = 560, Y0 = 30, Y1 = 270;
    const XMIN = -4, XMAX = 4, YMIN = -2, YMAX = 16;
    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 para = (x) => x * x;
    const line = (x) => m * x + b;

    // sample the parabola and the line across the window
    const pp = [], lp = [];
    for (let i = 0; i <= 120; i++) { const x = XMIN + (i / 120) * (XMAX - XMIN); pp.push(`${sx(x).toFixed(1)},${sy(para(x)).toFixed(1)}`); lp.push(`${sx(x).toFixed(1)},${sy(line(x)).toFixed(1)}`); }
    const parabola = pp.join(" "), lineStr = lp.join(" ");

    // shade the enclosed region between lowerX and upperX (line on top, parabola on bottom)
    let shade = "";
    if (fld.hasRegion) {
      const top = [], bot = [];
      for (let i = 0; i <= 60; i++) { const x = fld.lowerX + (i / 60) * (fld.upperX - fld.lowerX); top.push(`${sx(x).toFixed(1)},${sy(line(x)).toFixed(1)}`); bot.push(`${sx(x).toFixed(1)},${sy(para(x)).toFixed(1)}`); }
      shade = top.concat(bot.reverse()).join(" ");
    }

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const regionColor = fld.hasRegion ? C.teal : C.crimson;

    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" />
          <text x={X1 - 6} y={sy(0) - 5} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="end">x</text>
          {/* shaded enclosed region */}
          {fld.hasRegion && <polygon points={shade} fill={C.teal} fillOpacity="0.22" stroke="none" />}
          {/* the parabola y = x² */}
          <polyline points={parabola} fill="none" stroke={C.blue} strokeWidth="2" />
          {/* the line y = mx + b */}
          <polyline points={lineStr} fill="none" stroke={C.amber} strokeWidth="2" />
          {/* intersection markers */}
          {fld.hasRegion && [fld.lowerX, fld.upperX].map((ix) => <circle key={ix} cx={sx(ix)} cy={sy(para(ix))} r={4.5} fill={regionColor} stroke={C.ink} strokeWidth="1" />)}
          <text x={X0 + 4} y={Y0 + 14} fill={C.mute} fontSize="11" fontFamily="monospace">y = x² vs y = {fmt(m)}x + {fmt(b)} · area = {fmt(fld.area)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.hasRegion ? C.teal : C.crimson}`, color: fld.hasRegion ? C.mute : C.crimson, fontSize: 12.5 }}>
          {fld.hasRegion
            ? <><K.T>Enclosed region</K.T> from x = {fmt(fld.lowerX)} to x = {fmt(fld.upperX)} (width {fmt(fld.width)}). <K.T>area</K.T> = ∫(line − x²)dx = {fmt(fld.area)}.</>
            : <K.T>no enclosed region — the line misses the parabola</K.T>}
        </div>
        <Slider label="slope m" value={m} set={setM} min={-3} max={3} step={0.5} unit="" color={C.amber} onUp={() => event("adjusted", `Set slope m = ${fmt(m)}`, { response: `area ${fmt(fld.area)}` }, C.amber)} />
        <Slider label="intercept b" value={b} set={setB} min={-1} max={6} step={0.5} unit="" color={C.gold} onUp={() => event("adjusted", `Set intercept b = ${fmt(b)}`, { response: `area ${fmt(fld.area)}` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="area" v={fld.area} d={2} color={regionColor} />
          <StatMeter label="lowerX" v={fld.lowerX} d={2} color={C.blue} />
          <StatMeter label="upperX" v={fld.upperX} d={2} color={C.blue} />
          <StatMeter label="width" v={fld.width} d={2} color={C.amber} />
        </div>
      </>
    );
  }

  window.AreaBetweenTutor = K.makeTutor(AreaBetweenFig, { moduleLabel: "Area Between Curves bench", benchId: "areabetween" });
})();
