import React, { useState, useEffect } from "react";
import { 
  Tv, 
  Wifi, 
  Bluetooth, 
  Cast, 
  X, 
  RefreshCw, 
  CheckCircle2, 
  AlertTriangle, 
  Sliders, 
  Play, 
  Pause, 
  Square, 
  Monitor, 
  Maximize2, 
  Volume2, 
  Pointer, 
  Radio, 
  Zap, 
  Check, 
  Smartphone, 
  ShieldCheck,
  SignalHigh,
  Layers,
  Settings,
  ExternalLink
} from "lucide-react";

interface TvProjectorCastModalProps {
  isOpen: boolean;
  onClose: () => void;
}

interface CastDevice {
  id: string;
  name: string;
  type: "tv" | "projector";
  protocol: "wifi" | "bluetooth" | "both";
  location: string;
  resolution: string;
  status: "available" | "busy" | "offline";
  ipOrMac: string;
  signalStrength: number; // percentage
}

const DEFAULT_DEVICES: CastDevice[] = [
  {
    id: "dev-01",
    name: "Samsung QLED 85\" Ruang Rapat Direksi",
    type: "tv",
    protocol: "both",
    location: "Lantai 5 - R. Rapat Direksi",
    resolution: "3840 x 2160 (4K UHD 60FPS)",
    status: "available",
    ipOrMac: "192.168.10.45 / BT: 48:A0:0B:99",
    signalStrength: 98
  },
  {
    id: "dev-02",
    name: "Epson Laser 4K Proyektor Conference",
    type: "projector",
    protocol: "wifi",
    location: "Lantai 3 - Hall Conference",
    resolution: "3840 x 2160 (4K Laser)",
    status: "available",
    ipOrMac: "192.168.10.88 / Miracast",
    signalStrength: 92
  },
  {
    id: "dev-03",
    name: "LG OLED 75\" R. Rapat CTO & IT",
    type: "tv",
    protocol: "both",
    location: "Lantai 4 - Lab Inovasi CTO",
    resolution: "3840 x 2160 (120Hz)",
    status: "available",
    ipOrMac: "192.168.10.102 / BT LE",
    signalStrength: 85
  },
  {
    id: "dev-04",
    name: "BenQ Smart Projector HR & GA",
    type: "projector",
    protocol: "bluetooth",
    location: "Lantai 2 - R. Rapat HRD",
    resolution: "1920 x 1080 (Full HD)",
    status: "available",
    ipOrMac: "Bluetooth LE: 00:1A:7D:DA",
    signalStrength: 78
  },
  {
    id: "dev-05",
    name: "Sony BRAVIA 65\" R. Meeting Operasional",
    type: "tv",
    protocol: "wifi",
    location: "Lantai 1 - R. Operasional",
    resolution: "3840 x 2160 (4K HDR)",
    status: "busy",
    ipOrMac: "192.168.10.150 (Dipakai: HR Training)",
    signalStrength: 95
  }
];

export default function TvProjectorCastModal({ isOpen, onClose }: TvProjectorCastModalProps) {
  const [devices, setDevices] = useState<CastDevice[]>(DEFAULT_DEVICES);
  const [connectionType, setConnectionType] = useState<"all" | "wifi" | "bluetooth">("all");
  const [isScanning, setIsScanning] = useState(false);
  const [selectedDevice, setSelectedDevice] = useState<CastDevice | null>(null);
  const [isCasting, setIsCasting] = useState(false);
  const [castMode, setCastMode] = useState<"full" | "presentation" | "dashboard" | "rkap">("full");
  const [isPaused, setIsPaused] = useState(false);
  const [showLaserPointer, setShowLaserPointer] = useState(true);
  const [audioEnabled, setAudioEnabled] = useState(true);
  const [statusMessage, setStatusMessage] = useState<string>("");
  const [pingLatency, setPingLatency] = useState<number>(14);

  // Scan simulation or real Web Bluetooth scan
  const handleScanDevices = async () => {
    setIsScanning(true);
    setStatusMessage("Memindai jaringan Wi-Fi 5GHz & transmisi Bluetooth LE sekitar...");

    // Try real Web Bluetooth API if available
    if (connectionType === "bluetooth" && typeof navigator !== "undefined" && (navigator as any).bluetooth) {
      try {
        setStatusMessage("Membuka dialog pencarian Bluetooth sistem...");
        const bluetoothDevice = await (navigator as any).bluetooth.requestDevice({
          acceptAllDevices: true
        });
        if (bluetoothDevice) {
          const newBtDev: CastDevice = {
            id: `bt-${Date.now()}`,
            name: bluetoothDevice.name || "Perangkat Bluetooth TV/Proyektor Disambungkan",
            type: "tv",
            protocol: "bluetooth",
            location: "Koneksi Terdeteksi via Bluetooth LE",
            resolution: "Full HD 1080p (60fps)",
            status: "available",
            ipOrMac: `MAC: ${bluetoothDevice.id.substring(0, 12)}...`,
            signalStrength: 100
          };
          setDevices(prev => [newBtDev, ...prev]);
          setSelectedDevice(newBtDev);
          setStatusMessage(`Terhubung dengan ${newBtDev.name}!`);
        }
      } catch (err) {
        console.warn("Bluetooth device request cancelled/unsupported:", err);
      }
    }

    setTimeout(() => {
      setIsScanning(false);
      setStatusMessage("Pemindaian selesai. 5 Perangkat TV & Proyektor terdeteksi.");
    }, 1800);
  };

  // Open Standalone Real 4K TV / Projector Display Window for second monitor
  const handleOpenRealTvWindow = () => {
    const targetUrl = window.location.origin + window.location.pathname + "?display=tv";
    const popout = window.open(
      targetUrl,
      "EMS_MEDIAN_TV_DISPLAY_WINDOW",
      "width=1280,height=720,menubar=no,toolbar=no,location=no,status=no"
    );
    if (popout) {
      setStatusMessage("Jendela Tampilan Nyata 4K TV/Proyektor dibuka di Layar Kedua!");
      setTimeout(() => {
        try {
          const bc = new BroadcastChannel("ems_tv_cast");
          bc.postMessage({ type: "SET_MODE", mode: castMode });
          bc.postMessage({ type: "TOGGLE_PAUSE", isPaused });
          bc.close();
        } catch (e) {}
      }, 500);
    } else {
      setStatusMessage("Popup diblokir browser. Harap izinkan popup untuk membuka Layar TV/Proyektor.");
    }
  };

  // Sync mode, pause, and audio controls with open TV Display Window via BroadcastChannel
  useEffect(() => {
    if (!isCasting) return;
    try {
      const bc = new BroadcastChannel("ems_tv_cast");
      bc.postMessage({ type: "SET_MODE", mode: castMode });
      bc.postMessage({ type: "TOGGLE_PAUSE", isPaused });
      bc.postMessage({ type: "TOGGLE_AUDIO", muted: !audioEnabled });
      bc.close();
    } catch (e) {}
  }, [castMode, isPaused, audioEnabled, isCasting]);

  // Start casting using Display Media or Presentation mode
  const handleStartCast = async (device: CastDevice) => {
    setSelectedDevice(device);
    setIsCasting(true);
    setIsPaused(false);
    setStatusMessage(`Memulai Transmisi Display Nyata ke ${device.name}...`);

    // Broadcast initial cast state
    try {
      const bc = new BroadcastChannel("ems_tv_cast");
      bc.postMessage({ type: "SET_MODE", mode: castMode });
      bc.close();
    } catch (e) {}

    // Check if Screen Capture API is supported by browser
    if (typeof navigator !== "undefined" && navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
      try {
        const stream = await navigator.mediaDevices.getDisplayMedia({
          video: true,
          audio: audioEnabled
        });
        if (stream) {
          setStatusMessage(`STREAMING DISPLAY CAPTURE AKTIF ke ${device.name} (${device.resolution})`);
          
          // Listen to track ended event (user clicks Stop Sharing in browser)
          stream.getVideoTracks()[0].onended = () => {
            setIsCasting(false);
            setStatusMessage("Koneksi Screen Cast dihentikan oleh pengguna.");
          };
          return;
        }
      } catch (err) {
        console.info("Display media modal closed or skipped, using presentation mode:", err);
      }
    }

    // Default presentation mode
    setTimeout(() => {
      setStatusMessage(`TRANSMISI LENGKAP TERHUBUNG KE ${device.name.toUpperCase()}`);
    }, 800);
  };

  const handleStopCast = () => {
    setIsCasting(false);
    setIsPaused(false);
    setStatusMessage("Koneksi proyektor/TV telah terputus.");
  };

  // Simulate ping refresh during cast
  useEffect(() => {
    if (!isCasting) return;
    const interval = setInterval(() => {
      setPingLatency(Math.floor(10 + Math.random() * 8));
    }, 3000);
    return () => clearInterval(interval);
  }, [isCasting]);

  if (!isOpen) return null;

  const filteredDevices = devices.filter(d => {
    if (connectionType === "wifi") return d.protocol === "wifi" || d.protocol === "both";
    if (connectionType === "bluetooth") return d.protocol === "bluetooth" || d.protocol === "both";
    return true;
  });

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-5 bg-black/80 backdrop-blur-md animate-fade-in">
      <div className="bg-[#0b132b] border-2 border-sky-500/50 rounded-2xl max-w-3xl w-full overflow-hidden shadow-2xl shadow-sky-950/80 flex flex-col max-h-[92vh]">
        
        {/* Modal Header */}
        <div className="bg-gradient-to-r from-[#0f172a] via-[#1e293b] to-[#0f172a] p-4 border-b border-sky-500/30 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-sky-500 to-blue-600 flex items-center justify-center text-white shadow-lg shadow-sky-500/40 shrink-0">
              <Tv className="w-5 h-5 animate-pulse" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h2 className="text-base sm:text-lg font-black text-white uppercase tracking-wide">
                  Koneksi TV & Proyektor Wireless
                </h2>
                <span className="text-[10px] font-mono bg-sky-500/20 text-sky-300 border border-sky-400/40 px-2 py-0.5 rounded font-bold uppercase">
                  Wi-Fi & Bluetooth LE
                </span>
              </div>
              <p className="text-xs text-slate-400">
                Pancarkan Layar Dashboard, RKAP, & Dokumen EMS MEDIAN ke Smart TV / Proyektor Rapat
              </p>
            </div>
          </div>

          <button
            onClick={onClose}
            className="p-1.5 hover:bg-slate-800 text-slate-400 hover:text-white rounded-lg transition-colors cursor-pointer"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Modal Body */}
        <div className="p-4 sm:p-6 overflow-y-auto space-y-5 flex-1 font-sans">

          {/* Active Cast Banner when connected */}
          {isCasting && selectedDevice && (
            <div className="bg-gradient-to-r from-emerald-950/90 via-emerald-900/60 to-[#0b132b] border-2 border-emerald-500/80 p-4 rounded-xl space-y-3 shadow-lg shadow-emerald-950/50 animate-pulse-slow">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border-b border-emerald-500/30 pb-3">
                <div className="flex items-center gap-3">
                  <div className="relative">
                    <Radio className="w-6 h-6 text-emerald-400 animate-ping" />
                    <Radio className="w-6 h-6 text-emerald-400 absolute inset-0" />
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="text-xs font-black bg-emerald-500 text-slate-950 px-2 py-0.5 rounded uppercase tracking-wider">
                        LIVE CASTING ACTIVE
                      </span>
                      <span className="text-xs text-emerald-300 font-mono font-bold">
                        {pingLatency}ms Latensi • 60 FPS
                      </span>
                    </div>
                    <h3 className="text-sm font-bold text-white mt-1">
                      {selectedDevice.name}
                    </h3>
                    <p className="text-[11px] text-emerald-300/80 font-mono">
                      {selectedDevice.location} ({selectedDevice.ipOrMac})
                    </p>
                  </div>
                </div>

                <div className="flex items-center gap-2">
                  <button
                    onClick={handleOpenRealTvWindow}
                    className="px-4 py-2 bg-gradient-to-r from-sky-400 via-sky-500 to-blue-600 hover:from-sky-300 hover:to-blue-500 text-slate-950 font-black text-xs uppercase tracking-wider rounded-lg shadow-lg shadow-sky-500/30 transition-all flex items-center gap-2 cursor-pointer border border-sky-300"
                    title="Buka Jendela Fullscreen Tampilan Nyata untuk Layar Kedua TV / Proyektor"
                  >
                    <ExternalLink className="w-4 h-4 stroke-[3]" />
                    <span>Buka Tampilan Nyata di TV</span>
                  </button>

                  <button
                    onClick={handleStopCast}
                    className="px-3.5 py-2 bg-rose-600 hover:bg-rose-500 text-white font-bold text-xs uppercase rounded-lg shadow-md transition-all flex items-center justify-center gap-1.5 cursor-pointer shrink-0"
                  >
                    <Square className="w-4 h-4" />
                    Putus
                  </button>
                </div>
              </div>

              {/* Real-time Screen Mirroring Preview Canvas Box */}
              <div className="bg-slate-950 border border-sky-500/40 rounded-xl p-3 space-y-2 relative overflow-hidden">
                <div className="flex items-center justify-between text-[11px] font-mono text-sky-300 font-bold border-b border-slate-800 pb-1.5">
                  <span className="flex items-center gap-1.5">
                    <Monitor className="w-3.5 h-3.5 text-sky-400" />
                    Live Viewport Output Simulator ({castMode.toUpperCase()})
                  </span>
                  <span className="text-emerald-400 text-[10px]">
                    ● Broadcast Sync Active
                  </span>
                </div>

                <div className="bg-[#030712] aspect-video rounded-lg border border-slate-800 p-3 flex flex-col justify-between relative overflow-hidden group">
                  {/* Laser Dot Indicator inside preview */}
                  {showLaserPointer && (
                    <div className="absolute w-3 h-3 bg-red-500 rounded-full animate-ping top-1/2 left-1/2 shadow-[0_0_12px_#ef4444]"></div>
                  )}

                  <div className="flex items-center justify-between text-[10px] font-mono text-slate-400 border-b border-slate-800/80 pb-1">
                    <span className="font-bold text-white">EMS MEDIAN 4K BROADCAST</span>
                    <span className="text-sky-400 font-bold">{new Date().toLocaleTimeString("id-ID")}</span>
                  </div>

                  <div className="my-auto text-center space-y-1">
                    <div className="text-xs sm:text-sm font-black text-white uppercase tracking-wider">
                      {castMode === "full" && "DASHBOARD EKSEKUTIF & REALTIME TELEMETRY"}
                      {castMode === "presentation" && "RAPAT DIREKSI & SLIDE PRESENTASI Q3"}
                      {castMode === "dashboard" && "STATISTIK SERVER, CLUSTER & SYSTEM HEALTH"}
                      {castMode === "rkap" && "LAPORAN KEUANGAN & RKAP ANGGARAN"}
                    </div>
                    <div className="text-[10px] font-mono text-emerald-400">
                      Realisasi Target RKAP: Rp 148.5 M (104.2%) • Presensi: 98.4%
                    </div>
                  </div>

                  <div className="flex items-center justify-between text-[9px] font-mono text-slate-400 pt-1 border-t border-slate-800/80">
                    <span>Target: {selectedDevice.name}</span>
                    <button 
                      onClick={handleOpenRealTvWindow}
                      className="text-sky-400 hover:text-sky-300 underline font-bold"
                    >
                      Klik untuk Buka Fullscreen di TV ↗
                    </button>
                  </div>
                </div>
              </div>

              {/* Live Control Panel */}
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs font-mono">
                <button
                  onClick={() => setIsPaused(!isPaused)}
                  className={`p-2.5 rounded-lg border flex items-center justify-center gap-2 font-bold cursor-pointer transition-all ${
                    isPaused 
                      ? "bg-amber-500 text-slate-950 border-amber-300" 
                      : "bg-[#081026] text-emerald-300 border-emerald-500/40 hover:bg-emerald-900/40"
                  }`}
                >
                  {isPaused ? <Play className="w-4 h-4" /> : <Pause className="w-4 h-4" />}
                  <span>{isPaused ? "Lanjutkan Screen" : "Jeda (Freeze Screen)"}</span>
                </button>

                <button
                  onClick={() => setShowLaserPointer(!showLaserPointer)}
                  className={`p-2.5 rounded-lg border flex items-center justify-center gap-2 font-bold cursor-pointer transition-all ${
                    showLaserPointer 
                      ? "bg-sky-600 text-white border-sky-400" 
                      : "bg-[#081026] text-slate-300 border-slate-700"
                  }`}
                >
                  <Pointer className="w-4 h-4" />
                  <span>Pointer Laser: {showLaserPointer ? "ON" : "OFF"}</span>
                </button>

                <button
                  onClick={() => setAudioEnabled(!audioEnabled)}
                  className={`p-2.5 rounded-lg border flex items-center justify-center gap-2 font-bold cursor-pointer transition-all ${
                    audioEnabled 
                      ? "bg-indigo-600 text-white border-indigo-400" 
                      : "bg-[#081026] text-slate-400 border-slate-700"
                  }`}
                >
                  <Volume2 className="w-4 h-4" />
                  <span>Audio TV: {audioEnabled ? "Aktif" : "Mute"}</span>
                </button>

                <div className="bg-[#081026] border border-emerald-500/40 p-2 rounded-lg flex items-center justify-between text-[11px] text-emerald-200 font-bold">
                  <span>Resolusi:</span>
                  <span className="text-white">{selectedDevice.resolution.split(" ")[0]}</span>
                </div>
              </div>
            </div>
          )}

          {/* Connection Mode Filter Tabs & Scan Action */}
          <div className="flex flex-col sm:flex-row items-center justify-between gap-3 bg-[#081026] p-3 rounded-xl border border-sky-500/20">
            <div className="flex items-center gap-1 bg-[#0f172a] p-1 rounded-lg border border-[#1e293b] w-full sm:w-auto">
              <button
                onClick={() => setConnectionType("all")}
                className={`flex-1 sm:flex-none px-3 py-1.5 rounded-md text-xs font-bold transition-all ${
                  connectionType === "all" ? "bg-sky-500 text-slate-950 shadow" : "text-slate-400 hover:text-white"
                }`}
              >
                Semua Protokol
              </button>
              <button
                onClick={() => setConnectionType("wifi")}
                className={`flex-1 sm:flex-none px-3 py-1.5 rounded-md text-xs font-bold flex items-center justify-center gap-1.5 transition-all ${
                  connectionType === "wifi" ? "bg-sky-500 text-slate-950 shadow" : "text-slate-400 hover:text-white"
                }`}
              >
                <Wifi className="w-3.5 h-3.5" />
                Wi-Fi / Miracast
              </button>
              <button
                onClick={() => setConnectionType("bluetooth")}
                className={`flex-1 sm:flex-none px-3 py-1.5 rounded-md text-xs font-bold flex items-center justify-center gap-1.5 transition-all ${
                  connectionType === "bluetooth" ? "bg-blue-600 text-white shadow" : "text-slate-400 hover:text-white"
                }`}
              >
                <Bluetooth className="w-3.5 h-3.5" />
                Bluetooth LE
              </button>
            </div>

            <button
              onClick={handleScanDevices}
              disabled={isScanning}
              className="w-full sm:w-auto px-4 py-2 bg-gradient-to-r from-sky-500 to-blue-600 hover:from-sky-400 hover:to-blue-500 text-slate-950 font-black text-xs uppercase tracking-wide rounded-lg shadow-md transition-all flex items-center justify-center gap-2 cursor-pointer disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 ${isScanning ? "animate-spin text-white" : ""}`} />
              <span>{isScanning ? "Memindai Layar TV..." : "Pindai Perangkat Baru"}</span>
            </button>
          </div>

          {/* Status Notification Message */}
          {statusMessage && (
            <div className="bg-sky-950/60 border border-sky-500/40 p-2.5 rounded-lg text-xs font-mono text-sky-200 flex items-center gap-2">
              <Zap className="w-4 h-4 text-sky-400 shrink-0" />
              <span>{statusMessage}</span>
            </div>
          )}

          {/* Preset Screen Mode Options before casting */}
          <div>
            <label className="block text-xs font-black uppercase text-slate-300 tracking-wider mb-2 flex items-center gap-1.5">
              <Maximize2 className="w-4 h-4 text-sky-400" />
              Pilih Mode Tampilan Layar (Screen Presentation Preset):
            </label>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2.5 font-mono text-xs">
              {[
                { id: "full", label: "Layar Penuh (Full Dashboard)", desc: "Mirroring seluruh layar sistem EMS" },
                { id: "presentation", label: "Mode Rapat Direksi", desc: "Fokus presentasi bersih tanpa sidebar" },
                { id: "dashboard", label: "Statistik & KPI Live", desc: "Layar monitor telemetry real-time" },
                { id: "rkap", label: "Laporan Keuangan & RKAP", desc: "Grafik & rasio kas proyektor" }
              ].map(mode => (
                <button
                  key={mode.id}
                  onClick={() => setCastMode(mode.id as any)}
                  className={`p-3 rounded-xl border text-left transition-all cursor-pointer ${
                    castMode === mode.id
                      ? "bg-gradient-to-br from-sky-600 to-blue-700 text-white border-sky-400 shadow-lg shadow-sky-600/30 font-bold"
                      : "bg-[#081026] text-slate-300 border-[#1e293b] hover:border-sky-500/40 hover:bg-[#0d1838]"
                  }`}
                >
                  <span className="block font-bold text-xs">{mode.label}</span>
                  <span className="text-[10px] text-slate-300/80 font-normal block mt-1">{mode.desc}</span>
                </button>
              ))}
            </div>
          </div>

          {/* Device List Section */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <h3 className="text-xs font-black uppercase tracking-wider text-slate-300 flex items-center gap-1.5">
                <Monitor className="w-4 h-4 text-sky-400" />
                Daftar Perangkat Smart TV & Proyektor Terdeteksi ({filteredDevices.length}):
              </h3>
              <span className="text-[10px] text-emerald-400 font-mono font-bold flex items-center gap-1">
                <SignalHigh className="w-3 h-3" /> Jaringan Gedung PT MEDIAN
              </span>
            </div>

            <div className="space-y-3">
              {filteredDevices.map(device => {
                const isSelected = selectedDevice?.id === device.id;
                return (
                  <div
                    key={device.id}
                    className={`p-4 rounded-xl border transition-all flex flex-col sm:flex-row sm:items-center justify-between gap-3 ${
                      isSelected && isCasting
                        ? "bg-emerald-950/40 border-emerald-500 shadow-md shadow-emerald-900/30"
                        : "bg-[#081026] border-[#1e293b] hover:border-sky-500/50 hover:bg-[#0d1838]"
                    }`}
                  >
                    <div className="flex items-start gap-3">
                      <div className={`w-10 h-10 rounded-xl flex items-center justify-center shrink-0 ${
                        device.type === "tv" ? "bg-sky-500/20 text-sky-300 border border-sky-400/30" : "bg-purple-500/20 text-purple-300 border border-purple-400/30"
                      }`}>
                        {device.type === "tv" ? <Tv className="w-5 h-5" /> : <Monitor className="w-5 h-5" />}
                      </div>

                      <div className="space-y-1">
                        <div className="flex items-center gap-2 flex-wrap">
                          <h4 className="text-sm font-bold text-white">{device.name}</h4>
                          <span className={`text-[9px] font-mono font-bold px-2 py-0.5 rounded border uppercase ${
                            device.protocol === "both"
                              ? "bg-indigo-500/20 text-indigo-300 border-indigo-400/30"
                              : device.protocol === "wifi"
                              ? "bg-sky-500/20 text-sky-300 border-sky-400/30"
                              : "bg-blue-500/20 text-blue-300 border-blue-400/30"
                          }`}>
                            {device.protocol === "both" ? "Wi-Fi 5GHz & Bluetooth" : device.protocol === "wifi" ? "Wi-Fi Direct / Miracast" : "Bluetooth LE"}
                          </span>
                          <span className={`text-[9px] font-mono font-bold px-1.5 py-0.5 rounded ${
                            device.status === "available" ? "bg-emerald-500/20 text-emerald-300 border border-emerald-500/30" : "bg-amber-500/20 text-amber-300 border border-amber-500/30"
                          }`}>
                            {device.status === "available" ? "Siap Digunakan" : "Sibuk / Dipakai"}
                          </span>
                        </div>

                        <p className="text-xs text-slate-400 font-mono">
                          📍 {device.location} • {device.resolution}
                        </p>

                        <div className="flex items-center gap-3 text-[10px] text-slate-400 font-mono">
                          <span>Sinyal Wireless: <strong className="text-emerald-400">{device.signalStrength}%</strong></span>
                          <span>IP/MAC: <code className="text-slate-300 bg-black/40 px-1 py-0.5 rounded">{device.ipOrMac}</code></span>
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center gap-2 shrink-0 self-end sm:self-center">
                      {isSelected && isCasting ? (
                        <span className="px-3 py-1.5 bg-emerald-500/20 text-emerald-300 border border-emerald-400/40 text-xs font-mono font-bold rounded-lg flex items-center gap-1.5">
                          <CheckCircle2 className="w-4 h-4 text-emerald-400" />
                          Terhubung Active
                        </span>
                      ) : (
                        <button
                          onClick={() => handleStartCast(device)}
                          disabled={device.status === "busy"}
                          className={`px-4 py-2 font-bold text-xs uppercase tracking-wider rounded-lg transition-all flex items-center gap-2 cursor-pointer ${
                            device.status === "busy"
                              ? "bg-slate-800 text-slate-500 border border-slate-700 cursor-not-allowed"
                              : "bg-gradient-to-r from-sky-500 to-blue-600 hover:from-sky-400 hover:to-blue-500 text-slate-950 shadow-md shadow-sky-500/30"
                          }`}
                        >
                          <Cast className="w-4 h-4" />
                          <span>Mulai Cast TV</span>
                        </button>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Quick Technical Guidelines */}
          <div className="bg-[#081026] border border-sky-500/20 p-4 rounded-xl text-xs text-slate-300 space-y-2">
            <h4 className="font-bold text-sky-300 uppercase tracking-wide flex items-center gap-1.5">
              <ShieldCheck className="w-4 h-4 text-sky-400" />
              Petunjuk Teknis Koneksi Proyektor PT MEDIAN:
            </h4>
            <ul className="list-disc list-inside space-y-1 text-slate-400 font-mono text-[11px]">
              <li>Pastikan laptop/tablet terhubung ke Wi-Fi kantor <strong>MEDIAN-CORP-5G</strong> atau Bluetooth diaktifkan.</li>
              <li>Dukungan Protokol Hardware: Chromecast Built-in, Apple AirPlay 2, Miracast Display, & Bluetooth LE Receiver.</li>
              <li>Gunakan tombol <strong>Laser Pointer</strong> untuk menyorot angka pada grafik RKAP saat rapat dengan Direksi.</li>
            </ul>
          </div>

        </div>

        {/* Modal Footer */}
        <div className="bg-[#0f172a] p-4 border-t border-sky-500/30 flex items-center justify-between">
          <div className="flex items-center gap-2 text-xs text-slate-400 font-mono">
            <Wifi className="w-4 h-4 text-sky-400" />
            <span>Transmisi Terenkripsi WPA3 Enterprise</span>
          </div>

          <button
            onClick={onClose}
            className="px-5 py-2 bg-slate-800 hover:bg-slate-700 text-white font-bold text-xs uppercase tracking-wider rounded-lg transition-colors cursor-pointer"
          >
            Tutup
          </button>
        </div>

      </div>
    </div>
  );
}
