/* pythagoreanlab.jsx — PythagoreanTutor: the right-triangle bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   compute = window.BenchFields.pythagorean — the SAME function server/benches/pythagorean.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.pythagorean(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 PythagoreanFig({ task, setTask, tasks, report, event, done }) {
    const [legA, setLegA] = useState(3);
    const [legB, setLegB] = useState(4);
    const fld = useMemo(() => compute({ legA, legB }), [legA, legB]);
    useEffect(() => { report(fld); }, [legA, legB]); // eslint-disable-line

    // right angle at bottom-left corner (RX, RY). leg a = horizontal (∝ a), leg b = vertical (∝ b).
    const RX = 150, RY = 250, PX = 18; // pixels per unit
    const ax = legA * PX, by = legB * PX;
    const Bx = RX + ax, By = RY;          // end of horizontal leg a
    const Ty = RY - by, Tx = RX;          // top of vertical leg b
    const hyp = fld.hypotenuse;
    // small square on horizontal leg a (below it), on vertical leg b (left of it), and on hypotenuse (outward).
    const sq = Math.min(ax, by, 36); // illustrative unit-square size, capped
    const isTriple = fld.isPythagoreanTriple, isIso = fld.isIsosceles;

    // hypotenuse runs from B (bottom-right) to T (top-left); outward normal points up-right.
    const hx = Tx - Bx, hy = Ty - By, hl = Math.hypot(hx, hy) || 1;
    const nx = hy / hl, ny = -hx / hl; // unit normal pointing away from the right-angle corner
    const hsq = sq; // square edge along hypotenuse (illustrative)

    const t = tasks.find((x) => x.id === task) || tasks[0];

    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 }}>
          {/* small square on leg a (below the horizontal leg) */}
          <rect x={RX} y={RY} width={Math.max(0, ax)} height={hsq} fill={C.blue} opacity="0.10" stroke={C.blue} strokeWidth="1" />
          {/* small square on leg b (left of the vertical leg) */}
          <rect x={RX - hsq} y={Ty} width={hsq} height={Math.max(0, by)} fill={C.gold} opacity="0.10" stroke={C.gold} strokeWidth="1" />
          {/* square on the hypotenuse (outward) */}
          <polygon
            points={`${Bx},${By} ${Tx},${Ty} ${Tx + nx * hsq},${Ty + ny * hsq} ${Bx + nx * hsq},${By + ny * hsq}`}
            fill={C.teal} opacity="0.10" stroke={C.teal} strokeWidth="1" />
          {/* the right triangle */}
          <polygon points={`${RX},${RY} ${Bx},${By} ${Tx},${Ty}`} fill={C.teal} opacity="0.14" stroke={isIso ? C.gold : C.teal} strokeWidth="2" />
          {/* right-angle marker at the corner */}
          <rect x={RX} y={RY - 12} width={12} height={12} fill="none" stroke={C.faint} strokeWidth="1.2" />
          {/* leg + hypotenuse labels */}
          <text x={(RX + Bx) / 2} y={RY + 18} textAnchor="middle" fill={C.blue} fontSize="12" fontFamily="monospace">a = {fmt(legA)}</text>
          <text x={RX - 12} y={(RY + Ty) / 2} textAnchor="end" fill={C.gold} fontSize="12" fontFamily="monospace">b = {fmt(legB)}</text>
          <text x={(Bx + Tx) / 2 + nx * 16} y={(By + Ty) / 2 + ny * 16} textAnchor="middle" fill={C.ink} fontSize="13" fontFamily="monospace">c = {fmt(hyp)}</text>
          <text x={14} y={24} fill={C.mute} fontSize="11" fontFamily="monospace">a² + b² = c²  ·  {fmt(fld.hypSquared)} = c²{isTriple ? "  · integer triple" : ""}{isIso ? "  · isosceles" : ""}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${isTriple ? C.teal : C.line}`, color: isTriple ? C.teal : C.mute, fontSize: 12.5 }}>
          c = √(a²+b²) = {fmt(hyp)}. {isTriple ? "✓ integer Pythagorean triple." : "Square the legs and add — don't add a + b — to find c."}
        </div>
        <Slider label="leg a" value={legA} set={setLegA} min={1} max={20} step={1} color={C.blue} onUp={() => event("adjusted", `Set a = ${fmt(legA)}`, { response: `c ${fmt(fld.hypotenuse)}` }, C.blue)} />
        <Slider label="leg b" value={legB} set={setLegB} min={1} max={20} step={1} color={C.gold} onUp={() => event("adjusted", `Set b = ${fmt(legB)}`, { response: `c ${fmt(fld.hypotenuse)}` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="hypotenuse c" v={fld.hypotenuse} d={2} color={C.teal} />
          <StatMeter label="c² = a²+b²" v={fld.hypSquared} d={1} color={C.crimson} />
          <StatMeter label="area" v={fld.area} d={2} color={C.amber} />
          <StatMeter label="perimeter" v={fld.perimeter} d={2} color={C.blue} />
        </div>
      </>
    );
  }

  window.PythagoreanTutor = K.makeTutor(PythagoreanFig, { moduleLabel: "Pythagorean theorem bench", benchId: "pythagorean" });
})();
