/* stellarlab.jsx — StellarTutor: the single-star properties bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   compute = window.BenchFields.stellar — the SAME function server/benches/stellar.js calls,
   so client and server fields are identical by construction. Mirrors gaslawslab.jsx:
   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.stellar(s);

  // Map a surface temperature (K) to an approximate blackbody fill color:
  // deep red → orange → yellow → white → blue-white as T rises.
  function tempColor(tempK) {
    const stops = [
      [2000, "#ff3b18"], // deep red
      [3500, "#ff7a2a"], // orange-red
      [5000, "#ffc15a"], // orange-yellow
      [5778, "#fff2c0"], // sun: warm white
      [7500, "#ffffff"], // white
      [10000, "#cfe2ff"], // blue-white
      [20000, "#a8c6ff"],
      [40000, "#8fb3ff"], // blue
    ];
    let lo = stops[0], hi = stops[stops.length - 1];
    for (let i = 0; i < stops.length - 1; i++) {
      if (tempK >= stops[i][0] && tempK <= stops[i + 1][0]) { lo = stops[i]; hi = stops[i + 1]; break; }
    }
    const t = Math.max(0, Math.min(1, (tempK - lo[0]) / Math.max(1, hi[0] - lo[0])));
    const hx = (c) => [parseInt(c.slice(1, 3), 16), parseInt(c.slice(3, 5), 16), parseInt(c.slice(5, 7), 16)];
    const a = hx(lo[1]), b = hx(hi[1]);
    const mix = a.map((v, i) => Math.round(v + (b[i] - v) * t));
    return `rgb(${mix[0]},${mix[1]},${mix[2]})`;
  }

  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: 72, textAlign: "right" }}>{value}{unit ? ` ${unit}` : ""}</span>
      </div>
    );
  }

  function StellarFig({ task, setTask, tasks, report, event, done }) {
    const [radiusSolar, setRadiusSolar] = useState(1);
    const [tempK, setTempK] = useState(5778);
    const fld = useMemo(() => compute({ radiusSolar, tempK }), [radiusSolar, tempK]);
    useEffect(() => { report(fld); }, [radiusSolar, tempK]); // eslint-disable-line

    // Star disc: radius ∝ radiusSolar, log-scaled & clamped so 0.1..100 R☉ fits the canvas.
    const CX = 360, CY = 150;
    const rStar = Math.max(10, Math.min(120, 30 + 28 * Math.log10(Math.max(0.1, radiusSolar) * 10)));
    const fill = tempColor(tempK);
    // Sun reference disc (1 R☉ at the same scale) for comparison.
    const rSun = Math.max(10, Math.min(120, 30 + 28 * Math.log10(1 * 10)));
    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 }}>
          <defs>
            <radialGradient id="starGlow" cx="50%" cy="50%" r="50%">
              <stop offset="0%" stopColor={fill} stopOpacity="1" />
              <stop offset="70%" stopColor={fill} stopOpacity="0.92" />
              <stop offset="100%" stopColor={fill} stopOpacity="0.18" />
            </radialGradient>
          </defs>
          {/* the star */}
          <circle cx={CX} cy={CY} r={rStar + 18} fill="url(#starGlow)" opacity="0.5" />
          <circle cx={CX} cy={CY} r={rStar} fill={fill} stroke={C.line} strokeWidth="1" />
          <text x={CX} y={CY - rStar - 12} textAnchor="middle" fill={C.ink} fontSize="13" fontFamily="monospace">R = {fmt(radiusSolar)} R☉ · T = {Math.round(tempK)} K</text>
          {/* Sun reference for scale */}
          <circle cx={110} cy={235} r={rSun} fill={tempColor(5778)} stroke={C.line} strokeWidth="1" opacity="0.9" />
          <text x={110} y={235 + rSun + 16} textAnchor="middle" fill={C.faint} fontSize="11" fontFamily="monospace">Sun (1 R☉)</text>
          {/* readouts */}
          <text x={585} y={40} textAnchor="end" fill={C.teal} fontSize="13" fontFamily="monospace">L = {fmt(fld.luminosity)} L☉</text>
          <text x={585} y={60} textAnchor="end" fill={C.blue} fontSize="12" fontFamily="monospace">λ_peak = {Math.round(fld.peakWavelength)} nm</text>
          <text x={585} y={80} textAnchor="end" fill={C.amber} fontSize="12" fontFamily="monospace">M = {fmt(fld.absMag)}</text>
          <text x={585} y={100} textAnchor="end" fill={fld.isHot ? C.blue : C.crimson} fontSize="12" fontFamily="monospace">{fld.isHot ? "hot (T > 10000 K)" : "cool"}</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 }}>
          L/L☉ = (R/R☉)²(T/T☉)⁴ = {fmt(fld.luminosity)} L☉ · Wien: λ_peak = {Math.round(fld.peakWavelength)} nm. Grow the radius (↑R) or heat the surface (↑T) to raise luminosity; hotter stars glow bluer.
        </div>
        <Slider label="radius R" value={radiusSolar} set={setRadiusSolar} min={0.1} max={100} step={0.1} unit="R☉" color={C.gold} onUp={() => event("adjusted", `Set R = ${fmt(radiusSolar)} R☉`, { response: `L ${fmt(fld.luminosity)} L☉` }, C.gold)} />
        <Slider label="temperature T" value={tempK} set={setTempK} min={2000} max={40000} step={100} unit="K" color={C.blue} onUp={() => event("adjusted", `Set T = ${Math.round(tempK)} K`, { response: `λ ${Math.round(fld.peakWavelength)} nm · L ${fmt(fld.luminosity)} L☉` }, C.blue)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="luminosity L" v={fld.luminosity} d={2} unit="L☉" color={C.teal} />
          <StatMeter label="λ_peak" v={fld.peakWavelength} d={0} unit="nm" color={C.blue} />
          <StatMeter label="abs. magnitude" v={fld.absMag} d={2} color={C.amber} />
          <StatMeter label="T" v={fld.tempK} d={0} unit="K" color={fld.isHot ? C.blue : C.crimson} />
        </div>
      </>
    );
  }

  window.StellarTutor = K.makeTutor(StellarFig, { moduleLabel: "Stellar properties bench", benchId: "stellar" });
})();
