/* moonphaseslab.jsx — MoonPhasesTutor: the moon-phases bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.moonPhases — the SAME function server/benches/moonphases.js
   calls, so client and server fields are identical by construction. Follows the gaslaws template:
   a slider → 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.moonPhases(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 MoonPhasesFig({ task, setTask, tasks, report, event, done }) {
    const [moonAngle, setMoonAngle] = useState(90);
    const fld = useMemo(() => compute({ moonAngle }), [moonAngle]);
    useEffect(() => { report(fld); }, [moonAngle]); // eslint-disable-line

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const f = fld.illumFraction, waxing = fld.waxing;

    // ── view 1: top-down orbit. Sunlight comes from the LEFT (the new-moon side).
    // θ measured so 0° = between Earth and Sun (new), 180° = far side (full).
    const EX = 175, EY = 150, R = 95;          // Earth centre + orbit radius
    const rad = (moonAngle * Math.PI) / 180;
    // place the Moon: at θ=0 it sits toward the Sun (left of Earth), sweeping CCW.
    const mx = EX - Math.cos(rad) * R;
    const my = EY - Math.sin(rad) * R;
    const rays = [40, 90, 150, 210, 260];      // sunlight ray y-positions

    // ── view 2: the lit disc as seen from Earth. f = lit fraction; lit side: waxing→right.
    const DX = 470, DY = 150, DR = 70;
    // terminator is an ellipse whose horizontal radius shrinks from DR (new/full) — we
    // build the lit region as a path: outer semicircle (lit limb) + the terminator arc.
    const litRight = waxing;                    // waxing: lit on the right limb
    // half-width of the terminator ellipse, signed by which side is lit at f<0.5 vs >0.5.
    const k = DR * (1 - 2 * f);                 // +DR at new (f=0) → -DR at full (f=1)
    const litX = litRight ? 1 : -1;
    // path: start top, down the lit limb (semicircle), back up through the terminator.
    const limbSweep = litRight ? 1 : 0, termSweep = litRight ? 1 : 0;
    const discPath =
      `M ${DX} ${DY - DR} ` +
      `A ${DR} ${DR} 0 0 ${limbSweep} ${DX} ${DY + DR} ` +
      `A ${Math.abs(k)} ${DR} 0 0 ${(k * litX >= 0 ? termSweep : 1 - termSweep)} ${DX} ${DY - DR} Z`;

    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 }}>
          {/* ── view 1: orbit (top-down) ───────────────────────────────────────── */}
          <text x={EX} y={26} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">orbit (top-down)</text>
          {/* sunlight from the left */}
          {rays.map((y, i) => <line key={i} x1={4} y1={y} x2={60} y2={y} stroke={C.gold} strokeWidth="2" opacity="0.7" />)}
          <text x={6} y={290} fill={C.gold} fontSize="11" fontFamily="monospace">☀ Sun</text>
          {/* orbit path */}
          <circle cx={EX} cy={EY} r={R} fill="none" stroke={C.faint} strokeWidth="1" strokeDasharray="3 4" />
          {/* Earth */}
          <circle cx={EX} cy={EY} r={11} fill={C.blue} />
          <text x={EX} y={EY + 26} textAnchor="middle" fill={C.mute} fontSize="10" fontFamily="monospace">Earth</text>
          {/* Moon on orbit — half facing the Sun (left) is lit */}
          <circle cx={mx} cy={my} r={9} fill={C.mute} stroke={C.faint} strokeWidth="1" />
          <path d={`M ${mx} ${my - 9} A 9 9 0 0 0 ${mx} ${my + 9} Z`} fill={C.gold} opacity="0.95" />
          <text x={mx} y={my - 14} textAnchor="middle" fill={C.teal} fontSize="10" fontFamily="monospace">θ {fmt(moonAngle, 0)}°</text>

          {/* divider */}
          <line x1={350} y1={40} x2={350} y2={262} stroke={C.line} strokeWidth="1" />

          {/* ── view 2: disc as seen from Earth ────────────────────────────────── */}
          <text x={DX} y={26} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">as seen from Earth</text>
          {/* dark disc */}
          <circle cx={DX} cy={DY} r={DR} fill="#13202c" stroke={C.faint} strokeWidth="1" />
          {/* lit region */}
          {f > 0.001 ? <path d={discPath} fill={C.gold} opacity="0.95" /> : null}
          <text x={DX} y={DY + DR + 26} textAnchor="middle" fill={C.ink} fontSize="13" fontFamily="monospace">{fld.phaseName}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.isFull ? C.teal : C.line}`, color: fld.isFull ? C.teal : C.mute, fontSize: 12.5 }}>
          illuminated = (1 − cos θ)/2 = {fmt(f)}. {fld.isFull ? "● Full moon — the whole near side is lit." : fld.isNew ? "○ New moon — the near side is dark." : (waxing ? "waxing — the lit fraction is growing." : "waning — the lit fraction is shrinking.")}
        </div>
        <Slider label="orbital angle θ" value={moonAngle} set={setMoonAngle} min={0} max={360} step={5} unit="°" color={C.teal} onUp={() => event("adjusted", `Set θ = ${fmt(moonAngle, 0)}°`, { response: `${fld.phaseName} · lit ${fmt(f)}` }, C.teal)} />
        <div style={{ marginTop: 10, padding: "7px 10px", borderRadius: 6, background: C.panel, border: `1px solid ${C.line}`, color: C.amber, fontSize: 12.5, fontFamily: "monospace" }}>
          phase: {fld.phaseName}{fld.isFull ? " · FULL" : fld.isNew ? " · NEW" : waxing ? " · waxing" : " · waning"}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="illuminated fraction" v={fld.illumFraction} d={2} color={fld.isFull ? C.teal : C.gold} />
          <StatMeter label="orbital angle θ" v={fld.moonAngle} d={0} unit="°" color={C.teal} />
        </div>
      </>
    );
  }

  window.MoonPhasesTutor = K.makeTutor(MoonPhasesFig, { moduleLabel: "Moon phases bench", benchId: "moonphases" });
})();
