/* exponentiallab.jsx — ExponentialTutor: the exponential-functions bench y = a·bˣ. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just the
   FIGURE. computeFields = window.BenchFields.exponential — the SAME function
   server/benches/exponential.js calls, so client and server fields are identical by construction.
   Mirrors the single-figure lab TEMPLATE (public/gaslawslab.jsx). */
(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.exponential(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 ExponentialFig({ task, setTask, tasks, report, event, done }) {
    const [a, setA] = useState(100);
    const [base, setBase] = useState(2);
    const [xEval, setXEval] = useState(3);
    const fld = useMemo(() => compute({ a, base, xEval }), [a, base, xEval]);
    useEffect(() => { report(fld); }, [a, base, xEval]); // eslint-disable-line

    // plot region; x runs 0..10 across the width, y auto-scaled to the curve's range.
    const X0 = 70, X1 = 540, AY0 = 50, AY1 = 250;
    const XMAX = 10;
    const decay = fld.isDecay;
    const N = 60;
    const ys = [];
    for (let i = 0; i <= N; i++) { const x = (i / N) * XMAX; ys.push(a * Math.pow(base, x)); }
    const yMax = Math.max(...ys, fld.valueAtX, a) || 1;
    const yMin = 0;
    const sx = (x) => X0 + (x / XMAX) * (X1 - X0);
    const sy = (y) => AY1 - ((y - yMin) / (yMax - yMin || 1)) * (AY1 - AY0);

    const curve = ys.map((y, i) => `${i === 0 ? "M" : "L"} ${sx((i / N) * XMAX).toFixed(1)} ${sy(y).toFixed(1)}`).join(" ");
    const fillArea = `${curve} L ${sx(XMAX).toFixed(1)} ${AY1} L ${sx(0).toFixed(1)} ${AY1} Z`;
    const curveColor = decay ? C.gold : C.teal;
    const px = sx(xEval), py = sy(fld.valueAtX);

    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={AY0} x2={X0} y2={AY1} stroke={C.faint} strokeWidth="1.5" />
          <line x1={X0} y1={AY1} x2={X1} y2={AY1} stroke={C.faint} strokeWidth="1.5" />
          <text x={X0 - 6} y={AY0 + 4} textAnchor="end" fill={C.mute} fontSize="10" fontFamily="monospace">{fmt(yMax)}</text>
          <text x={X0 - 6} y={AY1} textAnchor="end" fill={C.mute} fontSize="10" fontFamily="monospace">0</text>
          <text x={X1} y={AY1 + 14} textAnchor="end" fill={C.mute} fontSize="10" fontFamily="monospace">x = {XMAX}</text>
          {/* shaded area under curve — growth vs decay differently */}
          <path d={fillArea} fill={curveColor} opacity={decay ? 0.08 : 0.14} />
          {/* the exponential curve */}
          <path d={curve} fill="none" stroke={curveColor} strokeWidth="2.5" />
          {/* y-intercept a */}
          <circle cx={sx(0)} cy={sy(a)} r={3} fill={C.blue} />
          {/* evaluated point (xEval, valueAtX) */}
          <line x1={px} y1={AY1} x2={px} y2={py} stroke={C.crimson} strokeWidth="1" strokeDasharray="3 3" />
          <circle cx={px} cy={py} r={4.5} fill={C.crimson} />
          <text x={px} y={py - 8} textAnchor="middle" fill={C.ink} fontSize="12" fontFamily="monospace">{fmt(fld.valueAtX)}</text>
          <text x={X0 + 6} y={AY0 - 6} fill={C.mute} fontSize="11" fontFamily="monospace">y = {fmt(a)}·{fmt(base)}ˣ · {decay ? "decay" : "growth"} · x = {fmt(xEval)}</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 }}>
          y = a·bˣ = {fmt(fld.valueAtX)} at x = {fmt(xEval)}. {decay ? `Decaying: half-life ≈ ${fmt(fld.doublingTime)} (×½ each step).` : `Growing: doubling time ≈ ${fmt(fld.doublingTime)}, rate ${fmt(fld.percentRate)}%.`}
        </div>
        <Slider label="initial value a" value={a} set={setA} min={1} max={500} step={1} unit="" color={C.blue} onUp={() => event("adjusted", `Set a = ${fmt(a)}`, { response: `y(${fmt(xEval)}) = ${fmt(fld.valueAtX)}` }, C.blue)} />
        <Slider label="growth factor b" value={base} set={setBase} min={0.1} max={5} step={0.1} unit="" color={C.teal} onUp={() => event("adjusted", `Set b = ${fmt(base)}`, { response: `${fld.isDecay ? "decay" : "growth"}, rate ${fmt(fld.percentRate)}%` }, C.teal)} />
        <Slider label="evaluate at x" value={xEval} set={setXEval} min={0} max={10} step={0.5} unit="" color={C.crimson} onUp={() => event("adjusted", `Set x = ${fmt(xEval)}`, { response: `y = ${fmt(fld.valueAtX)}` }, C.crimson)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="value at x" v={fld.valueAtX} d={2} color={C.crimson} />
          <StatMeter label="growth factor b" v={fld.growthFactor} d={2} color={C.teal} />
          <StatMeter label={decay ? "half-life" : "doubling time"} v={fld.doublingTime} d={2} color={C.gold} />
          <StatMeter label="percent rate" v={fld.percentRate} d={1} unit="%" color={C.blue} />
        </div>
      </>
    );
  }

  window.ExponentialTutor = K.makeTutor(ExponentialFig, { moduleLabel: "Exponential functions bench", benchId: "exponential" });
})();
