{{-- resources/views/petugas/pasien/index.blade.php --}}
<x-app-layout>
    <x-slot name="header">
        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <div>
                <h2 class="font-semibold text-xl md:text-2xl text-white leading-tight">
                    {{ __('Daftar Pasien') }}
                </h2>
                <p class="text-teal-100 text-sm mt-1">Kelola data pasien klinik</p>
            </div>
            <a href="{{ route('petugas.pasien.create') }}" 
               class="inline-flex items-center px-4 py-2 bg-white text-teal-600 border border-transparent rounded-lg font-semibold text-xs uppercase tracking-widest hover:bg-teal-50 focus:bg-teal-50 active:bg-teal-100 focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2 transition ease-in-out duration-150 transform hover:-translate-y-0.5 shadow-md hover:shadow-lg w-full sm:w-auto justify-center">
                <i class="fas fa-plus mr-2"></i> Tambah Pasien
            </a>
        </div>
    </x-slot>

    <div class="py-6 md:py-8">
        <div class="max-w-7xl mx-auto px-3 sm:px-4 lg:px-6">
            <!-- Alert Messages -->
            @if(session('success'))
            <div class="mb-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 text-green-800 dark:text-green-200 px-4 py-3 rounded-lg flex items-start" role="alert">
                <i class="fas fa-check-circle mt-0.5 mr-3 text-green-500"></i>
                <div class="flex-1">
                    <p class="font-medium">Berhasil!</p>
                    <p class="text-sm">{{ session('success') }}</p>
                </div>
                <button onclick="this.parentElement.remove()" class="ml-4 text-green-500 hover:text-green-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            @endif

            @if(session('error'))
            <div class="mb-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-800 dark:text-red-200 px-4 py-3 rounded-lg flex items-start" role="alert">
                <i class="fas fa-exclamation-circle mt-0.5 mr-3 text-red-500"></i>
                <div class="flex-1">
                    <p class="font-medium">Error!</p>
                    <p class="text-sm">{{ session('error') }}</p>
                </div> 
                <button onclick="this.parentElement.remove()" class="ml-4 text-red-500 hover:text-red-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            @endif

            <!-- Quick Stats Cards -->
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 mb-6">
                <!-- Total Pasien Card -->
                <div class="bg-white dark:bg-slate-800 p-4 rounded-xl shadow-sm border border-gray-200 dark:border-slate-700 hover:shadow-md transition-shadow duration-200">
                    <div class="flex items-center">
                        <div class="p-2.5 sm:p-3 rounded-xl bg-gradient-to-br from-teal-50 to-teal-100 dark:from-teal-900/20 dark:to-teal-900/10 mr-3 sm:mr-4">
                            <i class="fas fa-users text-teal-600 dark:text-teal-400 text-lg sm:text-xl"></i>
                        </div>
                        <div class="flex-1 min-w-0">
                            <p class="text-xs sm:text-sm font-medium text-gray-600 dark:text-gray-400 truncate">Total Pasien</p>
                            <p id="totalPasien" class="text-xl sm:text-2xl font-bold text-gray-900 dark:text-white truncate">-</p>
                        </div>
                    </div>
                    <div class="mt-2 pt-2 border-t border-gray-100 dark:border-slate-700">
                        <div class="text-xs text-gray-500 dark:text-gray-400 flex items-center">
                            <i class="fas fa-calendar-alt mr-1 text-gray-400"></i>
                            Update real-time
                        </div>
                    </div>
                </div>

                <!-- Wajah Terdaftar Card -->
                <div class="bg-white dark:bg-slate-800 p-4 rounded-xl shadow-sm border border-gray-200 dark:border-slate-700 hover:shadow-md transition-shadow duration-200">
                    <div class="flex items-center">
                        <div class="p-2.5 sm:p-3 rounded-xl bg-gradient-to-br from-green-50 to-green-100 dark:from-green-900/20 dark:to-green-900/10 mr-3 sm:mr-4">
                            <i class="fas fa-check-circle text-green-600 dark:text-green-400 text-lg sm:text-xl"></i>
                        </div>
                        <div class="flex-1 min-w-0">
                            <p class="text-xs sm:text-sm font-medium text-gray-600 dark:text-gray-400 truncate">Wajah Terdaftar</p>
                            <p id="wajahTerdaftar" class="text-xl sm:text-2xl font-bold text-gray-900 dark:text-white truncate">-</p>
                        </div>
                    </div>
                    <div class="mt-2 pt-2 border-t border-gray-100 dark:border-slate-700">
                        <div class="text-xs text-gray-500 dark:text-gray-400 flex items-center">
                            <i class="fas fa-camera mr-1 text-gray-400"></i>
                            Biometrik terdaftar
                        </div>
                    </div>
                </div>

                <!-- Pasien Aktif Card -->
                <div class="bg-white dark:bg-slate-800 p-4 rounded-xl shadow-sm border border-gray-200 dark:border-slate-700 hover:shadow-md transition-shadow duration-200">
                    <div class="flex items-center">
                        <div class="p-2.5 sm:p-3 rounded-xl bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-900/20 dark:to-blue-900/10 mr-3 sm:mr-4">
                            <i class="fas fa-heartbeat text-blue-600 dark:text-blue-400 text-lg sm:text-xl"></i>
                        </div>
                        <div class="flex-1 min-w-0">
                            <p class="text-xs sm:text-sm font-medium text-gray-600 dark:text-gray-400 truncate">Pasien Aktif</p>
                            <p id="pasienAktif" class="text-xl sm:text-2xl font-bold text-gray-900 dark:text-white truncate">-</p>
                        </div>
                    </div>
                    <div class="mt-2 pt-2 border-t border-gray-100 dark:border-slate-700">
                        <div class="text-xs text-gray-500 dark:text-gray-400 flex items-center">
                            <i class="fas fa-stethoscope mr-1 text-gray-400"></i>
                            Dalam perawatan
                        </div>
                    </div>
                </div>

                <!-- Belum Terdaftar Card -->
                <div class="bg-white dark:bg-slate-800 p-4 rounded-xl shadow-sm border border-gray-200 dark:border-slate-700 hover:shadow-md transition-shadow duration-200">
                    <div class="flex items-center">
                        <div class="p-2.5 sm:p-3 rounded-xl bg-gradient-to-br from-yellow-50 to-yellow-100 dark:from-yellow-900/20 dark:to-yellow-900/10 mr-3 sm:mr-4">
                            <i class="fas fa-exclamation-circle text-yellow-600 dark:text-yellow-400 text-lg sm:text-xl"></i>
                        </div>
                        <div class="flex-1 min-w-0">
                            <p class="text-xs sm:text-sm font-medium text-gray-600 dark:text-gray-400 truncate">Belum Terdaftar</p>
                            <p id="wajahBelum" class="text-xl sm:text-2xl font-bold text-gray-900 dark:text-white truncate">-</p>
                        </div>
                    </div>
                    <div class="mt-2 pt-2 border-t border-gray-100 dark:border-slate-700">
                        <div class="text-xs text-gray-500 dark:text-gray-400 flex items-center">
                            <i class="fas fa-clock mr-1 text-gray-400"></i>
                            Butuh verifikasi
                        </div>
                    </div>
                </div>
            </div>

            <!-- Main Card -->
            <div class="bg-white dark:bg-slate-800 overflow-hidden shadow-xl sm:rounded-lg">
                <div class="p-4 sm:p-6">
                    
                    <!-- Filters Card -->
                    <div class="mb-4 sm:mb-6 bg-gradient-to-br from-gray-50 to-gray-100 dark:from-slate-700 dark:to-slate-800 p-4 sm:p-5 rounded-xl border border-gray-200 dark:border-slate-600 shadow-sm">
                        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-4">
                            <h3 class="text-base sm:text-lg font-semibold text-gray-800 dark:text-gray-200 flex items-center">
                                <i class="fas fa-filter mr-2 text-teal-500 text-sm sm:text-base"></i>
                                Filter Data
                            </h3>
                            <span id="filterBadge" class="hidden px-3 py-1.5 bg-teal-100 dark:bg-teal-900 text-teal-800 dark:text-teal-200 rounded-full text-xs font-medium">
                                <i class="fas fa-check mr-1.5"></i> Filter Aktif
                            </span>
                        </div>
                        
                        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
                            <!-- Status Pasien Filter -->
                            <div>
                                <label class="block text-xs sm:text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5 sm:mb-2">
                                    <i class="fas fa-heartbeat mr-1.5 text-teal-500 text-xs sm:text-sm"></i>
                                    Status Pasien
                                </label>
                                <select id="statusFilter" 
                                        class="w-full text-xs sm:text-sm border-gray-300 dark:border-slate-600 dark:bg-slate-700 dark:text-white rounded-lg shadow-sm focus:border-teal-500 focus:ring-teal-500 transition-all duration-200 px-3 py-2">
                                    <option value="">Semua Status</option>
                                    <option value="AKTIF">Aktif</option>
                                    <option value="NONAKTIF">Nonaktif</option>
                                    <option value="MENINGGAL">Meninggal</option>
                                </select>
                            </div>

                            <!-- Wajah Terdaftar Filter -->
                            <div>
                                <label class="block text-xs sm:text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5 sm:mb-2">
                                    <i class="fas fa-camera mr-1.5 text-teal-500 text-xs sm:text-sm"></i>
                                    Wajah Terdaftar
                                </label>
                                <select id="wajahFilter" 
                                        class="w-full text-xs sm:text-sm border-gray-300 dark:border-slate-600 dark:bg-slate-700 dark:text-white rounded-lg shadow-sm focus:border-teal-500 focus:ring-teal-500 transition-all duration-200 px-3 py-2">
                                    <option value="">Semua Status</option>
                                    <option value="1">Sudah Terdaftar</option>
                                    <option value="0">Belum Terdaftar</option>
                                </select>
                            </div>

                            <!-- Reset Button -->
                            <div class="flex items-end">
                                <button id="resetFilters" 
                                        class="w-full px-4 py-2.5 text-xs sm:text-sm bg-gradient-to-r from-gray-200 to-gray-300 dark:from-slate-600 dark:to-slate-700 text-gray-700 dark:text-gray-300 rounded-lg hover:from-gray-300 hover:to-gray-400 dark:hover:from-slate-500 dark:hover:to-slate-600 transition-all duration-200 flex items-center justify-center font-medium shadow-sm hover:shadow-md transform hover:-translate-y-0.5">
                                    <i class="fas fa-redo mr-2"></i> Reset Filter
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Table Container -->
                    <div class="overflow-x-auto rounded-xl border border-gray-200 dark:border-slate-700 shadow-sm">
                        <table id="pasienTable" class="w-full table-auto display responsive nowrap" style="width:100%">
                            <thead class="bg-gradient-to-r from-gray-50 to-gray-100 dark:from-slate-700 dark:to-slate-800">
                                <tr>
                                    <th class="px-3 sm:px-4 py-3 text-left text-xs font-bold text-gray-600 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                        No. RM
                                    </th>
                                    <th class="px-3 sm:px-4 py-3 text-left text-xs font-bold text-gray-600 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                        Nama Lengkap
                                    </th>
                                    <th class="px-3 sm:px-4 py-3 text-left text-xs font-bold text-gray-600 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                        Jenis Kelamin
                                    </th>
                                    <th class="px-3 sm:px-4 py-3 text-left text-xs font-bold text-gray-600 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                        Usia
                                    </th>
                                    <th class="px-3 sm:px-4 py-3 text-left text-xs font-bold text-gray-600 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                        Telepon
                                    </th>
                                    <th class="px-3 sm:px-4 py-3 text-left text-xs font-bold text-gray-600 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                        Wajah
                                    </th>
                                    <th class="px-3 sm:px-4 py-3 text-center text-xs font-bold text-gray-600 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                        Aksi
                                    </th>
                                </tr>
                            </thead>
                            <tbody class="bg-white dark:bg-slate-800 divide-y divide-gray-200 dark:divide-slate-700">
                                <!-- Data akan diisi oleh DataTables -->
                            </tbody>
                        </table>
                    </div>

                    <!-- Info Stats -->
                    <div class="mt-4 sm:mt-6 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 text-xs sm:text-sm text-gray-600 dark:text-gray-400">
                        <div class="flex items-center">
                            <i class="fas fa-info-circle text-teal-500 mr-2 text-xs sm:text-sm"></i>
                            <span id="tableInfo" class="font-medium">Memuat data...</span>
                        </div>
                        <div class="flex flex-wrap items-center gap-2 sm:gap-3 w-full sm:w-auto">
                            <span id="filterInfo" class="text-xs"></span>
                            <button id="exportBtn" 
                                    class="inline-flex items-center px-3 sm:px-4 py-2 border border-teal-300 dark:border-teal-600 text-teal-600 dark:text-teal-400 rounded-lg hover:bg-teal-50 dark:hover:bg-teal-900/20 transition-all duration-200 font-medium shadow-sm hover:shadow-md transform hover:-translate-y-0.5 text-xs sm:text-sm">
                                <i class="fas fa-download mr-2 text-xs sm:text-sm"></i> Ekspor Data
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @push('styles')
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.4.1/css/responsive.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css">
    
    <style>
        /* DataTables Custom Styling */
        .dataTables_wrapper {
            @apply text-gray-700 dark:text-gray-300;
        }
        
        .dataTables_wrapper .dataTables_length select,
        .dataTables_wrapper .dataTables_filter input {
            @apply border-gray-300 dark:border-slate-600 dark:bg-slate-700 dark:text-white rounded-lg focus:border-teal-500 focus:ring-teal-500 transition-all;
        }

        .dataTables_wrapper .dataTables_filter input {
            @apply px-4 py-2 pl-10 shadow-sm;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button {
            @apply px-3 py-2 rounded-lg border border-gray-300 dark:border-slate-600 text-gray-700 dark:text-gray-300 hover:bg-teal-50 dark:hover:bg-slate-700 transition-all mx-1;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button.current {
            @apply bg-teal-500 text-white border-teal-500 hover:bg-teal-600 dark:hover:bg-teal-600;
        }

        .dataTables_wrapper .dataTables_paginate .paginate_button.disabled {
            @apply opacity-50 cursor-not-allowed;
        }
        
        #pasienTable tbody tr {
            transition: all 0.2s ease;
        }
        
        #pasienTable tbody tr:hover {
            @apply bg-teal-50 dark:bg-slate-700;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(20, 184, 166, 0.1);
        }
        
        .dark #pasienTable tbody tr:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        }
        
        /* Button animations */
        .action-btn {
            transition: all 0.2s ease;
            min-width: 2rem;
            min-height: 2rem;
        }
        
        .action-btn:hover {
            transform: translateY(-2px) scale(1.1);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        /* Responsive action buttons - wrap on small screens */
        td .flex.flex-wrap {
            gap: 0.25rem;
        }

        @media (max-width: 640px) {
            .action-btn {
                width: 1.75rem !important;
                height: 1.75rem !important;
                min-width: 1.75rem;
                min-height: 1.75rem;
                font-size: 0.65rem;
            }
        }

        /* Loading spinner */
        .dataTables_processing {
            @apply bg-white dark:bg-slate-800 rounded-lg shadow-lg p-4;
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .dataTables_wrapper .dataTables_length,
            .dataTables_wrapper .dataTables_filter {
                @apply mb-4;
            }
        }

        /* Search icon */
        .dataTables_filter {
            position: relative;
        }

        .dataTables_filter::before {
            content: "\f002";
            font-family: "Font Awesome 6 Free";
            font-weight: 900;
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
            pointer-events: none;
        }
    </style>
    @endpush

    @push('scripts')
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.4.1/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        $(document).ready(function() {
            console.log('🚀 Initializing DataTables...');
            
            // Initialize DataTable with improved configuration
            let table = $('#pasienTable').DataTable({
                processing: true,
                serverSide: true,
                responsive: true,
                ajax: {
                    url: "{{ route('petugas.pasien.datatables') }}",
                    type: 'GET',
                    data: function (d) {
                        // PERBAIKAN: Kirim parameter filter dengan benar
                        d.status_pasien = $('#statusFilter').val();
                        d.wajah_terdaftar = $('#wajahFilter').val();
                        console.log('📤 Sending data:', {
                            status_pasien: d.status_pasien,
                            wajah_terdaftar: d.wajah_terdaftar,
                            search: d.search ? d.search.value : ''
                        });
                    },
                    error: function(xhr, error, thrown) {
                        console.error('❌ DataTables Error:', error, thrown);
                        console.error('Response:', xhr.responseText);
                        
                        Swal.fire({
                            title: 'Error Memuat Data!',
                            html: `<div class="text-left">
                                <p class="mb-2">Gagal memuat data pasien.</p>
                                <p class="text-sm text-gray-600">Status: ${xhr.status}</p>
                                <p class="text-sm text-gray-600">Error: ${error}</p>
                                <p class="text-xs text-gray-500 mt-2">Silakan cek console untuk detail.</p>
                            </div>`,
                            icon: 'error',
                            confirmButtonColor: '#14b8a6',
                            background: document.documentElement.classList.contains('dark') ? '#1e293b' : '#fff',
                            color: document.documentElement.classList.contains('dark') ? '#fff' : '#000',
                        });
                    },
                    dataSrc: function(json) {
                        console.log('📥 Received data:', json);
                        updateQuickStats(json);
                        return json.data;
                    }
                },
                columns: [
                    { 
                        data: 'no_rekam_medis_formatted', 
                        name: 'no_rekam_medis',
                        className: 'font-mono text-xs sm:text-sm',
                        responsivePriority: 2
                    },
                    { 
                        data: 'nama_lengkap', 
                        name: 'nama_lengkap',
                        className: 'font-medium text-xs sm:text-sm',
                        responsivePriority: 1
                    },
                    { 
                        data: 'jenis_kelamin_formatted', 
                        name: 'jenis_kelamin',
                        orderable: false,
                        className: 'text-xs sm:text-sm',
                        responsivePriority: 5
                    },
                    { 
                        data: 'usia_formatted', 
                        name: 'usia',
                        orderable: false,
                        className: 'text-xs sm:text-sm',
                        responsivePriority: 4
                    },
                    { 
                        data: 'no_telepon', 
                        name: 'no_telepon',
                        orderable: false,
                        className: 'text-xs sm:text-sm font-mono',
                        responsivePriority: 6
                    },
                    { 
                        data: 'wajah_terdaftar_formatted', 
                        name: 'wajah_terdaftar',
                        orderable: false,
                        className: 'text-center text-xs sm:text-sm',
                        responsivePriority: 3
                    },
                    { 
                        data: 'aksi', 
                        name: 'aksi', 
                        orderable: false, 
                        searchable: false,
                        className: 'text-center',
                        responsivePriority: 1
                    }
                ],
                language: {
                    processing: '<div class="flex items-center justify-center"><i class="fas fa-spinner fa-spin mr-2 text-teal-500"></i> <span class="font-medium">Memuat data...</span></div>',
                    lengthMenu: "Tampilkan _MENU_ data per halaman",
                    zeroRecords: '<div class="text-center py-8"><i class="fas fa-inbox text-gray-400 text-4xl mb-3"></i><p class="text-gray-600 dark:text-gray-400 font-medium">Data tidak ditemukan</p><p class="text-sm text-gray-500">Coba ubah filter atau kata kunci pencarian</p></div>',
                    info: "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
                    infoEmpty: "Menampilkan 0 sampai 0 dari 0 data",
                    infoFiltered: "(disaring dari _MAX_ total data)",
                    search: "",
                    searchPlaceholder: "Cari nama, NIK, no. RM...",
                    paginate: {
                        first: '<i class="fas fa-angle-double-left"></i>',
                        last: '<i class="fas fa-angle-double-right"></i>',
                        next: '<i class="fas fa-chevron-right"></i>',
                        previous: '<i class="fas fa-chevron-left"></i>'
                    }
                },
                pageLength: 10,
                lengthMenu: [[5, 10, 25, 50, 100, -1], [5, 10, 25, 50, 100, "Semua"]],
                order: [[0, 'desc']], // Sort by No. RM descending
                dom: '<"flex flex-col sm:flex-row justify-between items-start sm:items-center mb-4 gap-3"lf>rt<"flex flex-col sm:flex-row justify-between items-center mt-4 gap-3"ip>',
                drawCallback: function() {
                    // Initialize tooltips
                    $('[data-bs-toggle="tooltip"]').each(function() {
                        if (this._bsTooltip) this._bsTooltip.dispose?.();
                        this._bsTooltip = new bootstrap.Tooltip(this);
                    });
                    
                    updateTableInfo(this.api());
                },
                initComplete: function() {
                    console.log('✅ DataTables initialized successfully');
                    
                    // Style search input
                    $('.dataTables_filter input')
                        .addClass('px-4 py-2 pl-10 border rounded-lg w-full sm:w-64 text-xs sm:text-sm')
                        .attr('placeholder', 'Cari nama, NIK, no. RM...');
                    
                    // Style length select
                    $('.dataTables_length select')
                        .addClass('px-3 py-2 border rounded-lg text-xs sm:text-sm');
                    
                    updateTableInfo(this.api());
                    showToast('Data berhasil dimuat', 'success');
                }
            });

            // PERBAIKAN: Filter events - reload table setiap filter berubah
            $('#statusFilter, #wajahFilter').on('change', function() {
                const statusVal = $('#statusFilter').val();
                const wajahVal = $('#wajahFilter').val();
                
                console.log('🔍 Filtering:', { 
                    status: statusVal || '(kosong/semua)', 
                    wajah: wajahVal || '(kosong/semua)'
                });
                
                table.ajax.reload(null, false); // false = keep current page
                updateFilterInfo();
                showFilterBadge();
                showToast('Filter diterapkan', 'info');
            });

            // Reset filters
            $('#resetFilters').on('click', function() {
                console.log('🔄 Resetting filters');
                
                $('#statusFilter').val('');
                $('#wajahFilter').val('');
                table.ajax.reload(null, false);
                updateFilterInfo();
                hideFilterBadge();
                showToast('Filter direset', 'success');
            });

            // Update table info
            function updateTableInfo(api) {
                const info = api.page.info();
                const text = `Menampilkan ${info.start + 1} sampai ${info.end} dari ${info.recordsTotal} data`;
                $('#tableInfo').text(text);
            }

            // Update filter info
            function updateFilterInfo() {
                let filterText = '';
                const statusFilter = $('#statusFilter').val();
                const wajahFilter = $('#wajahFilter').val();
                
                if (statusFilter) {
                    let statusText = $('#statusFilter option:selected').text();
                    filterText += `<span class="inline-flex items-center bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 px-3 py-1 rounded-full text-xs font-medium mr-2"><i class="fas fa-filter mr-1"></i>${statusText}</span>`;
                }
                
                if (wajahFilter) {
                    let wajahText = $('#wajahFilter option:selected').text();
                    let colorClass = wajahFilter === '1' 
                        ? 'bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200' 
                        : 'bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200';
                    filterText += `<span class="inline-flex items-center ${colorClass} px-3 py-1 rounded-full text-xs font-medium"><i class="fas fa-camera mr-1"></i>${wajahText}</span>`;
                }
                
                $('#filterInfo').html(filterText);
            }

            // Show/hide filter badge
            function showFilterBadge() {
                if ($('#statusFilter').val() || $('#wajahFilter').val()) {
                    $('#filterBadge').removeClass('hidden');
                }
            }

            function hideFilterBadge() {
                $('#filterBadge').addClass('hidden');
            }

            // Update quick stats
            function updateQuickStats(json) {
                if (json.recordsTotal !== undefined) {
                    $('#totalPasien').text(json.recordsTotal.toLocaleString('id-ID'));
                }
                
                if (json.stats) {
                    if (json.stats.wajah_terdaftar !== undefined) {
                        $('#wajahTerdaftar').text(json.stats.wajah_terdaftar.toLocaleString('id-ID'));
                    }
                    if (json.stats.pasien_aktif !== undefined) {
                        $('#pasienAktif').text(json.stats.pasien_aktif.toLocaleString('id-ID'));
                    }
                    if (json.stats.wajah_belum !== undefined) {
                        $('#wajahBelum').text(json.stats.wajah_belum.toLocaleString('id-ID'));
                    }
                }
            }

            // Export button handler
            $('#exportBtn').on('click', function() {
                Swal.fire({
                    title: 'Ekspor Data Pasien',
                    html: `
                        <p class="text-gray-600 dark:text-gray-400 mb-4 text-sm">Pilih format ekspor:</p>
                        <div class="grid grid-cols-2 gap-3">
                            <button onclick="exportData('excel')" class="px-3 py-3 bg-green-500 hover:bg-green-600 text-white rounded-lg transition flex flex-col items-center justify-center">
                                <i class="fas fa-file-excel text-lg mb-1"></i>
                                <div class="text-xs font-medium">Excel</div>
                            </button>
                            <button onclick="exportData('csv')" class="px-3 py-3 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition flex flex-col items-center justify-center">
                                <i class="fas fa-file-csv text-lg mb-1"></i>
                                <div class="text-xs font-medium">CSV</div>
                            </button>
                            <button onclick="exportData('pdf')" class="px-3 py-3 bg-red-500 hover:bg-red-600 text-white rounded-lg transition flex flex-col items-center justify-center">
                                <i class="fas fa-file-pdf text-lg mb-1"></i>
                                <div class="text-xs font-medium">PDF</div>
                            </button>
                            <button onclick="exportData('json')" class="px-3 py-3 bg-purple-500 hover:bg-purple-600 text-white rounded-lg transition flex flex-col items-center justify-center">
                                <i class="fas fa-file-code text-lg mb-1"></i>
                                <div class="text-xs font-medium">JSON</div>
                            </button>
                        </div>
                    `,
                    showConfirmButton: false,
                    showCancelButton: true,
                    cancelButtonText: 'Batal',
                    cancelButtonColor: '#6b7280',
                    background: document.documentElement.classList.contains('dark') ? '#1e293b' : '#fff',
                    color: document.documentElement.classList.contains('dark') ? '#fff' : '#000',
                });
            });

            // Toast notification
            function showToast(message, type = 'info') {
                const Toast = Swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 3000,
                    timerProgressBar: true,
                    background: document.documentElement.classList.contains('dark') ? '#1e293b' : '#fff',
                    color: document.documentElement.classList.contains('dark') ? '#fff' : '#000',
                    didOpen: (toast) => {
                        toast.addEventListener('mouseenter', Swal.stopTimer);
                        toast.addEventListener('mouseleave', Swal.resumeTimer);
                    }
                });

                Toast.fire({
                    icon: type,
                    title: message
                });
            }

            // Make functions global
            window.exportData = function(format) {
                Swal.close();
                showToast(`Mengekspor data ke ${format.toUpperCase()}...`, 'info');
                
                const status = $('#statusFilter').val() || '';
                const wajah = $('#wajahFilter').val() || '';
                const search = table.search();
                
                const exportUrl = "{{ route('petugas.pasien.datatables') }}" + 
                                `?export=${format}` +
                                `&status_pasien=${status}` +
                                `&wajah_terdaftar=${wajah}` +
                                `&search=${encodeURIComponent(search)}` +
                                `&draw=1&start=0&length=-1`;
                
                window.open(exportUrl, '_blank');
                
                setTimeout(() => {
                    showToast('Ekspor berhasil dimulai', 'success');
                }, 1000);
            };

            window.showToast = showToast;
        });

        // Global delete function dengan 2 pilihan: Soft Delete atau Hard Delete
        function confirmDelete(id, nama, noRM) {
            Swal.fire({
                title: 'Pilih Tipe Penghapusan',
                html: `<div class="text-left">
                    <p class="mb-3 text-sm text-gray-700 dark:text-gray-300">Anda akan menghapus pasien:</p>
                    <div class="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3 mb-4">
                        <p class="font-bold text-base text-gray-900 dark:text-white">${nama}</p>
                        <p class="text-xs text-gray-600 dark:text-gray-400 mt-1">No. RM: ${noRM}</p>
                    </div>
                    <p class="mb-3 text-xs font-medium text-gray-700 dark:text-gray-300">Pilih tipe penghapusan:</p>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <button onclick="proceedSoftDelete(${id}, '${nama}')" 
                                class="px-3 py-3 bg-gradient-to-br from-yellow-400 to-orange-500 hover:from-yellow-500 hover:to-orange-600 text-white rounded-lg transition flex flex-col items-center justify-center shadow-md hover:shadow-lg transform hover:-translate-y-0.5">
                            <i class="fas fa-save text-lg mb-1"></i>
                            <div class="text-xs font-bold">Simpan ke Riwayat</div>
                            <div class="text-xs mt-1 opacity-90">Data bisa di-restore</div>
                        </button>
                        <button onclick="proceedHardDelete(${id}, '${nama}')" 
                                class="px-3 py-3 bg-gradient-to-br from-red-500 to-red-700 hover:from-red-600 hover:to-red-800 text-white rounded-lg transition flex flex-col items-center justify-center shadow-md hover:shadow-lg transform hover:-translate-y-0.5">
                            <i class="fas fa-trash-alt text-lg mb-1"></i>
                            <div class="text-xs font-bold">Hapus Permanen</div>
                            <div class="text-xs mt-1 opacity-90">Data hilang selamanya</div>
                        </button>
                    </div>
                </div>`,
                icon: 'warning',
                showConfirmButton: false,
                showCancelButton: true,
                cancelButtonText: '<i class="fas fa-times mr-2"></i>Batal',
                cancelButtonColor: '#6b7280',
                background: document.documentElement.classList.contains('dark') ? '#1e293b' : '#fff',
                color: document.documentElement.classList.contains('dark') ? '#fff' : '#000',
                allowOutsideClick: false,
                allowEscapeKey: false
            });
        }

        // Soft Delete - Simpan ke Riwayat Penghapusan
        function proceedSoftDelete(id, nama) {
            Swal.fire({
                title: 'Simpan ke Riwayat Penghapusan?',
                html: `<div class="text-left">
                    <p class="mb-3 text-sm text-gray-600 dark:text-gray-400">Pasien akan disimpan di riwayat penghapusan dan dapat di-restore kapan saja.</p>
                    <label class="block mb-3">
                        <p class="text-xs font-medium text-gray-700 dark:text-gray-300 mb-2">Alasan penghapusan (optional):</p>
                        <textarea id="alasanPenghapusan" 
                                  class="w-full text-sm border border-gray-300 dark:border-slate-600 dark:bg-slate-700 dark:text-white rounded-lg p-3 focus:border-teal-500 focus:ring-teal-500 transition-all" 
                                  rows="3" 
                                  placeholder="Contoh: Pasien pindah, tidak aktif, dll..."></textarea>
                    </label>
                </div>`,
                icon: 'info',
                showCancelButton: true,
                confirmButtonColor: '#f59e0b',
                cancelButtonColor: '#6b7280',
                confirmButtonText: '<i class="fas fa-check mr-2"></i>Ya, Simpan ke Riwayat',
                cancelButtonText: '<i class="fas fa-times mr-2"></i>Batal',
                background: document.documentElement.classList.contains('dark') ? '#1e293b' : '#fff',
                color: document.documentElement.classList.contains('dark') ? '#fff' : '#000',
                showLoaderOnConfirm: true,
                preConfirm: () => {
                    const alasan = document.querySelector('#alasanPenghapusan')?.value || '';
                    
                    return fetch(`/petugas/pasien/${id}`, {
                        method: 'DELETE',
                        headers: {
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                            'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            deletion_type: 'soft',
                            alasan: alasan
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (!data.success) {
                            throw new Error(data.message || 'Gagal menghapus pasien');
                        }
                        return data;
                    })
                    .catch(error => {
                        Swal.showValidationMessage(`${error.message}`);
                    });
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Berhasil!',
                        html: `<div class="text-left">
                            <p class="text-sm"><i class="fas fa-check-circle text-green-500 mr-2"></i>Pasien "${nama}" berhasil disimpan ke Riwayat Penghapusan.</p>
                            <p class="text-xs text-gray-600 dark:text-gray-400 mt-2">Anda dapat melihatnya di menu <strong>Riwayat Penghapusan Pasien</strong> dan dapat di-restore kapan saja.</p>
                        </div>`,
                        icon: 'success',
                        confirmButtonColor: '#14b8a6',
                        timer: 3000,
                        timerProgressBar: true,
                        background: document.documentElement.classList.contains('dark') ? '#1e293b' : '#fff',
                        color: document.documentElement.classList.contains('dark') ? '#fff' : '#000',
                    }).then(() => {
                        $('#pasienTable').DataTable().ajax.reload();
                    });
                }
            });
        }

        // Hard Delete - Permanen Hapus Semua Data
        function proceedHardDelete(id, nama) {
            Swal.fire({
                title: '⚠️ PERINGATAN: Penghapusan Permanen',
                html: `<div class="text-left">
                    <div class="bg-red-50 dark:bg-red-900/20 border border-red-300 dark:border-red-800 rounded-lg p-4 mb-4">
                        <i class="fas fa-exclamation-triangle text-red-600 dark:text-red-400 text-lg mr-2"></i>
                        <span class="text-sm text-red-700 dark:text-red-300 font-medium">Tindakan ini TIDAK dapat dibatalkan!</span>
                    </div>
                    <p class="mb-3 text-sm text-gray-700 dark:text-gray-300">Pasien dan <strong>SEMUA data terkaitnya</strong> akan dihapus secara permanen:</p>
                    <ul class="text-xs text-gray-600 dark:text-gray-400 mb-4 space-y-1.5 bg-gray-50 dark:bg-slate-700 p-3 rounded-lg">
                        <li><i class="fas fa-times text-red-500 mr-2"></i> Pemeriksaan kesehatan</li>
                        <li><i class="fas fa-times text-red-500 mr-2"></i> Pembayaran & invoice</li>
                        <li><i class="fas fa-times text-red-500 mr-2"></i> Analisis AI</li>
                        <li><i class="fas fa-times text-red-500 mr-2"></i> Foto wajah & embedding</li>
                        <li><i class="fas fa-times text-red-500 mr-2"></i> Konsultasi & notifikasi</li>
                    </ul>
                    <p class="mb-3 text-xs font-medium text-gray-700 dark:text-gray-300">Konfirmasi dengan memasukkan password Anda:</p>
                    <input type="password" id="passwordConfirm" 
                           class="w-full text-sm border border-red-300 dark:border-slate-600 dark:bg-slate-700 dark:text-white rounded-lg p-2.5 focus:border-red-500 focus:ring-red-500 transition-all" 
                           placeholder="Masukkan password..." 
                           autocomplete="off">
                </div>`,
                icon: 'error',
                showCancelButton: true,
                confirmButtonColor: '#dc2626',
                cancelButtonColor: '#6b7280',
                confirmButtonText: '<i class="fas fa-trash-alt mr-2"></i>Ya, Hapus Permanen',
                cancelButtonText: '<i class="fas fa-times mr-2"></i>Batal',
                background: document.documentElement.classList.contains('dark') ? '#1e293b' : '#fff',
                color: document.documentElement.classList.contains('dark') ? '#fff' : '#000',
                showLoaderOnConfirm: true,
                allowOutsideClick: false,
                allowEscapeKey: false,
                preConfirm: () => {
                    const password = document.querySelector('#passwordConfirm')?.value || '';
                    
                    if (!password) {
                        Swal.showValidationMessage('Silakan masukkan password untuk konfirmasi');
                        return false;
                    }
                    
                    return fetch(`/petugas/pasien/${id}`, {
                        method: 'DELETE',
                        headers: {
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                            'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            deletion_type: 'hard',
                            password: password,
                            alasan: 'Penghapusan permanen oleh user'
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (!data.success) {
                            throw new Error(data.message || 'Gagal menghapus pasien');
                        }
                        return data;
                    })
                    .catch(error => {
                        Swal.showValidationMessage(`${error.message}`);
                    });
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Penghapusan Selesai',
                        html: `<div class="text-left">
                            <p class="text-sm mb-2"><i class="fas fa-check-circle text-red-500 mr-2"></i>Pasien "${nama}" dan semua data terkaitnya telah dihapus secara permanen.</p>
                            <p class="text-xs text-gray-600 dark:text-gray-400">Data tidak dapat dikembalikan lagi.</p>
                        </div>`,
                        icon: 'success',
                        confirmButtonColor: '#14b8a6',
                        timer: 3000,
                        timerProgressBar: true,
                        background: document.documentElement.classList.contains('dark') ? '#1e293b' : '#fff',
                        color: document.documentElement.classList.contains('dark') ? '#fff' : '#000',
                    }).then(() => {
                        $('#pasienTable').DataTable().ajax.reload();
                    });
                }
            });
        }
    </script>
    @endpush
</x-app-layout>