/* populationlab.jsx — PopulationTutor: the logistic population-growth bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is
   just the FIGURE. computeFields = window.BenchFields.population — the SAME function
   server/benches/population.js calls, so client and server fields are identical by
   construction. Follows the gaslawslab.jsx single-figure template. */
(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.population(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 PopulationFig({ task, setTask, tasks, report, event, done }) {
    const [r, setR] = useState(0.5);
    const [Kcap, setKcap] = useState(1000);
    const [N, setN] = useState(200);
    const fld = useMemo(() => compute({ r, K: Kcap, N }), [r, Kcap, N]);
    useEffect(() => { report(fld); }, [r, Kcap, N]); // eslint-disable-line

    // logistic curve N(t) = K / (1 + ((K-N0)/N0) e^(-r t)) sketched over a plot box.
    const PX0 = 70, PX1 = 430, PY0 = 50, PY1 = 250, N0 = 5;
    const yMax = Kcap * 1.15;
    const tMax = 20;
    const curve = [];
    for (let i = 0; i <= 60; i++) {
      const tt = (i / 60) * tMax;
      const Nt = Kcap / (1 + ((Kcap - N0) / N0) * Math.exp(-r * tt));
      const px = PX0 + (i / 60) * (PX1 - PX0);
      const py = PY1 - (Nt / yMax) * (PY1 - PY0);
      curve.push(`${px.toFixed(1)},${py.toFixed(1)}`);
    }
    const capY = PY1 - (Kcap / yMax) * (PY1 - PY0);
    const curY = PY1 - (Math.min(N, yMax) / yMax) * (PY1 - PY0);
    // dN/dt bar (right side), scaled to a reference max ~ r*K/4.
    const dRef = Math.max(1, r * Kcap / 4);
    const dFrac = Math.max(-1, Math.min(1, fld.dNdt / dRef));
    const BX = 500, BY0 = 60, BY1 = 240, BYM = (BY0 + BY1) / 2;
    const barH = Math.abs(dFrac) * (BY1 - BY0) / 2;
    const barY = dFrac >= 0 ? BYM - barH : BYM;
    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 }}>
          {/* plot axes */}
          <line x1={PX0} y1={PY1} x2={PX1} y2={PY1} stroke={C.faint} strokeWidth="1.5" />
          <line x1={PX0} y1={PY0} x2={PX0} y2={PY1} stroke={C.faint} strokeWidth="1.5" />
          <text x={PX0} y={PY0 - 6} fill={C.mute} fontSize="11" fontFamily="monospace">N over time (logistic)</text>
          <text x={PX1} y={PY1 + 16} textAnchor="end" fill={C.faint} fontSize="10" fontFamily="monospace">time →</text>
          {/* carrying capacity line */}
          <line x1={PX0} y1={capY} x2={PX1} y2={capY} stroke={C.gold} strokeWidth="1" strokeDasharray="4 3" />
          <text x={PX1 + 2} y={capY + 4} fill={C.gold} fontSize="10" fontFamily="monospace">K</text>
          {/* logistic curve */}
          <polyline points={curve.join(" ")} fill="none" stroke={C.teal} strokeWidth="2" />
          {/* current N marker */}
          <line x1={PX0} y1={curY} x2={PX1} y2={curY} stroke={C.blue} strokeWidth="1" strokeDasharray="2 3" opacity="0.7" />
          <circle cx={PX0 + 6} cy={curY} r={4} fill={C.blue} />
          <text x={PX0 + 12} y={curY - 5} fill={C.blue} fontSize="10" fontFamily="monospace">N = {fmt(N, 0)}</text>
          {/* dN/dt bar */}
          <line x1={BX - 14} y1={BYM} x2={BX + 14} y2={BYM} stroke={C.faint} strokeWidth="1" />
          <rect x={BX - 10} y={barY} width={20} height={Math.max(0.5, barH)} fill={fld.declining ? C.crimson : C.teal} opacity="0.85" />
          <text x={BX} y={BY0 - 8} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">dN/dt</text>
          <text x={BX} y={BY1 + 16} textAnchor="middle" fill={fld.declining ? C.crimson : C.teal} fontSize="11" fontFamily="monospace">{fmt(fld.dNdt, 1)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.declining ? C.crimson : C.line}`, color: fld.declining ? C.crimson : C.mute, fontSize: 12.5 }}>
          dN/dt = rN(1 − N/K) = {fmt(fld.dNdt, 1)}. {fld.declining ? "⚠ N > K — the population is declining." : fld.growthFastest ? "▸ near N = K/2: growth is fastest." : fld.nearCapacity ? "▸ near carrying capacity — growth slowing." : "Adjust N, r or K to change the growth rate."}
        </div>
        <Slider label="rate r" value={r} set={setR} min={0.1} max={2} step={0.05} color={C.blue} onUp={() => event("adjusted", `Set r = ${fmt(r, 2)}`, { response: `dN/dt ${fmt(fld.dNdt, 1)}` }, C.blue)} />
        <Slider label="capacity K" value={Kcap} set={setKcap} min={100} max={2000} step={50} color={C.gold} onUp={() => event("adjusted", `Set K = ${fmt(Kcap, 0)}`, { response: `dN/dt ${fmt(fld.dNdt, 1)}` }, C.gold)} />
        <Slider label="population N" value={N} set={setN} min={1} max={2200} step={10} color={C.crimson} onUp={() => event("adjusted", `Set N = ${fmt(N, 0)}`, { response: `dN/dt ${fmt(fld.dNdt, 1)}` }, C.crimson)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="dN/dt" v={fld.dNdt} d={1} color={fld.declining ? C.crimson : C.teal} />
          <StatMeter label="per-capita" v={fld.perCapita} d={3} color={C.blue} />
          <StatMeter label="N / K" v={fld.fractionK} d={2} color={C.amber} />
          <StatMeter label="status" v={fld.declining ? "declining" : fld.nearCapacity ? "at K" : fld.growthFastest ? "peak" : "growing"} color={fld.declining ? C.crimson : C.teal} />
        </div>
      </>
    );
  }

  window.PopulationTutor = K.makeTutor(PopulationFig, { moduleLabel: "Population-growth bench", benchId: "population" });
})();
