/* seasonslab.jsx — SeasonsTutor: the seasons & insolation bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   compute = window.BenchFields.seasons — the SAME function server/benches/seasons.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.seasons(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 SeasonsFig({ task, setTask, tasks, report, event, done }) {
    const [latitude, setLat] = useState(40);
    const [axialTilt, setTilt] = useState(23.5);
    const [dayOfYear, setDay] = useState(80);
    const fld = useMemo(() => compute({ latitude, axialTilt, dayOfYear }), [latitude, axialTilt, dayOfYear]);
    useEffect(() => { report(fld); }, [latitude, axialTilt, dayOfYear]); // eslint-disable-line

    // horizon with the Sun on an arc at the computed elevation angle (0..90°).
    const OX = 300, HY = 230, R = 170;
    const elev = Math.max(0, fld.solarElevation); // clamp below-horizon to the horizon for drawing
    const rad = elev * Math.PI / 180;
    const sunX = OX - R * Math.cos(rad), sunY = HY - R * Math.sin(rad);
    const below = fld.polarNight;
    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 }}>
          {/* sky arc */}
          <path d={`M ${OX - R} ${HY} A ${R} ${R} 0 0 1 ${OX + R} ${HY}`} fill="none" stroke={C.faint} strokeWidth="1.5" />
          {/* horizon */}
          <line x1={OX - R - 20} y1={HY} x2={OX + R + 20} y2={HY} stroke={C.faint} strokeWidth="2" />
          {/* elevation ray + sun */}
          <line x1={OX} y1={HY} x2={sunX} y2={sunY} stroke={below ? C.crimson : C.gold} strokeWidth="1.5" strokeDasharray={below ? "4 4" : "none"} />
          <circle cx={sunX} cy={sunY} r={11} fill={below ? C.crimson : C.gold} opacity={below ? 0.4 : 0.9} />
          <text x={OX} y={HY + 22} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">horizon · observer</text>
          <text x={OX + 8} y={HY - 8} fill={C.ink} fontSize="13" fontFamily="monospace">{below ? "Sun below horizon" : `elevation = ${fmt(fld.solarElevation)}°`}</text>
          <text x={OX - R} y={28} fill={C.mute} fontSize="11" fontFamily="monospace">lat {fmt(latitude)}° · tilt {fmt(axialTilt)}° · day {Math.round(dayOfYear)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${below ? C.crimson : C.line}`, color: below ? C.crimson : C.mute, fontSize: 12.5 }}>
          elevation = 90 − |lat − decl| = {fmt(fld.solarElevation)}° · insolation = {fmt(fld.insolation)}. {fld.sunOverhead ? "✓ Sun overhead." : below ? "⚠ polar night." : "Match latitude to declination to raise the Sun."}
        </div>
        <Slider label="latitude" value={latitude} set={setLat} min={-90} max={90} step={1} unit="°" color={C.blue} onUp={() => event("adjusted", `Set latitude = ${fmt(latitude)}°`, { response: `elev ${fmt(fld.solarElevation)}°` }, C.blue)} />
        <Slider label="axial tilt" value={axialTilt} set={setTilt} min={0} max={45} step={0.5} unit="°" color={C.crimson} onUp={() => event("adjusted", `Set tilt = ${fmt(axialTilt)}°`, { response: `decl ${fmt(fld.declination)}°` }, C.crimson)} />
        <Slider label="day of year" value={dayOfYear} set={setDay} min={1} max={365} step={1} color={C.gold} onUp={() => event("adjusted", `Set day = ${Math.round(dayOfYear)}`, { response: `decl ${fmt(fld.declination)}°` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="elevation" v={fld.solarElevation} d={1} unit="°" color={C.teal} />
          <StatMeter label="declination" v={fld.declination} d={1} unit="°" color={C.crimson} />
          <StatMeter label="insolation" v={fld.insolation} d={2} color={C.gold} />
          <StatMeter label="latitude" v={fld.latitude} d={1} unit="°" color={C.blue} />
        </div>
      </>
    );
  }

  window.SeasonsTutor = K.makeTutor(SeasonsFig, { moduleLabel: "Seasons & insolation bench", benchId: "seasons" });
})();
