import { useState } from "react";

const TARGETS = [
  { value: "drone_inbound", label: "Inbound Drone (FPV/ISR)" },
  { value: "drone_loiter", label: "Loitering ISR Drone" },
  { value: "mbt", label: "Main Battle Tank" },
  { value: "ifv", label: "Infantry Fighting Vehicle" },
  { value: "truck", label: "Logistics Truck" },
  { value: "personnel", label: "Personnel" },
];

const ROE = [
  { value: "standard", label: "Standard" },
  { value: "delegated", label: "Delegated (lower auth)" },
  { value: "restrictive", label: "Restrictive (higher auth)" },
];

const VECTORS = [
  { value: "closing", label: "Closing (toward us)" },
  { value: "crossing", label: "Crossing" },
  { value: "retreating", label: "Retreating" },
];

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", cls: "red",
      chain: ["Radar detect (0.1s)", "AI classify (0.2s)", "IFF check (0.1s)", "Launch cmd (0.3s)", "Motor spin (1.2s)", "Intercept (2-6s)"],
      fratSafe
    };
  }
  if (cls === "drone_inbound" && vec === "closing" && conf > 70) {
    return {
      level: "L2", auth: "PLATOON CDR", action: "RECOMMEND INTERCEPTOR", time: "15-30s", cls: "amber",
      chain: ["Radar detect", "AI classify", "COP display", "CDR reviews", "CDR approves", "Interceptor launch"],
      fratSafe
    };
  }
  if (cls === "drone_loiter" && conf > 70) {
    return {
      level: "L2", auth: "PLATOON CDR", action: "RECOMMEND FPV STRIKE ON ISR DRONE", time: "2-5 min", cls: "amber",
      chain: ["Detection", "Classification", "L2 recommendation", "CDR approval", "FPV tasked", "FPV launch", "Intercept"],
      fratSafe
    };
  }
  if ((cls === "mbt" || cls === "ifv") && conf > 70) {
    const a = roe === "restrictive" ? "BATTALION CDR" : "PLATOON CDR";
    return {
      level: "L2", auth: a, action: "RECOMMEND FPV STRIKE", time: roe === "restrictive" ? "3-8 min" : "30-120s", cls: "amber",
      chain: ["Fischer 26 detect", "AI classify", "L2 recommendation", `${a} reviews`, `${a} approves`, "FPV briefed", "FPV launch", "Strike", "BDA pass"],
      fratSafe
    };
  }
  if (cls === "personnel" && conf > 70) {
    const a = roe === "restrictive" ? "BATTALION CDR" : "COMPANY CDR";
    return {
      level: "L2", auth: a, action: "RECOMMEND — HIGHER AUTH REQUIRED", time: "2-8 min", cls: "amber",
      chain: ["Detection", "Classification", "L2 recommendation", `Escalate to ${a}`, `${a} reviews ROE`, `${a} approves/denies`, "FPV tasked", "Strike", "BDA"],
      fratSafe
    };
  }
  if (cls === "truck" && conf > 70) {
    return {
      level: "L2", auth: "PLATOON CDR", action: "RECOMMEND FPV STRIKE", time: "1-3 min", cls: "amber",
      chain: ["Detection", "Classification", "L2 recommendation", "CDR approval", "FPV strike", "BDA"],
      fratSafe
    };
  }
  return {
    level: "L1", auth: "NONE", action: "DISPLAY ON COP — MONITOR", time: "—", cls: "blue",
    chain: ["Detection", "COP display", "Continue monitoring"],
    fratSafe
  };
}

const LEVEL_COLORS = {
  red: { bg: "#dc2626", glow: "shadow-red-500/20" },
  amber: { bg: "#d97706", glow: "shadow-amber-500/20" },
  blue: { bg: "#3b82f6", glow: "shadow-blue-500/20" },
  green: { bg: "#059669", glow: "shadow-emerald-500/20" },
};

export default function DecisionEngine() {
  const [cls, setCls] = useState("mbt");
  const [conf, setConf] = useState(78);
  const [tti, setTti] = useState(45);
  const [vec, setVec] = useState("closing");
  const [roe, setRoe] = useState("standard");
  const [blue, setBlue] = useState(350);

  const result = decide(cls, conf, tti, vec, roe, blue);
  const lc = LEVEL_COLORS[result.cls];

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 p-4 md:p-8" style={{ fontFamily: "'JetBrains Mono', 'Fira Code', monospace" }}>
      <div className="max-w-2xl mx-auto">
        <div className="flex items-center gap-3 mb-1">
          <div className="w-2 h-2 rounded-full bg-red-400 animate-pulse" />
          <span className="text-[10px] tracking-[4px] text-slate-500 uppercase">Lisa 26 // Decision Authority</span>
        </div>
        <h1 className="text-2xl font-bold tracking-tight mb-1 text-white">DECISION ENGINE</h1>
        <p className="text-xs text-slate-500 mb-6">L1/L2/L3 Kill Chain Simulator — ROE Framework</p>

        {/* Inputs */}
        <div className="grid grid-cols-2 gap-3 mb-3">
          {[
            { label: "Target Classification", val: cls, set: setCls, opts: TARGETS },
            { label: "Movement Vector", val: vec, set: setVec, opts: VECTORS },
            { label: "ROE Posture", val: roe, set: setRoe, opts: ROE },
          ].map((sel) => (
            <div key={sel.label} className="bg-slate-900 border border-slate-800 rounded-lg p-3">
              <label className="text-[10px] text-slate-500 uppercase tracking-widest block mb-2">{sel.label}</label>
              <select value={sel.val} onChange={(e) => sel.set(e.target.value)}
                className="w-full bg-slate-800 border border-slate-700 rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-sky-500">
                {sel.opts.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
              </select>
            </div>
          ))}
          <div className="bg-slate-900 border border-slate-800 rounded-lg p-3">
            <label className="text-[10px] text-slate-500 uppercase tracking-widest block mb-2">Time to Impact (s)</label>
            <input type="number" value={tti} min={1} max={300} onChange={(e) => setTti(parseInt(e.target.value) || 1)}
              className="w-full bg-slate-800 border border-slate-700 rounded px-3 py-2 text-lg font-bold text-white focus:outline-none focus:border-sky-500" />
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3 mb-6">
          <div className="bg-slate-900 border border-slate-800 rounded-lg p-3">
            <label className="text-[10px] text-slate-500 uppercase tracking-widest block mb-2">
              AI Confidence: <span className={conf > 80 ? "text-emerald-400" : conf > 60 ? "text-amber-400" : "text-red-400"}>{conf}%</span>
            </label>
            <input type="range" min={10} max={99} value={conf} onChange={(e) => setConf(parseInt(e.target.value))}
              className="w-full h-1 appearance-none bg-slate-700 rounded cursor-pointer accent-sky-500" />
          </div>
          <div className="bg-slate-900 border border-slate-800 rounded-lg p-3">
            <label className="text-[10px] text-slate-500 uppercase tracking-widest block mb-2">
              Nearest Blue Force: <span className={blue >= 100 ? "text-emerald-400" : "text-red-400"}>{blue}m</span>
            </label>
            <input type="range" min={10} max={1000} step={10} value={blue} onChange={(e) => setBlue(parseInt(e.target.value))}
              className="w-full h-1 appearance-none bg-slate-700 rounded cursor-pointer accent-sky-500" />
          </div>
        </div>

        {/* Result */}
        <div className="bg-slate-900 border border-slate-800 rounded-xl p-6 mb-4">
          <div className="grid grid-cols-4 gap-4 mb-6">
            <div className="text-center">
              <div className="text-[10px] text-slate-500 uppercase tracking-widest mb-1">Level</div>
              <div className="text-4xl font-black" style={{ color: lc.bg }}>{result.level}</div>
            </div>
            <div className="text-center">
              <div className="text-[10px] text-slate-500 uppercase tracking-widest mb-1">Authority</div>
              <div className="text-sm font-bold text-white mt-2">{result.auth}</div>
            </div>
            <div className="text-center">
              <div className="text-[10px] text-slate-500 uppercase tracking-widest mb-1">Est. Time</div>
              <div className="text-lg font-bold text-sky-400 mt-1">{result.time}</div>
            </div>
            <div className="text-center">
              <div className="text-[10px] text-slate-500 uppercase tracking-widest mb-1">Confidence</div>
              <div className={`text-lg font-bold mt-1 ${conf > 80 ? "text-emerald-400" : conf > 60 ? "text-amber-400" : "text-red-400"}`}>{conf}%</div>
            </div>
          </div>

          {/* Action */}
          <div className="rounded-lg py-3 px-4 text-center text-sm font-bold tracking-wide mb-4"
            style={{ backgroundColor: lc.bg + "22", color: lc.bg, border: `1px solid ${lc.bg}44` }}>
            {!result.fratSafe && result.level !== "L1" ? "⚠ HOLD — FRATRICIDE CHECK REQUIRED" : result.action}
          </div>

          {/* Kill Chain */}
          <div className="text-[10px] text-slate-500 uppercase tracking-widest mb-2">Kill Chain</div>
          <div className="flex flex-wrap gap-1 items-center">
            {result.chain.map((step, i) => (
              <span key={i} className="flex items-center gap-1">
                <span className="bg-slate-800 text-slate-300 text-[11px] px-2 py-1 rounded">{i + 1}. {step}</span>
                {i < result.chain.length - 1 && <span className="text-slate-600 text-xs">→</span>}
              </span>
            ))}
          </div>

          {/* Fratricide check */}
          <div className={`mt-4 text-xs font-bold ${result.fratSafe ? "text-emerald-400" : "text-red-400"}`}>
            {result.fratSafe ? `✓ Fratricide clear — ${blue}m to nearest blue` : `⚠ FRATRICIDE RISK — ${blue}m to nearest blue (need 100m+)`}
          </div>
        </div>

        <div className="mt-6 text-center text-[10px] text-slate-600 tracking-widest uppercase">
          FSG-A // Lisa 26 // CC BY-SA 4.0
        </div>
      </div>
    </div>
  );
}
