import { lazy, Suspense, useEffect, useMemo, useRef, useState } from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';
import {
  Shield, Plane, Satellite, X, Camera, Activity, Clock, Anchor, MapPin,
  Zap, Compass, Eye, Layers, Radio, Crosshair, AlertTriangle, Globe, Wifi, WifiOff,
} from 'lucide-react';

const GlobeView = lazy(() => import('./components/GlobeView'));

function resolveWsUrl(): string {
  const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
  if (envUrl && envUrl.trim().length > 0) return envUrl.trim();
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  return `${protocol}//${window.location.hostname}:8000/ws`;
}

function timeAgo(dateStr: string): string {
  try {
    const diff = Date.now() - new Date(dateStr).getTime();
    if (diff < 60000) return 'Just now';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
    return `${Math.floor(diff / 86400000)}d ago`;
  } catch { return ''; }
}

const THREAT_CONFIG: Record<string, { cls: string; glow: string; bar: string }> = {
  SEVERE:   { cls: 'bg-red-500/20 text-red-400 border-red-500/50',         glow: 'shadow-[0_0_20px_rgba(239,68,68,0.4)]',    bar: 'bg-red-500' },
  HIGH:     { cls: 'bg-orange-500/20 text-orange-400 border-orange-500/50', glow: 'shadow-[0_0_20px_rgba(249,115,22,0.4)]',   bar: 'bg-orange-500' },
  ELEVATED: { cls: 'bg-amber-500/20 text-amber-300 border-amber-500/50',   glow: 'shadow-[0_0_15px_rgba(245,158,11,0.3)]',   bar: 'bg-amber-400' },
  GUARDED:  { cls: 'bg-blue-500/20 text-blue-300 border-blue-500/40',      glow: 'shadow-[0_0_15px_rgba(59,130,246,0.3)]',   bar: 'bg-blue-500' },
  LOW:      { cls: 'bg-emerald-500/20 text-emerald-400 border-emerald-500/40', glow: '',                                      bar: 'bg-emerald-500' },
  UNKNOWN:  { cls: 'bg-slate-800/40 text-slate-400 border-slate-600/50',   glow: '',                                         bar: 'bg-slate-600' },
  OFFLINE:  { cls: 'bg-slate-900/60 text-slate-500 border-slate-700/50',   glow: '',                                         bar: 'bg-slate-700' },
};


function App() {
  const wsUrl = useMemo(resolveWsUrl, []);
  const lastUpdateSigRef = useRef<string>('');

  const [rawData, setRawData] = useState<any>({
    planes: [], satellites: [], news: [], gpsInterference: [],
    webcams: [], ships: [], emergencySquawks: [],
    conflicts: [], cyber_attacks: [],
    aiAnalysis: { summary: "Initializing Global Surveillance...", threat_level: 'UNKNOWN', predictions: [] },
    bgp: {}, last_updated: {},
  });

  const [filters, setFilters] = useState({
    showPlanes: true, showSatellites: true, showShips: true, showWebcams: false,
    showNews: true, showConflicts: true, showCyber: true, militaryOnlySats: false,
    jammingOnlyPlanes: false, stationsVisible: true,
  });

  const [selectedItem, setSelectedItem] = useState<any>(null);
  const [showFilterPanel, setShowFilterPanel] = useState(false);
  const [feedTab, setFeedTab] = useState<'brief' | 'live' | 'predictions'>('brief');
  const [webcamViewer, setWebcamViewer] = useState<any>(null);
  const [camPov, setCamPov] = useState<{ lat: number; lng: number; altitude: number } | null>(null);
  const [showReticle, setShowReticle] = useState(false);
  const historyModeRef = useRef(false);

  const [utcTime, setUtcTime] = useState('');
  useEffect(() => {
    const update = () => setUtcTime(new Date().toISOString().replace('T', ' ').slice(0, 19) + 'Z');
    update();
    const t = setInterval(update, 1000);
    return () => clearInterval(t);
  }, []);

  const { lastJsonMessage, readyState, sendJsonMessage } = useWebSocket(wsUrl, { shouldReconnect: () => true, reconnectInterval: 3000 });

  useEffect(() => {
    (window as any).__ARGUS_NEXUS_REQUEST_SECTOR__ = (box: any) => sendJsonMessage({ type: 'request_sector', box });
    return () => { (window as any).__ARGUS_NEXUS_REQUEST_SECTOR__ = null; };
  }, [sendJsonMessage]);

  const [systemStatus, setSystemStatus] = useState('Initializing Sentinel...');

  useEffect(() => {
    const msg = lastJsonMessage as any;
    if (msg?.type === 'status') { setSystemStatus(msg.message); return; }
    if (msg?.type === 'sector_update') { (window as any).__ARGUS_NEXUS_ON_SECTOR_DATA__?.(msg); return; }
    if (msg?.type === 'update' && !historyModeRef.current) {
      const updateSig = JSON.stringify(msg.last_updated || {});
      if (updateSig === lastUpdateSigRef.current) return;
      lastUpdateSigRef.current = updateSig;
      setRawData((prev: any) => ({
        ...prev,
        planes:           msg.planes            || prev.planes,
        satellites:       msg.satellites         || prev.satellites,
        news:             msg.news               || prev.news,
        gpsInterference:  msg.gps_interference   || prev.gpsInterference,
        webcams:          msg.webcams            || prev.webcams,
        ships:            msg.ships              || prev.ships,
        emergencySquawks: msg.emergency_squawks  || prev.emergencySquawks,
        conflicts:        msg.conflicts          || prev.conflicts,
        cyber_attacks:    msg.cyber_attacks      || prev.cyber_attacks,
        aiAnalysis:       msg.ai_analysis        || prev.aiAnalysis,
        bgp:              msg.bgp                || prev.bgp,
        last_updated:     msg.last_updated       || prev.last_updated,
      }));
    }
  }, [lastJsonMessage]);

  const isOnline = readyState === ReadyState.OPEN;
  const threatLevel = rawData.aiAnalysis?.threat_level || 'UNKNOWN';
  const threatConf = THREAT_CONFIG[threatLevel] || THREAT_CONFIG.UNKNOWN;
  const criticalConflicts = useMemo(() => (rawData.conflicts || []).filter((c: any) => c.severity === 'CRITICAL'), [rawData.conflicts]);
  const milPlanes = useMemo(() => (rawData.planes || []).filter((p: any) => p.military), [rawData.planes]);

  const liveFeed = useMemo(() => {
    return [...(rawData.news || []).map((n: any) => ({ ...n, _feedType: 'news' })), ...(rawData.conflicts || []).map((c: any) => ({ ...c, _feedType: 'conflict' }))]
      .sort((a, b) => new Date(b.published_at || 0).getTime() - new Date(a.published_at || 0).getTime()).slice(0, 80);
  }, [rawData.news, rawData.conflicts]);

  return (
    <div className="relative w-screen h-screen overflow-hidden bg-[#020617] text-slate-200 font-mono select-none antialiased">

      {/* GLOBE */}
      <div className="absolute inset-0">
        <Suspense fallback={
          <div className="absolute inset-0 bg-[#020617] flex items-center justify-center z-50">
            <div className="text-center">
              <div className="w-12 h-12 border-2 border-sky-500/20 border-t-sky-400 rounded-full animate-spin mx-auto mb-4" />
              <p className="text-[10px] text-sky-400 font-bold uppercase tracking-[0.4em] animate-pulse">{systemStatus}</p>
            </div>
          </div>
        }>
          <GlobeView data={rawData} selectedItem={selectedItem} onSelectItem={(item) => item?.dataType === 'webcam' ? setWebcamViewer(item) : setSelectedItem(item)} onPovChange={setCamPov} />
        </Suspense>
      </div>

      {/* TARGETING RETICLE */}
      {showReticle && (
        <div className="absolute inset-0 pointer-events-none z-10 flex items-center justify-center">
          <div className="relative w-32 h-32">
            {/* Corner brackets */}
            <div className="absolute top-0 left-0 w-5 h-5 border-t-2 border-l-2 border-rose-400/70" />
            <div className="absolute top-0 right-0 w-5 h-5 border-t-2 border-r-2 border-rose-400/70" />
            <div className="absolute bottom-0 left-0 w-5 h-5 border-b-2 border-l-2 border-rose-400/70" />
            <div className="absolute bottom-0 right-0 w-5 h-5 border-b-2 border-r-2 border-rose-400/70" />
            {/* Center dot */}
            <div className="absolute inset-0 flex items-center justify-center">
              <div className="w-1.5 h-1.5 rounded-full bg-rose-400/80" />
            </div>
            {/* Crosshair lines */}
            <div className="absolute top-1/2 left-0 right-0 h-px bg-rose-400/30" />
            <div className="absolute left-1/2 top-0 bottom-0 w-px bg-rose-400/30" />
          </div>
          {camPov && (
            <div className="absolute" style={{ top: 'calc(50% + 72px)', transform: 'translateX(-50%)', left: '50%' }}>
              <span className="text-[9px] text-rose-400/70 font-mono tracking-widest bg-black/40 px-2 py-0.5 rounded">
                {camPov.lat >= 0 ? 'N' : 'S'}{Math.abs(camPov.lat).toFixed(4)}° {camPov.lng >= 0 ? 'E' : 'W'}{Math.abs(camPov.lng).toFixed(4)}°
              </span>
            </div>
          )}
        </div>
      )}

      {/* VIGNETTE */}
      <div className="absolute inset-0 pointer-events-none z-5" style={{
        background: 'radial-gradient(ellipse at center, transparent 55%, rgba(0,0,0,0.6) 100%)',
      }} />

      {/* TOP COMMAND BAR */}
      <header className="absolute top-0 left-0 right-0 h-14 z-20 flex items-center justify-between px-4 bg-gradient-to-b from-[#020617]/95 to-transparent backdrop-blur-sm pointer-events-none border-b border-slate-800/40">
        {/* LEFT: LOGO + STATUS */}
        <div className="flex items-center gap-4 pointer-events-auto">
          <div className="flex items-center gap-2.5">
            <div className="relative flex items-center justify-center w-8 h-8 rounded-lg bg-sky-900/40 border border-sky-500/40 shadow-[0_0_15px_rgba(14,165,233,0.25)]">
              <Shield size={15} className="text-sky-400" />
            </div>
            <div>
              <div className="text-sm font-black tracking-[0.2em] text-white drop-shadow-[0_0_8px_rgba(255,255,255,0.4)]">ARGUS NEXUS</div>
              <div className="text-[8px] text-sky-500 tracking-[0.35em] font-bold uppercase">Strategic Command</div>
            </div>
          </div>

          <div className="h-5 w-px bg-slate-700/60" />

          <div className={`flex items-center gap-1.5 px-2.5 py-1 rounded border text-[9px] font-bold tracking-wider ${isOnline ? 'border-emerald-500/30 text-emerald-400' : 'border-red-500/30 text-red-400 animate-pulse'}`}>
            {isOnline ? <Wifi size={10}/> : <WifiOff size={10}/>}
            {isOnline ? 'DATALINK SECURE' : 'LINK LOST'}
          </div>

          <div className="flex items-center gap-1.5 bg-slate-900/60 border border-slate-700/50 px-2.5 py-1 rounded text-[9px] text-slate-400">
            <Clock size={10} className="text-sky-500" /> {utcTime}
          </div>
        </div>

        {/* CENTER: THREAT LEVEL */}
        <div className={`flex items-center gap-3 px-4 py-1.5 rounded-lg border ${threatConf.cls} ${threatConf.glow} backdrop-blur-sm`}>
          <div className={`w-2 h-2 rounded-full ${threatConf.bar} animate-pulse`} />
          <span className="text-[9px] text-slate-400 tracking-widest">THREAT</span>
          <span className="text-sm font-black tracking-wider">{threatLevel}</span>
        </div>

        {/* RIGHT: STATS + CONTROLS */}
        <div className="flex items-center gap-3 pointer-events-auto">
          {/* Entity counts */}
          <div className="flex items-center gap-3 text-[10px] bg-slate-900/60 border border-slate-700/50 px-3 py-1.5 rounded backdrop-blur-sm">
            <StatBadge icon={<Plane size={11} className="text-amber-400"/>} value={rawData.planes.length} label="AC" />
            <div className="w-px h-4 bg-slate-700" />
            <StatBadge icon={<Satellite size={11} className="text-sky-400"/>} value={rawData.satellites.length} label="SAT" />
            <div className="w-px h-4 bg-slate-700" />
            <StatBadge icon={<Anchor size={11} className="text-blue-400"/>} value={rawData.ships.length} label="VES" />
            <div className="w-px h-4 bg-slate-700" />
            <StatBadge icon={<AlertTriangle size={11} className="text-rose-400"/>} value={criticalConflicts.length} label="CRT" pulse={criticalConflicts.length > 0} />
          </div>

          {/* Reticle toggle */}
          <button onClick={() => setShowReticle(r => !r)} title="Toggle targeting reticle"
            className={`p-2 rounded border transition-all ${showReticle ? 'bg-rose-500/20 border-rose-400 text-rose-300' : 'bg-slate-900/60 border-slate-700 text-slate-400 hover:border-rose-500/50 hover:text-rose-300'} backdrop-blur-sm`}>
            <Crosshair size={15} />
          </button>

          {/* Filter toggle */}
          <button onClick={() => setShowFilterPanel(!showFilterPanel)}
            className={`p-2 rounded border transition-all ${showFilterPanel ? 'bg-sky-500/20 border-sky-400 text-sky-300' : 'bg-slate-900/60 border-slate-700 text-slate-400 hover:border-sky-500/50 hover:text-sky-300'} backdrop-blur-sm`}>
            <Layers size={15} />
          </button>
        </div>
      </header>

      {/* LEFT SIDEBAR – INTELLIGENCE FEED */}
      <aside className="absolute left-4 top-16 bottom-12 w-[340px] z-20 pointer-events-none flex flex-col">
        <div className="pointer-events-auto h-full flex flex-col bg-slate-950/70 border border-slate-800/80 rounded-xl backdrop-blur-xl shadow-2xl shadow-black/60 overflow-hidden">

          {/* Tab bar */}
          <div className="flex border-b border-slate-800/80 bg-slate-900/40">
            <FeedTab icon={<Radio size={10}/>} label="AI Brief" active={feedTab==='brief'} onClick={()=>setFeedTab('brief')} />
            <FeedTab icon={<Activity size={10}/>} label="Live Intel" active={feedTab==='live'} onClick={()=>setFeedTab('live')} />
            <FeedTab icon={<Crosshair size={10}/>} label="Predictions" active={feedTab==='predictions'} onClick={()=>setFeedTab('predictions')} />
          </div>

          <div className="flex-1 overflow-y-auto scrollbar-hide p-3 space-y-3">

            {/* ── AI BRIEF ── */}
            {feedTab === 'brief' && (
              <div className="space-y-4">
                {/* Summary */}
                <div className="p-3 rounded-lg bg-sky-950/20 border border-sky-500/20">
                  <div className="flex items-center gap-1.5 mb-2">
                    <Radio size={9} className="text-sky-400" />
                    <span className="text-[9px] font-bold text-sky-500 tracking-widest uppercase">Strategic Summary</span>
                    <span className="ml-auto text-[8px] text-slate-600">{rawData.aiAnalysis?.source || 'heuristic'}</span>
                  </div>
                  <p className="text-[11px] leading-relaxed text-slate-300">{rawData.aiAnalysis?.summary}</p>
                </div>

                {/* Key Drivers */}
                {rawData.aiAnalysis?.key_drivers?.length > 0 && (
                  <div className="space-y-1.5">
                    <SectionHeader icon={<Zap size={9} className="text-amber-400"/>} label="Signal Drivers" />
                    {rawData.aiAnalysis.key_drivers.map((d: any, i: number) => (
                      <div key={i} className="flex items-start gap-2.5 p-2.5 rounded-lg bg-slate-900/50 border border-slate-800/80 hover:border-slate-700 transition-colors">
                        <span className="text-sm mt-0.5">{d.icon}</span>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center justify-between mb-0.5">
                            <span className="text-[10px] font-bold text-slate-200">{d.signal}</span>
                            <WeightBadge weight={d.weight} />
                          </div>
                          <p className="text-[9px] text-slate-500 leading-tight">{d.detail}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                )}

                {/* Regional Theaters */}
                {rawData.aiAnalysis?.regional_briefs?.length > 0 && (
                  <div className="space-y-1.5">
                    <SectionHeader icon={<MapPin size={9}/>} label="Regional Theaters" />
                    {rawData.aiAnalysis.regional_briefs.map((r: any, i: number) => (
                      <div key={i}
                        className="p-2.5 rounded-lg bg-slate-900/50 border border-slate-800/80 hover:border-sky-500/30 transition-all cursor-pointer group"
                        onClick={() => setSelectedItem({ lat: r.lat, lon: r.lon, name: r.region, summary: r.summary, dataType: 'news' })}>
                        <div className="flex items-center justify-between mb-1">
                          <span className="text-[10px] font-bold text-slate-200 group-hover:text-sky-400 transition-colors">{r.region}</span>
                          <WeightBadge weight={r.status} />
                        </div>
                        <p className="text-[9px] text-slate-500 line-clamp-2 leading-snug">{r.summary}</p>
                      </div>
                    ))}
                  </div>
                )}

                {/* Intel Correlations */}
                {rawData.aiAnalysis?.correlations?.length > 0 && (
                  <div className="space-y-1.5">
                    <SectionHeader icon={<Compass size={9}/>} label="Intel Correlations" />
                    {rawData.aiAnalysis.correlations.map((c: string, i: number) => (
                      <div key={i} className="flex gap-2 p-2.5 rounded-lg bg-sky-500/5 border border-sky-500/10">
                        <div className="w-1 h-1 rounded-full bg-sky-400 mt-1.5 flex-shrink-0" />
                        <p className="text-[9px] text-sky-200/70 italic leading-snug">{c}</p>
                      </div>
                    ))}
                  </div>
                )}

                {/* Watch Items */}
                {rawData.aiAnalysis?.watch_items?.length > 0 && (
                  <div className="space-y-1.5">
                    <SectionHeader icon={<Eye size={9} className="text-rose-400"/>} label="Watch List" />
                    {rawData.aiAnalysis.watch_items.map((w: string, i: number) => (
                      <div key={i} className="flex gap-2 p-2 rounded bg-rose-500/5 border border-rose-500/10">
                        <span className="text-rose-400 text-[9px] mt-0.5 flex-shrink-0">▶</span>
                        <p className="text-[9px] text-rose-200/70 leading-snug">{w}</p>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}

            {/* ── LIVE INTEL ── */}
            {feedTab === 'live' && (
              <div className="space-y-2">
                {liveFeed.map((item: any, idx: number) => (
                  <div key={idx} onClick={() => setSelectedItem({ ...item, dataType: item._feedType })}
                    className="p-2.5 rounded-lg bg-slate-900/40 border border-slate-800 hover:border-sky-500/40 hover:bg-slate-800/50 transition-all cursor-pointer group">
                    <div className="flex items-center gap-2 mb-1.5">
                      <span className={`text-[8px] px-1.5 py-0.5 rounded font-bold uppercase tracking-wider ${item._feedType === 'conflict' ? 'bg-rose-500/20 text-rose-400' : 'bg-sky-500/20 text-sky-400'}`}>
                        {item.category || item.event_type || 'INTEL'}
                      </span>
                      {item._feedType === 'conflict' && item.severity && (
                        <span className={`text-[7px] px-1 rounded font-black ${item.severity === 'CRITICAL' ? 'bg-red-500/20 text-red-400' : item.severity === 'HIGH' ? 'bg-orange-500/20 text-orange-400' : 'bg-slate-700 text-slate-400'}`}>{item.severity}</span>
                      )}
                      <span className="ml-auto text-[8px] text-slate-600">{timeAgo(item.published_at)}</span>
                    </div>
                    <p className="text-[10px] font-medium text-slate-300 group-hover:text-white line-clamp-2 leading-snug">{item.title}</p>
                  </div>
                ))}
              </div>
            )}

            {/* ── PREDICTIONS ── */}
            {feedTab === 'predictions' && (
              <div className="space-y-3">
                <div className="text-[9px] text-slate-500 leading-relaxed p-2 rounded bg-slate-900/30 border border-slate-800">
                  AI-synthesized threat predictions from movement, OSINT, and SIGINT correlation.
                </div>
                {(rawData.aiAnalysis?.predictions || []).length === 0 && (
                  <div className="text-center py-8 text-slate-600 text-[10px]">No predictions available yet.</div>
                )}
                {(rawData.aiAnalysis?.predictions || []).map((p: any, i: number) => (
                  <div key={i}
                    className="p-3 rounded-lg bg-slate-900/60 border border-amber-500/20 hover:border-amber-500/40 transition-all cursor-pointer group"
                    onClick={() => setSelectedItem({ ...p, name: p.location, dataType: 'prediction' })}>
                    <div className="flex items-start justify-between mb-2">
                      <div className="flex items-center gap-2">
                        <Crosshair size={12} className="text-amber-400 flex-shrink-0" />
                        <span className="text-[11px] font-bold text-amber-300 group-hover:text-amber-200">{p.location}</span>
                      </div>
                      <span className="text-[10px] font-black text-amber-400 bg-amber-500/10 px-2 py-0.5 rounded border border-amber-500/20">{p.probability}</span>
                    </div>
                    <p className="text-[10px] text-slate-300 font-medium mb-1.5 line-clamp-2">{p.event}</p>
                    {p.reason && <p className="text-[9px] text-slate-500 leading-snug line-clamp-3">{p.reason}</p>}
                    <div className="flex items-center gap-1.5 mt-2 text-[8px] text-slate-600">
                      <MapPin size={8}/>
                      <span>{p.lat?.toFixed(2)}°, {p.lon?.toFixed(2)}°</span>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </aside>

      {/* RIGHT SIDEBAR – TARGET DETAILS */}
      {selectedItem && (
        <aside className="absolute right-4 top-16 bottom-12 w-[320px] z-20 pointer-events-none">
          <div className="pointer-events-auto h-full flex flex-col bg-slate-950/80 border border-sky-900/50 rounded-xl backdrop-blur-xl shadow-[0_0_30px_rgba(14,165,233,0.15)] overflow-hidden">
            <div className="p-3.5 border-b border-sky-900/50 bg-sky-950/20 flex justify-between items-start flex-shrink-0">
              <div>
                <span className="text-[8px] text-sky-400 font-bold tracking-widest uppercase mb-1 block">Target Acquired</span>
                <h3 className="text-[13px] font-black text-white uppercase tracking-wide">
                  {selectedItem.callsign || selectedItem.name || selectedItem.title?.slice(0, 32) || 'Unknown Entity'}
                </h3>
                {selectedItem.dataType && (
                  <span className="text-[8px] text-sky-600 tracking-widest uppercase">{selectedItem.dataType}</span>
                )}
              </div>
              <button onClick={() => setSelectedItem(null)} className="p-1 rounded hover:bg-rose-500/20 text-slate-500 hover:text-rose-400 transition-colors ml-2 flex-shrink-0"><X size={14}/></button>
            </div>

            <div className="flex-1 p-4 space-y-4 overflow-y-auto scrollbar-hide">
              <div className="grid grid-cols-2 gap-2">
                <DetailBox label="Latitude" value={selectedItem.lat?.toFixed(5) ?? 'N/A'} />
                <DetailBox label="Longitude" value={(selectedItem.lon ?? selectedItem.lng)?.toFixed(5) ?? 'N/A'} />
                {selectedItem.alt != null && <DetailBox label="Altitude" value={`${Math.round(selectedItem.alt).toLocaleString()} m`} />}
                {selectedItem.velocity != null && <DetailBox label="Velocity" value={`${Math.round(selectedItem.velocity)} kt`} />}
                {selectedItem.heading != null && <DetailBox label="Heading" value={`${Math.round(selectedItem.heading)}°`} />}
                {selectedItem.country && <DetailBox label="Origin" value={selectedItem.country} />}
                {selectedItem.vessel_type && <DetailBox label="Class" value={selectedItem.vessel_type} />}
                {selectedItem.type && <DetailBox label="Type" value={selectedItem.type} />}
                {selectedItem.probability && <DetailBox label="Probability" value={selectedItem.probability} />}
              </div>

              {(selectedItem.summary || selectedItem.title || selectedItem.event || selectedItem.reason) && (
                <div className="p-3 bg-slate-900/50 border border-slate-700/50 rounded-lg text-[10px] leading-relaxed text-slate-300 space-y-2">
                  {selectedItem.event && <p className="font-medium text-slate-200">{selectedItem.event}</p>}
                  {selectedItem.reason && <p className="text-slate-400 italic">{selectedItem.reason}</p>}
                  {!selectedItem.event && (selectedItem.summary || selectedItem.title) && <p>{selectedItem.summary || selectedItem.title}</p>}
                </div>
              )}

              {selectedItem.military && (
                <div className="flex items-center gap-2 px-3 py-2 bg-rose-500/10 border border-rose-500/30 rounded text-[9px] text-rose-400 font-bold tracking-wider">
                  <AlertTriangle size={10}/> MILITARY ASSET
                </div>
              )}

              {selectedItem.image && (
                <img src={selectedItem.image} alt="Target" className="w-full h-36 object-cover rounded-lg border border-slate-700/50" />
              )}
            </div>

            <div className="p-2.5 border-t border-slate-800/80 bg-slate-950/50 flex justify-between items-center flex-shrink-0">
              <span className="text-[7px] text-slate-600 tracking-widest uppercase">ID: {selectedItem.id || selectedItem.icao || 'SYS-GEN'}</span>
              <span className="text-[7px] text-slate-600 tracking-widest uppercase">{utcTime}</span>
            </div>
          </div>
        </aside>
      )}

      {/* LAYER FILTER PANEL */}
      {showFilterPanel && (
        <div className="absolute top-16 right-16 w-56 z-30 bg-slate-950/95 border border-slate-700/80 rounded-xl p-4 backdrop-blur-xl shadow-2xl pointer-events-auto">
          <h3 className="text-[9px] font-bold text-slate-400 uppercase tracking-widest mb-3 border-b border-slate-800 pb-2 flex items-center gap-1.5"><Layers size={9}/> Display Layers</h3>
          <div className="space-y-1.5">
            <ToggleRow label="Airspace / Aircraft" active={filters.showPlanes} onClick={() => setFilters(f => ({...f, showPlanes: !f.showPlanes}))} />
            <ToggleRow label="Maritime / Vessels" active={filters.showShips} onClick={() => setFilters(f => ({...f, showShips: !f.showShips}))} />
            <ToggleRow label="Satellites / Orbital" active={filters.showSatellites} onClick={() => setFilters(f => ({...f, showSatellites: !f.showSatellites}))} />
            <ToggleRow label="Cyber Intel" active={filters.showCyber} onClick={() => setFilters(f => ({...f, showCyber: !f.showCyber}))} />
            <ToggleRow label="GPS Jamming" active={true} onClick={() => {}} />
            <ToggleRow label="Conflict Events" active={filters.showConflicts} onClick={() => setFilters(f => ({...f, showConflicts: !f.showConflicts}))} />
            <ToggleRow label="News Rings" active={filters.showNews} onClick={() => setFilters(f => ({...f, showNews: !f.showNews}))} />
          </div>
        </div>
      )}

      {/* BOTTOM STATUS BAR */}
      <footer className="absolute bottom-0 left-0 right-0 h-9 z-20 flex items-center justify-between px-4 bg-[#020617]/90 border-t border-slate-800/60 backdrop-blur-sm pointer-events-none">
        <div className="flex items-center gap-5 text-[9px] text-slate-600">
          <span className="flex items-center gap-1.5"><Globe size={9} className="text-sky-700"/> ARGUS NEXUS v2.1</span>
          <span className="flex items-center gap-1.5"><Plane size={9} className="text-amber-700"/>{rawData.planes.length.toLocaleString()} AC · <span className="text-rose-700">{milPlanes.length} MIL</span></span>
          <span className="flex items-center gap-1.5"><Anchor size={9} className="text-blue-700"/>{rawData.ships.length} VES</span>
          <span className="flex items-center gap-1.5"><Satellite size={9} className="text-sky-700"/>{rawData.satellites.length} SAT</span>
        </div>
        <div className="flex items-center gap-4 text-[9px] text-slate-600">
          {camPov && (
            <span className="flex items-center gap-1 text-slate-700 font-mono">
              {camPov.lat >= 0 ? 'N' : 'S'}{Math.abs(camPov.lat).toFixed(3)}°&nbsp;
              {camPov.lng >= 0 ? 'E' : 'W'}{Math.abs(camPov.lng).toFixed(3)}°&nbsp;
              ALT {camPov.altitude.toFixed(2)}
            </span>
          )}
          {rawData.gpsInterference?.length > 0 && (
            <span className="text-rose-600 animate-pulse flex items-center gap-1"><Radio size={9}/>{rawData.gpsInterference.length} GPS JAM</span>
          )}
          {rawData.cyber_attacks?.length > 0 && (
            <span className="text-orange-700 flex items-center gap-1"><Zap size={9}/>{rawData.cyber_attacks.length} CYBER</span>
          )}
          <span className={`font-bold ${isOnline ? 'text-emerald-700' : 'text-red-700 animate-pulse'}`}>
            {isOnline ? '● LIVE' : '○ OFFLINE'}
          </span>
          <span>{utcTime}</span>
        </div>
      </footer>

      {/* ALTITUDE LEGEND */}
      <div className="absolute bottom-11 left-4 z-20 pointer-events-none flex flex-col gap-0.5">
        {[
          { color: '#ff2615', label: 'MIL' },
          { color: '#00d9ff', label: '>10k m' },
          { color: '#33ff80', label: '>5k m' },
          { color: '#ffb300', label: '>2k m' },
          { color: '#ff6600', label: '>500 m' },
          { color: '#ffffff', label: 'GND' },
        ].map(({ color, label }) => (
          <div key={label} className="flex items-center gap-1.5">
            <div className="w-2 h-2 rounded-full flex-shrink-0" style={{ backgroundColor: color, boxShadow: `0 0 4px ${color}88` }} />
            <span className="text-[7px] text-slate-600 tracking-wider">{label}</span>
          </div>
        ))}
      </div>

      {/* WEBCAM MODAL */}
      {webcamViewer && (
        <div className="absolute inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm pointer-events-auto">
          <div className="w-[800px] h-[500px] bg-slate-950 border border-slate-700 rounded-xl overflow-hidden shadow-2xl flex flex-col">
            <div className="h-10 border-b border-slate-800 flex items-center justify-between px-4 bg-slate-900/80">
              <span className="text-xs font-bold text-slate-200 tracking-wider uppercase flex items-center gap-2"><Camera size={13}/> LIVE SURVEILLANCE FEED — {webcamViewer.name || webcamViewer.location}</span>
              <button onClick={() => setWebcamViewer(null)} className="text-slate-400 hover:text-white transition-colors"><X size={16}/></button>
            </div>
            <iframe src={webcamViewer.embed_url} className="flex-1 w-full border-none" allow="autoplay; fullscreen" />
          </div>
        </div>
      )}
    </div>
  );
}

// ── UI COMPONENTS ──
function StatBadge({ icon, value, label, pulse }: { icon: React.ReactNode; value: number; label: string; pulse?: boolean }) {
  return (
    <div className={`flex items-center gap-1 ${pulse ? 'animate-pulse' : ''}`}>
      {icon}
      <span className="font-bold text-white">{value.toLocaleString()}</span>
      <span className="text-slate-600 text-[8px]">{label}</span>
    </div>
  );
}
function FeedTab({ icon, label, active, onClick }: { icon: React.ReactNode; label: string; active: boolean; onClick: () => void }) {
  return (
    <button onClick={onClick} className={`flex-1 py-2.5 text-[9px] font-bold uppercase tracking-widest transition-all border-b-2 flex items-center justify-center gap-1 ${active ? 'border-sky-500 text-sky-400 bg-sky-900/10' : 'border-transparent text-slate-600 hover:text-slate-400 hover:bg-white/3'}`}>
      {icon}{label}
    </button>
  );
}
function SectionHeader({ icon, label }: { icon: React.ReactNode; label: string }) {
  return (
    <div className="flex items-center gap-1.5 text-[9px] font-bold text-sky-500 tracking-widest uppercase mb-1">
      {icon}{label}
    </div>
  );
}
function WeightBadge({ weight }: { weight: string }) {
  const cls = weight === 'CRITICAL' ? 'bg-red-500/20 text-red-400' : weight === 'HIGH' ? 'bg-orange-500/20 text-orange-400' : weight === 'ELEVATED' ? 'bg-amber-500/20 text-amber-400' : 'bg-slate-800 text-slate-500';
  return <span className={`text-[7px] px-1.5 py-0.5 rounded font-black ${cls}`}>{weight}</span>;
}
function DetailBox({ label, value }: { label: string; value: string | number }) {
  return (
    <div className="bg-slate-900/60 border border-slate-800/80 rounded-lg p-2.5">
      <span className="block text-[8px] text-slate-600 tracking-widest uppercase mb-1">{label}</span>
      <span className="text-[11px] font-bold text-slate-200">{value}</span>
    </div>
  );
}
function ToggleRow({ label, active, onClick }: { label: string; active: boolean; onClick: () => void }) {
  return (
    <div className="flex justify-between items-center cursor-pointer p-1.5 rounded hover:bg-white/5 transition-colors" onClick={onClick}>
      <span className="text-[10px] text-slate-400">{label}</span>
      <div className={`w-7 h-3.5 rounded-full p-0.5 transition-colors ${active ? 'bg-sky-500' : 'bg-slate-700'}`}>
        <div className={`w-2.5 h-2.5 bg-white rounded-full transition-transform shadow-sm ${active ? 'translate-x-3.5' : ''}`}/>
      </div>
    </div>
  );
}

export default App;
