/* refractionlab.jsx — RefractionTutor: a light ray crossing a planar interface between two
   media. Built on window.BenchKit (harness) + window.BenchFields (shared field math), so this
   file is just the FIGURE. compute = window.BenchFields.refraction — the SAME function
   server/benches/refraction.js calls, so client and server fields are identical by construction.
   Sliders → BenchFields.refraction(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.refraction(s);
  const RAD = Math.PI / 180;

  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: 160 }}>{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 RefractionFig({ task, setTask, tasks, report, event, done }) {
    const [n1, setN1] = useState(1.5);
    const [n2, setN2] = useState(1.0);
    const [incidentAngle, setIncidentAngle] = useState(30);
    const fld = useMemo(() => compute({ n1, n2, incidentAngle }), [n1, n2, incidentAngle]);
    useEffect(() => { report(fld); }, [n1, n2, incidentAngle]); // eslint-disable-line

    // Geometry: horizontal interface across the middle; medium 1 above, medium 2 below.
    const W = 600, H = 300, IY = 150, HX = 300; // interface y, hit point x
    const L = 120; // ray length
    // tint ∝ index (clamped to [1,2.5])
    const tint = (n) => 0.05 + Math.min(1, Math.max(0, (n - 1) / 1.5)) * 0.20;
    const th1 = incidentAngle * RAD;
    // incident ray comes from upper-left into the hit point (above interface)
    const ix = HX - Math.sin(th1) * L, iy = IY - Math.cos(th1) * L;
    const tir = !!fld.isTIR;
    // refracted ray (into medium 2, below) at refractAngle; reflected ray (back into medium 1) on TIR
    const th2 = fld.refractAngle * RAD;
    const rx = HX + Math.sin(th2) * L, ry = IY + Math.cos(th2) * L;          // refracted
    const reflx = HX + Math.sin(th1) * L, refly = IY - Math.cos(th1) * L;    // reflected (mirror of incident)

    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 }}>
          {/* media tints */}
          <rect x={0} y={0} width={W} height={IY} fill={C.blue} opacity={tint(n1)} />
          <rect x={0} y={IY} width={W} height={H - IY} fill={C.teal} opacity={tint(n2)} />
          {/* interface */}
          <line x1={0} y1={IY} x2={W} y2={IY} stroke={C.faint} strokeWidth="1.5" />
          {/* normal (dashed vertical at hit point) */}
          <line x1={HX} y1={20} x2={HX} y2={H - 20} stroke={C.mute} strokeWidth="1" strokeDasharray="4 4" />
          {/* incident ray */}
          <line x1={ix} y1={iy} x2={HX} y2={IY} stroke={C.gold} strokeWidth="2.5" />
          <text x={ix - 4} y={iy - 4} fill={C.gold} fontSize="11" fontFamily="monospace" textAnchor="end">θ₁ = {Math.round(incidentAngle)}°</text>
          {tir ? (
            <>
              {/* reflected ray back into medium 1 */}
              <line x1={HX} y1={IY} x2={reflx} y2={refly} stroke={C.crimson} strokeWidth="2.5" />
              <text x={reflx + 4} y={refly - 2} fill={C.crimson} fontSize="12" fontFamily="monospace">TIR</text>
            </>
          ) : (
            <>
              {/* refracted ray into medium 2 */}
              <line x1={HX} y1={IY} x2={rx} y2={ry} stroke={C.crimson} strokeWidth="2.5" />
              <text x={rx + 6} y={ry + 4} fill={C.crimson} fontSize="11" fontFamily="monospace">θ₂ = {fmt(fld.refractAngle)}°</text>
            </>
          )}
          {/* labels */}
          <text x={10} y={20} fill={C.ink} fontSize="11" fontFamily="monospace">medium 1 · n₁ = {fmt(n1)}</text>
          <text x={10} y={H - 10} fill={C.ink} fontSize="11" fontFamily="monospace">medium 2 · n₂ = {fmt(n2)}</text>
          <text x={W - 10} y={IY - 8} fill={C.mute} fontSize="11" fontFamily="monospace" textAnchor="end">θ_c = {fmt(fld.criticalAngle)}°</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${tir ? C.crimson : C.line}`, color: tir ? C.crimson : C.mute, fontSize: 12.5 }}>
          n₁·sinθ₁ = n₂·sinθ₂ · {tir ? "⚠ total internal reflection — the ray cannot escape (θ₁ > θ_c)." : (fld.bendsTowardNormal ? "bends toward the normal (n₂ > n₁)." : "bends away from the normal (n₂ < n₁).")}
        </div>
        <Slider label="index n₁ (incident)" value={n1} set={setN1} min={1} max={2.5} step={0.01} color={C.blue} onUp={() => event("adjusted", `Set n₁ = ${fmt(n1)}`, { response: tir ? "TIR" : `θ₂ ${fmt(fld.refractAngle)}°` }, C.blue)} />
        <Slider label="index n₂ (refracting)" value={n2} set={setN2} min={1} max={2.5} step={0.01} color={C.teal} onUp={() => event("adjusted", `Set n₂ = ${fmt(n2)}`, { response: tir ? "TIR" : `θ₂ ${fmt(fld.refractAngle)}°` }, C.teal)} />
        <Slider label="incident angle θ₁" value={incidentAngle} set={setIncidentAngle} min={0} max={89} step={1} unit="°" color={C.gold} onUp={() => event("adjusted", `Set θ₁ = ${Math.round(incidentAngle)}°`, { response: tir ? "TIR" : `θ₂ ${fmt(fld.refractAngle)}°` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="refraction θ₂" v={fld.refractAngle} d={1} unit="°" color={tir ? C.crimson : C.teal} />
          <StatMeter label="critical θ_c" v={fld.criticalAngle} d={1} unit="°" color={C.amber} />
          <StatMeter label="incident θ₁" v={fld.incidentAngle} d={0} unit="°" color={C.gold} />
          <StatMeter label="index ratio n₁/n₂" v={fld.indexRatio} d={2} color={C.blue} />
        </div>
      </>
    );
  }

  window.RefractionTutor = K.makeTutor(RefractionFig, { moduleLabel: "Refraction bench", benchId: "refraction" });
})();
