function ParcelScanner({ year }) {
    const [scanning, setScanning] = React.useState(false);
    const [manualInput, setManualInput] = React.useState('');
    const [employee, setEmployee] = React.useState(null);
    const [loading, setLoading] = React.useState(false);
    const [stats, setStats] = React.useState({ total: 0, collected: 0 });
    
    // Search Suggestions State
    const [allEmployees, setAllEmployees] = React.useState([]);
    const [suggestions, setSuggestions] = React.useState([]);
    const [showSuggestions, setShowSuggestions] = React.useState(false);
    
    // Batch Mode State
    const [isBatchMode, setIsBatchMode] = React.useState(true);
    const [batchLog, setBatchLog] = React.useState([]); // Queue/History for batch

    // List View State
    const [viewMode, setViewMode] = React.useState('scan'); // 'scan' | 'list' | 'rekap'
    const [listFilter, setListFilter] = React.useState('collected'); // 'collected' | 'uncollected'
    const [employeeList, setEmployeeList] = React.useState([]);
    const [listSearch, setListSearch] = React.useState('');
    const [loadingList, setLoadingList] = React.useState(false);
    const [selectedListIds, setSelectedListIds] = React.useState([]);

    // Recap State
    const [rekapData, setRekapData] = React.useState([]);
    const [loadingRekap, setLoadingRekap] = React.useState(false);
    
    // Audio Refs (Howler)
    const soundSuccessRef = React.useRef(null);
    const soundErrorRef = React.useRef(null);
    const soundAlreadyCollectedRef = React.useRef(null);
    
    // Refs
    const collectBtnRef = React.useRef(null);
    const inputRef = React.useRef(null);

    // Stats & Data Fetcher
    const fetchData = async () => {
        const client = window.SupabaseUtils.getClient();
        if (!client) return;
        
        // Stats for Current Year
        const { count: total } = await client.from('employees').select('id', { count: 'exact', head: true })
            .eq('is_active', true)
            .eq('tahun', year);

        const { count: collected } = await client.from('employees').select('id', { count: 'exact', head: true })
            .eq('is_active', true)
            .eq('is_parcel_collected', true)
            .eq('tahun', year);

        setStats({ total: total || 0, collected: collected || 0 });

        // Fetch lightweight data for suggestions (Year filtered)
        // Added is_parcel_collected to show status in suggestions
        const { data } = await client
            .from('employees')
            .select('id, nik, nama, satminkal, is_parcel_collected')
            .eq('is_active', true)
            .eq('tahun', year)
            .order('nama', { ascending: true });
            
        if (data) {
            setAllEmployees(data);
        }
    };

    // Centralized Refresh Function to ensure all views are in sync
    const refreshAll = () => {
        fetchData(); // Update Stats & Suggestions
        fetchHistory(); // Update Log
        // Update List/Rekap if visible
        if (viewMode === 'list') fetchList();
        if (viewMode === 'rekap') fetchRekap();
    };

    // Load History from DB (Persistent Log)
    const fetchHistory = async () => {
        const client = window.SupabaseUtils.getClient();
        if (!client) return;

        const { data } = await client
            .from('employees')
            .select('*')
            .eq('is_parcel_collected', true)
            .eq('tahun', year)
            .order('collected_at', { ascending: false })
            .limit(20); // Last 20 items
        
        if (data) {
            const historyItems = data.map(emp => ({
                id: `hist-${emp.id}`, // Unique ID for log key
                key: emp.nik || emp.id,
                time: emp.collected_at ? new Date(emp.collected_at).toLocaleTimeString('id-ID', {hour: '2-digit', minute:'2-digit'}) : '-',
                status: 'success',
                msg: 'Riwayat Database',
                empName: emp.nama,
                empSatminkal: emp.satminkal,
                empId: emp.id,
                isHistory: true // Flag to distinguish
            }));
            setBatchLog(historyItems);
        }
    };

    // Realtime Subscription Logic
    const refreshAllRef = React.useRef(refreshAll);
    React.useEffect(() => {
        refreshAllRef.current = refreshAll;
    });

    React.useEffect(() => {
        const client = window.SupabaseUtils.getClient();
        if (!client) return;

        const channel = client
            .channel('public:employees')
            .on('postgres_changes', { event: '*', schema: 'public', table: 'employees' }, (payload) => {
                const record = payload.new || payload.old;
                // Only refresh if the change belongs to the active year
                if (record && record.tahun == year) {
                     if (refreshAllRef.current) refreshAllRef.current();
                }
            })
            .subscribe();

        return () => {
            client.removeChannel(channel);
        };
    }, [year]);

    React.useEffect(() => {
        fetchData();
        fetchHistory();
        
        // Init Sounds
        soundSuccessRef.current = new Howl({
            src: [window.AppAssets.audioSuccess],
            volume: 0.8
        });
        soundErrorRef.current = new Howl({
            src: [window.AppAssets.audioError],
            volume: 0.8
        });
        soundAlreadyCollectedRef.current = new Howl({
            src: [window.AppAssets.audioAlreadyCollected],
            volume: 1.0
        });
    }, [year]); // Refetch on year change

    // Auto-focus Logic
    React.useEffect(() => {
        // If in Batch Mode, always focus input
        if (isBatchMode && !scanning) {
            setTimeout(() => inputRef.current?.focus(), 100);
        } 
        // If in Normal Mode, focus Button if employee loaded and ready
        else if (employee && !employee.is_parcel_collected && employee.is_active && !scanning) {
            setTimeout(() => collectBtnRef.current?.focus(), 100);
        }
    }, [isBatchMode, employee, stats, scanning]); // Re-run when mode changes or stats update (after action)

    // Refs for Scanner
    const scannerRef = React.useRef(null);
    const scannerRunningRef = React.useRef(false); // Track if scanner is actually running
    const isBatchModeRef = React.useRef(isBatchMode);
    
    // Keep batch mode ref in sync to avoid scanner restart
    React.useEffect(() => {
        isBatchModeRef.current = isBatchMode;
    }, [isBatchMode]);

    // Scanner Logic (Webcam)
    React.useEffect(() => {
        let isMounted = true;

        if (scanning) {
            // Delay initialization slightly to ensure DOM element exists
            const timer = setTimeout(async () => {
                if (!isMounted) return;

                if (!window.Html5Qrcode) {
                    Swal.fire("Error", "Library Scanner belum termuat. Refresh halaman.", "error");
                    if (isMounted) setScanning(false);
                    return;
                }

                // Cleanup previous instance if any
                if (scannerRef.current) {
                    try {
                        if (scannerRunningRef.current) {
                            await scannerRef.current.stop();
                        }
                        scannerRef.current.clear();
                    } catch (e) { console.warn("Cleanup error", e); }
                    scannerRef.current = null;
                    scannerRunningRef.current = false;
                }

                // Create new instance
                const scanner = new Html5Qrcode("reader");
                scannerRef.current = scanner;

                try {
                    await scanner.start(
                        { facingMode: "environment" },
                        { 
                            fps: 10, 
                            qrbox: { width: 250, height: 250 },
                            aspectRatio: 1.0 
                        },
                        (decodedText) => {
                            // Success Callback
                            if (isBatchModeRef.current) {
                                // Batch Mode: Keep scanning
                                processBatchItem(decodedText);
                            } else {
                                // Detail Mode: Stop scanning to show result
                                handleSearch(decodedText);
                                if (isMounted) setScanning(false);
                            }
                        },
                        (errorMessage) => {
                            // parse error, ignore
                        }
                    );
                    
                    if (isMounted) {
                        scannerRunningRef.current = true;
                    } else {
                        // If unmounted during start, stop immediately
                        await scanner.stop();
                        scannerRunningRef.current = false;
                    }

                } catch (err) {
                    console.error("Scanner Error:", err);
                    scannerRunningRef.current = false;
                    
                    if (isMounted) {
                        // Only show alert if it's a real error, not just user cancellation/stop
                        const msg = err?.message || '';
                        if (!msg.includes("not running")) {
                             Swal.fire({
                                icon: "error",
                                title: "Gagal Akses Kamera",
                                text: "Pastikan izin kamera diberikan dan tidak sedang digunakan aplikasi lain.",
                                confirmButtonText: "Tutup"
                            });
                        }
                        setScanning(false);
                    }
                }
            }, 300); // 300ms delay for DOM readiness

            return () => {
                isMounted = false;
                clearTimeout(timer);
            };
        } else {
            // When scanning turned off, cleanup safely
            const cleanup = async () => {
                if (scannerRef.current) {
                    try {
                        if (scannerRunningRef.current) {
                            await scannerRef.current.stop();
                        }
                        try {
                            scannerRef.current.clear();
                        } catch(e) { /* ignore clear error */ }
                    } catch (e) { 
                        console.warn("Stop scanner warning:", e); 
                    } finally {
                        scannerRef.current = null;
                        scannerRunningRef.current = false;
                    }
                }
            };
            cleanup();
        }
    }, [scanning]); // Only depend on scanning state

    // Handle Input Change & Filter Suggestions
    const handleInputChange = (e) => {
        const value = e.target.value;
        setManualInput(value);
        
        if (!value.trim()) {
            setSuggestions([]);
            return;
        }

        const lowerVal = value.toLowerCase();
        const filtered = allEmployees.filter(emp => {
            const nikMatch = (emp.nik || '').toLowerCase().includes(lowerVal);
            const nameMatch = (emp.nama || '').toLowerCase().includes(lowerVal);
            return nikMatch || nameMatch;
        }).slice(0, 10); // Limit to 10 suggestions

        setSuggestions(filtered);
        setShowSuggestions(true);
    };

    const handleInputFocus = () => {
        if (manualInput.trim() && suggestions.length > 0) {
            setShowSuggestions(true);
        }
    };

    const handleSuggestionClick = (emp) => {
        // Use NIK if available, else ID
        const key = emp.nik || emp.id;
        setManualInput(key);
        setSuggestions([]);
        setShowSuggestions(false);
        
        // Auto submit based on mode
        if (isBatchMode) {
            processBatchItem(key);
        } else {
            handleSearch(key);
        }
    };

    // Close suggestions when clicking outside
    React.useEffect(() => {
        const handleClickOutside = (event) => {
            if (inputRef.current && !inputRef.current.contains(event.target) && !event.target.closest('.suggestion-item')) {
                setShowSuggestions(false);
            }
        };
        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, []);

    // Play Sound Helper (Howler)
    const playSound = (type) => {
        try {
            if (type === 'success') {
                if (soundSuccessRef.current) soundSuccessRef.current.play();
            } else if (type === 'already_collected') {
                if (soundAlreadyCollectedRef.current) soundAlreadyCollectedRef.current.play();
            } else {
                if (soundErrorRef.current) soundErrorRef.current.play();
            }
        } catch (e) {
            console.error("Audio Play Error:", e);
        }
    };

    // --- NORMAL MODE HANDLERS ---

    const handleSearch = async (key) => {
        if (!key) return;
        setLoading(true);
        setEmployee(null);
        // Hide suggestions when searching
        setShowSuggestions(false);

        try {
            const client = window.SupabaseUtils.getClient();
            // Search by NIK or ID + YEAR
            let { data } = await client
                .from('employees')
                .select('*')
                .eq('nik', key)
                .eq('tahun', year) // Filter Year
                .maybeSingle();
            
            if (!data) {
                const { data: byId } = await client
                    .from('employees')
                    .select('*')
                    .eq('id', key)
                    .eq('tahun', year) // Filter Year
                    .maybeSingle();
                data = byId;
            }

            if (data) {
                setEmployee(data);
                
                // Sound & Warning Logic
                if (data.is_parcel_collected) {
                    playSound('already_collected');
                    Swal.fire({
                        icon: 'error', // Changed to Error for stronger feedback
                        title: 'GAGAL SCAN!',
                        html: `
                            <div style="font-size: 1.1em; font-weight: bold; margin-bottom: 10px;">Data sudah diambil sebelumnya.</div>
                            <div class="text-sm bg-red-50 p-3 rounded text-left">
                                <div><b>Nama:</b> ${data.nama}</div>
                                <div><b>Waktu Ambil:</b> ${new Date(data.collected_at).toLocaleString('id-ID')}</div>
                            </div>
                        `,
                        timer: 4000,
                        showConfirmButton: false,
                        background: '#fef2f2', 
                        color: '#991b1b'
                    });
                } else if (!data.is_active) {
                    playSound('error');
                    Swal.fire({
                        icon: 'error',
                        title: 'PEGAWAI NON-AKTIF',
                        text: `${data.nama} statusnya tidak aktif.`,
                        timer: 3000,
                        showConfirmButton: false
                    });
                } else {
                    // Valid & Eligible
                    playSound('success');
                }
            } else {
                playSound('error');
                Swal.fire({
                    icon: 'error',
                    title: 'Tidak Ditemukan',
                    text: `Data dengan kunci "${key}" tidak ditemukan.`,
                    timer: 1500,
                    showConfirmButton: false
                });
            }
        } catch (err) {
            console.error(err);
            Swal.fire("Error", "Gagal mencari data.", "error");
        } finally {
            setLoading(false);
        }
    };

    const handleCollect = async () => {
        if (!employee) return;
        try {
            const client = window.SupabaseUtils.getClient();
            const now = new Date().toISOString();

            const { error } = await client
                .from('employees')
                .update({ is_parcel_collected: true, collected_at: now })
                .eq('id', employee.id);

            if (error) throw error;

            playSound('success');
            setEmployee(prev => ({ ...prev, is_parcel_collected: true, collected_at: now }));
            setStats(prev => ({ ...prev, collected: prev.collected + 1 }));
            
            // Sync all data
            refreshAll();

            Swal.fire({
                icon: 'success',
                title: 'PARSEL DIAMBIL',
                text: `${employee.nama} telah mengambil parsel.`,
                timer: 1500,
                showConfirmButton: false,
                background: '#f0fdf4'
            });

        } catch (err) {
            Swal.fire("Gagal", window.SupabaseUtils.formatError(err), "error");
        }
    };

    const handleCancelCollection = async () => {
        try {
            const client = window.SupabaseUtils.getClient();
            const { error } = await client
                .from('employees')
                .update({ is_parcel_collected: false, collected_at: null })
                .eq('id', employee.id);

            if (error) throw error;

            setEmployee(prev => ({ ...prev, is_parcel_collected: false, collected_at: null }));
            setStats(prev => ({ ...prev, collected: Math.max(0, prev.collected - 1) }));
            refreshAll();
            
            Swal.fire({ icon: 'info', title: 'Dibatalkan', timer: 1000, showConfirmButton: false });
        } catch (err) {
            Swal.fire("Error", "Gagal membatalkan.", "error");
        }
    };

    // --- BATCH MODE HANDLERS ---

    const fetchList = async () => {
        setLoadingList(true);
        setSelectedListIds([]); // Reset selection on fetch
        try {
            const client = window.SupabaseUtils.getClient();
            const isCollected = listFilter === 'collected';
            
            let query = client
                .from('employees')
                .select('*')
                .eq('is_active', true)
                .eq('tahun', year)
                .eq('is_parcel_collected', isCollected);
            
            if (isCollected) {
                query = query.order('collected_at', { ascending: false });
            } else {
                query = query.order('nama', { ascending: true });
            }

            const { data, error } = await query;
            
            if (error) throw error;
            setEmployeeList(data || []);
        } catch (err) {
            console.error("Fetch List Error", err);
        } finally {
            setLoadingList(false);
        }
    };

    const fetchRekap = async () => {
        setLoadingRekap(true);
        try {
            const client = window.SupabaseUtils.getClient();
            const { data, error } = await client
                .from('employees')
                .select('id, satminkal, lembaga, is_parcel_collected')
                .eq('is_active', true)
                .eq('tahun', year);

            if (error) throw error;

            // Aggregate Data
            const stats = {};
            (data || []).forEach(emp => {
                // Determine Unit Name (Satminkal or Lembaga Lain)
                const unit = emp.satminkal || emp.lembaga || 'Lain-lain / Tidak Ada';
                const cleanUnit = unit.trim();

                if (!stats[cleanUnit]) {
                    stats[cleanUnit] = { name: cleanUnit, total: 0, collected: 0, uncollected: 0 };
                }
                
                stats[cleanUnit].total++;
                if (emp.is_parcel_collected) {
                    stats[cleanUnit].collected++;
                } else {
                    stats[cleanUnit].uncollected++;
                }
            });

            // Convert to Array & Sort by Total Descending
            const sorted = Object.values(stats).sort((a, b) => b.total - a.total);
            setRekapData(sorted);

        } catch (err) {
            console.error("Fetch Rekap Error", err);
        } finally {
            setLoadingRekap(false);
        }
    };

    React.useEffect(() => {
        if (viewMode === 'list') {
            fetchList();
        } else if (viewMode === 'rekap') {
            fetchRekap();
        }
    }, [viewMode, listFilter, year]);

    const handleBatchReset = async (logId, empId) => {
        if (!empId) return;
        
        try {
            const client = window.SupabaseUtils.getClient();
            const { error } = await client
                .from('employees')
                .update({ is_parcel_collected: false, collected_at: null })
                .eq('id', empId);

            if (error) throw error;

            // Update Log State to reflect cancellation
            setBatchLog(prev => prev.map(item => {
                // Match either log ID or Employee ID (for history items)
                if (item.id === logId || item.empId === empId) {
                    return { ...item, status: 'cancelled', msg: 'Dibatalkan manual' };
                }
                return item;
            }));

            // Update Stats
            setStats(prev => ({ ...prev, collected: Math.max(0, prev.collected - 1) }));
            
            refreshAll();
            
            // If in Detail mode and viewing this employee, update view
            if (employee && employee.id === empId) {
                setEmployee(prev => ({ ...prev, is_parcel_collected: false, collected_at: null }));
            }

            Swal.fire({
                icon: 'success',
                title: 'Status Direset',
                text: 'Pengambilan parsel dibatalkan.',
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 2000
            });

        } catch (err) {
            console.error("Batch Error", err);
            Swal.fire("Gagal Reset", "Terjadi kesalahan saat membatalkan.", "error");
        }
    };

    const handleManualCollect = async (item) => {
        Swal.fire({
            title: 'Konfirmasi Pengambilan',
            text: `Tandai parsel "${item.nama}" sebagai SUDAH diambil?`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#10b981',
            confirmButtonText: 'Ya, Tandai',
            cancelButtonText: 'Batal'
        }).then(async (res) => {
            if (res.isConfirmed) {
                try {
                    const client = window.SupabaseUtils.getClient();
                    const now = new Date().toISOString();
                    const { error } = await client
                        .from('employees')
                        .update({ is_parcel_collected: true, collected_at: now })
                        .eq('id', item.id);
                    
                    if (error) throw error;

                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil',
                        text: 'Data berhasil diperbarui',
                        timer: 1000,
                        showConfirmButton: false
                    });
                    
                    // Refresh EVERYTHING
                    setStats(prev => ({ ...prev, collected: prev.collected + 1 }));
                    refreshAll();
                    
                } catch (err) {
                    Swal.fire("Gagal", window.SupabaseUtils.formatError(err), "error");
                }
            }
        });
    };

    // Bulk Action Handlers
    const handleListSelectAll = (e, filteredItems) => {
        if (e.target.checked) {
            setSelectedListIds(filteredItems.map(i => i.id));
        } else {
            setSelectedListIds([]);
        }
    };

    const handleListSelectOne = (id) => {
        setSelectedListIds(prev => 
            prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
        );
    };

    const handleBulkListAction = async () => {
        if (selectedListIds.length === 0) return;

        const isCollecting = listFilter === 'uncollected';
        const actionText = isCollecting ? 'Tandai SUDAH Diambil' : 'Reset Status (Belum Diambil)';
        const confirmBtnColor = isCollecting ? '#10b981' : '#d33';

        const result = await Swal.fire({
            title: `Proses ${selectedListIds.length} Data?`,
            text: `Anda akan melakukan tindakan: ${actionText}`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: confirmBtnColor,
            confirmButtonText: 'Ya, Proses!',
            cancelButtonText: 'Batal'
        });

        if (!result.isConfirmed) return;

        try {
            const client = window.SupabaseUtils.getClient();
            const now = new Date().toISOString();
            
            let updatePayload = {};
            if (isCollecting) {
                updatePayload = { is_parcel_collected: true, collected_at: now };
            } else {
                updatePayload = { is_parcel_collected: false, collected_at: null };
            }

            const { error } = await client
                .from('employees')
                .update(updatePayload)
                .in('id', selectedListIds);

            if (error) throw error;

            Swal.fire({
                icon: 'success',
                title: 'Berhasil',
                text: `${selectedListIds.length} data telah diperbarui.`,
                timer: 1500,
                showConfirmButton: false
            });

            // Refresh stats and list
            if (isCollecting) {
                setStats(prev => ({ ...prev, collected: prev.collected + selectedListIds.length }));
            } else {
                setStats(prev => ({ ...prev, collected: Math.max(0, prev.collected - selectedListIds.length) }));
            }
            
            setSelectedListIds([]);
            refreshAll();

        } catch (err) {
            console.error(err);
            Swal.fire("Gagal", window.SupabaseUtils.formatError(err), "error");
        }
    };

    // Cooldown ref to prevent rapid double scans of same code
    const lastScanRef = React.useRef({ code: '', time: 0 });

    const processBatchItem = async (key) => {
        if (!key) return;
        
        // Anti-spam / Debounce check (2 seconds for same code)
        const now = Date.now();
        if (key === lastScanRef.current.code && (now - lastScanRef.current.time) < 2000) {
            console.log("Duplicate scan ignored:", key);
            return;
        }
        lastScanRef.current = { code: key, time: now };

        setShowSuggestions(false); // Hide if processing
        
        try {
            const client = window.SupabaseUtils.getClient();
            
            // 1. Find Employee
            let { data: emp } = await client.from('employees').select('*').eq('nik', key).maybeSingle();
            if (!emp) {
                const { data: byId } = await client.from('employees').select('*').eq('id', key).maybeSingle();
                emp = byId;
            }

            // Validation & Log Object
            const logItem = {
                id: Date.now(),
                key: key,
                time: new Date().toLocaleTimeString(),
                status: 'pending',
                msg: '',
                empName: emp ? emp.nama : 'Tidak Ditemukan',
                empSatminkal: emp ? emp.satminkal : '-',
                empId: emp ? emp.id : null
            };

            if (!emp) {
                logItem.status = 'error';
                logItem.msg = 'Data tidak ditemukan';
                playSound('error');
                // Optional: Alert for not found? Usually just log is enough for speed, but let's be consistent
                Swal.fire({
                    icon: 'error',
                    title: 'TIDAK DITEMUKAN',
                    text: `Data "${key}" tidak ada dalam database.`,
                    timer: 1500,
                    showConfirmButton: false
                });
            } else if (!emp.is_active) {
                logItem.status = 'error';
                logItem.msg = 'Pegawai Non-Aktif';
                playSound('error');
                
                // Peringatan Keras untuk Non-Aktif
                Swal.fire({
                    icon: 'error',
                    title: 'PEGAWAI NON-AKTIF!',
                    text: `${emp.nama} berstatus non-aktif. Tidak berhak menerima parsel.`,
                    timer: 3000,
                    showConfirmButton: false,
                    background: '#fef2f2',
                    color: '#991b1b'
                });
            } else if (emp.is_parcel_collected) {
                logItem.status = 'warning';
                logItem.msg = `Sudah diambil: ${new Date(emp.collected_at).toLocaleTimeString()}`;
                playSound('already_collected'); 
                
                // Peringatan Keras untuk Duplikasi
                Swal.fire({
                    icon: 'warning',
                    title: 'SUDAH DIAMBIL!',
                    html: `
                        <div class="text-lg font-bold">${emp.nama}</div>
                        <div class="text-sm mt-2">Telah mengambil pada: ${new Date(emp.collected_at).toLocaleString('id-ID')}</div>
                    `,
                    timer: 4000, // Agak lama biar notice
                    showConfirmButton: true, // Butuh klik OK biar sadar (opsional, tapi user minta keras)
                    confirmButtonColor: '#d33',
                    background: '#fff7ed', 
                    color: '#c2410c'
                });
            } else {
                // Execute Update
                const now = new Date().toISOString();
                const { error } = await client
                    .from('employees')
                    .update({ is_parcel_collected: true, collected_at: now })
                    .eq('id', emp.id);

                if (error) {
                    logItem.status = 'error';
                    logItem.msg = 'Gagal update DB';
                    playSound('error');
                } else {
                    logItem.status = 'success';
                    logItem.msg = 'Berhasil';
                    playSound('success');
                    setStats(prev => ({ ...prev, collected: prev.collected + 1 }));
                    refreshAll();
                }
            }

            // Add to Log (Top)
            setBatchLog(prev => [logItem, ...prev].slice(0, 50));

        } catch (err) {
            console.error("Batch Error", err);
            playSound('error');
        } finally {
            setManualInput(''); // Clear input
            inputRef.current?.focus(); // Ensure focus back
        }
    };

    const handleFormSubmit = (e) => {
        e.preventDefault();
        if (isBatchMode) {
            processBatchItem(manualInput);
        } else {
            handleSearch(manualInput);
        }
    };

    return (
        <div className="p-4 md:p-8" data-name="parcel-scanner" data-file="components/ParcelScanner.js">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                <div>
                    <h2 className="text-2xl font-bold text-gray-800 flex items-center gap-2">
                        <div className="icon-qr-code text-indigo-600"></div>
                        Cek Pengambilan Parsel
                    </h2>
                    <p className="text-gray-500 text-sm mt-1">
                        Scan QR Code atau input NIK. Gunakan mode cepat untuk antrian banyak.
                    </p>
                </div>
                
                {/* Mode Toggle & Stats */}
                <div className="w-full md:w-auto flex flex-col md:flex-row items-stretch md:items-center gap-4">
                    <div className="flex items-center gap-1 bg-white p-1 rounded-lg border border-gray-300 shadow-sm w-full md:w-auto">
                        <button
                            onClick={() => setIsBatchMode(true)}
                            className={`flex-1 md:flex-none px-3 py-2 md:py-1.5 text-xs font-bold rounded transition-all flex items-center justify-center gap-1 ${
                                isBatchMode ? 'bg-orange-500 text-white shadow' : 'text-gray-500 hover:bg-gray-100'
                            }`}
                        >
                            <div className="icon-zap text-xs"></div>
                            Cepat
                        </button>
                        <button
                            onClick={() => setIsBatchMode(false)}
                            className={`flex-1 md:flex-none px-3 py-2 md:py-1.5 text-xs font-bold rounded transition-all text-center ${
                                !isBatchMode ? 'bg-indigo-600 text-white shadow' : 'text-gray-500 hover:bg-gray-100'
                            }`}
                        >
                            Detail
                        </button>
                    </div>

                    {/* Stats with Percentage */}
                    <div className="flex items-center bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden">
                        <div className="px-3 py-1.5 text-center min-w-[70px]">
                            <div className="text-[10px] text-gray-400 font-bold uppercase">Sudah</div>
                            <div className="text-lg font-bold text-green-600 leading-none">{stats.collected}</div>
                        </div>
                        
                        <div className="flex flex-col justify-center items-center px-2 w-24 border-x border-gray-100 bg-gray-50/50 self-stretch">
                            <div className="text-xs font-bold text-gray-600">
                                {stats.total > 0 ? ((stats.collected / stats.total) * 100).toFixed(2) : '0.00'}%
                            </div>
                            <div className="w-full h-1.5 bg-gray-200 rounded-full mt-1 overflow-hidden">
                                <div 
                                    className="h-full bg-green-500 transition-all duration-500 ease-out" 
                                    style={{ width: `${stats.total > 0 ? (stats.collected / stats.total) * 100 : 0}%` }}
                                ></div>
                            </div>
                        </div>

                        <div className="px-3 py-1.5 text-center min-w-[70px]">
                            <div className="text-[10px] text-gray-400 font-bold uppercase">Belum</div>
                            <div className="text-lg font-bold text-gray-500 leading-none">{stats.total - stats.collected}</div>
                        </div>
                    </div>
                </div>
            </div>

            <div className="flex gap-2 mb-6 overflow-x-auto pb-2">
                <button
                    onClick={() => setViewMode('scan')}
                    className={`px-4 py-2 rounded-lg font-bold text-sm flex items-center gap-2 transition-all ${
                        viewMode === 'scan' 
                        ? 'bg-indigo-600 text-white shadow-md' 
                        : 'bg-white text-gray-600 hover:bg-gray-50 border border-gray-200'
                    }`}
                >
                    <div className="icon-scan-line"></div>
                    Scan / Input
                </button>
                <button
                    onClick={() => setViewMode('list')}
                    className={`px-4 py-2 rounded-lg font-bold text-sm flex items-center gap-2 transition-all ${
                        viewMode === 'list' 
                        ? 'bg-indigo-600 text-white shadow-md' 
                        : 'bg-white text-gray-600 hover:bg-gray-50 border border-gray-200'
                    }`}
                >
                    <div className="icon-list-checks"></div>
                    Daftar Data
                </button>
                <button
                    onClick={() => setViewMode('rekap')}
                    className={`px-4 py-2 rounded-lg font-bold text-sm flex items-center gap-2 transition-all ${
                        viewMode === 'rekap' 
                        ? 'bg-indigo-600 text-white shadow-md' 
                        : 'bg-white text-gray-600 hover:bg-gray-50 border border-gray-200'
                    }`}
                >
                    <div className="icon-chart-bar"></div>
                    Rekap Lembaga
                </button>
            </div>

            {viewMode === 'rekap' ? (
                 <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 animate-fade-in">
                    {loadingRekap ? (
                        <div className="col-span-full p-12 text-center text-gray-500">
                            <div className="inline-block animate-spin w-8 h-8 border-4 border-indigo-500 border-t-transparent rounded-full mb-3"></div>
                            <div>Menghitung data rekapitulasi...</div>
                        </div>
                    ) : rekapData.length === 0 ? (
                        <div className="col-span-full p-12 text-center text-gray-500">
                            Belum ada data untuk direkap.
                        </div>
                    ) : (
                        rekapData.map((item, idx) => (
                            <div key={idx} className="bg-white p-4 rounded-lg shadow border border-gray-200 hover:shadow-md transition-shadow">
                                <h4 className="font-bold text-gray-800 text-lg mb-2 truncate" title={item.name}>
                                    {item.name}
                                </h4>
                                <div className="flex items-center gap-2 mb-3">
                                    <div className="flex-1 bg-gray-100 rounded-full h-2 overflow-hidden">
                                        <div 
                                            className="bg-green-500 h-full rounded-full transition-all duration-500" 
                                            style={{width: `${(item.collected / item.total) * 100}%`}}
                                        ></div>
                                    </div>
                                    <div className="text-xs font-bold text-gray-500">
                                        {Math.round((item.collected / item.total) * 100)}%
                                    </div>
                                </div>
                                <div className="grid grid-cols-3 gap-2 text-center">
                                    <div className="bg-blue-50 p-2 rounded border border-blue-100">
                                        <div className="text-xs text-blue-600 font-bold uppercase">Total</div>
                                        <div className="text-lg font-bold text-blue-800">{item.total}</div>
                                    </div>
                                    <div className="bg-green-50 p-2 rounded border border-green-100">
                                        <div className="text-xs text-green-600 font-bold uppercase">Sudah</div>
                                        <div className="text-lg font-bold text-green-800">{item.collected}</div>
                                    </div>
                                    <div className="bg-red-50 p-2 rounded border border-red-100">
                                        <div className="text-xs text-red-600 font-bold uppercase">Belum</div>
                                        <div className="text-lg font-bold text-red-800">{item.uncollected}</div>
                                    </div>
                                </div>
                            </div>
                        ))
                    )}
                 </div>
            ) : viewMode === 'list' ? (
                <div className="bg-white rounded-lg shadow border border-gray-200 animate-fade-in">
                    <div className="p-4 border-b border-gray-200 bg-gray-50">
                        {/* Header Controls */}
                        <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                            <div className="flex p-1 bg-gray-200 rounded-lg">
                                <button
                                    onClick={() => setListFilter('collected')}
                                    className={`px-4 py-1.5 rounded-md text-sm font-bold transition-all ${
                                        listFilter === 'collected' 
                                        ? 'bg-white text-green-700 shadow-sm' 
                                        : 'text-gray-500 hover:text-gray-700'
                                    }`}
                                >
                                    Sudah Ambil
                                </button>
                                <button
                                    onClick={() => setListFilter('uncollected')}
                                    className={`px-4 py-1.5 rounded-md text-sm font-bold transition-all ${
                                        listFilter === 'uncollected' 
                                        ? 'bg-white text-red-700 shadow-sm' 
                                        : 'text-gray-500 hover:text-gray-700'
                                    }`}
                                >
                                    Belum Ambil
                                </button>
                            </div>

                            <div className="relative w-full md:w-64">
                                <div className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
                                    <div className="icon-search text-sm"></div>
                                </div>
                                <input 
                                    type="text" 
                                    placeholder="Cari Nama / NIK / Satminkal..."
                                    className="w-full pl-9 pr-4 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:ring-1 focus:ring-indigo-500"
                                    value={listSearch}
                                    onChange={(e) => setListSearch(e.target.value)}
                                />
                            </div>
                            
                            {/* Bulk Action Bar */}
                            {selectedListIds.length > 0 && (
                                <div className="animate-slide-in flex items-center gap-4 bg-indigo-50 px-4 py-2 rounded-lg border border-indigo-100 shadow-sm mt-4 md:mt-0">
                                    <div className="text-sm font-bold text-indigo-800 whitespace-nowrap">
                                        {selectedListIds.length} Dipilih
                                    </div>
                                    <button
                                        onClick={handleBulkListAction}
                                        className={`text-xs font-bold px-3 py-1.5 rounded shadow-sm flex items-center gap-2 transition-colors ${
                                            listFilter === 'uncollected'
                                            ? 'bg-green-600 hover:bg-green-700 text-white'
                                            : 'bg-red-600 hover:bg-red-700 text-white'
                                        }`}
                                    >
                                        <div className={`icon-${listFilter === 'uncollected' ? 'check' : 'rotate-ccw'} text-xs`}></div>
                                        {listFilter === 'uncollected' ? 'Ambil Masal' : 'Reset Masal'}
                                    </button>
                                    <button
                                        onClick={() => setSelectedListIds([])}
                                        className="text-gray-400 hover:text-gray-600"
                                    >
                                        <div className="icon-x text-lg"></div>
                                    </button>
                                </div>
                            )}
                        </div>
                    </div>
                    
                    <div className="overflow-x-auto max-h-[600px] overflow-y-auto">
                        <table className="w-full text-sm text-left">
                            <thead className="bg-gray-100 text-gray-600 font-medium sticky top-0 z-10 shadow-sm">
                                <tr>
                                    <th className="px-4 py-3 w-10 text-center">
                                        <input 
                                            type="checkbox"
                                            className="rounded text-indigo-600 focus:ring-indigo-500 w-4 h-4 cursor-pointer"
                                            onChange={(e) => {
                                                const filtered = employeeList.filter(item => 
                                                    (item.nama || '').toLowerCase().includes(listSearch.toLowerCase()) || 
                                                    (item.nik || '').includes(listSearch) ||
                                                    (item.satminkal || '').toLowerCase().includes(listSearch.toLowerCase())
                                                );
                                                handleListSelectAll(e, filtered);
                                            }}
                                            checked={
                                                employeeList.length > 0 && 
                                                selectedListIds.length > 0 && 
                                                employeeList
                                                    .filter(item => 
                                                        (item.nama || '').toLowerCase().includes(listSearch.toLowerCase()) || 
                                                        (item.nik || '').includes(listSearch)
                                                    )
                                                    .every(i => selectedListIds.includes(i.id))
                                            }
                                        />
                                    </th>
                                    <th className="px-4 py-3 w-12">No</th>
                                    {listFilter === 'collected' && <th className="px-6 py-3">Waktu Ambil</th>}
                                    <th className="px-6 py-3">Nama Pegawai</th>
                                    <th className="px-6 py-3">Satminkal</th>
                                    <th className="px-6 py-3 text-right">Aksi</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-200">
                                {loadingList ? (
                                    <tr>
                                        <td colSpan="6" className="px-6 py-8 text-center text-gray-500">
                                            <div className="inline-block animate-spin w-6 h-6 border-2 border-indigo-500 border-t-transparent rounded-full mb-2"></div>
                                            <div>Memuat data...</div>
                                        </td>
                                    </tr>
                                ) : employeeList.length === 0 ? (
                                    <tr>
                                        <td colSpan="6" className="px-6 py-8 text-center text-gray-500">
                                            Tidak ada data {listFilter === 'collected' ? 'yang sudah mengambil' : 'yang belum mengambil'}.
                                        </td>
                                    </tr>
                                ) : (
                                    employeeList
                                        .filter(item => 
                                            (item.nama || '').toLowerCase().includes(listSearch.toLowerCase()) || 
                                            (item.nik || '').includes(listSearch) ||
                                            (item.satminkal || '').toLowerCase().includes(listSearch.toLowerCase())
                                        )
                                        .map((item, index) => (
                                        <tr key={item.id} className={`hover:bg-gray-50 ${selectedListIds.includes(item.id) ? 'bg-indigo-50' : ''}`}>
                                            <td className="px-4 py-3 text-center">
                                                <input 
                                                    type="checkbox"
                                                    className="rounded text-indigo-600 focus:ring-indigo-500 w-4 h-4 cursor-pointer"
                                                    checked={selectedListIds.includes(item.id)}
                                                    onChange={() => handleListSelectOne(item.id)}
                                                />
                                            </td>
                                            <td className="px-4 py-3 text-gray-400 text-xs">{index + 1}</td>
                                            {listFilter === 'collected' && (
                                                <td className="px-6 py-3 text-indigo-700 font-mono text-xs font-medium">
                                                    {item.collected_at ? new Date(item.collected_at).toLocaleString('id-ID', {
                                                        day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit'
                                                    }) : '-'}
                                                </td>
                                            )}
                                            <td className="px-6 py-3">
                                                <div className="font-bold text-gray-800">{item.nama}</div>
                                                <div className="text-xs text-gray-500">{item.nik || '-'}</div>
                                            </td>
                                            <td className="px-6 py-3 text-gray-600">{item.satminkal}</td>
                                            <td className="px-6 py-3 text-right">
                                                {listFilter === 'collected' ? (
                                                    <button 
                                                        onClick={() => {
                                                            Swal.fire({
                                                                title: 'Batalkan Pengambilan?',
                                                                text: `Status pengambilan parsel untuk "${item.nama}" akan direset.`,
                                                                icon: 'warning',
                                                                showCancelButton: true,
                                                                confirmButtonColor: '#d33',
                                                                confirmButtonText: 'Ya, Reset',
                                                                cancelButtonText: 'Batal'
                                                            }).then((res) => {
                                                                if (res.isConfirmed) {
                                                                    handleBatchReset(null, item.id);
                                                                }
                                                            });
                                                        }}
                                                        className="text-red-600 hover:text-red-800 text-xs border border-red-200 bg-red-50 hover:bg-red-100 px-3 py-1.5 rounded transition-colors"
                                                    >
                                                        Batal
                                                    </button>
                                                ) : (
                                                    <button 
                                                        onClick={() => handleManualCollect(item)}
                                                        className="text-green-600 hover:text-green-800 text-xs border border-green-200 bg-green-50 hover:bg-green-100 px-3 py-1.5 rounded transition-colors"
                                                    >
                                                        Ambil Manual
                                                    </button>
                                                )}
                                            </td>
                                        </tr>
                                    ))
                                )}
                                {employeeList.length > 0 && !loadingList && employeeList.filter(item => (item.nama || '').toLowerCase().includes(listSearch.toLowerCase())).length === 0 && (
                                     <tr>
                                        <td colSpan="6" className="px-6 py-8 text-center text-gray-500">
                                            Tidak ditemukan data yang cocok dengan "{listSearch}".
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            ) : (
                <>
            {/* Input Section (Always Visible & Sticky/Prominent in Batch Mode) */}
            <div className={`bg-white p-4 rounded-lg shadow border border-gray-200 mb-6 ${isBatchMode ? 'border-orange-400 ring-2 ring-orange-100' : ''}`}>
                 <form onSubmit={handleFormSubmit} className="flex flex-col md:flex-row gap-4 relative">
                    <div className="flex-1 relative w-full">
                        <div className="absolute left-3 top-3.5 text-gray-400 z-20">
                            <div className={`icon-${isBatchMode ? 'zap' : 'search'} text-lg`}></div>
                        </div>
                        <input 
                            ref={inputRef}
                            type="text" 
                            value={manualInput}
                            onChange={handleInputChange}
                            onFocus={handleInputFocus}
                            className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none text-base md:text-lg font-mono relative z-10"
                            placeholder={isBatchMode ? "Scan Barcode (Auto)..." : "Cari NIK/Nama..."}
                            autoFocus
                            autoComplete="off"
                        />
                        
                        {/* Suggestions Dropdown */}
                        {showSuggestions && suggestions.length > 0 && (
                            <div className="absolute top-full left-0 right-0 bg-white border border-gray-200 shadow-lg rounded-b-lg mt-1 z-50 max-h-60 overflow-y-auto animate-fade-in">
                                {suggestions.map((emp, idx) => (
                                    <div 
                                        key={emp.id}
                                        className={`suggestion-item px-4 py-2 hover:bg-indigo-50 cursor-pointer border-b border-gray-100 last:border-0 flex justify-between items-center group transition-colors ${idx % 2 === 0 ? 'bg-white' : 'bg-gray-50/30'}`}
                                        onClick={() => handleSuggestionClick(emp)}
                                    >
                                        <div>
                                            <div className="font-bold text-gray-800 text-sm group-hover:text-indigo-700 flex items-center gap-2">
                                                {emp.nama}
                                                {emp.is_parcel_collected && (
                                                    <span className="bg-green-100 text-green-700 text-[10px] px-1.5 py-0.5 rounded-full border border-green-200 flex items-center gap-0.5">
                                                        <div className="icon-check text-[10px]"></div> Sudah
                                                    </span>
                                                )}
                                            </div>
                                            <div className="text-xs text-gray-500 flex items-center gap-2">
                                                <span className="font-mono bg-gray-100 px-1 rounded">{emp.nik || 'No NIK'}</span>
                                                <span className="text-gray-400">•</span>
                                                <span>{emp.satminkal}</span>
                                            </div>
                                        </div>
                                        <div className="icon-corner-down-left text-gray-300 group-hover:text-indigo-400 text-sm"></div>
                                    </div>
                                ))}
                            </div>
                        )}

                        {isBatchMode && (
                            <div className="absolute right-3 top-1/2 transform -translate-y-1/2 z-20">
                                <span className="bg-orange-100 text-orange-700 text-xs px-2 py-1 rounded font-bold animate-pulse">
                                    AUTO-ENTER
                                </span>
                            </div>
                        )}
                    </div>
                    {/* Webcam Toggle */}
                    <button 
                        type="button"
                        onClick={() => setScanning(!scanning)}
                        className={`p-3 rounded border transition-colors w-full md:w-auto flex items-center justify-center gap-2 ${
                            scanning 
                            ? 'bg-red-50 border-red-200 text-red-600' 
                            : 'bg-gray-50 border-gray-200 text-gray-600 hover:bg-gray-100'
                        }`}
                        title="Gunakan Kamera"
                    >
                        <div className={`icon-camera${scanning ? '-off' : ''} text-xl`}></div>
                        <span className="md:hidden font-bold">{scanning ? 'Tutup Kamera' : 'Buka Kamera'}</span>
                    </button>
                 </form>

                 
            </div>

            {/* FULL SCREEN SCANNER OVERLAY */}
            {scanning && (
                <div className="fixed inset-0 z-[100] bg-black text-white flex flex-col animate-fade-in">
                    {/* Header */}
                    <div className="flex justify-between items-center p-4 bg-gray-900 border-b border-gray-800">
                        <div>
                            <h2 className="text-lg font-bold text-white flex items-center gap-2">
                                <div className="icon-scan-line text-green-400"></div>
                                Scan Kamera
                            </h2>
                            <p className="text-xs text-gray-400">
                                {isBatchMode ? 'Mode Cepat: Scan berturut-turut' : 'Mode Detail: Scan untuk info'}
                            </p>
                        </div>
                        <button 
                            onClick={() => setScanning(false)}
                            className="bg-red-600 hover:bg-red-700 text-white p-2 rounded-full transition-colors"
                        >
                            <div className="icon-x text-2xl"></div>
                        </button>
                    </div>
                    
                    {/* Scanner Area */}
                    <div className="flex-1 bg-black relative flex items-center justify-center overflow-hidden">
                         <div id="reader" className="w-full h-full max-w-lg mx-auto bg-black"></div>
                         
                         {/* Overlay Lines */}
                         <div className="absolute inset-0 pointer-events-none flex items-center justify-center">
                            <div className="w-64 h-64 border-2 border-green-500/50 rounded-lg relative">
                                <div className="absolute top-0 left-0 w-8 h-8 border-t-4 border-l-4 border-green-500 -mt-0.5 -ml-0.5"></div>
                                <div className="absolute top-0 right-0 w-8 h-8 border-t-4 border-r-4 border-green-500 -mt-0.5 -mr-0.5"></div>
                                <div className="absolute bottom-0 left-0 w-8 h-8 border-b-4 border-l-4 border-green-500 -mb-0.5 -ml-0.5"></div>
                                <div className="absolute bottom-0 right-0 w-8 h-8 border-b-4 border-r-4 border-green-500 -mb-0.5 -mr-0.5"></div>
                                <div className="absolute top-1/2 left-0 right-0 h-0.5 bg-red-500 opacity-50"></div>
                            </div>
                         </div>
                    </div>

                    {/* Results / History List (Bottom Sheet) */}
                    <div className="h-1/3 bg-gray-900 border-t border-gray-800 flex flex-col">
                        <div className="p-2 px-4 bg-gray-800 border-b border-gray-700 flex justify-between items-center">
                            <span className="text-sm font-bold text-gray-300">Hasil Scan Terakhir</span>
                            <span className="text-xs text-gray-500">{batchLog.length} item</span>
                        </div>
                        <div className="flex-1 overflow-y-auto p-2 space-y-2">
                             {batchLog.length === 0 ? (
                                <div className="text-center text-gray-600 py-8 text-sm">Belum ada scan sesi ini.</div>
                             ) : (
                                batchLog.slice(0, 10).map((log) => (
                                    <div key={log.id} className={`p-3 rounded border flex justify-between items-center ${
                                        log.status === 'success' ? 'bg-green-900/20 border-green-800' :
                                        log.status === 'error' ? 'bg-red-900/20 border-red-800' :
                                        log.status === 'warning' ? 'bg-yellow-900/20 border-yellow-800' : 
                                        'bg-gray-800 border-gray-700 opacity-50'
                                    }`}>
                                        <div className="overflow-hidden">
                                            <div className={`font-bold text-sm truncate ${
                                                log.status === 'success' ? 'text-green-400' :
                                                log.status === 'error' ? 'text-red-400' :
                                                log.status === 'warning' ? 'text-yellow-400' : 'text-gray-400'
                                            }`}>
                                                {log.empName}
                                            </div>
                                            <div className="text-xs text-gray-400 truncate font-medium mb-0.5">
                                                {log.empSatminkal || '-'}
                                            </div>
                                            <div className="text-xs text-gray-500 flex gap-2">
                                                <span className="font-mono">{log.time}</span>
                                                <span>•</span>
                                                <span className="truncate">{log.msg || log.status}</span>
                                            </div>
                                        </div>
                                        {log.status === 'success' && (
                                            <button 
                                                onClick={() => handleBatchReset(log.id, log.empId)}
                                                className="text-red-400 hover:text-red-300 px-2 py-1 text-xs border border-red-900/50 rounded bg-red-900/20"
                                            >
                                                Batal
                                            </button>
                                        )}
                                    </div>
                                ))
                             )}
                        </div>
                    </div>
                </div>
            )}

            {/* Content Area */}
            {isBatchMode ? (
                // --- BATCH LOG VIEW ---
                <div className="bg-white rounded-lg shadow border border-gray-200 min-h-[200px] md:min-h-[400px] flex flex-col transition-all">
                    <div className="p-3 md:p-4 border-b border-gray-200 bg-orange-50 flex flex-col md:flex-row justify-between items-start md:items-center gap-2">
                        <h3 className="font-bold text-orange-800 flex items-center gap-2 text-sm md:text-base">
                            <div className="icon-list"></div>
                            Antrian Scan Sesi Ini
                        </h3>
                        <div className="text-[10px] md:text-xs text-orange-600 italic">
                            Data diproses otomatis.
                        </div>
                    </div>
                    <div className="flex-1 overflow-auto max-h-[300px] md:max-h-[500px]">
                        {batchLog.length === 0 ? (
                            <div className="h-full flex flex-col items-center justify-center text-gray-400 p-6 min-h-[150px]">
                                <div className="icon-zap text-3xl mb-1 opacity-30"></div>
                                <p className="text-sm font-medium">Belum ada data discan.</p>
                                <p className="text-xs text-center mt-1">Siap untuk scan cepat.</p>
                            </div>
                        ) : (
                            <table className="w-full text-sm text-left">
                                <thead className="bg-gray-50 text-gray-500 sticky top-0 z-10">
                                    <tr>
                                        <th className="px-3 py-2 w-20 hidden md:table-cell">Waktu</th>
                                        <th className="px-3 py-2 w-28 hidden sm:table-cell">Input/NIK</th>
                                        <th className="px-3 py-2">Nama</th>
                                        <th className="px-3 py-2 hidden lg:table-cell">Satminkal</th>
                                        <th className="px-3 py-2 w-24">Status</th>
                                        <th className="px-3 py-2 hidden xl:table-cell">Ket</th>
                                        <th className="px-3 py-2 w-16 text-right">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100">
                                    {batchLog.map((log) => (
                                        <tr key={log.id} className={`
                                            ${log.status === 'success' ? 'bg-green-50/50' : log.status === 'error' ? 'bg-red-50/50' : log.status === 'cancelled' ? 'bg-gray-100 opacity-75' : 'bg-yellow-50'} 
                                            transition-colors animate-slide-in
                                        `}>
                                            <td className="px-3 py-2 text-gray-500 font-mono text-xs hidden md:table-cell">{log.time}</td>
                                            <td className="px-3 py-2 font-mono text-gray-700 text-xs hidden sm:table-cell">{log.key}</td>
                                            <td className="px-3 py-2">
                                                <div className="font-bold text-gray-800 text-sm md:text-base leading-tight">{log.empName}</div>
                                                <div className="text-[10px] text-gray-500 md:hidden mt-0.5">{log.empSatminkal}</div>
                                            </td>
                                            <td className="px-3 py-2 text-gray-600 text-sm hidden lg:table-cell">{log.empSatminkal}</td>
                                            <td className="px-3 py-2">
                                                {log.status === 'success' && <span className="text-green-600 font-bold flex items-center gap-1 text-xs"><div className="icon-check text-xs"></div> OK</span>}
                                                {log.status === 'error' && <span className="text-red-600 font-bold flex items-center gap-1 text-xs"><div className="icon-x text-xs"></div> Gagal</span>}
                                                {log.status === 'warning' && <span className="text-yellow-600 font-bold flex items-center gap-1 text-xs"><div className="icon-triangle-alert text-xs"></div> Cek</span>}
                                                {log.status === 'cancelled' && <span className="text-gray-500 font-bold flex items-center gap-1 text-xs"><div className="icon-slash text-xs"></div> Batal</span>}
                                            </td>
                                            <td className="px-3 py-2 text-gray-600 text-xs hidden xl:table-cell">{log.msg}</td>
                                            <td className="px-3 py-2 text-right">
                                                {log.status === 'success' && (
                                                    <button 
                                                        onClick={() => handleBatchReset(log.id, log.empId)}
                                                        className="text-red-500 hover:text-red-700 bg-white border border-red-200 hover:bg-red-50 px-2 py-1 rounded text-xs transition-colors"
                                                        title="Batalkan Pengambilan"
                                                    >
                                                        Reset
                                                    </button>
                                                )}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        )}
                    </div>
                </div>
            ) : (
                // --- NORMAL SINGLE VIEW ---
                <div className="bg-white rounded-lg shadow border border-gray-200 min-h-[120px]">
                    {loading ? (
                        <div className="h-full flex flex-col items-center justify-center p-4">
                            <div className="animate-spin w-6 h-6 border-2 border-indigo-500 border-t-transparent rounded-full mb-2"></div>
                            <p className="text-gray-500 text-xs">Mencari data...</p>
                        </div>
                    ) : !employee ? (
                        <div className="h-full flex flex-col items-center justify-center text-gray-400 p-4 min-h-[120px]">
                            <div className="icon-scan-line text-3xl mb-1 opacity-40"></div>
                            <p className="text-sm font-medium">Siap Memindai</p>
                        </div>
                    ) : (
                        <div className={`flex flex-col h-full rounded-lg overflow-hidden border-t-8 ${employee.is_parcel_collected ? 'border-green-500' : 'border-indigo-500'}`}>
                            <div className="p-4 md:p-8 flex-1">
                                <div className="flex flex-col md:flex-row justify-between items-start mb-6 gap-4">
                                    <div>
                                        <h2 className="text-2xl md:text-3xl font-bold text-gray-800 leading-tight">{employee.nama}</h2>
                                        <p className="text-base md:text-lg text-gray-500 mt-1">{employee.jabatan || 'Tanpa Jabatan'}</p>
                                    </div>
                                    <div className="self-start md:self-auto">
                                        {employee.is_parcel_collected ? (
                                            <div className="bg-green-100 text-green-800 px-4 py-1 rounded-full font-bold inline-flex items-center gap-2 text-xs md:text-sm">
                                                <div className="icon-circle-check"></div> SUDAH
                                            </div>
                                        ) : (
                                            <div className="bg-gray-100 text-gray-600 px-4 py-1 rounded-full font-bold inline-flex items-center gap-2 text-xs md:text-sm">
                                                <div className="icon-clock"></div> BELUM
                                            </div>
                                        )}
                                    </div>
                                </div>

                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-6 mb-8">
                                    <div className="bg-gray-50 p-3 md:p-4 rounded-lg">
                                        <label className="text-xs font-bold text-gray-400 uppercase">NIK</label>
                                        <div className="text-lg md:text-xl font-mono text-gray-800 break-all">{employee.nik || '-'}</div>
                                    </div>
                                    <div className="bg-gray-50 p-3 md:p-4 rounded-lg">
                                        <label className="text-xs font-bold text-gray-400 uppercase">Satminkal</label>
                                        <div className="text-lg md:text-xl text-gray-800">{employee.satminkal}</div>
                                    </div>
                                </div>

                                {/* Action Buttons */}
                                <div className="mt-8">
                                    {employee.is_parcel_collected ? (
                                        <div className="w-full py-4 bg-red-50 border-2 border-red-200 rounded-lg flex flex-col items-center justify-center text-red-800 gap-1">
                                            <div className="flex items-center gap-2 text-xl font-bold">
                                                <div className="icon-x-circle"></div>
                                                SUDAH DIAMBIL
                                            </div>
                                            <div className="text-sm text-red-600">
                                                Pada: {new Date(employee.collected_at).toLocaleString('id-ID', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' })}
                                            </div>
                                            
                                            {/* Correction Link (Small) */}
                                            <button 
                                                onClick={handleCancelCollection}
                                                className="mt-4 text-xs text-gray-400 hover:text-red-600 underline flex items-center gap-1 transition-colors"
                                                title="Batalkan status pengambilan (Koreksi)"
                                            >
                                                <div className="icon-rotate-ccw text-[10px]"></div>
                                                Koreksi Status (Reset)
                                            </button>
                                        </div>
                                    ) : (
                                        <button 
                                            ref={collectBtnRef}
                                            onClick={handleCollect}
                                            disabled={!employee.is_active}
                                            className={`w-full py-4 rounded-lg shadow-lg text-white font-bold text-xl flex items-center justify-center gap-3 transition-transform active:scale-95 focus:ring-4 focus:ring-indigo-300 outline-none ${
                                                employee.is_active ? 'bg-indigo-600 hover:bg-indigo-700' : 'bg-gray-400 cursor-not-allowed'
                                            }`}
                                        >
                                            <div className="icon-package text-2xl"></div>
                                            {employee.is_active ? 'SERAHKAN PARSEL (ENTER)' : 'PEGAWAI NON-AKTIF'}
                                        </button>
                                    )}
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            )}
            </>
            )}

            {/* History List for Normal Mode (Always visible at bottom) */}
            {!isBatchMode && batchLog.length > 0 && (
                <div className="mt-8 bg-white rounded-lg shadow border border-gray-200 overflow-hidden">
                    <div className="p-4 bg-gray-50 border-b border-gray-200 flex justify-between items-center">
                        <h3 className="font-bold text-gray-700 flex items-center gap-2">
                            <div className="icon-history text-gray-500"></div>
                            Riwayat Pengambilan Terakhir
                        </h3>
                    </div>
                    <div className="overflow-x-auto">
                        <table className="w-full text-sm text-left">
                            <thead className="bg-gray-50 text-gray-500">
                                <tr>
                                    <th className="px-4 py-2">Waktu</th>
                                    <th className="px-4 py-2">Nama</th>
                                    <th className="px-4 py-2">Satminkal</th>
                                    <th className="px-4 py-2 text-right">Aksi</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-100">
                                {batchLog.filter(l => l.status !== 'cancelled').slice(0, 5).map(log => (
                                    <tr key={log.id} className="hover:bg-gray-50">
                                        <td className="px-4 py-2 text-gray-500 text-xs font-mono">{log.time}</td>
                                        <td className="px-4 py-2 font-bold text-gray-700">{log.empName}</td>
                                        <td className="px-4 py-2 text-gray-600 text-xs">{log.empSatminkal}</td>
                                        <td className="px-4 py-2 text-right">
                                            <button 
                                                onClick={() => handleBatchReset(log.id, log.empId)}
                                                className="text-red-500 hover:text-red-700 text-xs font-medium border border-red-100 hover:bg-red-50 px-2 py-1 rounded"
                                            >
                                                Batal
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                        {batchLog.filter(l => l.status !== 'cancelled').length > 5 && (
                            <div className="p-2 text-center text-xs text-gray-400 bg-gray-50">
                                ... dan {batchLog.filter(l => l.status !== 'cancelled').length - 5} data lainnya (Lihat Mode Scan Cepat untuk lengkapnya)
                            </div>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
}