/* hubblelab.jsx — HubbleTutor: the Hubble's-law bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.hubble — the SAME function server/benches/hubble.js
   calls, so client and server fields are identical by construction. Mirrors gaslawslab.jsx:
   sliders → BenchFields.hubble(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.hubble(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: 78, textAlign: "right" }}>{value}{unit ? ` ${unit}` : ""}</span>
      </div>
    );
  }

  function HubbleFig({ task, setTask, tasks, report, event, done }) {
    const [distanceMpc, setDistanceMpc] = useState(100);
    const [hubbleConstant, setHubbleConstant] = useState(70);
    const fld = useMemo(() => compute({ distanceMpc, hubbleConstant }), [distanceMpc, hubbleConstant]);
    useEffect(() => { report(fld); }, [distanceMpc, hubbleConstant]); // eslint-disable-line

    // velocity-vs-distance plot: x = distance 0..1000 Mpc, y = recession velocity 0..75000 km/s.
    const PX0 = 70, PX1 = 470, PY0 = 40, PY1 = 250;
    const DMAX = 1000, VMAX = 75000; // VMAX = H0max(75)*DMAX
    const xOf = (d) => PX0 + (d / DMAX) * (PX1 - PX0);
    const yOf = (v) => PY1 - (v / VMAX) * (PY1 - PY0);
    // the Hubble line of slope H0: from origin to (DMAX, H0*DMAX).
    const lineEndV = hubbleConstant * DMAX;
    const gx = xOf(distanceMpc), gy = yOf(fld.recessionVel);
    const hot = fld.isRelativistic;

    // redshift spectrum bar: a few "spectral lines" shifted right ∝ redshift.
    const SBX0 = 500, SBX1 = 575, SBY0 = 60, SBY1 = 250;
    const shift = Math.min(1, fld.redshift / 0.25); // map z up to 0.25 across the bar height fraction
    const baseLines = [0.18, 0.34, 0.52, 0.7];
    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 }}>
          {/* axes */}
          <line x1={PX0} y1={PY0} x2={PX0} y2={PY1} stroke={C.faint} strokeWidth="1.5" />
          <line x1={PX0} y1={PY1} x2={PX1} y2={PY1} stroke={C.faint} strokeWidth="1.5" />
          <text x={PX0 - 6} y={PY0 + 2} fill={C.mute} fontSize="10" fontFamily="monospace" textAnchor="end">v (km/s)</text>
          <text x={PX1} y={PY1 + 16} fill={C.mute} fontSize="10" fontFamily="monospace" textAnchor="end">d (Mpc)</text>
          {/* Hubble line (slope H0) */}
          <line x1={xOf(0)} y1={yOf(0)} x2={xOf(DMAX)} y2={yOf(lineEndV)} stroke={C.blue} strokeWidth="2" opacity="0.85" />
          <text x={xOf(DMAX) - 4} y={yOf(lineEndV) - 6} fill={C.blue} fontSize="10" fontFamily="monospace" textAnchor="end">v = H₀ d</text>
          {/* current galaxy marker */}
          <line x1={gx} y1={PY1} x2={gx} y2={gy} stroke={C.faint} strokeDasharray="3 3" strokeWidth="1" />
          <line x1={PX0} y1={gy} x2={gx} y2={gy} stroke={C.faint} strokeDasharray="3 3" strokeWidth="1" />
          <circle cx={gx} cy={gy} r={6} fill={hot ? C.crimson : C.teal} />
          <text x={gx + 9} y={gy - 4} fill={C.ink} fontSize="11" fontFamily="monospace">{fmt(fld.recessionVel)} km/s</text>
          {/* redshift spectrum bar */}
          <rect x={SBX0} y={SBY0} width={SBX1 - SBX0} height={SBY1 - SBY0} fill={C.panel} stroke={C.line} strokeWidth="1" rx="3" />
          <text x={(SBX0 + SBX1) / 2} y={SBY0 - 6} fill={C.mute} fontSize="10" fontFamily="monospace" textAnchor="middle">redshift</text>
          {baseLines.map((f, i) => {
            const yy = SBY0 + (f + shift * 0.18) * (SBY1 - SBY0);
            const ratio = Math.min(1, f + shift * 0.18);
            const col = ratio > 0.6 ? C.crimson : (ratio > 0.4 ? C.amber : C.teal);
            return <line key={i} x1={SBX0 + 4} y1={yy} x2={SBX1 - 4} y2={yy} stroke={col} strokeWidth="3" />;
          })}
          <text x={(SBX0 + SBX1) / 2} y={SBY1 + 14} fill={hot ? C.crimson : C.mute} fontSize="10" fontFamily="monospace" textAnchor="middle">z = {fmt(fld.redshift)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${hot ? C.crimson : C.line}`, color: hot ? C.crimson : C.mute, fontSize: 12.5 }}>
          v = H₀·d = {fmt(fld.recessionVel)} km/s · z ≈ v/c = {fmt(fld.redshift)}. {hot ? "⚠ high-redshift galaxy (z > 0.1) — far across the expanding universe." : "Move the galaxy farther (↑d) or raise H₀ to speed its recession."}
        </div>
        <Slider label="galaxy distance d" value={distanceMpc} set={setDistanceMpc} min={1} max={1000} step={1} unit="Mpc" color={C.teal} onUp={() => event("adjusted", `Set d = ${fmt(distanceMpc)} Mpc`, { response: `v ${fmt(fld.recessionVel)} km/s` }, C.teal)} />
        <Slider label="Hubble constant H₀" value={hubbleConstant} set={setHubbleConstant} min={60} max={75} step={0.5} unit="km/s/Mpc" color={C.blue} onUp={() => event("adjusted", `Set H₀ = ${fmt(hubbleConstant)} km/s/Mpc`, { response: `v ${fmt(fld.recessionVel)} km/s` }, C.blue)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="recession v" v={fld.recessionVel} d={0} unit="km/s" color={hot ? C.crimson : C.teal} />
          <StatMeter label="redshift z" v={fld.redshift} d={3} color={C.amber} />
          <StatMeter label="lookback" v={fld.lookbackTime} d={0} unit="Myr" color={C.blue} />
          <StatMeter label="distance d" v={fld.distance} d={1} unit="Mpc" color={C.gold} />
        </div>
      </>
    );
  }

  window.HubbleTutor = K.makeTutor(HubbleFig, { moduleLabel: "Hubble's law bench", benchId: "hubble" });
})();
