/* platetectonicslab.jsx — PlateTectonicsTutor: the seafloor-spreading bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just the
   FIGURE. computeFields = window.BenchFields.plateTectonics — the SAME function
   server/benches/platetectonics.js calls, so client and server fields are identical by
   construction. Follows the single-figure lab TEMPLATE (see public/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.plateTectonics(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: 140 }}>{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: 76, textAlign: "right" }}>{value}{unit ? ` ${unit}` : ""}</span>
      </div>
    );
  }

  function PlateTectonicsFig({ task, setTask, tasks, report, event, done }) {
    const [spreadRateMm, setSpreadRateMm] = useState(50);
    const [distanceKm, setDistanceKm] = useState(500);
    const fld = useMemo(() => compute({ spreadRateMm, distanceKm }), [spreadRateMm, distanceKm]);
    useEffect(() => { report(fld); }, [spreadRateMm, distanceKm]); // eslint-disable-line

    // cross-section: ridge axis in the centre; seafloor spreads symmetrically outward.
    // x maps distance 0..2000 km onto each flank; colour bands ∝ age (oldest at the edges).
    const CX = 300, RIDGE_TOP = 70, SEA = 150, FLOOR = 250;
    const X0 = 40, X1 = 560, MAXD = 2000;
    const halfW = CX - X0;                                   // px per flank for 0..MAXD km
    const px = (d) => (d / MAXD) * halfW;                    // km → px on a flank
    const NB = 8;                                            // age bands per flank
    const ageMax = MAXD / Math.max(1, spreadRateMm);         // oldest age at the edge (Myr)
    const bandColor = (frac) => {                            // frac 0(young)..1(old)
      const cols = [C.teal, C.blue, C.gold, C.amber, C.crimson];
      return cols[Math.min(cols.length - 1, Math.floor(frac * cols.length))];
    };
    const bands = [];
    for (let i = 0; i < NB; i++) {
      const w = halfW / NB, frac = (i + 0.5) / NB;
      bands.push({ x: CX + i * w, w, color: bandColor(frac) });     // right flank
      bands.push({ x: CX - (i + 1) * w, w, color: bandColor(frac) }); // left flank
    }
    const markX = CX + Math.min(halfW, px(distanceKm));

    return (
      <>
        <TaskStrip tasks={tasks} cur={task} setCur={setTask} done={done} goal={(tasks.find((x) => x.id === task) || tasks[0] || {}).goal} />
        <svg viewBox="0 0 600 300" style={{ width: "100%", background: SVG_BG, border: `1px solid ${C.line}`, borderRadius: 8 }}>
          {/* ocean water */}
          <rect x={X0} y={SEA} width={X1 - X0} height={FLOOR - SEA} fill={C.blue} opacity="0.07" />
          {/* age bands of seafloor crust (oldest, brightest at the edges) */}
          {bands.map((b, i) => <rect key={i} x={b.x} y={FLOOR} width={b.w} height={28} fill={b.color} opacity="0.6" />)}
          {/* mid-ocean ridge in the centre */}
          <polygon points={`${CX - 26},${FLOOR} ${CX},${RIDGE_TOP + 40} ${CX + 26},${FLOOR}`} fill={C.gold} opacity="0.85" />
          <line x1={CX} y1={RIDGE_TOP + 40} x2={CX} y2={FLOOR + 28} stroke={C.crimson} strokeWidth="1.5" strokeDasharray="4 3" />
          <text x={CX} y={RIDGE_TOP + 34} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">mid-ocean ridge</text>
          {/* spreading-direction arrows */}
          <line x1={CX + 34} y1={FLOOR + 14} x2={CX + 34 + Math.min(70, spreadRateMm / 2)} y2={FLOOR + 14} stroke={C.ink} strokeWidth="2" markerEnd="url(#ptArrow)" />
          <line x1={CX - 34} y1={FLOOR + 14} x2={CX - 34 - Math.min(70, spreadRateMm / 2)} y2={FLOOR + 14} stroke={C.ink} strokeWidth="2" markerEnd="url(#ptArrow)" />
          <defs>
            <marker id="ptArrow" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
              <path d="M0,0 L6,3 L0,6 Z" fill={C.ink} />
            </marker>
          </defs>
          {/* sample marker at the chosen distance, labelled with its age */}
          <line x1={markX} y1={SEA} x2={markX} y2={FLOOR + 28} stroke={C.crimson} strokeWidth="2" />
          <circle cx={markX} cy={FLOOR} r={5} fill={C.crimson} />
          <text x={markX} y={SEA - 6} textAnchor="middle" fill={C.crimson} fontSize="12" fontFamily="monospace">{fmt(fld.age)} Myr</text>
          <text x={markX} y={FLOOR + 50} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">{Math.round(distanceKm)} km</text>
          <text x={X0 + 6} y={RIDGE_TOP - 2 + 14} fill={C.mute} fontSize="11" fontFamily="monospace">half-rate {fmt(spreadRateMm)} mm/yr · full {fmt(fld.fullSpreadRate)} mm/yr</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.isOld ? C.crimson : C.line}`, color: fld.isOld ? C.crimson : C.mute, fontSize: 12.5 }}>
          age = distance / rate = {Math.round(fld.distance)} km / {fmt(fld.spreadRate)} mm·yr⁻¹ = {fmt(fld.age)} Myr.
          {fld.isOld ? " ⚠ old crust (> 100 Myr) far from the ridge." : fld.isFastSpreading ? " Fast-spreading ridge (> 50 mm/yr)." : " Move outward (↑distance) or slow the ridge (↓rate) to age the crust."}
        </div>
        <Slider label="half-spreading rate" value={spreadRateMm} set={setSpreadRateMm} min={10} max={150} step={5} unit="mm/yr" color={C.gold} onUp={() => event("adjusted", `Set half-rate = ${fmt(spreadRateMm)} mm/yr`, { response: `age ${fmt(fld.age)} Myr` }, C.gold)} />
        <Slider label="distance from ridge" value={distanceKm} set={setDistanceKm} min={0} max={2000} step={50} unit="km" color={C.blue} onUp={() => event("adjusted", `Set distance = ${Math.round(distanceKm)} km`, { response: `age ${fmt(fld.age)} Myr` }, C.blue)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="age" v={fld.age} d={1} unit="Myr" color={fld.isOld ? C.crimson : C.teal} />
          <StatMeter label="half-rate" v={fld.spreadRate} d={1} unit="mm/yr" color={fld.isFastSpreading ? C.crimson : C.gold} />
          <StatMeter label="distance" v={fld.distance} d={0} unit="km" color={C.blue} />
          <StatMeter label="full rate" v={fld.fullSpreadRate} d={1} unit="mm/yr" color={C.amber} />
        </div>
      </>
    );
  }

  window.PlateTectonicsTutor = K.makeTutor(PlateTectonicsFig, { moduleLabel: "Plate tectonics bench", benchId: "platetectonics" });
})();
