/* photosynthesislab.jsx — PhotosynthesisTutor: the limiting-factor leaf bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just
   the FIGURE. compute = window.BenchFields.photosynthesis — the SAME function
   server/benches/photosynthesis.js calls, so client and server fields are identical by
   construction. Mirrors the gas-laws 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.photosynthesis(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 PhotosynthesisFig({ task, setTask, tasks, report, event, done }) {
    const [lightLevel, setLight] = useState(60);
    const [co2Level, setCO2] = useState(80);
    const [temperature, setTemp] = useState(25);
    const fld = useMemo(() => compute({ lightLevel, co2Level, temperature }), [lightLevel, co2Level, temperature]);
    useEffect(() => { report(fld); }, [lightLevel, co2Level, temperature]); // eslint-disable-line

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const lim = fld.limitingFactor;
    const LIMCOLOR = { light: C.amber, co2: C.blue, temperature: C.crimson };
    const limColor = LIMCOLOR[lim] || C.faint;

    // layout: a leaf glyph centre, three input gauges across the top, a rate bar at the right.
    const gauge = (x, label, v, vmax, color, on) => {
      const W = 110, H = 12, fillW = (Math.max(0, Math.min(vmax, v)) / vmax) * W;
      return (
        <g key={label}>
          <text x={x} y={28} fill={on ? color : C.mute} fontSize="11" fontFamily="monospace">{label}{on ? " ◀ limiting" : ""}</text>
          <rect x={x} y={36} width={W} height={H} rx={3} fill="none" stroke={on ? color : C.faint} strokeWidth={on ? 2 : 1} />
          <rect x={x} y={36} width={fillW} height={H} rx={3} fill={color} opacity={0.85} />
        </g>
      );
    };

    // leaf glyph: greenness ∝ rate; bubbles ∝ rate (O₂ output).
    const r = fld.rate; // 0..100
    const green = 0.18 + (r / 100) * 0.6;
    const cx = 250, cy = 175;
    const bubbles = [];
    const nB = Math.round((r / 100) * 7);
    for (let i = 0; i < nB; i++) bubbles.push({ x: cx + 36 + (i % 3) * 12, y: cy - 30 - (i * 13) % 70, rr: 2 + (i % 3) });

    // output rate bar (right side).
    const BX = 500, BY0 = 70, BY1 = 280, barH = (r / 100) * (BY1 - BY0);

    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 }}>
          {/* input gauges */}
          {gauge(30, `light ${Math.round(lightLevel)}%`, lightLevel, 100, C.amber, lim === "light")}
          {gauge(160, `CO₂ ${Math.round(co2Level)}%`, co2Level, 100, C.blue, lim === "co2")}
          {gauge(290, `temp ${Math.round(temperature)}°C`, temperature, 50, C.crimson, lim === "temperature")}

          {/* leaf glyph */}
          <ellipse cx={cx} cy={cy} rx={70} ry={42} fill={C.teal} opacity={green} stroke={C.teal} strokeWidth="1.5" />
          <path d={`M${cx - 64} ${cy} Q${cx} ${cy - 6} ${cx + 64} ${cy}`} stroke={C.teal} strokeWidth="1.5" fill="none" opacity="0.7" />
          <line x1={cx} y1={cy} x2={cx} y2={cy + 60} stroke={C.faint} strokeWidth="3" />
          {/* limiting-factor ring + label */}
          <ellipse cx={cx} cy={cy} rx={82} ry={54} fill="none" stroke={limColor} strokeWidth="2.5" strokeDasharray="5 4" opacity="0.9" />
          <text x={cx} y={cy + 4} textAnchor="middle" fill={C.ink} fontSize="13" fontFamily="monospace">rate {fmt(r)}</text>
          <text x={cx} y={cy + 90} textAnchor="middle" fill={limColor} fontSize="12" fontFamily="monospace">{fld.isOptimal ? "optimal ✓" : `limiting: ${lim}`}</text>
          {/* O₂ bubbles ∝ rate */}
          {bubbles.map((b, i) => <circle key={i} cx={b.x} cy={b.y} r={b.rr} fill={C.teal} opacity="0.75" />)}

          {/* output rate bar */}
          <rect x={BX} y={BY0} width={26} height={BY1 - BY0} fill="none" stroke={C.faint} strokeWidth="1.5" rx="3" />
          <rect x={BX} y={BY1 - barH} width={26} height={barH} fill={fld.isOptimal ? C.teal : limColor} opacity="0.85" rx="3" />
          <text x={BX + 13} y={BY0 - 8} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">rate</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.isOptimal ? C.teal : C.line}`, color: fld.isOptimal ? C.teal : C.mute, fontSize: 12.5 }}>
          rate ∝ min(light, CO₂, temp factor) · rate = {fmt(r)}. {fld.isOptimal ? "✓ conditions are optimal." : `${lim} is limiting — raise it to lift the rate.`}
        </div>
        <Slider label="light intensity" value={lightLevel} set={setLight} min={0} max={100} step={5} unit="%" color={C.amber} onUp={() => event("adjusted", `Set light = ${Math.round(lightLevel)}%`, { response: `rate ${fmt(fld.rate)}, ${fld.limitingFactor} limiting` }, C.amber)} />
        <Slider label="CO₂ concentration" value={co2Level} set={setCO2} min={0} max={100} step={5} unit="%" color={C.blue} onUp={() => event("adjusted", `Set CO₂ = ${Math.round(co2Level)}%`, { response: `rate ${fmt(fld.rate)}, ${fld.limitingFactor} limiting` }, C.blue)} />
        <Slider label="temperature" value={temperature} set={setTemp} min={0} max={50} step={1} unit="°C" color={C.crimson} onUp={() => event("adjusted", `Set temp = ${Math.round(temperature)}°C`, { response: `rate ${fmt(fld.rate)}, ${fld.limitingFactor} limiting` }, C.crimson)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="rate" v={fld.rate} d={1} color={fld.isOptimal ? C.teal : limColor} />
          <StatMeter label="temp factor" v={fld.tempFactor} d={2} color={C.crimson} />
          <StatMeter label="light" v={lightLevel} d={0} unit="%" color={C.amber} />
          <StatMeter label="CO₂" v={co2Level} d={0} unit="%" color={C.blue} />
        </div>
        <div style={{ marginTop: 8, fontSize: 12, color: C.mute }}>
          Limiting factor: <span style={{ color: limColor, fontFamily: "monospace" }}>{lim}</span>
          {fld.isOptimal ? <span style={{ color: C.teal }}> · optimal</span> : null}
        </div>
      </>
    );
  }

  window.PhotosynthesisTutor = K.makeTutor(PhotosynthesisFig, { moduleLabel: "Photosynthesis bench", benchId: "photosynthesis" });
})();
