/* densitylab.jsx — DensityTutor: the object-in-a-fluid density bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just
   the FIGURE. computeFields = window.BenchFields.density — the SAME function
   server/benches/density.js calls, so client and server fields are identical by construction. */
(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.density(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 DensityFig({ task, setTask, tasks, report, event, done }) {
    const [mass, setMass] = useState(80);
    const [volume, setVolume] = useState(100);
    const [fluidDensity, setFluidDensity] = useState(1.0);
    const fld = useMemo(() => compute({ mass, volume, fluidDensity }), [mass, volume, fluidDensity]);
    useEffect(() => { report(fld); }, [mass, volume, fluidDensity]); // eslint-disable-line

    // tank: x [70..540], water surface at WY, bottom at TY1. Block is a square sized ∝ volume.
    const X0 = 70, X1 = 540, TY0 = 40, TY1 = 250, WY = 80;
    const floats = fld.floats;
    const sub = fld.submergedFraction; // 0..1 fraction of block height below the waterline
    const side = Math.max(34, Math.min(110, 30 + Math.sqrt(volume) * 2.6));
    const bx = (X0 + X1) / 2 - side / 2;
    // floating: top of block above water, "sub" of its height below WY; sinking: rests on bottom.
    const by = floats ? (WY - side * (1 - sub)) : (TY1 - side);
    const fluidTint = Math.min(0.9, 0.12 + (fluidDensity - 0.5) / 13.5 * 0.7); // ∝ fluid density
    const t = tasks.find((x) => x.id === task) || tasks[0];
    const blockColor = floats ? C.teal : C.crimson;
    // buoyant arrow: from below the block centre pointing up.
    const cx = (X0 + X1) / 2, arrowBase = floats ? Math.min(TY1 - 8, by + side + 36) : TY1 - 8, arrowTop = by + 6;

    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 }}>
          {/* tank walls + bottom */}
          <rect x={X0} y={TY0} width={X1 - X0} height={TY1 - TY0} fill="none" stroke={C.faint} strokeWidth="1.5" rx="4" />
          {/* fluid body (surface at WY) */}
          <rect x={X0} y={WY} width={X1 - X0} height={TY1 - WY} fill={C.blue} opacity={fluidTint} />
          <line x1={X0} y1={WY} x2={X1} y2={WY} stroke={C.blue} strokeWidth="2" opacity="0.8" />
          {/* the object */}
          <rect x={bx} y={by} width={side} height={side} fill={blockColor} opacity="0.85" stroke={C.ink} strokeWidth="1" rx="3" />
          <text x={cx} y={by + side / 2 + 4} textAnchor="middle" fill={C.ink} fontSize="12" fontFamily="monospace">ρ = {fmt(fld.density)}</text>
          {/* buoyant-force arrow (upward) */}
          <line x1={cx} y1={arrowBase} x2={cx} y2={arrowTop} stroke={C.gold} strokeWidth="3" />
          <polygon points={`${cx - 6},${arrowTop + 10} ${cx + 6},${arrowTop + 10} ${cx},${arrowTop}`} fill={C.gold} />
          <text x={cx + 12} y={(arrowBase + arrowTop) / 2} fill={C.gold} fontSize="11" fontFamily="monospace">F_b = {fmt(fld.buoyantForce)} N</text>
          {/* labels */}
          <text x={X0 + 6} y={TY0 - 8} fill={C.mute} fontSize="11" fontFamily="monospace">m = {Math.round(mass)} g · V = {Math.round(volume)} cm³ · ρ_fluid = {fmt(fluidDensity)} g/cm³</text>
          <text x={X1 - 6} y={WY - 6} textAnchor="end" fill={floats ? C.teal : C.crimson} fontSize="13" fontFamily="monospace">{floats ? "FLOATS" : "SINKS"}</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 }}>
          ρ = m/V = {fmt(fld.density)} g/cm³ vs ρ_fluid = {fmt(fluidDensity)} g/cm³ · {floats ? `floats with ${Math.round(sub * 100)}% submerged.` : "sinks (ρ ≥ ρ_fluid). Lower the mass or raise the volume to float it."}
        </div>
        <Slider label="object mass m" value={mass} set={setMass} min={1} max={1000} step={1} unit="g" color={C.crimson} onUp={() => event("adjusted", `Set m = ${Math.round(mass)} g`, { response: `ρ ${fmt(fld.density)} · ${fld.floats ? "floats" : "sinks"}` }, C.crimson)} />
        <Slider label="object volume V" value={volume} set={setVolume} min={1} max={1000} step={1} unit="cm³" color={C.teal} onUp={() => event("adjusted", `Set V = ${Math.round(volume)} cm³`, { response: `ρ ${fmt(fld.density)} · ${fld.floats ? "floats" : "sinks"}` }, C.teal)} />
        <Slider label="fluid density" value={fluidDensity} set={setFluidDensity} min={0.5} max={14} step={0.1} unit="g/cm³" color={C.blue} onUp={() => event("adjusted", `Set ρ_fluid = ${fmt(fluidDensity)} g/cm³`, { response: `ρ ${fmt(fld.density)} · ${fld.floats ? "floats" : "sinks"}` }, C.blue)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="density ρ" v={fld.density} d={2} unit="g/cm³" color={floats ? C.teal : C.crimson} />
          <StatMeter label="buoyant force" v={fld.buoyantForce} d={2} unit="N" color={C.gold} />
          <StatMeter label="submerged" v={fld.submergedFraction} d={2} color={C.amber} />
          <StatMeter label="fluid ρ" v={fld.fluidDensity} d={2} unit="g/cm³" color={C.blue} />
        </div>
      </>
    );
  }

  window.DensityTutor = K.makeTutor(DensityFig, { moduleLabel: "Density bench", benchId: "density" });
})();
