/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useMemo, useEffect } from "react";
import { Employee, AttendanceRecord, SalarySettings } from "../types";
import { generateAttendancePDF, generateAttendanceCSV } from "../utils/pdfExport";
import { 
  QrCode, 
  Camera, 
  CheckCircle2, 
  Clock, 
  AlertTriangle, 
  UserCheck, 
  MapPin, 
  Calendar, 
  Search, 
  Filter, 
  Download, 
  RefreshCw, 
  ShieldCheck, 
  DollarSign, 
  User, 
  FileSpreadsheet, 
  Printer, 
  X, 
  Sparkles,
  ChevronRight,
  Zap,
  Building2,
  FileCheck,
  Maximize2,
  Minimize2,
  Volume2,
  VolumeX,
  Flame,
  CheckCircle,
  Wifi,
  WifiOff,
  Database,
  UploadCloud,
  Server,
  HardDrive
} from "lucide-react";

interface EmployeeAttendanceModuleProps {
  employees: Employee[];
  currentUser: Employee | null;
  isServerSessionReady: boolean;
  onUpdateSalarySettings?: (empId: string, settings: SalarySettings) => void;
  onSelectEmployee?: (empId: string) => void;
}

export default function EmployeeAttendanceModule({
  employees,
  currentUser,
  isServerSessionReady,
  onUpdateSalarySettings,
  onSelectEmployee
}: EmployeeAttendanceModuleProps) {
  // Production attendance directory.
  // Database tenant adalah satu-satunya source of truth.
  const [attendanceLogs, setAttendanceLogs] =
    useState<AttendanceRecord[]>([]);

  useEffect(() => {
    if (!isServerSessionReady) {
      return;
    }

    let cancelled = false;

    const loadAttendance = async () => {
      try {
        const response = await fetch(
          "/api/erp/attendance",
          {
            method: "GET",
            credentials: "same-origin",
            headers: {
              "Accept": "application/json"
            },
            cache: "no-store"
          }
        );

        const body = await response
          .json()
          .catch(() => ({}));

        if (!response.ok) {
          throw new Error(
            body?.message ||
            body?.error ||
            `Gagal membaca absensi (HTTP ${response.status})`
          );
        }

        if (!Array.isArray(body?.attendance)) {
          throw new Error(
            "Server tidak mengembalikan attendance canonical."
          );
        }

        if (cancelled) {
          return;
        }

        setAttendanceLogs(
          body.attendance as AttendanceRecord[]
        );

        // Bersihkan cache simulator generasi lama.
        localStorage.removeItem(
          "simulated_attendance_logs"
        );

        localStorage.removeItem(
          "offline_attendance_queue"
        );

        console.log(
          "[ERP][ATTENDANCE] Tenant database loaded:",
          body?.tenantId,
          body.attendance.length
        );

      } catch (error) {
        console.error(
          "[ERP][ATTENDANCE] Database load failed:",
          error
        );

        if (!cancelled) {
          setAttendanceLogs([]);
        }
      }
    };

    loadAttendance();

    return () => {
      cancelled = true;
    };
  }, [isServerSessionReady]);

  // Active Scanner Modal State
  const [isScanModalOpen, setIsScanModalOpen] = useState(false);
  const [selectedScannerEmpId, setSelectedScannerEmpId] = useState<string>("");
  const [scanMode, setScanMode] = useState<"checkIn" | "checkOut">("checkIn");
  const [isScanningActive, setIsScanningActive] = useState(false);
  const [scanResultAlert, setScanResultAlert] = useState<{
    type: "success" | "warning" | "error";
    message: string;
    record?: AttendanceRecord;
  } | null>(null);

  // Name Tag Preview Modal
  const [selectedBadgeEmp, setSelectedBadgeEmp] = useState<Employee | null>(null);

  // Export Laporan Modal state
  const [isExportModalOpen, setIsExportModalOpen] = useState(false);
  const [exportScope, setExportScope] = useState<"filtered" | "all">("filtered");

  // Network connection & Offline-to-Online Sync states
  const [isOnline, setIsOnline] = useState<boolean>(() => 
    typeof window !== "undefined" && typeof navigator !== "undefined" ? navigator.onLine : true
  );
  const [isSimulatedOffline, setIsSimulatedOffline] = useState<boolean>(false);
  const [isSyncingOfflineQueue, setIsSyncingOfflineQueue] = useState<boolean>(false);
  const [lastSyncTime, setLastSyncTime] = useState<string | null>(null);
  const [syncToastMessage, setSyncToastMessage] = useState<string | null>(null);

  // Effective connection status
  const effectiveOnline = isOnline && !isSimulatedOffline;

  // Legacy offline queue dipertahankan sementara sebagai UI state.
  // Production scan saat ini wajib online; queue browser bukan authority.
  const [offlineQueue, setOfflineQueue] =
    useState<AttendanceRecord[]>([]);

  // Window event listeners for browser network connection status
  useEffect(() => {
    const handleOnline = () => {
      setIsOnline(true);
    };
    const handleOffline = () => {
      setIsOnline(false);
    };
    window.addEventListener("online", handleOnline);
    window.addEventListener("offline", handleOffline);
    return () => {
      window.removeEventListener("online", handleOnline);
      window.removeEventListener("offline", handleOffline);
    };
  }, []);


  // Handler for syncing offline data queue to server
  const handleSyncOfflineData = () => {
    if (offlineQueue.length === 0) {
      setSyncToastMessage("Tidak ada antrean data absensi offline di LocalStorage.");
      setTimeout(() => setSyncToastMessage(null), 4000);
      return;
    }

    if (!effectiveOnline) {
      playScanBeep("error");
      setSyncToastMessage("GAGAL SYNC: Koneksi sedang offline atau Mode Simulasi Offline aktif. Harap aktifkan jaringan online terlebih dahulu.");
      setTimeout(() => setSyncToastMessage(null), 5000);
      return;
    }

    setIsSyncingOfflineQueue(true);
    setSyncToastMessage("Sedang mentransmisikan data absensi offline dari LocalStorage ke Server Pusat...");

    setTimeout(() => {
      const nowStr = new Date().toLocaleTimeString("id-ID", { hour: '2-digit', minute: '2-digit', second: '2-digit' }) + " WIB";
      const queuedIds = new Set(offlineQueue.map(q => q.id));

      // Update attendanceLogs state: mark items as syncedToServer = true
      setAttendanceLogs(prevLogs => 
        prevLogs.map(log => {
          if (queuedIds.has(log.id) || log.syncedToServer === false) {
            return {
              ...log,
              syncedToServer: true,
              isOfflineScanned: true,
              offlineSyncedAt: nowStr,
              notes: `${log.notes ? log.notes.replace(' | Tersimpan di LocalStorage Queue (Offline)', '') : ''} | Disinkronkan ke server pada ${nowStr}`
            };
          }
          return log;
        })
      );

      const syncedCount = offlineQueue.length;
      setOfflineQueue([]);
      setIsSyncingOfflineQueue(false);
      setLastSyncTime(nowStr);

      playScanBeep("success");
      setSyncToastMessage(`BERHASIL SYNC! ${syncedCount} data absensi offline dari LocalStorage sukses terkirim dan tersimpan di server terpusat (${nowStr}).`);
      setTimeout(() => setSyncToastMessage(null), 6000);
    }, 1500);
  };

  // Auto trigger sync when network returns online and there are queued items
  useEffect(() => {
    if (effectiveOnline && offlineQueue.length > 0 && !isSyncingOfflineQueue) {
      handleSyncOfflineData();
    }
  }, [effectiveOnline]);

  // FOCUS MODE (High-Speed Mass Event Scanner) States
  const [isFocusMode, setIsFocusMode] = useState(false);
  const [eventName, setEventName] = useState("Townhall & Corporate Annual Event 2026");
  const [soundEnabled, setSoundEnabled] = useState(true);
  const [focusSearchQuery, setFocusSearchQuery] = useState("");
  const [eventScanSessionCount, setEventScanSessionCount] = useState(0);

  // Audio Synth Beep Generator for instant scan confirmation (Success / Warning / Error)
  const playScanBeep = (type: "success" | "warning" | "error" = "success") => {
    if (!soundEnabled) return;
    try {
      const AudioCtx = window.AudioContext || (window as any).webkitAudioContext;
      if (!AudioCtx) return;
      const audioCtx = new AudioCtx();

      if (type === "success") {
        // High two-tone ascending chime (C5 -> G5)
        const osc1 = audioCtx.createOscillator();
        const osc2 = audioCtx.createOscillator();
        const gain = audioCtx.createGain();

        osc1.type = "sine";
        osc2.type = "sine";
        osc1.frequency.setValueAtTime(523.25, audioCtx.currentTime); // C5
        osc2.frequency.setValueAtTime(783.99, audioCtx.currentTime + 0.1); // G5

        gain.gain.setValueAtTime(0.2, audioCtx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.35);

        osc1.connect(gain);
        osc2.connect(gain);
        gain.connect(audioCtx.destination);

        osc1.start(audioCtx.currentTime);
        osc1.stop(audioCtx.currentTime + 0.1);
        osc2.start(audioCtx.currentTime + 0.1);
        osc2.stop(audioCtx.currentTime + 0.35);

      } else if (type === "warning") {
        // Double pulse amber alert (A4 -> E5)
        const osc = audioCtx.createOscillator();
        const gain = audioCtx.createGain();

        osc.type = "triangle";
        osc.frequency.setValueAtTime(440, audioCtx.currentTime);
        osc.frequency.setValueAtTime(659.25, audioCtx.currentTime + 0.12);

        gain.gain.setValueAtTime(0.25, audioCtx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.3);

        osc.connect(gain);
        gain.connect(audioCtx.destination);

        osc.start(audioCtx.currentTime);
        osc.stop(audioCtx.currentTime + 0.3);

      } else if (type === "error") {
        // Descending low buzz error chord (220Hz saw -> 110Hz)
        const osc = audioCtx.createOscillator();
        const gain = audioCtx.createGain();

        osc.type = "sawtooth";
        osc.frequency.setValueAtTime(220, audioCtx.currentTime);
        osc.frequency.linearRampToValueAtTime(110, audioCtx.currentTime + 0.3);

        gain.gain.setValueAtTime(0.3, audioCtx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.35);

        osc.connect(gain);
        gain.connect(audioCtx.destination);

        osc.start(audioCtx.currentTime);
        osc.stop(audioCtx.currentTime + 0.35);
      }
    } catch (e) {
      // Autoplay AudioContext restriction ignored
    }
  };

  // Filter & Search states
  const [searchQuery, setSearchQuery] = useState("");
  const [filterStatus, setFilterStatus] = useState<string>("All");
  const [filterDate, setFilterDate] = useState<string>(new Date().toISOString().split("T")[0]);


  // Filtered Logs
  const filteredLogs = useMemo(() => {
    return attendanceLogs.filter(log => {
      const matchSearch = log.employeeName.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          log.employeeNip.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          log.employeeDivision.toLowerCase().includes(searchQuery.toLowerCase());
      const matchStatus = filterStatus === "All" ? true :
                          filterStatus === "Pending Sync" ? log.syncedToServer === false :
                          log.status === filterStatus;
      const matchDate = !filterDate || log.date === filterDate;
      return matchSearch && matchStatus && matchDate;
    });
  }, [attendanceLogs, searchQuery, filterStatus, filterDate]);

  // Summary statistics for selected date
  const stats = useMemo(() => {
    const todayLogs = attendanceLogs.filter(l => l.date === filterDate);
    const tepatWaktu = todayLogs.filter(l => l.status === "Tepat Waktu").length;
    const terlambat = todayLogs.filter(l => l.status === "Terlambat").length;
    const izin = todayLogs.filter(l => l.status === "Izin / Sakit" || l.status === "Dinas Luar").length;
    const alpa = Math.max(0, employees.length - todayLogs.length);
    return { total: employees.length, mejelas: todayLogs.length, tepatWaktu, terlambat, izin, alpa };
  }, [attendanceLogs, employees, filterDate]);

  // Handler production untuk scanning employee QR.
  // Browser hanya menentukan employeeId + mode.
  // Tenant, waktu, identitas dan status ditentukan server.
  const handleExecuteQrScan = async (
    targetEmpId?: string,
    simulateError: boolean = false
  ) => {
    const employeeId =
      targetEmpId || selectedScannerEmpId;

    const empToScan = employees.find(
      e => e.id === employeeId
    );

    setScanResultAlert(null);

    if (simulateError || !empToScan) {
      playScanBeep("error");

      setScanResultAlert({
        type: "error",
        message:
          "PEMINDAIAN QR GAGAL! Pegawai tidak valid pada tenant aktif."
      });

      return;
    }

    if (!isServerSessionReady) {
      playScanBeep("error");

      setScanResultAlert({
        type: "error",
        message:
          "Session tenant belum siap. Silakan tunggu lalu coba kembali."
      });

      return;
    }

    // Offline write belum diaktifkan untuk production.
    // Jangan membuat record palsu di browser.
    if (!effectiveOnline) {
      playScanBeep("error");

      setScanResultAlert({
        type: "error",
        message:
          "ABSENSI OFFLINE BELUM DIAKTIFKAN. Hubungkan perangkat ke jaringan agar scan dapat diverifikasi server."
      });

      return;
    }

    setIsScanningActive(true);

    try {
      const response = await fetch(
        "/api/erp/attendance/scan",
        {
          method: "POST",
          credentials: "same-origin",
          headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
          },
          body: JSON.stringify({
            employeeId: empToScan.id,
            mode: scanMode
          })
        }
      );

      const body = await response
        .json()
        .catch(() => ({}));

      if (!response.ok) {
        throw new Error(
          body?.message ||
          body?.error ||
          `Gagal memproses absensi (HTTP ${response.status})`
        );
      }

      if (!body?.attendance) {
        throw new Error(
          "Server tidak mengembalikan attendance canonical."
        );
      }

      const canonicalRecord =
        body.attendance as AttendanceRecord;

      setAttendanceLogs(prev => {
        const exists = prev.some(
          log => log.id === canonicalRecord.id
        );

        if (exists) {
          return prev.map(log =>
            log.id === canonicalRecord.id
              ? canonicalRecord
              : log
          );
        }

        return [
          canonicalRecord,
          ...prev
        ];
      });

      const alertType =
        canonicalRecord.status === "Terlambat"
          ? "warning"
          : "success";

      const message =
        scanMode === "checkIn"
          ? canonicalRecord.status === "Terlambat"
            ? `Absensi Masuk Berhasil. Terlambat ${canonicalRecord.lateMinutes} menit.`
            : "Absensi Masuk Berhasil. Status: Tepat Waktu."
          : `Absensi Pulang Berhasil. Check-out tercatat pada ${canonicalRecord.checkOutTime || "server time"}.`;

      setScanResultAlert({
        type: alertType,
        message:
          `${message} [SERVER VERIFIED]`,
        record: canonicalRecord
      });

      playScanBeep(alertType);

      setEventScanSessionCount(
        prev => prev + 1
      );

      console.log(
        "[ERP][ATTENDANCE][SCAN] Database save success:",
        canonicalRecord.id,
        canonicalRecord.employeeId,
        scanMode
      );

    } catch (error: any) {
      console.error(
        "[ERP][ATTENDANCE][SCAN] failed:",
        error
      );

      playScanBeep("error");

      setScanResultAlert({
        type: "error",
        message:
          error?.message ||
          "Gagal memproses absensi."
      });

    } finally {
      setIsScanningActive(false);
    }
  };

  // Sync attendance statistics directly to selected employee payroll salary settings
  const handleSyncAttendanceToPayroll = (empId: string) => {
    const targetEmp = employees.find(e => e.id === empId);
    if (!targetEmp || !onUpdateSalarySettings) return;

    // Count late times and absence days for target employee from log
    const empLogs = attendanceLogs.filter(l => l.employeeId === empId);
    const lateTimes = empLogs.filter(l => l.status === "Terlambat").length;
    const alpaDays = empLogs.filter(l => l.status === "Absen / Alpa").length;

    const ratePerLate = 50000; // Rp 50.000 per keterlambatan
    const ratePerAlpa = Math.round((targetEmp.salarySettings?.baseSalary || 5000000) / 25); // 1 hari alpa = 1/25 x Gaji Pokok

    const lateDeductionAmount = lateTimes * ratePerLate;
    const absenceDeductionAmount = alpaDays * ratePerAlpa;

    const currentSettings = targetEmp.salarySettings || {
      payGrade: "Grade 2 - Staf Operational",
      baseSalary: 6500000,
      positionAllowance: 600000,
      tunjanganTKUPercent: 35,
      tunjanganTKUAmount: 2275000,
      transportAllowance: 800000,
      mealAllowance: 750000,
      communicationAllowance: 150000,
      performanceBonus: 600000,
      overtimeHours: 0,
      overtimeRatePerHour: 50000,
      taxStatus: "TK/0",
      taxRatePercent: 5,
      bpjsKesehatanPercent: 1.0,
      bpjsKetenagakerjaanPercent: 3.0,
      customAllowances: [],
      customDeductions: [],
      bankName: "Bank BCA",
      bankAccountNumber: "5270112233",
      bankAccountHolder: targetEmp.name.toUpperCase()
    };

    onUpdateSalarySettings(empId, {
      ...currentSettings,
      lateDeductionTimes: lateTimes,
      lateDeductionAmount,
      absenceDeductionDays: alpaDays,
      absenceDeductionAmount
    });

    alert(`Data Absensi ${targetEmp.name} berhasil disinkronkan ke Manajer Payroll:\n- Keterlambatan: ${lateTimes}x (Potongan: Rp ${lateDeductionAmount.toLocaleString('id-ID')})\n- Absen/Alpa: ${alpaDays} Hari (Potongan: Rp ${absenceDeductionAmount.toLocaleString('id-ID')})`);
  };

  // Render Focus Mode (Mass Event Kiosk Mode) when activated
  if (isFocusMode) {
    const filteredFocusEmployees = employees.filter(e =>
      e.name.toLowerCase().includes(focusSearchQuery.toLowerCase()) ||
      e.nip.toLowerCase().includes(focusSearchQuery.toLowerCase()) ||
      e.division.toLowerCase().includes(focusSearchQuery.toLowerCase())
    );

    const todayEventLogs = attendanceLogs.filter(l => l.date === new Date().toISOString().split("T")[0]);

    return (
      <div className="min-h-screen bg-[#050505] text-slate-100 p-4 sm:p-6 font-sans space-y-6 animate-fadeIn relative">
        
        {/* FOCUS MODE KIOSK TOP BAR */}
        <div className="bg-[#0a0a0a] border-2 border-[#facc15] p-4 sm:p-5 rounded-xl shadow-2xl flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4">
          <div className="space-y-1">
            <div className="flex items-center gap-2">
              <span className="bg-[#facc15] text-black text-[10px] font-black px-2.5 py-0.5 uppercase tracking-wider font-mono flex items-center gap-1 shadow-md">
                <Zap className="w-3.5 h-3.5 fill-black" />
                HRD EVENT FOCUS MODE • PEMINDAIAN MASSAL
              </span>
              <span className="text-xs text-emerald-400 font-mono font-bold flex items-center gap-1">
                <span className="w-2 h-2 rounded-full bg-emerald-400 animate-ping inline-block" />
                Kiosk Scanner Active
              </span>
            </div>

            <div className="flex items-center gap-2 pt-1">
              <label className="text-xs text-slate-400 font-mono font-bold shrink-0">Nama Event:</label>
              <select
                value={eventName}
                onChange={e => setEventName(e.target.value)}
                className="bg-[#111] border border-[#333] text-[#facc15] font-black text-sm px-3 py-1 font-mono outline-none focus:border-[#facc15] cursor-pointer rounded-none"
              >
                <option value="Townhall & Corporate Annual Event 2026">Townhall & Corporate Annual Event 2026</option>
                <option value="RUPS Tahunan & Seminar Strategis">RUPS Tahunan & Seminar Strategis</option>
                <option value="Workshop Leadership HRD & Management">Workshop Leadership HRD & Management</option>
                <option value="Family Day & Gathering Perusahaan">Family Day & Gathering Perusahaan</option>
                <option value="Training K3 & Orientasi Pegawai">Training K3 & Orientasi Pegawai</option>
              </select>
            </div>
          </div>

          {/* Right Kiosk Top Actions & Live Event Stats */}
          <div className="flex flex-wrap items-center gap-3">
            
            {/* Audio Sound Toggle & Test Buttons */}
            <div className="flex items-center gap-1.5">
              <button
                type="button"
                onClick={() => setSoundEnabled(!soundEnabled)}
                className={`px-3 py-2 border text-xs font-mono font-bold flex items-center gap-1.5 transition-all cursor-pointer ${
                  soundEnabled
                    ? "bg-emerald-950/80 border-emerald-500/50 text-emerald-300"
                    : "bg-slate-900 border-slate-700 text-slate-400"
                }`}
                title="Aktifkan/Matikan Audio Beep saat QR dipindai"
              >
                {soundEnabled ? <Volume2 className="w-4 h-4 text-emerald-400" /> : <VolumeX className="w-4 h-4" />}
                <span>Suara Beep: {soundEnabled ? "ON" : "OFF"}</span>
              </button>

              {soundEnabled && (
                <div className="flex items-center gap-1 bg-[#111] p-1 border border-[#333]">
                  <button
                    type="button"
                    onClick={() => playScanBeep("success")}
                    className="px-2 py-1 bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-300 border border-emerald-500/40 text-[10px] font-mono font-bold cursor-pointer"
                    title="Uji coba efek suara Beep Sukses"
                  >
                    🔊 Sukses
                  </button>
                  <button
                    type="button"
                    onClick={() => playScanBeep("warning")}
                    className="px-2 py-1 bg-amber-500/20 hover:bg-amber-500/30 text-amber-300 border border-amber-500/40 text-[10px] font-mono font-bold cursor-pointer"
                    title="Uji coba efek suara Beep Terlambat"
                  >
                    🔔 Terlambat
                  </button>
                  <button
                    type="button"
                    onClick={() => playScanBeep("error")}
                    className="px-2 py-1 bg-rose-500/20 hover:bg-rose-500/30 text-rose-300 border border-rose-500/40 text-[10px] font-mono font-bold cursor-pointer"
                    title="Uji coba efek suara Beep Gagal (Error)"
                  >
                    🚨 Error
                  </button>
                </div>
              )}
            </div>

            {/* Live Scan Counters */}
            <div className="bg-[#111] border border-[#333] px-3.5 py-1.5 text-center font-mono text-xs">
              <span className="text-[9px] text-slate-400 uppercase block font-bold">Terabsen Event Ini</span>
              <span className="text-sm font-black text-[#facc15]">{todayEventLogs.length} / {employees.length}</span>
            </div>

            <div className="bg-[#111] border border-[#333] px-3.5 py-1.5 text-center font-mono text-xs">
              <span className="text-[9px] text-slate-400 uppercase block font-bold">Sesi Scan Massal</span>
              <span className="text-sm font-black text-emerald-400">+{eventScanSessionCount} Scan</span>
            </div>

            {/* Network Status Badge in Focus Mode */}
            <div className={`px-3 py-1.5 border text-xs font-mono font-bold flex items-center gap-1.5 ${
              !effectiveOnline 
                ? "bg-amber-950/80 border-amber-500/60 text-amber-300"
                : "bg-emerald-950/80 border-emerald-500/50 text-emerald-300"
            }`}>
              {!effectiveOnline ? (
                <WifiOff className="w-4 h-4 text-amber-400 animate-pulse" />
              ) : (
                <Wifi className="w-4 h-4 text-emerald-400" />
              )}
              <span>{!effectiveOnline ? "OFFLINE (LocalStorage)" : "ONLINE (Server)"}</span>
              {offlineQueue.length > 0 && (
                <span className="bg-rose-500 text-white text-[9px] px-1.5 py-0.2 rounded-full font-black animate-bounce ml-1">
                  {offlineQueue.length}
                </span>
              )}
            </div>

            {offlineQueue.length > 0 && effectiveOnline && (
              <button
                type="button"
                onClick={handleSyncOfflineData}
                disabled={isSyncingOfflineQueue}
                className="bg-emerald-500 hover:bg-emerald-400 text-black border border-emerald-300 px-3 py-1.5 text-xs font-mono font-black uppercase flex items-center gap-1.5 cursor-pointer shadow-lg"
              >
                <UploadCloud className="w-4 h-4" />
                <span>Sync ({offlineQueue.length})</span>
              </button>
            )}

            {/* Exit Focus Mode Button */}
            <button
              type="button"
              onClick={() => setIsFocusMode(false)}
              className="bg-rose-950 hover:bg-rose-800 text-rose-200 border border-rose-600/60 font-black uppercase text-xs px-4 py-2 flex items-center gap-1.5 transition-all cursor-pointer shadow-lg"
            >
              <Minimize2 className="w-4 h-4" />
              Keluar Focus Mode
            </button>
          </div>
        </div>

        {/* MAIN FOCUS MODE CONTENT: GIANT QR SCANNER & LIVE EVENT STREAM */}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
          
          {/* CENTER/LEFT: ENLARGED GIANT QR SCANNER BOX (7 Cols) */}
          <div className="lg:col-span-7 bg-[#0a0a0a] border-2 border-[#facc15]/50 rounded-xl p-6 space-y-6 shadow-2xl relative">
            
            {/* Scan Mode Switcher & Operator Banner */}
            <div className="flex flex-col sm:flex-row items-center justify-between gap-3 border-b border-[#222] pb-4">
              <div>
                <h3 className="text-base font-black text-white uppercase tracking-tight flex items-center gap-2 font-mono">
                  <Camera className="w-5 h-5 text-[#facc15]" />
                  Pemindai Massal Name Tag QR Code
                </h3>
                <p className="text-xs text-slate-400 font-mono">
                  Area Tampilan Kamera Diperbesar untuk Pemindaian Massal Cepat Jarak Jauh.
                </p>
              </div>

              {/* Check-In / Check-Out Mode Selector */}
              <div className="flex items-center gap-1 bg-[#111] p-1 border border-[#333] font-mono text-xs">
                <button
                  type="button"
                  onClick={() => setScanMode("checkIn")}
                  className={`px-3 py-1 font-bold transition-all cursor-pointer ${
                    scanMode === "checkIn"
                      ? "bg-emerald-500 text-black shadow-md font-black"
                      : "text-slate-400 hover:text-white"
                  }`}
                >
                  Check-In Event
                </button>
                <button
                  type="button"
                  onClick={() => setScanMode("checkOut")}
                  className={`px-3 py-1 font-bold transition-all cursor-pointer ${
                    scanMode === "checkOut"
                      ? "bg-blue-500 text-white shadow-md font-black"
                      : "text-slate-400 hover:text-white"
                  }`}
                >
                  Check-Out Event
                </button>
              </div>
            </div>

            {/* Quick Employee Picker for Rapid Scan Operation */}
            <div className="space-y-2 font-mono">
              <div className="flex items-center justify-between">
                <label className="text-xs font-bold text-[#facc15] uppercase tracking-wider flex items-center gap-1.5">
                  <UserCheck className="w-4 h-4 text-[#facc15]" />
                  Pilih Name Tag Pegawai (Atau Ketik NIP / Nama):
                </label>
                <span className="text-[10px] text-slate-500">Mass Scan Console</span>
              </div>

              <div className="flex flex-col sm:flex-row gap-2">
                <div className="relative flex-1">
                  <Search className="w-4 h-4 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2" />
                  <input
                    type="text"
                    placeholder="Ketik NIP / Nama / Divisi..."
                    value={focusSearchQuery}
                    onChange={e => setFocusSearchQuery(e.target.value)}
                    className="w-full bg-[#111] border border-[#333] text-[#facc15] font-bold pl-9 pr-3 py-2 text-xs outline-none focus:border-[#facc15]"
                  />
                </div>

                <select
                  value={selectedScannerEmpId}
                  onChange={e => setSelectedScannerEmpId(e.target.value)}
                  className="bg-[#111] border border-[#333] text-white font-bold px-3 py-2 text-xs focus:border-[#facc15] outline-none cursor-pointer max-w-xs"
                >
                  {filteredFocusEmployees.map(e => (
                    <option key={e.id} value={e.id}>
                      {e.name} ({e.nip}) - {e.division}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {/* ENLARGED GIANT QR SCANNER VIEWFINDER BOX */}
            <div className="relative bg-[#050505] border-4 border-dashed border-[#facc15] p-8 sm:p-10 text-center space-y-5 overflow-hidden rounded-xl shadow-2xl">
              
              {/* Laser Scan Line Animation Effect */}
              {isScanningActive && (
                <div className="absolute inset-x-0 h-1 bg-gradient-to-r from-transparent via-[#facc15] to-transparent shadow-[0_0_20px_#facc15] animate-bounce top-1/2 -translate-y-1/2 z-20" />
              )}

              {isScanningActive ? (
                <div className="py-12 space-y-4 animate-pulse">
                  <div className="w-24 h-24 border-8 border-[#facc15] border-t-transparent rounded-full animate-spin mx-auto shadow-[0_0_30px_rgba(250,204,21,0.6)]" />
                  <div className="space-y-1">
                    <p className="text-base font-black text-[#facc15] uppercase tracking-widest font-mono">
                      MEMINDAI ENKRIPSI NAME TAG QR...
                    </p>
                    <p className="text-xs text-slate-400 font-mono">Verifikasi Kunci Enkripsi NIP Pegawai & GPS Server</p>
                  </div>
                </div>
              ) : (
                <>
                  {/* GIANT QR SVG DISPLAY */}
                  <div className="w-48 h-48 sm:w-56 sm:h-56 bg-white p-3 mx-auto border-4 border-slate-900 relative shadow-2xl transition-transform hover:scale-105 duration-300">
                    <svg viewBox="0 0 100 100" className="w-full h-full text-black fill-current">
                      <path d="M0,0 H40 V40 H0 Z M10,10 V30 H30 V10 Z" />
                      <path d="M60,0 H100 V40 H60 Z M70,10 V30 H90 V10 Z" />
                      <path d="M0,60 H40 V100 H0 Z M10,70 V90 H30 V70 Z" />
                      <rect x="20" y="20" width="10" height="10" />
                      <rect x="70" y="20" width="10" height="10" />
                      <rect x="20" y="70" width="10" height="10" />
                      <rect x="45" y="10" width="10" height="30" />
                      <rect x="45" y="45" width="20" height="20" />
                      <rect x="70" y="55" width="25" height="15" />
                      <rect x="10" y="45" width="25" height="10" />
                      <rect x="55" y="80" width="35" height="15" />
                    </svg>

                    {/* Corner Target Framing Lines */}
                    <div className="absolute -top-2 -left-2 w-6 h-6 border-t-4 border-l-4 border-[#facc15]" />
                    <div className="absolute -top-2 -right-2 w-6 h-6 border-t-4 border-r-4 border-[#facc15]" />
                    <div className="absolute -bottom-2 -left-2 w-6 h-6 border-b-4 border-l-4 border-[#facc15]" />
                    <div className="absolute -bottom-2 -right-2 w-6 h-6 border-b-4 border-r-4 border-[#facc15]" />
                  </div>

                  {/* Target Employee Info Badge */}
                  {(() => {
                    const targetEmp = employees.find(e => e.id === selectedScannerEmpId) || employees[0];
                    return (
                      <div className="bg-[#111] border border-[#333] p-3 rounded-lg max-w-md mx-auto space-y-1 font-mono">
                        <div className="flex items-center justify-center gap-2">
                          <span className="text-xs text-slate-400">Pegawai Terpilih:</span>
                          <strong className="text-sm text-white">{targetEmp?.name}</strong>
                          <span className="text-xs text-[#facc15] font-bold">({targetEmp?.nip})</span>
                        </div>
                        <p className="text-[10px] text-slate-400">{targetEmp?.position} • {targetEmp?.division}</p>
                      </div>
                    );
                  })()}

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-w-md mx-auto">
                    <button
                      type="button"
                      onClick={() => handleExecuteQrScan(selectedScannerEmpId, false)}
                      className="bg-gradient-to-r from-[#facc15] to-yellow-500 hover:from-yellow-400 hover:to-amber-400 text-black font-black uppercase text-xs tracking-wider py-3.5 shadow-2xl cursor-pointer transition-all border-2 border-yellow-300 flex items-center justify-center gap-1.5"
                    >
                      <Zap className="w-4 h-4 fill-black" />
                      <span>PEMINDAIAN INSTAN (SUKSES)</span>
                    </button>

                    <button
                      type="button"
                      onClick={() => handleExecuteQrScan(selectedScannerEmpId, true)}
                      className="bg-gradient-to-r from-rose-600 to-red-600 hover:from-rose-500 hover:to-red-500 text-white font-black uppercase text-xs tracking-wider py-3.5 shadow-2xl cursor-pointer transition-all border-2 border-rose-400 flex items-center justify-center gap-1.5"
                    >
                      <AlertTriangle className="w-4 h-4 text-white" />
                      <span>SIMULASI SCAN GAGAL (ERROR)</span>
                    </button>
                  </div>
                </>
              )}
            </div>

            {/* SCAN RESULT ALERT BANNER */}
            {scanResultAlert && (
              <div className={`p-4 border-2 font-mono text-xs space-y-2 animate-fadeIn rounded-xl shadow-xl ${
                scanResultAlert.type === "error"
                  ? "bg-rose-950/90 border-rose-500 text-rose-200"
                  : scanResultAlert.type === "warning"
                  ? "bg-amber-950/80 border-amber-500 text-amber-200"
                  : "bg-emerald-950/80 border-emerald-500 text-emerald-200"
              }`}>
                <div className="flex items-center justify-between font-black text-sm border-b border-current/30 pb-2">
                  <div className="flex items-center gap-2">
                    {scanResultAlert.type === "error" ? (
                      <AlertTriangle className="w-5 h-5 text-rose-400 shrink-0 animate-bounce" />
                    ) : (
                      <CheckCircle2 className="w-5 h-5 text-emerald-400 shrink-0" />
                    )}
                    <span>{scanResultAlert.message}</span>
                  </div>
                  <span className={`text-[10px] px-2 py-0.5 rounded text-white font-mono font-bold ${
                    scanResultAlert.type === "error" ? "bg-rose-600" : "bg-black/50"
                  }`}>
                    {scanResultAlert.type === "error" ? "SCAN REJECTED" : "EVENT VERIFIED"}
                  </span>
                </div>
                {scanResultAlert.record && (
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-[11px] pt-1">
                    <div>Nama: <strong className="text-white block">{scanResultAlert.record.employeeName}</strong></div>
                    <div>NIP: <strong className="text-[#facc15] block">{scanResultAlert.record.employeeNip}</strong></div>
                    <div>Waktu: <strong className="text-white block">{scanResultAlert.record.checkInTime || scanResultAlert.record.checkOutTime}</strong></div>
                    <div>Status: <strong className="text-white block">{scanResultAlert.record.status}</strong></div>
                  </div>
                )}
              </div>
            )}

          </div>

          {/* RIGHT SIDEBAR: REAL-TIME EVENT ATTENDANCE STREAM (5 Cols) */}
          <div className="lg:col-span-5 bg-[#0a0a0a] border-2 border-[#222] rounded-xl p-5 space-y-4 shadow-xl font-mono">
            
            <div className="flex items-center justify-between border-b border-[#222] pb-3">
              <div className="flex items-center gap-2">
                <Clock className="w-5 h-5 text-[#facc15]" />
                <div>
                  <h3 className="text-xs font-black text-white uppercase tracking-wider">
                    STREAM ABSENSI HASIL SCAN REAL-TIME
                  </h3>
                  <p className="text-[10px] text-slate-400">
                    Daftar Masuk Peserta Event Terkini
                  </p>
                </div>
              </div>
              <span className="text-[10px] bg-[#facc15] text-black px-2 py-0.5 font-bold uppercase">
                {todayEventLogs.length} Terabsen
              </span>
            </div>

            {/* Stream List */}
            <div className="space-y-2.5 max-h-[580px] overflow-y-auto pr-1">
              {todayEventLogs.length === 0 ? (
                <div className="text-center py-12 text-slate-500 text-xs italic">
                  Belum ada log pemindaian di sesi event ini. Gunakan scanner untuk memindai Name Tag.
                </div>
              ) : (
                todayEventLogs.map(log => (
                  <div key={log.id} className="bg-[#050505] border border-[#222] hover:border-[#facc15]/50 p-3 rounded-lg flex items-center justify-between gap-3 transition-colors">
                    <div className="flex items-center gap-3 min-w-0">
                      <div className="w-10 h-10 bg-[#151515] border border-[#333] overflow-hidden shrink-0 flex items-center justify-center">
                        {log.photoUrl ? (
                          <img src={log.photoUrl} alt={log.employeeName} className="w-full h-full object-cover" />
                        ) : (
                          <User className="w-5 h-5 text-slate-500" />
                        )}
                      </div>
                      <div className="min-w-0 space-y-0.5">
                        <h4 className="text-xs font-bold text-white truncate">{log.employeeName}</h4>
                        <span className="text-[10px] text-slate-400 block truncate">{log.employeePosition}</span>
                        <span className="text-[9px] text-[#facc15] block font-mono font-bold">{log.employeeNip}</span>
                      </div>
                    </div>

                    <div className="text-right shrink-0 space-y-1">
                      <span className="text-xs font-bold text-emerald-400 block">
                        {log.checkInTime || log.checkOutTime}
                      </span>
                      <span className={`text-[9px] font-bold px-2 py-0.5 border inline-block ${
                        log.status === "Tepat Waktu" ? "bg-emerald-500/10 text-emerald-300 border-emerald-500/30" : "bg-amber-500/10 text-amber-300 border-amber-500/30"
                      }`}>
                        {log.status}
                      </span>
                    </div>
                  </div>
                ))
              )}
            </div>

            {/* Quick Action Footer */}
            <div className="pt-2 border-t border-[#222] flex items-center justify-between text-[10px] text-slate-400">
              <span>System: HRD Kiosk Event v2.4</span>
              <button
                type="button"
                onClick={() => setIsExportModalOpen(true)}
                className="text-[#facc15] hover:underline cursor-pointer font-bold uppercase"
              >
                Unduh Rekap Event
              </button>
            </div>

          </div>

        </div>

      </div>
    );
  }

  return (
    <div className="space-y-6 font-sans text-slate-100 animate-fadeIn">
      
      {/* Top Banner Header */}
      <div className="bg-[#0a0a0a] border border-[#222] p-5 flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
        <div className="space-y-1">
          <div className="flex items-center gap-2">
            <span className="bg-[#facc15] text-black text-[10px] font-black px-2 py-0.5 uppercase tracking-wider font-mono">
              MODUL HRD ABSENSI DIGITAL
            </span>
            <span className="text-xs text-slate-400 font-mono">Real-time QR Tag Attendance System</span>
          </div>
          <h2 className="text-lg font-black text-white uppercase tracking-tight flex items-center gap-2">
            <QrCode className="w-5 h-5 text-[#facc15]" />
            Absensi Pegawai & Scan Name Tag QR Code
          </h2>
          <p className="text-xs text-slate-400 font-mono">
            Catat kehadiran pegawai secara presisi menggunakan scanner QR Name Tag, verifikasi lokasi GPS, serta otomatisasi sinkronisasi potongan absensi ke Manajer Payroll.
          </p>
        </div>

        <div className="flex flex-wrap items-center gap-2.5">
          <button
            type="button"
            onClick={() => {
              if (!selectedScannerEmpId) setSelectedScannerEmpId(employees[0]?.id || "");
              setIsFocusMode(true);
            }}
            className="bg-gradient-to-r from-amber-500 to-yellow-400 hover:from-amber-400 hover:to-yellow-300 text-black font-black uppercase tracking-wider text-xs px-4 py-2 flex items-center gap-2 shadow-xl transition-all cursor-pointer border border-yellow-300"
            title="Aktifkan Focus Mode Pemindaian Massal untuk Event Perusahaan"
          >
            <Zap className="w-4 h-4 text-black fill-black" />
            Focus Mode Scan Event
          </button>
          <button
            type="button"
            onClick={() => setIsExportModalOpen(true)}
            className="bg-[#111] hover:bg-[#222] text-[#facc15] border border-[#333] hover:border-[#facc15] font-black uppercase tracking-wider text-xs px-4 py-2 flex items-center gap-2 shadow-lg transition-all cursor-pointer"
            title="Konversi data log absensi ke format PDF / CSV untuk Administrasi Payroll"
          >
            <Download className="w-4 h-4 text-[#facc15]" />
            Unduh Laporan
          </button>
          <button
            type="button"
            onClick={() => {
              setSelectedScannerEmpId(employees[0]?.id || "");
              setIsScanModalOpen(true);
            }}
            className="bg-[#facc15] hover:bg-yellow-500 text-black font-black uppercase tracking-wider text-xs px-4 py-2 flex items-center gap-2 shadow-lg transition-all cursor-pointer"
          >
            <Camera className="w-4 h-4 text-black" />
            Scanner QR
          </button>
        </div>
      </div>

      {/* OFFLINE-TO-ONLINE SYNC CONTROL BANNER */}
      <div className={`p-4 border-2 rounded-xl flex flex-col md:flex-row items-start md:items-center justify-between gap-4 shadow-xl font-mono text-xs transition-all ${
        !effectiveOnline
          ? "bg-amber-950/40 border-amber-500/60 text-amber-200"
          : offlineQueue.length > 0
          ? "bg-blue-950/40 border-blue-500/60 text-blue-200"
          : "bg-emerald-950/30 border-emerald-500/40 text-emerald-200"
      }`}>
        <div className="flex items-center gap-3">
          <div className={`p-2.5 rounded-lg border shrink-0 ${
            !effectiveOnline 
              ? "bg-amber-500/20 border-amber-500/50 text-amber-300 animate-pulse" 
              : offlineQueue.length > 0
              ? "bg-blue-500/20 border-blue-500/50 text-blue-300"
              : "bg-emerald-500/20 border-emerald-500/50 text-emerald-300"
          }`}>
            {!effectiveOnline ? (
              <WifiOff className="w-5 h-5 text-amber-400" />
            ) : (
              <Wifi className="w-5 h-5 text-emerald-400" />
            )}
          </div>

          <div className="space-y-1">
            <div className="flex flex-wrap items-center gap-2">
              <span className={`px-2 py-0.5 text-[10px] font-black uppercase tracking-wider rounded ${
                !effectiveOnline ? "bg-amber-500 text-black" : "bg-emerald-500 text-black"
              }`}>
                {effectiveOnline ? "ONLINE • SERVER TERHUBUNG" : "OFFLINE • LOCALSTORAGE MODE"}
              </span>

              {offlineQueue.length > 0 ? (
                <span className="bg-rose-500/20 text-rose-300 border border-rose-500/50 px-2 py-0.5 text-[10px] font-bold animate-pulse">
                  ⚠️ {offlineQueue.length} Data Pending Sync di LocalStorage
                </span>
              ) : (
                <span className="bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 px-2 py-0.5 text-[10px]">
                  ✓ Semua Data Absensi Tersinkronisasi ke Server
                </span>
              )}
            </div>

            <p className="text-xs text-slate-300">
              {!effectiveOnline
                ? "Pemindaian saat ini tersimpan otomatis di LocalStorage (Offline Queue). Data akan dikirim otomatis saat koneksi kembali online."
                : offlineQueue.length > 0
                ? `Terdapat ${offlineQueue.length} record absensi offline yang tersimpan di LocalStorage. Klik tombol di kanan untuk mengunggah ke server.`
                : "Koneksi jaringan aktif & stabil. Hasil pemindaian QR Name Tag langsung terverifikasi dan tersimpan ke database server secara real-time."}
            </p>

            {lastSyncTime && (
              <span className="text-[10px] text-slate-400 block">
                SINKRONISASI TERAKHIR: <strong className="text-white">{lastSyncTime}</strong>
              </span>
            )}
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-2.5 shrink-0 w-full md:w-auto justify-end">
          {/* Toggle Simulate Offline Mode */}
          <button
            type="button"
            onClick={() => setIsSimulatedOffline(!isSimulatedOffline)}
            className={`px-3 py-1.5 border text-[11px] font-bold font-mono transition-all cursor-pointer flex items-center gap-1.5 ${
              isSimulatedOffline
                ? "bg-amber-500 text-black border-amber-400 shadow-lg"
                : "bg-[#111] hover:bg-[#222] text-slate-300 border-[#333]"
            }`}
            title="Aktifkan/Matikan Simulasi Offline untuk menguji fitur simpan LocalStorage"
          >
            <HardDrive className="w-3.5 h-3.5" />
            <span>Simulasi Offline: {isSimulatedOffline ? "ON" : "OFF"}</span>
          </button>

          {/* Sync Now Button */}
          <button
            type="button"
            onClick={handleSyncOfflineData}
            disabled={isSyncingOfflineQueue || offlineQueue.length === 0}
            className={`px-4 py-2 font-black uppercase text-xs tracking-wider transition-all cursor-pointer flex items-center gap-2 border shadow-lg ${
              isSyncingOfflineQueue
                ? "bg-blue-600 text-white border-blue-400 animate-pulse cursor-wait"
                : offlineQueue.length > 0 && effectiveOnline
                ? "bg-emerald-500 hover:bg-emerald-400 text-black border-emerald-300 shadow-emerald-500/20"
                : "bg-[#151515] text-slate-500 border-[#222] cursor-not-allowed"
            }`}
          >
            <UploadCloud className={`w-4 h-4 ${isSyncingOfflineQueue ? "animate-bounce" : ""}`} />
            <span>
              {isSyncingOfflineQueue
                ? "MENGIRIM KE SERVER..."
                : `SINKRONKAN SEKARANG (${offlineQueue.length})`}
            </span>
          </button>
        </div>
      </div>

      {/* SYNC NOTIFICATION TOAST */}
      {syncToastMessage && (
        <div className="bg-blue-950/90 border-2 border-blue-400 text-blue-100 p-3.5 font-mono text-xs rounded-xl flex items-center justify-between gap-3 animate-fadeIn shadow-2xl">
          <div className="flex items-center gap-2">
            <Database className="w-4 h-4 text-blue-400 shrink-0 animate-spin" />
            <span className="font-bold">{syncToastMessage}</span>
          </div>
          <button
            type="button"
            onClick={() => setSyncToastMessage(null)}
            className="text-slate-400 hover:text-white text-xs px-2 py-0.5 bg-black/40 border border-slate-700"
          >
            Tutup
          </button>
        </div>
      )}

      {/* Summary KPI Cards */}
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
        <div className="bg-[#0a0a0a] border border-[#222] p-3.5 space-y-1">
          <span className="text-[10px] font-mono font-bold text-slate-500 uppercase block">Total Pegawai</span>
          <div className="text-xl font-black text-white font-mono">{stats.total}</div>
          <span className="text-[9px] text-slate-400 font-mono block">Pegawai Terdaftar</span>
        </div>

        <div className="bg-[#0a0a0a] border border-[#222] p-3.5 space-y-1">
          <span className="text-[10px] font-mono font-bold text-slate-500 uppercase block">Hadir Hari Ini</span>
          <div className="text-xl font-black text-emerald-400 font-mono">{stats.mejelas}</div>
          <span className="text-[9px] text-emerald-500 font-mono block">Check-in Terverifikasi</span>
        </div>

        <div className="bg-[#0a0a0a] border border-[#222] p-3.5 space-y-1">
          <span className="text-[10px] font-mono font-bold text-slate-500 uppercase block">Tepat Waktu</span>
          <div className="text-xl font-black text-cyan-400 font-mono">{stats.tepatWaktu}</div>
          <span className="text-[9px] text-cyan-500 font-mono block">&lt; 08:30 WIB</span>
        </div>

        <div className="bg-[#0a0a0a] border border-[#222] p-3.5 space-y-1">
          <span className="text-[10px] font-mono font-bold text-slate-500 uppercase block">Terlambat</span>
          <div className="text-xl font-black text-amber-400 font-mono">{stats.terlambat}</div>
          <span className="text-[9px] text-amber-500 font-mono block">Dipotong di Payroll</span>
        </div>

        <div className="bg-[#0a0a0a] border border-[#222] p-3.5 space-y-1">
          <span className="text-[10px] font-mono font-bold text-slate-500 uppercase block">Izin / Dinas</span>
          <div className="text-xl font-black text-blue-400 font-mono">{stats.izin}</div>
          <span className="text-[9px] text-blue-500 font-mono block">Tercatat di HRD</span>
        </div>

        <div className="bg-[#0a0a0a] border border-[#222] p-3.5 space-y-1">
          <span className="text-[10px] font-mono font-bold text-slate-500 uppercase block">Tanpa Keterangan</span>
          <div className="text-xl font-black text-rose-500 font-mono">{stats.alpa}</div>
          <span className="text-[9px] text-rose-400 font-mono block">Potongan Gaji Pokok</span>
        </div>
      </div>

      {/* Main Grid: Name Tag Badges Gallery & Attendance History Table */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        
        {/* Left Column: List Pegawai & Visual Name Tag Cards */}
        <div className="bg-[#0a0a0a] border border-[#222] p-4 space-y-4">
          <div className="flex items-center justify-between border-b border-[#222] pb-2">
            <h3 className="text-xs font-black text-[#facc15] uppercase tracking-wider flex items-center gap-2 font-mono">
              <UserCheck className="w-4 h-4 text-[#facc15]" />
              Kartu Name Tag Pegawai ({employees.length})
            </h3>
            <span className="text-[10px] text-slate-500 font-mono">Klik untuk Pratinjau QR Badge</span>
          </div>

          <p className="text-[11px] text-slate-400 font-mono">
            Setiap pegawai memiliki Name Tag resmi yang dilengkapi QR Code NIP terenkripsi untuk dipindai pada mesin absensi portal kantor.
          </p>

          <div className="space-y-2 max-h-[520px] overflow-y-auto pr-1">
            {employees.map(emp => (
              <div 
                key={emp.id}
                className="bg-[#050505] border border-[#222] hover:border-[#facc15]/50 p-3 transition-colors flex items-center justify-between gap-3 group"
              >
                <div className="flex items-center gap-3">
                  <div className="w-9 h-9 bg-[#151515] border border-[#333] overflow-hidden shrink-0 flex items-center justify-center">
                    {emp.photoUrl ? (
                      <img src={emp.photoUrl} alt={emp.name} className="w-full h-full object-cover" />
                    ) : (
                      <User className="w-5 h-5 text-slate-500" />
                    )}
                  </div>
                  <div className="space-y-0.5">
                    <h4 className="text-xs font-bold text-white group-hover:text-[#facc15] transition-colors">{emp.name}</h4>
                    <span className="text-[10px] text-slate-400 font-mono block">{emp.position}</span>
                    <span className="text-[9px] text-[#facc15] font-mono font-bold">{emp.nip}</span>
                  </div>
                </div>

                <div className="flex items-center gap-1.5 shrink-0">
                  <button
                    type="button"
                    onClick={() => setSelectedBadgeEmp(emp)}
                    className="p-1.5 bg-[#111] hover:bg-[#222] text-slate-300 border border-[#333] cursor-pointer"
                    title="Pratinjau Name Tag QR Pegawai"
                  >
                    <QrCode className="w-4 h-4 text-[#facc15]" />
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      setSelectedScannerEmpId(emp.id);
                      setIsScanModalOpen(true);
                    }}
                    className="p-1.5 bg-[#facc15] hover:bg-yellow-500 text-black border border-yellow-400 font-black cursor-pointer text-[10px] uppercase px-2"
                    title="Scan Absensi Pegawai Ini"
                  >
                    Scan
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Right Column: Attendance Records Table & Payroll Sync Tools */}
        <div className="lg:col-span-2 space-y-4">
          
          {/* Table Toolbar */}
          <div className="bg-[#0a0a0a] border border-[#222] p-4 flex flex-col sm:flex-row items-center justify-between gap-3">
            <div className="relative w-full sm:w-72">
              <Search className="w-3.5 h-3.5 text-slate-500 absolute left-3 top-1/2 -translate-y-1/2" />
              <input
                type="text"
                placeholder="Cari nama, NIP, divisi..."
                value={searchQuery}
                onChange={e => setSearchQuery(e.target.value)}
                className="w-full bg-[#050505] border border-[#222] text-white placeholder-slate-600 pl-8 pr-3 py-1.5 text-xs font-mono outline-none focus:border-[#facc15]"
              />
            </div>

            <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto">
              <input
                type="date"
                value={filterDate}
                onChange={e => setFilterDate(e.target.value)}
                className="bg-[#050505] border border-[#222] text-white text-xs px-2.5 py-1.5 font-mono outline-none focus:border-[#facc15]"
              />

              <select
                value={filterStatus}
                onChange={e => setFilterStatus(e.target.value)}
                className="bg-[#050505] border border-[#222] text-white text-xs px-2.5 py-1.5 font-mono outline-none focus:border-[#facc15]"
              >
                <option value="All">Semua Status</option>
                <option value="Pending Sync">⚡ Pending Sync (Offline Queue)</option>
                <option value="Tepat Waktu">Tepat Waktu</option>
                <option value="Terlambat">Terlambat</option>
                <option value="Izin / Sakit">Izin / Sakit</option>
                <option value="Dinas Luar">Dinas Luar</option>
                <option value="Absen / Alpa">Absen / Alpa</option>
              </select>
            </div>
          </div>

          {/* Attendance Log Table */}
          <div className="bg-[#0a0a0a] border border-[#222] overflow-hidden">
            <div className="p-3.5 bg-[#050505] border-b border-[#222] flex flex-wrap items-center justify-between gap-2">
              <span className="text-xs font-black text-slate-300 uppercase tracking-wider font-mono flex items-center gap-2">
                <Clock className="w-4 h-4 text-[#facc15]" />
                Log Absensi Harian ({filteredLogs.length} Entri Ditemukan)
              </span>
              
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={() => generateAttendancePDF(filteredLogs, filterDate, stats)}
                  className="bg-[#111] hover:bg-[#222] text-[#facc15] border border-[#333] hover:border-[#facc15] px-2.5 py-1 text-[10px] font-bold uppercase transition-colors cursor-pointer flex items-center gap-1.5 font-mono"
                  title="Unduh Laporan Absensi saat ini ke format PDF"
                >
                  <FileCheck className="w-3.5 h-3.5 text-[#facc15]" />
                  Unduh PDF
                </button>
                <button
                  type="button"
                  onClick={() => generateAttendanceCSV(filteredLogs, filterDate)}
                  className="bg-[#111] hover:bg-[#222] text-emerald-400 border border-[#333] hover:border-emerald-500 px-2.5 py-1 text-[10px] font-bold uppercase transition-colors cursor-pointer flex items-center gap-1.5 font-mono"
                  title="Unduh Laporan Absensi saat ini ke format CSV (Excel)"
                >
                  <FileSpreadsheet className="w-3.5 h-3.5 text-emerald-400" />
                  Unduh CSV
                </button>
                <button
                  type="button"
                  onClick={() => setIsExportModalOpen(true)}
                  className="bg-[#facc15] hover:bg-yellow-500 text-black px-2.5 py-1 text-[10px] font-black uppercase transition-colors cursor-pointer flex items-center gap-1 font-mono"
                  title="Opsi Lengkap Ekspor Laporan Absensi"
                >
                  <Download className="w-3.5 h-3.5 text-black" />
                  Opsi Laporan
                </button>
              </div>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full text-left text-xs font-mono">
                <thead className="bg-[#111] text-slate-400 text-[10px] uppercase border-b border-[#222]">
                  <tr>
                    <th className="p-3">Pegawai & NIP</th>
                    <th className="p-3">Waktu Check In</th>
                    <th className="p-3">Waktu Check Out</th>
                    <th className="p-3">Status Absensi</th>
                    <th className="p-3">Status Sync Server</th>
                    <th className="p-3">Lokasi / Verification</th>
                    <th className="p-3 text-right">Aksi Sync Payroll</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-[#1a1a1a]">
                  {filteredLogs.length > 0 ? (
                    filteredLogs.map(log => (
                      <tr key={log.id} className="hover:bg-[#0f0f0f] transition-colors">
                        <td className="p-3 space-y-0.5">
                          <span className="font-bold text-white block">{log.employeeName}</span>
                          <span className="text-[10px] text-slate-400 block">{log.employeePosition}</span>
                          <span className="text-[9px] text-[#facc15] block font-mono">{log.employeeNip}</span>
                        </td>
                        <td className="p-3">
                          {log.checkInTime ? (
                            <span className="font-bold text-emerald-400 bg-emerald-500/10 px-2 py-0.5 border border-emerald-500/30">
                              {log.checkInTime}
                            </span>
                          ) : (
                            <span className="text-slate-600 italic">-</span>
                          )}
                        </td>
                        <td className="p-3">
                          {log.checkOutTime ? (
                            <span className="font-bold text-blue-400 bg-blue-500/10 px-2 py-0.5 border border-blue-500/30">
                              {log.checkOutTime}
                            </span>
                          ) : (
                            <span className="text-slate-600 italic">Belum Out</span>
                          )}
                        </td>
                        <td className="p-3">
                          <span className={`px-2 py-0.5 font-bold text-[10px] border inline-block ${
                            log.status === "Tepat Waktu" ? "bg-emerald-500/10 text-emerald-300 border-emerald-500/30" :
                            log.status === "Terlambat" ? "bg-amber-500/10 text-amber-300 border-amber-500/30" :
                            log.status === "Absen / Alpa" ? "bg-rose-500/10 text-rose-400 border-rose-500/30" :
                            "bg-blue-500/10 text-blue-300 border-blue-500/30"
                          }`}>
                            {log.status} {log.lateMinutes > 0 ? `(+${log.lateMinutes}m)` : ''}
                          </span>
                        </td>
                        <td className="p-3">
                          {log.syncedToServer === false ? (
                            <span className="px-2 py-0.5 text-[9px] font-bold bg-amber-500/20 text-amber-300 border border-amber-500/50 flex items-center gap-1 w-max animate-pulse" title="Tersimpan di LocalStorage - Menunggu koneksi online untuk sync">
                              <HardDrive className="w-3 h-3 text-amber-400" /> LOCALSTORAGE (PENDING)
                            </span>
                          ) : (
                            <div className="space-y-0.5">
                              <span className="px-2 py-0.5 text-[9px] font-bold bg-emerald-500/10 text-emerald-300 border border-emerald-500/30 flex items-center gap-1 w-max">
                                <Server className="w-3 h-3 text-emerald-400" /> ONLINE SERVER
                              </span>
                              {log.offlineSyncedAt && (
                                <span className="text-[8px] text-slate-500 block font-mono">Synced {log.offlineSyncedAt}</span>
                              )}
                            </div>
                          )}
                        </td>
                        <td className="p-3 text-[10px] text-slate-400 space-y-0.5">
                          <div className="flex items-center gap-1 text-slate-300">
                            <MapPin className="w-3 h-3 text-[#facc15] shrink-0" />
                            <span className="truncate max-w-[150px]">{log.locationName}</span>
                          </div>
                          <span className="text-[9px] text-slate-500 block truncate">{log.verifiedByScanner}</span>
                        </td>
                        <td className="p-3 text-right">
                          <button
                            type="button"
                            onClick={() => handleSyncAttendanceToPayroll(log.employeeId)}
                            className="bg-[#111] hover:bg-[#222] text-[#facc15] border border-[#333] hover:border-[#facc15] px-2.5 py-1 text-[10px] font-bold uppercase transition-colors cursor-pointer"
                            title="Sinkronkan potongan keterlambatan/alpa pegawai ke Manajer Payroll"
                          >
                            Sync Payroll
                          </button>
                        </td>
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td colSpan={7} className="text-center py-12 text-slate-500 font-mono italic">
                        Tidak ada log absensi yang cocok untuk kriteria pencarian / tanggal ini.
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>

        </div>
      </div>

      {/* SCANNER MODAL DIALOG */}
      {isScanModalOpen && (
        <div className="fixed inset-0 z-50 bg-black/80 backdrop-blur-sm flex items-center justify-center p-4 animate-fadeIn">
          <div className="bg-[#0a0a0a] border-2 border-[#facc15]/40 text-slate-100 w-full max-w-xl p-6 space-y-6 shadow-2xl relative">
            
            {/* Modal Header */}
            <div className="flex items-start justify-between border-b border-[#222] pb-4">
              <div className="flex items-center gap-3">
                <div className="p-2.5 bg-[#facc15]/10 border border-[#facc15]/30 text-[#facc15]">
                  <Camera className="w-6 h-6 text-[#facc15]" />
                </div>
                <div>
                  <h3 className="text-base font-black text-white uppercase tracking-tight">
                    SIMULATOR SCANNER NAME TAG QR CODE
                  </h3>
                  <p className="text-xs text-slate-400 font-mono">
                    Pindai QR Code Name Tag Pegawai untuk Pencatatan Kehadiran
                  </p>
                </div>
              </div>
              <button 
                type="button"
                onClick={() => setIsScanModalOpen(false)}
                className="text-slate-400 hover:text-white bg-[#111] p-1.5 border border-[#333] cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Quick Focus Mode Switcher Banner */}
            <div className="bg-[#111] border border-[#facc15]/40 p-3 rounded flex items-center justify-between gap-2 font-mono">
              <div className="flex items-center gap-2">
                <Zap className="w-4 h-4 text-[#facc15] fill-[#facc15]" />
                <span className="text-xs font-bold text-white">Butuh Pemindaian Cepat Jarak Jauh?</span>
              </div>
              <button
                type="button"
                onClick={() => {
                  setIsScanModalOpen(false);
                  setIsFocusMode(true);
                }}
                className="bg-[#facc15] hover:bg-yellow-400 text-black px-3 py-1 text-[11px] font-black uppercase cursor-pointer transition-colors shrink-0"
              >
                Buka Focus Mode Massal
              </button>
            </div>

            {/* Offline/Online Network Indicator Badge inside Modal */}
            <div className={`p-2.5 border rounded flex items-center justify-between font-mono text-xs ${
              !effectiveOnline 
                ? "bg-amber-950/60 border-amber-500/60 text-amber-300" 
                : "bg-emerald-950/50 border-emerald-500/40 text-emerald-300"
            }`}>
              <div className="flex items-center gap-2">
                {!effectiveOnline ? (
                  <WifiOff className="w-4 h-4 text-amber-400 animate-pulse" />
                ) : (
                  <Wifi className="w-4 h-4 text-emerald-400" />
                )}
                <span className="font-bold">
                  {!effectiveOnline 
                    ? "MODE OFFLINE: Hasil scan akan disimpan di LocalStorage Queue" 
                    : "MODE ONLINE: Hasil scan langsung dikirim ke Server Database"}
                </span>
              </div>
              {offlineQueue.length > 0 && (
                <span className="bg-rose-500/20 text-rose-300 border border-rose-500/50 px-2 py-0.5 text-[10px] font-bold">
                  {offlineQueue.length} Pending
                </span>
              )}
            </div>

            {/* Mode Selector & Employee Target Picker */}
            <div className="space-y-4 font-mono text-xs">
              <div className="grid grid-cols-2 gap-3">
                <button
                  type="button"
                  onClick={() => setScanMode("checkIn")}
                  className={`p-3 font-bold border text-center transition-all cursor-pointer ${
                    scanMode === "checkIn"
                      ? "bg-emerald-500/20 border-emerald-500 text-emerald-300"
                      : "bg-[#111] border-[#222] text-slate-400"
                  }`}
                >
                  <span className="block text-sm font-black uppercase">Absen Masuk (Check-In)</span>
                  <span className="text-[10px] text-slate-400 block mt-0.5">Cut-off Terlambat: 08:30 WIB</span>
                </button>

                <button
                  type="button"
                  onClick={() => setScanMode("checkOut")}
                  className={`p-3 font-bold border text-center transition-all cursor-pointer ${
                    scanMode === "checkOut"
                      ? "bg-blue-500/20 border-blue-500 text-blue-300"
                      : "bg-[#111] border-[#222] text-slate-400"
                  }`}
                >
                  <span className="block text-sm font-black uppercase">Absen Pulang (Check-Out)</span>
                  <span className="text-[10px] text-slate-400 block mt-0.5">Waktu Operasional Kerja Selesai</span>
                </button>
              </div>

              <div>
                <label className="block text-slate-400 font-bold uppercase mb-1">
                  Pilih Pegawai Pemilik Name Tag QR:
                </label>
                <select
                  value={selectedScannerEmpId}
                  onChange={e => setSelectedScannerEmpId(e.target.value)}
                  className="w-full bg-[#111] border border-[#222] text-[#facc15] font-bold px-3 py-2 text-xs focus:border-[#facc15] outline-none cursor-pointer"
                >
                  {employees.map(e => (
                    <option key={e.id} value={e.id}>
                      {e.name} ({e.nip}) - {e.position}
                    </option>
                  ))}
                </select>
              </div>

              {/* View Finder Camera Simulation Frame */}
              <div className="relative bg-[#050505] border-2 border-dashed border-[#facc15]/60 p-8 text-center space-y-4 overflow-hidden rounded-none">
                {isScanningActive ? (
                  <div className="py-8 space-y-3 animate-pulse">
                    <div className="w-16 h-16 border-4 border-[#facc15] border-t-transparent rounded-full animate-spin mx-auto" />
                    <p className="text-xs font-bold text-[#facc15] uppercase tracking-wider">
                      Memindai Enkripsi QR Name Tag Pegawai...
                    </p>
                  </div>
                ) : (
                  <>
                    <div className="w-24 h-24 bg-white p-2 mx-auto border-2 border-slate-700 relative shadow-xl">
                      {/* Simple SVG QR Pattern Mockup */}
                      <svg viewBox="0 0 100 100" className="w-full h-full text-black fill-current">
                        <path d="M0,0 H40 V40 H0 Z M10,10 V30 H30 V10 Z" />
                        <path d="M60,0 H100 V40 H60 Z M70,10 V30 H90 V10 Z" />
                        <path d="M0,60 H40 V100 H0 Z M10,70 V90 H30 V70 Z" />
                        <rect x="20" y="20" width="10" height="10" />
                        <rect x="70" y="20" width="10" height="10" />
                        <rect x="20" y="70" width="10" height="10" />
                        <rect x="45" y="10" width="10" height="30" />
                        <rect x="45" y="45" width="20" height="20" />
                        <rect x="70" y="55" width="25" height="15" />
                        <rect x="10" y="45" width="25" height="10" />
                        <rect x="55" y="80" width="35" height="15" />
                      </svg>
                      {/* Corner Target Markers */}
                      <div className="absolute -top-1 -left-1 w-3 h-3 border-t-2 border-l-2 border-[#facc15]" />
                      <div className="absolute -top-1 -right-1 w-3 h-3 border-t-2 border-r-2 border-[#facc15]" />
                      <div className="absolute -bottom-1 -left-1 w-3 h-3 border-b-2 border-l-2 border-[#facc15]" />
                      <div className="absolute -bottom-1 -right-1 w-3 h-3 border-b-2 border-r-2 border-[#facc15]" />
                    </div>

                    <div className="space-y-1">
                      <p className="text-xs font-bold text-white uppercase">Arahkan Kamera ke Name Tag QR Pegawai</p>
                      <p className="text-[10px] text-slate-400 font-mono">
                        Data Terbaca: <code className="text-[#facc15]">MEDIAN-TAG:{selectedScannerEmpId || "EMP-ID"}</code>
                      </p>
                    </div>

                    <div className="flex flex-wrap items-center justify-between gap-2 pt-1 border-t border-[#222]">
                      <div className="flex items-center gap-1">
                        <button
                          type="button"
                          onClick={() => setSoundEnabled(!soundEnabled)}
                          className="text-[10px] text-slate-400 hover:text-white flex items-center gap-1 font-mono"
                        >
                          {soundEnabled ? <Volume2 className="w-3.5 h-3.5 text-emerald-400" /> : <VolumeX className="w-3.5 h-3.5" />}
                          <span>Audio Beep: {soundEnabled ? "ON" : "OFF"}</span>
                        </button>
                        {soundEnabled && (
                          <div className="flex items-center gap-1 ml-2">
                            <button
                              type="button"
                              onClick={() => playScanBeep("success")}
                              className="px-1.5 py-0.5 bg-emerald-500/20 text-emerald-300 text-[9px] font-mono hover:bg-emerald-500/40"
                              title="Uji Beep Sukses"
                            >
                              🔊 Sukses
                            </button>
                            <button
                              type="button"
                              onClick={() => playScanBeep("warning")}
                              className="px-1.5 py-0.5 bg-amber-500/20 text-amber-300 text-[9px] font-mono hover:bg-amber-500/40"
                              title="Uji Beep Terlambat"
                            >
                              🔔 Warning
                            </button>
                            <button
                              type="button"
                              onClick={() => playScanBeep("error")}
                              className="px-1.5 py-0.5 bg-rose-500/20 text-rose-300 text-[9px] font-mono hover:bg-rose-500/40"
                              title="Uji Beep Error"
                            >
                              🚨 Error
                            </button>
                          </div>
                        )}
                      </div>
                    </div>

                    <div className="flex flex-col sm:flex-row gap-2 pt-2">
                      <button
                        type="button"
                        onClick={() => handleExecuteQrScan(selectedScannerEmpId, false)}
                        className="flex-1 bg-[#facc15] hover:bg-yellow-500 text-black font-black uppercase text-xs px-4 py-2.5 shadow-lg cursor-pointer transition-all flex items-center justify-center gap-1"
                      >
                        ⚡ SCAN ABSENSI SUKSES
                      </button>

                      <button
                        type="button"
                        onClick={() => handleExecuteQrScan(selectedScannerEmpId, true)}
                        className="bg-rose-950 hover:bg-rose-800 border border-rose-600/60 text-rose-200 font-bold uppercase text-xs px-4 py-2.5 cursor-pointer transition-all flex items-center justify-center gap-1"
                      >
                        <AlertTriangle className="w-3.5 h-3.5 text-rose-400" />
                        SIMULASI SCAN GAGAL
                      </button>
                    </div>
                  </>
                )}
              </div>

              {/* Scan Result Notification */}
              {scanResultAlert && (
                <div className={`p-4 border font-mono text-xs space-y-2 animate-fadeIn ${
                  scanResultAlert.type === "error"
                    ? "bg-rose-500/15 border-rose-500/50 text-rose-200"
                    : scanResultAlert.type === "warning"
                    ? "bg-amber-500/10 border-amber-500/40 text-amber-300"
                    : "bg-emerald-500/10 border-emerald-500/40 text-emerald-300"
                }`}>
                  <div className="flex items-center gap-2 font-bold text-sm">
                    {scanResultAlert.type === "error" ? (
                      <AlertTriangle className="w-5 h-5 text-rose-400 shrink-0" />
                    ) : (
                      <CheckCircle2 className="w-5 h-5 text-emerald-400 shrink-0" />
                    )}
                    <span>{scanResultAlert.message}</span>
                  </div>
                  {scanResultAlert.record && (
                    <div className="text-[11px] text-slate-300 space-y-0.5 border-t border-current/20 pt-2">
                      <div>Nama Pegawai: <strong className="text-white">{scanResultAlert.record.employeeName}</strong> ({scanResultAlert.record.employeeNip})</div>
                      <div>Status: <strong className="text-white">{scanResultAlert.record.status}</strong></div>
                      <div>Waktu Scan: <strong className="text-white">{scanResultAlert.record.checkInTime || scanResultAlert.record.checkOutTime}</strong></div>
                      <div>Lokasi: <strong className="text-white">{scanResultAlert.record.locationName}</strong></div>
                    </div>
                  )}
                </div>
              )}

            </div>
          </div>
        </div>
      )}

      {/* NAME TAG PREVIEW & PRINT MODAL */}
      {selectedBadgeEmp && (
        <div className="fixed inset-0 z-50 bg-black/85 backdrop-blur-sm flex items-center justify-center p-4 animate-fadeIn">
          <div className="bg-[#0a0a0a] border border-[#333] text-slate-100 w-full max-w-sm p-6 space-y-6 shadow-2xl relative font-sans">
            
            <div className="flex items-center justify-between border-b border-[#222] pb-3">
              <span className="text-xs font-black text-[#facc15] uppercase tracking-wider font-mono">
                Official Employee ID Badge
              </span>
              <button 
                type="button"
                onClick={() => setSelectedBadgeEmp(null)}
                className="text-slate-400 hover:text-white bg-[#111] p-1 border border-[#333] cursor-pointer"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            {/* Printable ID Card Badge Card (Styling) */}
            <div className="bg-[#ffffff] text-slate-900 border-4 border-slate-900 p-5 space-y-4 shadow-2xl relative font-sans">
              
              {/* Badge Top Header */}
              <div className="bg-slate-900 text-amber-400 p-2.5 text-center -mx-5 -mt-5 space-y-0.5">
                <div className="text-[9px] font-black uppercase tracking-widest text-slate-300">
                  PT MEDIAN MULTI DAYA
                </div>
                <div className="text-xs font-black tracking-tight text-white uppercase">
                  KARTU IDENTITAS PEGAWAI
                </div>
              </div>

              {/* Photo & QR Section */}
              <div className="flex items-center justify-between gap-3 pt-2">
                <div className="w-20 h-24 bg-slate-200 border-2 border-slate-900 overflow-hidden shrink-0 flex items-center justify-center">
                  {selectedBadgeEmp.photoUrl ? (
                    <img src={selectedBadgeEmp.photoUrl} alt={selectedBadgeEmp.name} className="w-full h-full object-cover" />
                  ) : (
                    <User className="w-10 h-10 text-slate-500" />
                  )}
                </div>

                <div className="space-y-1 text-right flex-1">
                  <span className="text-[9px] text-slate-500 uppercase font-bold block">SCAN ABSENSI QR</span>
                  <div className="w-20 h-20 bg-white p-1 border-2 border-slate-900 ml-auto shadow-sm">
                    <svg viewBox="0 0 100 100" className="w-full h-full text-slate-900 fill-current">
                      <path d="M0,0 H40 V40 H0 Z M10,10 V30 H30 V10 Z" />
                      <path d="M60,0 H100 V40 H60 Z M70,10 V30 H90 V10 Z" />
                      <path d="M0,60 H40 V100 H0 Z M10,70 V90 H30 V70 Z" />
                      <rect x="20" y="20" width="10" height="10" />
                      <rect x="70" y="20" width="10" height="10" />
                      <rect x="20" y="70" width="10" height="10" />
                      <rect x="45" y="10" width="10" height="30" />
                      <rect x="45" y="45" width="20" height="20" />
                    </svg>
                  </div>
                  <span className="text-[8px] font-mono font-bold text-slate-700 block">{selectedBadgeEmp.nip}</span>
                </div>
              </div>

              {/* Employee Bio details */}
              <div className="border-t-2 border-slate-900 pt-3 space-y-1 text-center">
                <h3 className="font-black text-slate-900 text-sm uppercase leading-tight">{selectedBadgeEmp.name}</h3>
                <p className="text-[10px] font-bold text-slate-700 uppercase">{selectedBadgeEmp.position}</p>
                <p className="text-[9px] font-mono text-slate-500 uppercase">{selectedBadgeEmp.division}</p>
              </div>

              {/* Badge Footer */}
              <div className="bg-slate-100 -mx-5 -mb-5 p-2 text-center text-[8px] font-mono text-slate-600 border-t border-slate-300">
                Dokumen Resmi PT Median Multi Daya • Wajib Dikenakan di Area HQ
              </div>
            </div>

            <div className="flex items-center gap-2 pt-2">
              <button
                type="button"
                onClick={() => window.print()}
                className="w-full bg-[#facc15] hover:bg-yellow-500 text-black font-black uppercase text-xs py-2 flex items-center justify-center gap-2 cursor-pointer"
              >
                <Printer className="w-4 h-4" />
                Cetak Name Tag ID
              </button>
            </div>

          </div>
        </div>
      )}

      {/* UNDUH LAPORAN ABSENSI & PAYROLL MODAL */}
      {isExportModalOpen && (
        <div className="fixed inset-0 z-50 bg-black/85 backdrop-blur-sm flex items-center justify-center p-4 animate-fadeIn">
          <div className="bg-[#0a0a0a] border-2 border-[#facc15]/40 text-slate-100 w-full max-w-lg p-6 space-y-5 shadow-2xl relative font-sans">
            
            <div className="flex items-start justify-between border-b border-[#222] pb-4">
              <div className="flex items-center gap-3">
                <div className="p-2.5 bg-[#facc15]/10 border border-[#facc15]/30 text-[#facc15]">
                  <Download className="w-6 h-6 text-[#facc15]" />
                </div>
                <div>
                  <h3 className="text-base font-black text-white uppercase tracking-tight">
                    UNDUH LAPORAN ABSENSI PEGAWAI
                  </h3>
                  <p className="text-xs text-slate-400 font-mono">
                    Konversi Log Kehadiran Pegawai ke Format PDF atau CSV Payroll
                  </p>
                </div>
              </div>
              <button 
                type="button"
                onClick={() => setIsExportModalOpen(false)}
                className="text-slate-400 hover:text-white bg-[#111] p-1.5 border border-[#333] cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="space-y-4 font-mono text-xs">
              
              {/* Scope Selection */}
              <div className="space-y-1.5">
                <label className="block text-slate-300 font-bold uppercase text-[11px]">
                  Pilih Cakupan Data Laporan:
                </label>
                <div className="grid grid-cols-2 gap-2">
                  <button
                    type="button"
                    onClick={() => setExportScope("filtered")}
                    className={`p-3 border text-left transition-all cursor-pointer ${
                      exportScope === "filtered"
                        ? "bg-[#facc15]/10 border-[#facc15] text-[#facc15]"
                        : "bg-[#050505] border-[#222] text-slate-400 hover:border-[#333]"
                    }`}
                  >
                    <span className="font-bold block text-xs">Data Terfilter ({filteredLogs.length} Entri)</span>
                    <span className="text-[10px] text-slate-400 block mt-0.5">Filter Tanggal: {filterDate || "Semua"} & Status: {filterStatus}</span>
                  </button>

                  <button
                    type="button"
                    onClick={() => setExportScope("all")}
                    className={`p-3 border text-left transition-all cursor-pointer ${
                      exportScope === "all"
                        ? "bg-[#facc15]/10 border-[#facc15] text-[#facc15]"
                        : "bg-[#050505] border-[#222] text-slate-400 hover:border-[#333]"
                    }`}
                  >
                    <span className="font-bold block text-xs">Seluruh Database ({attendanceLogs.length} Entri)</span>
                    <span className="text-[10px] text-slate-400 block mt-0.5">Seluruh riwayat log absensi di sistem</span>
                  </button>
                </div>
              </div>

              {/* Data Summary Preview */}
              <div className="bg-[#050505] border border-[#222] p-3 space-y-2 text-[11px]">
                <div className="flex justify-between text-slate-400">
                  <span>Target Entri Laporan:</span>
                  <span className="text-white font-bold">{exportScope === "filtered" ? filteredLogs.length : attendanceLogs.length} Entri Log</span>
                </div>
                <div className="flex justify-between text-slate-400">
                  <span>Keterlambatan Tercatat:</span>
                  <span className="text-amber-400 font-bold">
                    {(exportScope === "filtered" ? filteredLogs : attendanceLogs).filter(l => l.status === "Terlambat").length} Kasus
                  </span>
                </div>
                <div className="flex justify-between text-slate-400">
                  <span>Absen / Alpa:</span>
                  <span className="text-rose-400 font-bold">
                    {(exportScope === "filtered" ? filteredLogs : attendanceLogs).filter(l => l.status === "Absen / Alpa").length} Kasus
                  </span>
                </div>
              </div>

              {/* Action Buttons for Formats */}
              <div className="space-y-2 pt-2">
                <label className="block text-slate-300 font-bold uppercase text-[11px]">
                  Pilih Format File Unduhan:
                </label>
                
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <button
                    type="button"
                    onClick={() => {
                      const logsToExport = exportScope === "filtered" ? filteredLogs : attendanceLogs;
                      generateAttendancePDF(logsToExport, filterDate, stats);
                      setIsExportModalOpen(false);
                    }}
                    className="p-3 bg-[#111] hover:bg-[#1a1a1a] border border-[#facc15]/60 hover:border-[#facc15] text-left transition-all cursor-pointer group"
                  >
                    <div className="flex items-center gap-2 mb-1">
                      <FileCheck className="w-5 h-5 text-[#facc15]" />
                      <span className="font-bold text-white text-xs group-hover:text-[#facc15]">Unduh Format PDF</span>
                    </div>
                    <p className="text-[10px] text-slate-400 leading-relaxed">
                      Dokumen resmi PDF A4 Landscape dengan tabel rekapitulasi, header PT Median Multi Daya, dan ringkasan KPI payroll.
                    </p>
                  </button>

                  <button
                    type="button"
                    onClick={() => {
                      const logsToExport = exportScope === "filtered" ? filteredLogs : attendanceLogs;
                      generateAttendanceCSV(logsToExport, filterDate);
                      setIsExportModalOpen(false);
                    }}
                    className="p-3 bg-[#111] hover:bg-[#1a1a1a] border border-emerald-500/60 hover:border-emerald-400 text-left transition-all cursor-pointer group"
                  >
                    <div className="flex items-center gap-2 mb-1">
                      <FileSpreadsheet className="w-5 h-5 text-emerald-400" />
                      <span className="font-bold text-white text-xs group-hover:text-emerald-400">Unduh Format CSV</span>
                    </div>
                    <p className="text-[10px] text-slate-400 leading-relaxed">
                      Spreadsheet Excel CSV dengan pemisah koma (\uFEFF BOM supported) siap diimpor ke sistem administrasi payroll.
                    </p>
                  </button>
                </div>
              </div>

            </div>

            <div className="pt-2 border-t border-[#222] flex justify-end">
              <button
                type="button"
                onClick={() => setIsExportModalOpen(false)}
                className="px-4 py-2 bg-[#111] hover:bg-[#222] text-slate-400 hover:text-white text-xs font-mono font-bold border border-[#333] cursor-pointer"
              >
                Tutup
              </button>
            </div>

          </div>
        </div>
      )}

    </div>
  );
}
