/* halflifelab.jsx — HalfLifeTutor: the radioactive-dating bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   compute = window.BenchFields.halfLife — the SAME function server/benches/halflife.js calls,
   so client and server fields are identical by construction. Follows the gaslaws template:
   sliders → BenchFields.fn(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.halfLife(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 HalfLifeFig({ task, setTask, tasks, report, event, done }) {
    const [halfLife, setHL] = useState(5730);
    const [elapsed, setElapsed] = useState(2000);
    const [N0, setN0] = useState(100);
    const fld = useMemo(() => compute({ halfLife, elapsed, N0 }), [halfLife, elapsed, N0]);
    useEffect(() => { report(fld); }, [halfLife, elapsed, N0]); // eslint-disable-line

    // decay curve: x = number of half-lives (0..6), y = fraction remaining.
    const X0 = 60, X1 = 470, AY0 = 40, AY1 = 240, MAXH = 6;
    const sx = (h) => X0 + Math.min(h, MAXH) / MAXH * (X1 - X0);
    const sy = (f) => AY1 - f * (AY1 - AY0);
    const pts = [];
    for (let i = 0; i <= 60; i++) { const h = (i / 60) * MAXH; pts.push(`${sx(h)},${sy(Math.pow(0.5, h))}`); }
    const curX = sx(fld.nHalfLives), curY = sy(fld.fractionRemaining);
    // remaining-amount bar on the right.
    const barX = 520, barW = 36, barH = AY1 - AY0;
    const fillH = fld.fractionRemaining * barH;
    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 }}>
          {/* axes */}
          <line x1={X0} y1={AY1} x2={X1} y2={AY1} stroke={C.faint} strokeWidth="1.5" />
          <line x1={X0} y1={AY0} x2={X0} y2={AY1} stroke={C.faint} strokeWidth="1.5" />
          {/* decay curve */}
          <polyline points={pts.join(" ")} fill="none" stroke={C.teal} strokeWidth="2" />
          {/* current point */}
          <line x1={curX} y1={AY0} x2={curX} y2={AY1} stroke={C.gold} strokeWidth="1" strokeDasharray="3 3" />
          <circle cx={curX} cy={curY} r={5} fill={C.crimson} />
          <text x={X0} y={AY0 - 8} fill={C.mute} fontSize="11" fontFamily="monospace">N/N₀ = {fmt(fld.fractionRemaining)} · {fmt(fld.nHalfLives)} half-lives</text>
          <text x={(X0 + X1) / 2} y={AY1 + 18} textAnchor="middle" fill={C.mute} fontSize="10" fontFamily="monospace">half-lives elapsed →</text>
          {/* remaining bar */}
          <rect x={barX} y={AY0} width={barW} height={barH} fill="none" stroke={C.faint} strokeWidth="1" />
          <rect x={barX} y={AY1 - fillH} width={barW} height={fillH} fill={C.blue} opacity="0.7" />
          <text x={barX + barW / 2} y={AY0 - 8} textAnchor="middle" fill={C.ink} fontSize="11" fontFamily="monospace">{fmt(fld.remaining)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${C.line}`, color: C.mute, fontSize: 12.5 }}>
          N/N₀ = (1/2)^(t/t½) = {fmt(fld.fractionRemaining)}. {fld.mostlyDecayed ? "✓ mostly decayed (≤10%)." : "Increase elapsed time (or shorten t½) to decay further."}
        </div>
        <Slider label="half-life t½" value={halfLife} set={setHL} min={1} max={10000} step={1} color={C.gold} onUp={() => event("adjusted", `Set t½ = ${fmt(halfLife)}`, { response: `N/N₀ ${fmt(fld.fractionRemaining)}` }, C.gold)} />
        <Slider label="time elapsed t" value={elapsed} set={setElapsed} min={0} max={40000} step={50} color={C.crimson} onUp={() => event("adjusted", `Set t = ${fmt(elapsed)}`, { response: `N/N₀ ${fmt(fld.fractionRemaining)}` }, C.crimson)} />
        <Slider label="initial amount N₀" value={N0} set={setN0} min={1} max={1000} step={1} color={C.blue} onUp={() => event("adjusted", `Set N₀ = ${fmt(N0)}`, { response: `remaining ${fmt(fld.remaining)}` }, C.blue)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="fraction left" v={fld.fractionRemaining} d={3} color={C.teal} />
          <StatMeter label="half-lives" v={fld.nHalfLives} d={2} color={C.gold} />
          <StatMeter label="remaining" v={fld.remaining} d={1} color={C.blue} />
          <StatMeter label="half-life" v={fld.halfLife} d={0} color={C.amber} />
        </div>
      </>
    );
  }

  window.HalfLifeTutor = K.makeTutor(HalfLifeFig, { moduleLabel: "Radioactive-dating bench", benchId: "halflife" });
})();
