import { useState } from "react";

const SENSOR_TYPES = [
  { type: "ISR Drone", icon: "🛩", defaultConf: 72 },
  { type: "FPV Thermal", icon: "🌡", defaultConf: 68 },
  { type: "Fischer 26", icon: "📡", defaultConf: 81 },
];

const ADD_TYPES = [
  { type: "HUMINT Report", icon: "👤" },
  { type: "SIGINT Intercept", icon: "📻" },
  { type: "OSINT Social Media", icon: "🌐" },
  { type: "Satellite Imagery", icon: "🛰" },
  { type: "Ground Observer", icon: "👁" },
  { type: "Acoustic Sensor", icon: "🔊" },
];

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

function getColor(val) {
  if (val > 90) return { bg: "#059669", text: "#ecfdf5", label: "CONFIRMED TARGET" };
  if (val > 70) return { bg: "#d97706", text: "#fffbeb", label: "PROBABLE TARGET" };
  if (val > 50) return { bg: "#dc2626", text: "#fef2f2", label: "POSSIBLE TARGET" };
  return { bg: "#6b7280", text: "#f9fafb", label: "UNCERTAIN" };
}

export default function ThreatFusion() {
  const [sources, setSources] = useState(
    SENSOR_TYPES.map((s) => ({ ...s, conf: s.defaultConf, id: Math.random() }))
  );
  const [addIdx, setAddIdx] = useState(0);

  const fused = fuse(sources);
  const color = getColor(fused);
  const formula = sources.map((s) => `(1−${(s.conf / 100).toFixed(2)})`).join(" × ");

  const updateConf = (id, val) =>
    setSources((prev) => prev.map((s) => (s.id === id ? { ...s, conf: val } : s)));

  const remove = (id) => setSources((prev) => prev.filter((s) => s.id !== id));

  const addSource = () => {
    const t = ADD_TYPES[addIdx % ADD_TYPES.length];
    setSources((prev) => [...prev, { ...t, conf: 50, id: Math.random() }]);
    setAddIdx((i) => i + 1);
  };

  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">
        {/* Header */}
        <div className="flex items-center gap-3 mb-1">
          <div className="w-2 h-2 rounded-full bg-emerald-400 animate-pulse" />
          <span className="text-[10px] tracking-[4px] text-slate-500 uppercase">Lisa 26 // Sensor Fusion</span>
        </div>
        <h1 className="text-2xl font-bold tracking-tight mb-1 text-white">THREAT FUSION ENGINE</h1>
        <p className="text-xs text-slate-500 mb-6">Dempster-Shafer multi-source fusion — STANAG 2022</p>

        {/* Sources */}
        <div className="space-y-2 mb-6">
          {sources.map((s) => {
            const c = s.conf > 80 ? "text-emerald-400" : s.conf > 60 ? "text-amber-400" : "text-red-400";
            return (
              <div key={s.id} className="bg-slate-900 border border-slate-800 rounded-lg p-3 flex items-center gap-3">
                <span className="text-lg w-8 text-center">{s.icon}</span>
                <span className="text-xs text-slate-400 w-36 truncate">{s.type}</span>
                <input
                  type="range"
                  min={5}
                  max={99}
                  value={s.conf}
                  onChange={(e) => updateConf(s.id, parseInt(e.target.value))}
                  className="flex-1 h-1 appearance-none bg-slate-700 rounded cursor-pointer accent-sky-500"
                />
                <span className={`text-sm font-bold w-12 text-right ${c}`}>{s.conf}%</span>
                <button onClick={() => remove(s.id)} className="text-slate-600 hover:text-red-400 transition-colors text-sm ml-1">✕</button>
              </div>
            );
          })}
        </div>

        {/* Add button */}
        <button
          onClick={addSource}
          className="w-full py-2 border border-dashed border-slate-700 rounded-lg text-xs text-slate-500 hover:border-sky-500 hover:text-sky-400 transition-all mb-8 tracking-widest uppercase"
        >
          + Add Source
        </button>

        {/* Fused Result */}
        <div className="bg-slate-900 border border-slate-800 rounded-xl p-6 mb-4">
          <div className="grid grid-cols-3 gap-4 mb-6">
            <div className="text-center">
              <div className="text-[10px] text-slate-500 uppercase tracking-widest mb-1">Sources</div>
              <div className="text-3xl font-bold text-sky-400">{sources.length}</div>
            </div>
            <div className="text-center">
              <div className="text-[10px] text-slate-500 uppercase tracking-widest mb-1">Fused Confidence</div>
              <div className="text-3xl font-bold" style={{ color: color.bg }}>{fused.toFixed(1)}%</div>
            </div>
            <div className="text-center">
              <div className="text-[10px] text-slate-500 uppercase tracking-widest mb-1">Assessment</div>
              <div className="text-sm font-bold mt-2" style={{ color: color.bg }}>{color.label}</div>
            </div>
          </div>

          {/* Progress bar */}
          <div className="h-2 bg-slate-800 rounded-full overflow-hidden mb-4">
            <div
              className="h-full rounded-full transition-all duration-500"
              style={{ width: `${fused}%`, backgroundColor: color.bg }}
            />
          </div>

          {/* Status */}
          <div
            className="rounded-lg py-3 px-4 text-center text-sm font-bold tracking-wide"
            style={{ backgroundColor: color.bg + "22", color: color.bg, border: `1px solid ${color.bg}44` }}
          >
            {fused > 85 ? "L2 RECOMMEND STRIKE" : fused > 70 ? "CONTINUE ISR — BUILD CONFIDENCE" : "MONITOR — INSUFFICIENT DATA"}
          </div>
        </div>

        {/* Formula */}
        <div className="bg-slate-900 border border-slate-800 rounded-lg p-4 text-xs text-slate-500">
          <div className="text-[10px] uppercase tracking-widest text-slate-600 mb-2">Dempster-Shafer Formula</div>
          <div className="break-all">
            C<sub>fused</sub> = 1 − {formula} = <span className="text-white font-bold">{(fused / 100).toFixed(4)}</span>
          </div>
        </div>

        {/* Footer */}
        <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>
  );
}
