import { useState, useEffect } from "react";

// ═══ SOLAR AZIMUTH ═══
function solarAz() {
  const d = new Date(), doy = Math.floor((d - new Date(d.getFullYear(), 0, 0)) / 864e5);
  const h = d.getUTCHours() + d.getUTCMinutes() / 60;
  const dec = 23.45 * Math.sin(2 * Math.PI * (284 + doy) / 365);
  const dR = dec * Math.PI / 180, lR = 66 * Math.PI / 180;
  const eq = 229.18 * (0.000075 + 0.001868 * Math.cos(2 * Math.PI * doy / 365) - 0.032077 * Math.sin(2 * Math.PI * doy / 365));
  const ha = ((h * 60 + eq + 80) / 4 - 180) * Math.PI / 180;
  const az = Math.atan2(-Math.cos(dR) * Math.sin(ha), Math.sin(dR) * Math.cos(lR) - Math.cos(dR) * Math.cos(ha) * Math.sin(lR)) * 180 / Math.PI;
  return Math.round(((az + 360) % 360) * 10) / 10;
}

// ═══ DEMPSTER-SHAFER ═══
function fuse(sources) {
  if (!sources.length) return 0;
  let miss = 1;
  sources.forEach(s => miss *= (1 - s.conf / 100));
  return (1 - miss) * 100;
}

// ═══ LINK BUDGET ═══
function calcLink(tx, freq, txg, rxg, dist, env, h) {
  const fspl = 20 * Math.log10(dist) + 20 * Math.log10(freq) + 32.44;
  const rx = tx + txg + rxg - fspl - env;
  const nf = -110, reqSnr = 10;
  const snr = rx - nf, margin = snr - reqSnr;
  const maxPL = tx + txg + rxg - nf - reqSnr - env;
  const maxDist = Math.pow(10, (maxPL - 20 * Math.log10(freq) - 32.44) / 20);
  const wl = 300 / freq;
  const f1 = Math.sqrt(wl * dist * 1000 / 4);
  const losKm = Math.sqrt(2 * 6371 * h / 1000);
  return { rx, snr, margin, maxDist, f1, losKm, fspl };
}

// ═══ GSD ═══
function calcGSD(alt, sw, fl, px) { return (alt * sw / (fl * px)) * 100; }

// ═══ DECISION ENGINE ═══
function decide(cls, conf, tti, vec, roe, blue) {
  const fratSafe = blue >= 100;
  if (cls === "drone_inbound" && vec === "closing" && tti < 10 && conf > 85)
    return { level: "L3", auth: "AUTONOMOUS", action: "INTERCEPTOR LAUNCH", time: "4-8s", color: "#dc2626", fratSafe };
  if ((cls === "mbt" || cls === "ifv") && conf > 70) {
    const a = roe === "restrictive" ? "BN CDR" : "PLT CDR";
    return { level: "L2", auth: a, action: "RECOMMEND FPV STRIKE", time: roe === "restrictive" ? "3-8 min" : "30-120s", color: "#d97706", fratSafe };
  }
  if (cls === "personnel" && conf > 70)
    return { level: "L2", auth: roe === "restrictive" ? "BN CDR" : "COY CDR", action: "HIGHER AUTH", time: "2-8 min", color: "#d97706", fratSafe };
  if (cls === "drone_inbound" && conf > 70)
    return { level: "L2", auth: "PLT CDR", action: "RECOMMEND INTERCEPT", time: "15-30s", color: "#d97706", fratSafe };
  if (conf > 70)
    return { level: "L2", auth: "PLT CDR", action: "RECOMMEND STRIKE", time: "1-3 min", color: "#d97706", fratSafe };
  return { level: "L1", auth: "—", action: "MONITOR", time: "—", color: "#3b82f6", fratSafe };
}

const TABS = ["OVERVIEW", "MISSION", "FUSION", "LINK", "COVERAGE", "DECISION"];

// ═══ METRIC BOX ═══
function M({ label, value, color = "#e2e8f0", sub, small }) {
  return (
    <div className="text-center">
      <div className="text-[9px] text-slate-500 uppercase tracking-[2px] mb-1">{label}</div>
      <div className={`font-bold ${small ? "text-base" : "text-xl"}`} style={{ color }}>{value}</div>
      {sub && <div className="text-[10px] text-slate-600 mt-0.5">{sub}</div>}
    </div>
  );
}

// ═══ STATUS BAR ═══
function Status({ color, children }) {
  return (
    <div className="rounded py-2 px-3 text-center text-xs font-bold tracking-wide"
      style={{ backgroundColor: color + "18", color, border: `1px solid ${color}33` }}>
      {children}
    </div>
  );
}

export default function StaffConsole() {
  const [tab, setTab] = useState("OVERVIEW");
  const [clock, setClock] = useState(new Date());

  // ═══ SHARED STATE ═══
  const [f26Alt, setF26Alt] = useState(300);
  const [targetDist, setTargetDist] = useState(8);
  const [mastH, setMastH] = useState(10);
  const [sunAzimuth, setSunAzimuth] = useState(0);

  // Fusion
  const [sources, setSources] = useState([
    { type: "Fischer 26 ISR", icon: "📡", conf: 78, id: 1 },
    { type: "FPV Thermal", icon: "🌡", conf: 65, id: 2 },
    { type: "HUMINT Report", icon: "👤", conf: 45, id: 3 },
  ]);

  // Link budget
  const [txPwr, setTxPwr] = useState(30);
  const [freq, setFreq] = useState(300);

  // Decision
  const [targetCls, setTargetCls] = useState("mbt");
  const [aiConf, setAiConf] = useState(78);
  const [tti, setTti] = useState(45);
  const [vec, setVec] = useState("closing");
  const [roe, setRoe] = useState("standard");
  const [blueDist, setBlueDist] = useState(350);

  // Coverage
  const [isrAlt, setIsrAlt] = useState(200);

  useEffect(() => {
    setSunAzimuth(solarAz());
    const t = setInterval(() => setClock(new Date()), 1000);
    return () => clearInterval(t);
  }, []);

  // ═══ COMPUTED ═══
  const fusedConf = fuse(sources);
  const link = calcLink(txPwr, freq, 6, 3, targetDist, 10, f26Alt);
  const linkOk = link.margin > 0;
  const gsd = calcGSD(isrAlt, 6.287, 6, 4056);
  const frameW = Math.round((isrAlt * 6.287) / 6);
  const frameH = Math.round((isrAlt * 4.712) / 6);
  const coverageRate = Math.round((85 / 3.6) * frameW * 3600 / 10000);
  const decision = decide(targetCls, aiConf, tti, vec, roe, blueDist);
  const lambda = 0.3454;
  const f1 = Math.sqrt(lambda * targetDist * 500 * targetDist * 500 / (targetDist * 1000));
  const losKm = Math.sqrt(2 * 6371 * f26Alt / 1000);

  const systemStatus = linkOk && fusedConf > 50 ? "#059669" : linkOk ? "#d97706" : "#dc2626";
  const systemLabel = linkOk && fusedConf > 50 ? "OPERATIONAL" : linkOk ? "DEGRADED" : "LINK FAILURE";

  const InputN = ({ label, value, set, min, max, step = 1 }) => (
    <div>
      <label className="text-[9px] text-slate-500 uppercase tracking-[2px] block mb-1">{label}</label>
      <input type="number" value={value} min={min} max={max} step={step}
        onChange={e => set(parseFloat(e.target.value) || 0)}
        className="w-full bg-slate-800 border border-slate-700 rounded px-2 py-1.5 text-sm font-bold text-white focus:outline-none focus:border-sky-500" />
    </div>
  );

  const Slider = ({ label, value, set, min, max, step = 1, color }) => (
    <div>
      <label className="text-[9px] text-slate-500 uppercase tracking-[2px] block mb-1">
        {label}: <span style={{ color }}>{value}{typeof value === "number" && "%"}</span>
      </label>
      <input type="range" min={min} max={max} step={step} value={value}
        onChange={e => set(parseInt(e.target.value))}
        className="w-full h-1 appearance-none bg-slate-700 rounded cursor-pointer accent-sky-500" />
    </div>
  );

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100" style={{ fontFamily: "'JetBrains Mono', 'Fira Code', monospace" }}>

      {/* ═══ HEADER ═══ */}
      <div className="bg-slate-900 border-b border-slate-800 px-4 py-2 flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="w-2 h-2 rounded-full animate-pulse" style={{ backgroundColor: systemStatus }} />
          <span className="text-sm font-bold text-white tracking-wide">LISA 26</span>
          <span className="text-[10px] text-slate-500 tracking-[3px] uppercase">Staff Planning Console</span>
        </div>
        <div className="flex items-center gap-4">
          <span className="text-[10px] px-2 py-0.5 rounded font-bold tracking-wide"
            style={{ backgroundColor: systemStatus + "22", color: systemStatus }}>{systemLabel}</span>
          <span className="text-xs text-slate-500 tabular-nums">
            {clock.toUTCString().slice(17, 25)} UTC
          </span>
        </div>
      </div>

      {/* ═══ TABS ═══ */}
      <div className="bg-slate-900 border-b border-slate-800 px-4 flex gap-1 overflow-x-auto">
        {TABS.map(t => (
          <button key={t} onClick={() => setTab(t)}
            className={`px-3 py-2 text-[10px] tracking-[2px] font-bold transition-colors border-b-2 ${
              tab === t ? "border-sky-500 text-sky-400" : "border-transparent text-slate-500 hover:text-slate-300"
            }`}>{t}</button>
        ))}
      </div>

      <div className="p-4 max-w-4xl mx-auto">

        {/* ═══════════ OVERVIEW ═══════════ */}
        {tab === "OVERVIEW" && (
          <div className="space-y-4">
            <div className="grid grid-cols-5 gap-3">
              {[
                { l: "F26 Alt", v: `${f26Alt}m`, c: "#3b82f6" },
                { l: "Link Margin", v: `${link.margin.toFixed(0)} dB`, c: linkOk ? "#059669" : "#dc2626" },
                { l: "Fused Conf", v: `${fusedConf.toFixed(1)}%`, c: fusedConf > 85 ? "#059669" : fusedConf > 60 ? "#d97706" : "#dc2626" },
                { l: "Decision", v: decision.level, c: decision.color },
                { l: "GSD", v: `${gsd.toFixed(1)} cm`, c: "#a78bfa" },
              ].map(m => (
                <div key={m.l} className="bg-slate-900 border border-slate-800 rounded-lg p-3 text-center">
                  <div className="text-[9px] text-slate-500 uppercase tracking-[2px] mb-1">{m.l}</div>
                  <div className="text-2xl font-bold" style={{ color: m.c }}>{m.v}</div>
                </div>
              ))}
            </div>

            <div className="grid grid-cols-2 gap-3">
              {/* Left: Mission summary */}
              <div className="bg-slate-900 border border-slate-800 rounded-lg p-4">
                <div className="text-[10px] text-slate-500 uppercase tracking-[3px] mb-3">Mission Parameters</div>
                <div className="space-y-2 text-xs">
                  <div className="flex justify-between"><span className="text-slate-400">Fischer 26 altitude</span><span className="text-white font-bold">{f26Alt}m ASL</span></div>
                  <div className="flex justify-between"><span className="text-slate-400">Target distance</span><span className="text-white font-bold">{targetDist} km</span></div>
                  <div className="flex justify-between"><span className="text-slate-400">LOS horizon</span><span className="text-emerald-400 font-bold">{losKm.toFixed(0)} km</span></div>
                  <div className="flex justify-between"><span className="text-slate-400">Fresnel F1</span><span className="text-sky-400 font-bold">{f1.toFixed(1)}m</span></div>
                  <div className="flex justify-between"><span className="text-slate-400">Solar azimuth</span><span className="text-amber-400 font-bold">☀ {sunAzimuth}°</span></div>
                  <div className="flex justify-between"><span className="text-slate-400">FPV approach</span><span className="text-amber-400 font-bold">{Math.round(sunAzimuth)}° ±15°</span></div>
                  <div className="flex justify-between"><span className="text-slate-400">Coverage rate</span><span className="text-violet-400 font-bold">{coverageRate} ha/h</span></div>
                  <div className="flex justify-between"><span className="text-slate-400">Frame size</span><span className="text-white font-bold">{frameW}×{frameH}m</span></div>
                </div>
              </div>

              {/* Right: Decision + Fusion summary */}
              <div className="bg-slate-900 border border-slate-800 rounded-lg p-4">
                <div className="text-[10px] text-slate-500 uppercase tracking-[3px] mb-3">Threat Assessment</div>
                <div className="space-y-2 text-xs">
                  <div className="flex justify-between"><span className="text-slate-400">Sources active</span><span className="text-sky-400 font-bold">{sources.length}</span></div>
                  <div className="flex justify-between"><span className="text-slate-400">Fused confidence</span><span style={{ color: fusedConf > 85 ? "#059669" : "#d97706" }} className="font-bold">{fusedConf.toFixed(1)}%</span></div>
                  <div className="flex justify-between"><span className="text-slate-400">Target class</span><span className="text-white font-bold">{targetCls.toUpperCase()}</span></div>
                  <div className="flex justify-between"><span className="text-slate-400">Decision level</span><span style={{ color: decision.color }} className="font-bold">{decision.level}</span></div>
                  <div className="flex justify-between"><span className="text-slate-400">Authority</span><span className="text-white font-bold">{decision.auth}</span></div>
                  <div className="flex justify-between"><span className="text-slate-400">Est. time</span><span className="text-sky-400 font-bold">{decision.time}</span></div>
                  <div className="flex justify-between"><span className="text-slate-400">Blue force</span><span className={decision.fratSafe ? "text-emerald-400" : "text-red-400"} >{blueDist}m {decision.fratSafe ? "✓" : "⚠"}</span></div>
                  <div className="flex justify-between"><span className="text-slate-400">ROE posture</span><span className="text-white font-bold">{roe.toUpperCase()}</span></div>
                </div>
                <div className="mt-3">
                  <Status color={decision.fratSafe ? decision.color : "#dc2626"}>
                    {!decision.fratSafe && decision.level !== "L1" ? "⚠ HOLD — FRATRICIDE CHECK" : decision.action}
                  </Status>
                </div>
              </div>
            </div>

            {/* Link status bar */}
            <div className="bg-slate-900 border border-slate-800 rounded-lg p-3">
              <div className="flex items-center justify-between mb-2">
                <span className="text-[10px] text-slate-500 uppercase tracking-[3px]">MANET Link</span>
                <span className="text-xs font-bold" style={{ color: linkOk ? "#059669" : "#dc2626" }}>
                  {linkOk ? "OK" : "BLOCKED"} — Margin {link.margin.toFixed(0)} dB — Max {link.maxDist.toFixed(0)} km
                </span>
              </div>
              <div className="h-1.5 bg-slate-800 rounded-full overflow-hidden">
                <div className="h-full rounded-full transition-all duration-500"
                  style={{ width: `${Math.min(100, Math.max(0, (link.margin + 10) * 2))}%`, backgroundColor: linkOk ? "#059669" : "#dc2626" }} />
              </div>
            </div>
          </div>
        )}

        {/* ═══════════ MISSION ═══════════ */}
        {tab === "MISSION" && (
          <div className="space-y-4">
            <div className="bg-slate-900 border border-slate-800 rounded-xl p-5">
              <div className="text-[10px] text-slate-500 uppercase tracking-[3px] mb-4">Mission Parameters</div>
              <div className="grid grid-cols-3 gap-4 mb-6">
                <InputN label="F26 Altitude (m ASL)" value={f26Alt} set={setF26Alt} min={50} max={1000} step={10} />
                <InputN label="Distance to Target (km)" value={targetDist} set={setTargetDist} min={1} max={50} step={0.5} />
                <InputN label="GCS Mast Height (m)" value={mastH} set={setMastH} min={0} max={50} />
              </div>
              <div className="grid grid-cols-4 gap-4 mb-4">
                <M label="Fresnel F1" value={`${f1.toFixed(1)}m`} color="#38bdf8" />
                <M label="LOS Horizon" value={`${losKm.toFixed(0)}km`} color="#34d399" />
                <M label="Link" value={linkOk ? "OK" : "BLOCKED"} color={linkOk ? "#34d399" : "#f87171"} />
                <M label="Solar Az" value={`${sunAzimuth}°`} color="#fbbf24" sub={`FPV: ${Math.round(sunAzimuth)}° ±15°`} />
              </div>
              <Status color={linkOk ? "#059669" : "#dc2626"}>
                {linkOk ? "STRIKE VIABLE — Link OK" : "LINK BLOCKED — Raise F26 altitude"}
              </Status>
            </div>
          </div>
        )}

        {/* ═══════════ FUSION ═══════════ */}
        {tab === "FUSION" && (
          <div className="space-y-4">
            <div className="bg-slate-900 border border-slate-800 rounded-xl p-5">
              <div className="text-[10px] text-slate-500 uppercase tracking-[3px] mb-4">Observation Sources</div>
              <div className="space-y-2 mb-4">
                {sources.map((s, i) => (
                  <div key={s.id} className="flex items-center gap-3 bg-slate-800 rounded-lg p-2">
                    <span className="text-base w-7 text-center">{s.icon}</span>
                    <span className="text-[11px] text-slate-400 w-32 truncate">{s.type}</span>
                    <input type="range" min={5} max={99} value={s.conf}
                      onChange={e => setSources(p => p.map((x, j) => j === i ? { ...x, conf: parseInt(e.target.value) } : x))}
                      className="flex-1 h-1 appearance-none bg-slate-700 rounded cursor-pointer accent-sky-500" />
                    <span className={`text-xs font-bold w-10 text-right ${s.conf > 80 ? "text-emerald-400" : s.conf > 60 ? "text-amber-400" : "text-red-400"}`}>{s.conf}%</span>
                    <button onClick={() => setSources(p => p.filter((_, j) => j !== i))} className="text-slate-600 hover:text-red-400 text-xs">✕</button>
                  </div>
                ))}
              </div>
              <button onClick={() => setSources(p => [...p, { type: ["SIGINT", "OSINT", "Ground Observer", "Acoustic", "Satellite"][p.length % 5], icon: ["📻", "🌐", "👁", "🔊", "🛰"][p.length % 5], conf: 50, id: Date.now() }])}
                className="w-full py-1.5 border border-dashed border-slate-700 rounded text-[10px] text-slate-500 hover:border-sky-500 hover:text-sky-400 transition-all tracking-[3px] uppercase">+ Add Source</button>

              <div className="grid grid-cols-3 gap-4 mt-5 mb-3">
                <M label="Sources" value={sources.length} color="#38bdf8" />
                <M label="Fused" value={`${fusedConf.toFixed(1)}%`} color={fusedConf > 85 ? "#34d399" : fusedConf > 60 ? "#fbbf24" : "#f87171"} />
                <M label="Assessment" value={fusedConf > 90 ? "CONFIRMED" : fusedConf > 70 ? "PROBABLE" : fusedConf > 50 ? "POSSIBLE" : "UNCERTAIN"} color={fusedConf > 85 ? "#34d399" : "#fbbf24"} small />
              </div>
              <div className="h-2 bg-slate-800 rounded-full overflow-hidden mb-3">
                <div className="h-full rounded-full transition-all duration-300"
                  style={{ width: `${fusedConf}%`, backgroundColor: fusedConf > 85 ? "#059669" : fusedConf > 60 ? "#d97706" : "#dc2626" }} />
              </div>
              <Status color={fusedConf > 85 ? "#059669" : fusedConf > 60 ? "#d97706" : "#dc2626"}>
                {fusedConf > 85 ? "L2 RECOMMEND STRIKE" : fusedConf > 60 ? "CONTINUE ISR" : "INSUFFICIENT DATA"}
              </Status>
              <div className="mt-3 text-[10px] text-slate-600 break-all">
                C = 1 − {sources.map(s => `(1−${(s.conf/100).toFixed(2)})`).join("×")} = {(fusedConf/100).toFixed(4)}
              </div>
            </div>
          </div>
        )}

        {/* ═══════════ LINK ═══════════ */}
        {tab === "LINK" && (
          <div className="space-y-4">
            <div className="bg-slate-900 border border-slate-800 rounded-xl p-5">
              <div className="text-[10px] text-slate-500 uppercase tracking-[3px] mb-4">MANET Link Budget</div>
              <div className="grid grid-cols-4 gap-3 mb-4">
                <InputN label="TX Power (dBm)" value={txPwr} set={setTxPwr} min={10} max={40} />
                <InputN label="Freq (MHz)" value={freq} set={setFreq} min={100} max={6000} />
                <InputN label="Distance (km)" value={targetDist} set={setTargetDist} min={1} max={100} />
                <InputN label="F26 Height (m)" value={f26Alt} set={setF26Alt} min={10} max={500} />
              </div>
              <div className="grid grid-cols-4 gap-4 mb-4">
                <M label="RX Power" value={`${link.rx.toFixed(0)} dBm`} color={linkOk ? "#34d399" : "#f87171"} />
                <M label="SNR" value={`${link.snr.toFixed(0)} dB`} color={linkOk ? "#34d399" : "#f87171"} />
                <M label="Margin" value={`${link.margin.toFixed(0)} dB`} color={linkOk ? "#34d399" : "#f87171"} />
                <M label="Max Range" value={`${link.maxDist.toFixed(0)} km`} color="#38bdf8" />
              </div>
              <div className="h-2 bg-slate-800 rounded-full overflow-hidden mb-3">
                <div className="h-full rounded-full transition-all duration-300"
                  style={{ width: `${Math.min(100, Math.max(0, (link.margin + 10) * 2))}%`, backgroundColor: linkOk ? "#059669" : "#dc2626" }} />
              </div>
              <div className="grid grid-cols-3 gap-4 mb-3">
                <M label="Fresnel F1" value={`${link.f1.toFixed(0)}m`} color="#e2e8f0" sub={f26Alt > link.f1 * 0.6 ? "✓ Clear" : "✕ Obstructed"} />
                <M label="LOS Horizon" value={`${link.losKm.toFixed(0)} km`} color="#e2e8f0" sub={link.losKm > targetDist ? "✓ Within" : "✕ Beyond"} />
                <M label="FSPL" value={`${link.fspl.toFixed(1)} dB`} color="#94a3b8" sub="+10 dB env" />
              </div>
              <Status color={linkOk ? "#059669" : "#dc2626"}>
                {link.margin > 20 ? "EXCELLENT LINK" : link.margin > 10 ? "RELIABLE LINK" : link.margin > 0 ? "MARGINAL" : "NO LINK — RELAY NEEDED"}
              </Status>
            </div>
          </div>
        )}

        {/* ═══════════ COVERAGE ═══════════ */}
        {tab === "COVERAGE" && (
          <div className="space-y-4">
            <div className="bg-slate-900 border border-slate-800 rounded-xl p-5">
              <div className="text-[10px] text-slate-500 uppercase tracking-[3px] mb-4">ISR Coverage — Arducam IMX477 on Fischer 26</div>
              <div className="mb-4">
                <InputN label="ISR Altitude (m AGL)" value={isrAlt} set={setIsrAlt} min={30} max={1000} step={10} />
              </div>
              <div className="grid grid-cols-4 gap-4 mb-5">
                <M label="GSD" value={`${gsd.toFixed(1)}`} color="#a78bfa" sub="cm/px" />
                <M label="Frame" value={`${frameW}×${frameH}`} color="#e2e8f0" sub="meters" />
                <M label="Rate" value={coverageRate.toString()} color="#34d399" sub="ha/h" />
                <M label="Max (2h)" value={Math.round(coverageRate * 2).toString()} color="#fbbf24" sub="hectares" />
              </div>
              <div className="text-[10px] text-slate-500 uppercase tracking-[3px] mb-2">Detection @ {gsd.toFixed(1)} cm/px</div>
              <div className="space-y-0.5">
                {[
                  ["Vehicle detection", 100], ["Vehicle classification", 30], ["Vehicle ID", 12],
                  ["Personnel detection", 60], ["Activity recognition", 10], ["Damage assessment", 50],
                ].map(([name, req]) => {
                  const ok = gsd <= req;
                  return (
                    <div key={name} className="flex items-center gap-2 text-[11px] py-1 border-b border-slate-800">
                      <span className="text-slate-400 w-40">{name}</span>
                      <span className={`flex-1 font-bold ${ok ? "text-emerald-400" : "text-red-400"}`}>
                        {ok ? "✓ YES" : "✕ NO"} ({ok ? "+" : "-"}{Math.abs(Math.round((1 - gsd / req) * 100))}%)
                      </span>
                      <span className="text-slate-600 w-16 text-right">≤{req} cm</span>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        )}

        {/* ═══════════ DECISION ═══════════ */}
        {tab === "DECISION" && (
          <div className="space-y-4">
            <div className="bg-slate-900 border border-slate-800 rounded-xl p-5">
              <div className="text-[10px] text-slate-500 uppercase tracking-[3px] mb-4">Decision Engine — L1/L2/L3</div>
              <div className="grid grid-cols-3 gap-3 mb-3">
                {[
                  { l: "Target", v: targetCls, s: setTargetCls, o: [["drone_inbound","Inbound Drone"],["mbt","MBT"],["ifv","IFV"],["truck","Truck"],["personnel","Personnel"]] },
                  { l: "Vector", v: vec, s: setVec, o: [["closing","Closing"],["crossing","Crossing"],["retreating","Retreating"]] },
                  { l: "ROE", v: roe, s: setRoe, o: [["standard","Standard"],["delegated","Delegated"],["restrictive","Restrictive"]] },
                ].map(sel => (
                  <div key={sel.l}>
                    <label className="text-[9px] text-slate-500 uppercase tracking-[2px] block mb-1">{sel.l}</label>
                    <select value={sel.v} onChange={e => sel.s(e.target.value)}
                      className="w-full bg-slate-800 border border-slate-700 rounded px-2 py-1.5 text-xs text-white focus:outline-none focus:border-sky-500">
                      {sel.o.map(([val, lab]) => <option key={val} value={val}>{lab}</option>)}
                    </select>
                  </div>
                ))}
              </div>
              <div className="grid grid-cols-3 gap-3 mb-4">
                <InputN label="Time to Impact (s)" value={tti} set={setTti} min={1} max={300} />
                <Slider label="AI Confidence" value={aiConf} set={setAiConf} min={10} max={99} color={aiConf > 80 ? "#34d399" : "#fbbf24"} />
                <Slider label="Nearest Blue" value={blueDist} set={setBlueDist} min={10} max={1000} step={10} color={blueDist >= 100 ? "#34d399" : "#f87171"} />
              </div>

              <div className="grid grid-cols-4 gap-4 mb-4">
                <M label="Level" value={decision.level} color={decision.color} />
                <M label="Authority" value={decision.auth} small />
                <M label="Est. Time" value={decision.time} color="#38bdf8" small />
                <M label="Confidence" value={`${aiConf}%`} color={aiConf > 80 ? "#34d399" : "#fbbf24"} />
              </div>
              <Status color={!decision.fratSafe && decision.level !== "L1" ? "#dc2626" : decision.color}>
                {!decision.fratSafe && decision.level !== "L1" ? "⚠ HOLD — FRATRICIDE CHECK" : decision.action}
              </Status>
              <div className={`mt-3 text-xs font-bold ${decision.fratSafe ? "text-emerald-400" : "text-red-400"}`}>
                {decision.fratSafe ? `✓ Fratricide clear — ${blueDist}m` : `⚠ FRATRICIDE RISK — ${blueDist}m (need 100m+)`}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* ═══ FOOTER ═══ */}
      <div className="bg-slate-900 border-t border-slate-800 px-4 py-2 text-center text-[9px] text-slate-600 tracking-[4px] uppercase">
        FSG-A // Lisa 26 Staff Console // CC BY-SA 4.0 // Fischer Ventures EOOD
      </div>
    </div>
  );
}
