<x-app-layout>
    <div class="mb-12">
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 mb-8">
            <div class="relative">
                <div
                    class="absolute -left-3 -top-3 w-20 h-20 bg-gradient-to-br from-amber-500/10 to-orange-600/10 rounded-full blur-xl">
                </div>
                <h1 class="text-4xl font-black tracking-tight dark:text-white relative z-10 mb-2">
                    <span class="bg-gradient-to-r from-amber-600 to-orange-600 bg-clip-text text-transparent">
                        Potongan Biaya
                    </span>
                </h1>
                <p class="text-slate-500 dark:text-slate-400 text-sm pl-1">
                    <i data-lucide="percent" class="w-4 h-4 inline mr-2"></i>
                    Berikan potongan fleksibel untuk mahasiswa
                </p>
            </div>

            <div class="flex items-center gap-4">
                <a href="{{ route('dashboard') }}"
                    class="px-4 py-2.5 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-xl text-sm font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-gray-700 transition-all flex items-center gap-2 shadow-sm">
                    <i data-lucide="arrow-left" class="w-4 h-4"></i>
                    <span>Kembali</span>
                </a>
            </div>
        </div>

        <!-- Flash Messages -->
        @if (session('success'))
            <div
                class="mb-6 p-4 bg-gradient-to-r from-green-500/10 to-emerald-600/10 border border-green-500/20 rounded-2xl flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-green-500/10 text-green-500 flex items-center justify-center">
                    <i data-lucide="check-circle" class="w-5 h-5"></i>
                </div>
                <div class="flex-1">
                    <p class="font-medium text-green-700 dark:text-green-400">{{ session('success') }}</p>
                </div>
                <button onclick="this.parentElement.remove()" class="text-green-500 hover:text-green-600">
                    <i data-lucide="x" class="w-4 h-4"></i>
                </button>
            </div>
        @endif

        @if (session('error'))
            <div
                class="mb-6 p-4 bg-gradient-to-r from-red-500/10 to-rose-600/10 border border-red-500/20 rounded-2xl flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-red-500/10 text-red-500 flex items-center justify-center">
                    <i data-lucide="alert-triangle" class="w-5 h-5"></i>
                </div>
                <div class="flex-1">
                    <p class="font-medium text-red-700 dark:text-red-400">{{ session('error') }}</p>
                </div>
                <button onclick="this.parentElement.remove()" class="text-red-500 hover:text-red-600">
                    <i data-lucide="x" class="w-4 h-4"></i>
                </button>
            </div>
        @endif

        <!-- Main Card -->
        <div class="group relative">
            <div
                class="absolute -inset-1 bg-gradient-to-r from-amber-600/10 to-orange-600/10 rounded-3xl blur opacity-0 group-hover:opacity-30 transition duration-500">
            </div>
            <div
                class="relative bg-white dark:bg-[#1a1a2e] rounded-3xl border border-slate-200 dark:border-white/5 shadow-xl overflow-hidden">

                <!-- Card Header -->
                <div class="p-6 border-b border-slate-100 dark:border-white/5">
                    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                        <div>
                            <h3 class="text-xl font-bold text-gray-900 dark:text-white">Form Potongan Fleksibel</h3>
                            <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">
                                Pilih mahasiswa, lalu atur kriteria potongan
                            </p>
                        </div>
                        <div class="text-sm text-slate-500 dark:text-slate-400">
                            Total: <span
                                class="font-bold text-amber-600 dark:text-amber-400">{{ $mahasiswa->total() }}</span>
                            mahasiswa valid
                        </div>
                    </div>
                </div>

                <!-- Filter Section -->
                <div class="p-6 border-b border-slate-100 dark:border-white/5 bg-slate-50/50 dark:bg-white/5">
                    <form method="GET" action="{{ route('potongan-biaya.index') }}" class="space-y-4">
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            @if ($isGlobal)
                                <div>
                                    <label
                                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Kampus</label>
                                    <select name="kampus_id"
                                        class="w-full px-4 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm focus:ring-2 focus:ring-amber-500">
                                        <option value="all">Semua Kampus</option>
                                        @foreach ($kampusList as $kampus)
                                            <option value="{{ $kampus->id }}"
                                                {{ ($filters['kampus_id'] ?? '') == $kampus->id ? 'selected' : '' }}>
                                                {{ $kampus->nama }}
                                                {{ $kampus->singkatan ? '(' . $kampus->singkatan . ')' : '' }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            @endif

                            <div class="{{ $isGlobal ? 'md:col-span-2' : 'md:col-span-3' }}">
                                <label
                                    class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Pencarian</label>
                                <div class="relative">
                                    <i data-lucide="search"
                                        class="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-slate-400"></i>
                                    <input type="text" name="search" value="{{ $filters['search'] ?? '' }}"
                                        placeholder="Cari nama atau NIM..."
                                        class="w-full pl-10 pr-4 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm focus:ring-2 focus:ring-amber-500">
                                </div>
                            </div>
                        </div>

                        <div class="flex justify-end gap-2">
                            <button type="submit"
                                class="px-4 py-2 bg-gradient-to-r from-amber-600 to-orange-700 text-white rounded-lg text-sm font-medium hover:shadow-lg hover:shadow-amber-500/25 transition-all flex items-center gap-2">
                                <i data-lucide="filter" class="w-4 h-4"></i> Filter
                            </button>

                            @if (request()->hasAny(['kampus_id', 'search']))
                                <a href="{{ route('potongan-biaya.index') }}"
                                    class="px-4 py-2 bg-white dark:bg-gray-800 border border-slate-200 dark:border-gray-700 rounded-lg text-sm font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-gray-700 transition-all flex items-center gap-2">
                                    <i data-lucide="x" class="w-4 h-4"></i> Reset
                                </a>
                            @endif
                        </div>
                    </form>
                </div>

                <!-- Info Alert -->
                <div class="p-4 bg-blue-50 dark:bg-blue-900/20 border-b">
                    <div class="flex items-start gap-3 text-sm">
                        <i data-lucide="info" class="w-5 h-5 text-blue-500 flex-shrink-0"></i>
                        <div>
                            <p class="font-medium mb-1">Informasi:</p>
                            <ul class="list-disc list-inside space-y-1">
                                <li>Hanya menampilkan mahasiswa dengan status valid</li>
                                <li>Potongan hanya bisa diberikan sekali per item biaya</li>
                                <li>Item yang sudah dipotong tidak akan terpengaruh</li>
                                <li class="text-amber-600 font-medium">⚠️ UKT tidak bisa dipotong bersamaan dengan
                                    SPB/SPP</li>
                                <li class="text-green-600 font-medium">✅ SPB dan SPP bisa dipotong bersamaan dengan
                                    konfigurasi berbeda</li>
                            </ul>
                        </div>
                    </div>
                </div>

                <!-- Table Section -->
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="bg-slate-50/50 dark:bg-white/5 border-b">
                                <th class="py-4 px-6 w-12">
                                    <input type="checkbox" id="selectAll" class="w-4 h-4 text-amber-600 rounded">
                                </th>
                                <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">NIM</th>
                                <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">Nama</th>
                                <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">Kampus
                                </th>
                                <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">Prodi
                                </th>
                                <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">Angkatan
                                </th>
                                <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">Status
                                </th>
                                <th class="text-left py-4 px-6 text-xs font-semibold text-slate-500 uppercase">Aksi</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y">
                            @forelse($mahasiswa as $m)
                                <tr
                                    class="hover:bg-slate-50/50 dark:hover:bg-white/5 {{ !$m->has_angsuran ? 'opacity-50 bg-gray-50' : '' }}">
                                    <td class="py-4 px-6">
                                        @if ($m->has_angsuran)
                                            <input type="checkbox" name="mahasiswa_ids[]" value="{{ $m->id }}"
                                                class="mahasiswa-checkbox w-4 h-4 text-amber-600 rounded">
                                        @else
                                            <span class="text-xs text-red-500" title="Belum punya rencana angsuran"><i
                                                    data-lucide="x-circle" class="w-4 h-4"></i></span>
                                        @endif
                                    </td>
                                    <td class="py-4 px-6 font-mono text-sm">{{ $m->nim }}</td>
                                    <td class="py-4 px-6 font-medium">{{ $m->nama }}</td>
                                    <td class="py-4 px-6 text-sm">{{ $m->kampus->nama ?? '-' }}</td>
                                    <td class="py-4 px-6 text-sm">{{ $m->prodi->nama ?? '-' }}</td>
                                    <td class="py-4 px-6 text-sm">{{ $m->angkatan }}</td>
                                    <td class="py-4 px-6">
                                        @if ($m->has_angsuran)
                                            <span
                                                class="px-2 py-1 bg-green-500/10 text-green-600 rounded-lg text-xs">Valid</span>
                                        @else
                                            <span class="px-2 py-1 bg-red-500/10 text-red-600 rounded-lg text-xs">Belum
                                                Ada</span>
                                        @endif
                                    </td>
                                    <td class="py-4 px-6">
                                        @if ($m->has_angsuran)
                                            <button type="button" onclick="showAngsuranDetail({{ $m->id }})"
                                                class="text-xs text-amber-600 hover:underline flex items-center gap-1">
                                                <i data-lucide="eye" class="w-3 h-3"></i> Detail
                                            </button>
                                        @endif
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="8" class="py-12 text-center text-slate-500">Tidak ada数据</td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>

                <!-- Pagination & Actions -->
                <div class="p-6 border-t">
                    <div class="flex flex-col sm:flex-row justify-between items-center gap-4">
                        <div class="flex items-center gap-4">
                            <span class="text-sm text-slate-500" id="selectedCount">0 mahasiswa dipilih</span>
                            <button type="button" onclick="clearSelection()"
                                class="text-xs text-amber-600 hover:underline">Hapus pilihan</button>
                        </div>
                        <div class="flex gap-3">
                            <button type="button" onclick="showPotonganFleksibelModal()"
                                class="px-6 py-2.5 bg-gradient-to-r from-amber-500 to-orange-600 text-white rounded-xl text-sm font-medium hover:shadow-lg hover:shadow-amber-500/25 transition-all flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
                                id="potonganBtn" disabled>
                                <i data-lucide="percent" class="w-4 h-4"></i>
                                Terapkan Potongan
                            </button>
                        </div>
                    </div>
                    @if ($mahasiswa->hasPages())
                        <div class="mt-6">{{ $mahasiswa->links('vendor.pagination.tailwind') }}</div>
                    @endif
                </div>
            </div>
        </div>
    </div>

    <!-- MODAL POTONGAN FLEKSIBEL -->
    <div id="potonganFleksibelModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
        <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
                onclick="closePotonganFleksibelModal()"></div>
            <div
                class="inline-block align-bottom bg-white dark:bg-[#1a1a2e] rounded-3xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full">
                <div class="p-6">
                    <div class="flex items-center gap-4 mb-6">
                        <div
                            class="w-12 h-12 rounded-xl bg-amber-500/10 text-amber-500 flex items-center justify-center">
                            <i data-lucide="settings" class="w-6 h-6"></i>
                        </div>
                        <div>
                            <h3 class="text-lg font-bold text-gray-900 dark:text-white">Potongan Fleksibel</h3>
                            <p class="text-sm text-slate-500 dark:text-slate-400">Atur potongan per jenis biaya (SPB
                                dan SPP bisa berbeda)</p>
                        </div>
                    </div>

                    <div id="selectedMahasiswaInfo"
                        class="mb-4 p-3 bg-green-50 dark:bg-green-900/20 rounded-lg hidden">
                        <div class="flex items-start gap-2">
                            <i data-lucide="users" class="w-4 h-4 text-green-600 shrink-0 mt-0.5"></i>
                            <div>
                                <p class="text-sm font-medium text-green-700 dark:text-green-300">Mahasiswa Terpilih
                                </p>
                                <p id="selectedMahasiswaList" class="text-xs text-green-600 dark:text-green-400 mt-1">
                                </p>
                            </div>
                        </div>
                    </div>

                    <div class="mb-4 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                        <p class="text-sm text-blue-700 dark:text-blue-300 flex items-start gap-2">
                            <i data-lucide="info" class="w-4 h-4 shrink-0 mt-0.5"></i>
                            <span>Potongan akan diterapkan ke <span id="selectedCountModal" class="font-bold">0</span>
                                mahasiswa terpilih.</span>
                        </p>
                    </div>

                    <div class="space-y-6">
                        <!-- Pilih Jenis Biaya - hanya menampilkan yang tersedia berdasarkan mahasiswa -->
                        <div id="jenisBiayaContainer">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                                Jenis Biaya yang Akan Dipotong <span class="text-red-500">*</span>
                            </label>
                            <div class="flex flex-wrap gap-4" id="jenisCheckboxGroup">
                                <!-- Dinamis di JS -->
                            </div>
                            <div id="jenisWarning" class="text-xs text-amber-600 mt-2 hidden"></div>
                        </div>

                        <!-- Range Semester (untuk SPP dan UKT) -->
                        <div id="semesterContainer" class="hidden">
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Semester Mulai
                                    </label>
                                    <select id="semesterStart"
                                        class="w-full px-3 py-2 bg-white dark:bg-gray-800 border rounded-lg text-sm">
                                        @for ($i = 1; $i <= 14; $i++)
                                            <option value="{{ $i }}">Semester {{ $i }}</option>
                                        @endfor
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Semester Sampai
                                    </label>
                                    <select id="semesterEnd"
                                        class="w-full px-3 py-2 bg-white dark:bg-gray-800 border rounded-lg text-sm">
                                        @for ($i = 1; $i <= 14; $i++)
                                            <option value="{{ $i }}" {{ $i == 14 ? 'selected' : '' }}>
                                                Semester {{ $i }}</option>
                                        @endfor
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- KONFIGURASI PER JENIS (Dinamis) - SPP di atas SPB -->
                        <div id="jenisConfigContainer" class="space-y-4">
                            <div class="text-center text-slate-400 py-4 p-4 border-2 border-dashed rounded-xl">
                                Pilih jenis biaya terlebih dahulu
                            </div>
                        </div>

                        <!-- Error Message -->
                        <div id="potonganFleksibelError" class="text-sm text-red-600 dark:text-red-400 hidden"></div>
                    </div>

                    <div class="mt-6 flex justify-end gap-3">
                        <button type="button" onclick="closePotonganFleksibelModal()"
                            class="px-4 py-2 bg-white dark:bg-gray-800 border border-slate-200 rounded-lg text-sm font-medium">
                            Batal
                        </button>
                        <button type="button" onclick="showPotonganConfirmModal()"
                            class="px-4 py-2 bg-gradient-to-r from-amber-500 to-orange-600 text-white rounded-lg text-sm font-medium">
                            Lanjutkan
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- MODAL KONFIRMASI POTONGAN -->
    <div id="potonganConfirmModal" class="fixed inset-0 z-[10001] hidden overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:p-0">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
                onclick="closePotonganConfirmModal()"></div>
            <div
                class="inline-block align-bottom bg-white dark:bg-[#1a1a2e] rounded-3xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-5xl sm:w-full">
                <div class="bg-gradient-to-r from-amber-500 to-orange-600 px-6 py-4">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 rounded-xl bg-white/20 text-white flex items-center justify-center">
                            <i data-lucide="alert-triangle" class="w-5 h-5"></i>
                        </div>
                        <div>
                            <h3 class="text-lg font-bold text-white">Konfirmasi Potongan Fleksibel</h3>
                            <p class="text-sm text-white/80" id="potonganConfirmMessage"></p>
                        </div>
                    </div>
                </div>

                <div class="p-6">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6" id="summaryStats"></div>

                    <div class="bg-slate-50 dark:bg-white/5 rounded-xl p-4">
                        <div class="flex justify-between items-center mb-3">
                            <span class="text-sm font-medium text-slate-700 dark:text-slate-300">Detail Item yang Akan
                                Dipotong</span>
                            <span class="text-xs text-slate-400" id="itemCountBadge"></span>
                        </div>
                        <div id="potonganSummaryList" class="max-h-96 overflow-y-auto space-y-2"></div>
                    </div>

                    <div class="mt-6 flex justify-end gap-3">
                        <button type="button" onclick="closePotonganConfirmModal()"
                            class="px-4 py-2 bg-white dark:bg-gray-800 border border-slate-200 rounded-xl text-sm font-medium">Batal</button>
                        <button type="button" onclick="applyPotongan()"
                            class="px-6 py-2 bg-gradient-to-r from-amber-500 to-orange-600 text-white rounded-xl text-sm font-medium flex items-center gap-2">
                            <i data-lucide="check" class="w-4 h-4"></i> Ya, Terapkan
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Detail Angsuran -->
    <div id="detailModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
        <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onclick="closeDetailModal()">
            </div>
            <div
                class="inline-block align-bottom bg-white dark:bg-[#1a1a2e] rounded-3xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full">
                <div class="p-6">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-lg font-bold" id="detailModalTitle">Detail Angsuran</h3>
                        <button onclick="closeDetailModal()" class="text-slate-400 hover:text-slate-500">
                            <i data-lucide="x" class="w-5 h-5"></i>
                        </button>
                    </div>
                    <div id="detailModalContent" class="space-y-4">
                        <div class="text-center py-8" id="detailLoading">
                            <div
                                class="inline-block animate-spin rounded-full h-8 w-8 border-4 border-amber-500 border-t-transparent">
                            </div>
                            <p class="mt-2 text-sm text-slate-500">Memuat...</p>
                        </div>
                        <div id="detailData" class="hidden"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">

    <style>
        #potonganConfirmModal {
            z-index: 10001;
        }

        #potonganFleksibelModal {
            z-index: 9999;
        }

        .swal2-container {
            z-index: 99999 !important;
        }

        .swal2-popup {
            border-radius: 24px !important;
            padding: 2rem !important;
        }

        .animate-spin {
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            from {
                transform: rotate(0deg);
            }

            to {
                transform: rotate(360deg);
            }
        }

        .summary-item {
            transition: all 0.2s ease;
        }

        .summary-item:hover {
            transform: translateX(4px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
    </style>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        // ============ HARDCODE MAX CICILAN ============
        const MAX_CICILAN = {
            SPB: 48,
            SPP: 6,
            UKT: 6
        };

        // ============ KONFIGURASI PER JENIS ============
        let konfigurasiPerJenis = {
            SPB: {
                cicilan_start: 1,
                cicilan_end: 48,
                metode: 'nominal',
                nilai: 0
            },
            SPP: {
                cicilan_start: 1,
                cicilan_end: 6,
                metode: 'nominal',
                nilai: 0
            },
            UKT: {
                cicilan_start: 1,
                cicilan_end: 6,
                metode: 'nominal',
                nilai: 0
            }
        };

        let potonganData = {};
        let semuaMahasiswaTerpilih = [];
        let availableJenisSet = new Set(); // Jenis yang tersedia dari mahasiswa terpilih

        function escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function formatRupiah(angka) {
            if (!angka && angka !== 0) return '0';
            return new Intl.NumberFormat('id-ID').format(angka);
        }

        function parseRupiah(str) {
            if (!str) return 0;
            return parseInt(str.toString().replace(/[^0-9]/g, '')) || 0;
        }

        // ============ UPDATE JENIS TERPILIH (berdasarkan availableJenisSet) ============
        function renderJenisCheckboxes() {
            const container = document.getElementById('jenisCheckboxGroup');
            const hasSPB = availableJenisSet.has('SPB');
            const hasSPP = availableJenisSet.has('SPP');
            const hasUKT = availableJenisSet.has('UKT');

            let html = '';

            // Urutan: SPP, SPB, UKT (SPP di atas SPB)
            if (hasSPP) {
                html += `
                    <label class="flex items-center gap-2 jenis-label" data-jenis="SPP">
                        <input type="checkbox" name="jenisBiaya" value="SPP" onchange="updateJenisTerpilih()"
                            class="jenis-checkbox rounded border-slate-300 text-amber-600 focus:ring-amber-500">
                        <span class="text-sm">SPP</span>
                    </label>
                `;
            }
            if (hasSPB) {
                html += `
                    <label class="flex items-center gap-2 jenis-label" data-jenis="SPB">
                        <input type="checkbox" name="jenisBiaya" value="SPB" onchange="updateJenisTerpilih()"
                            class="jenis-checkbox rounded border-slate-300 text-amber-600 focus:ring-amber-500">
                        <span class="text-sm">SPB</span>
                    </label>
                `;
            }
            if (hasUKT) {
                html += `
                    <label class="flex items-center gap-2 jenis-label" data-jenis="UKT">
                        <input type="checkbox" name="jenisBiaya" value="UKT" onchange="updateJenisTerpilih()"
                            class="jenis-checkbox rounded border-slate-300 text-amber-600 focus:ring-amber-500">
                        <span class="text-sm">UKT</span>
                    </label>
                `;
            }

            container.innerHTML = html;

            // Reset semua checkbox
            document.querySelectorAll('.jenis-checkbox').forEach(cb => cb.checked = false);
        }

        window.updateJenisTerpilih = function() {
            const selectedJeniss = Array.from(document.querySelectorAll('.jenis-checkbox:checked')).map(cb => cb.value);
            const container = document.getElementById('jenisConfigContainer');
            const semesterContainer = document.getElementById('semesterContainer');
            const jenisWarning = document.getElementById('jenisWarning');

            // Tampilkan semester container jika ada SPP atau UKT
            const hasSemesterJenis = selectedJeniss.some(jenis => jenis === 'SPP' || jenis === 'UKT');
            semesterContainer.style.display = hasSemesterJenis ? 'block' : 'none';
            jenisWarning.classList.add('hidden');

            if (selectedJeniss.length === 0) {
                container.innerHTML =
                    '<div class="text-center text-slate-400 py-4 p-4 border-2 border-dashed rounded-xl">Pilih jenis biaya terlebih dahulu</div>';
                return;
            }

            // Urutkan: SPP dulu, baru SPB/UKT
            const sortedJeniss = [...selectedJeniss].sort((a, b) => {
                if (a === 'SPP') return -1;
                if (b === 'SPP') return 1;
                return 0;
            });

            let html =
                '<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">Konfigurasi Per Jenis Biaya</label>';

            for (const jenis of sortedJeniss) {
                const config = konfigurasiPerJenis[jenis];
                const maxCicilan = MAX_CICILAN[jenis];
                const warna = jenis === 'SPB' ? 'blue' : (jenis === 'SPP' ? 'green' : 'purple');

                html += `
            <div class="p-4 rounded-xl border border-${warna}-200 bg-${warna}-50/20">
                <div class="flex items-center gap-2 mb-3">
                    <span class="px-2 py-1 text-xs font-bold rounded-lg bg-${warna}-500 text-white">${jenis}</span>
                    <span class="text-xs text-slate-500">Maks cicilan: ${maxCicilan}</span>
                </div>
                <div class="grid grid-cols-2 gap-3 mb-3">
                    <div>
                        <label class="text-xs text-slate-600">Cicilan Mulai</label>
                        <input type="number" id="cicilan_start_${jenis}" value="${config.cicilan_start}"
                            min="1" max="${maxCicilan}" class="w-full px-3 py-2 bg-white dark:bg-gray-800 border rounded-lg text-sm mt-1">
                    </div>
                    <div>
                        <label class="text-xs text-slate-600">Cicilan Sampai</label>
                        <input type="number" id="cicilan_end_${jenis}" value="${config.cicilan_end}"
                            min="1" max="${maxCicilan}" class="w-full px-3 py-2 bg-white dark:bg-gray-800 border rounded-lg text-sm mt-1">
                    </div>
                </div>
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="text-xs text-slate-600">Metode</label>
                        <select id="metode_${jenis}" class="w-full px-3 py-2 bg-white dark:bg-gray-800 border rounded-lg text-sm mt-1" onchange="updateMetode('${jenis}')">
                            <option value="nominal" ${config.metode === 'nominal' ? 'selected' : ''}>Nominal (Rp)</option>
                            <option value="persen" ${config.metode === 'persen' ? 'selected' : ''}>Persen (%)</option>
                        </select>
                    </div>
                    <div>
                        <label class="text-xs text-slate-600">Nilai Potongan</label>
                        <div class="relative mt-1">
                            <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-xs text-slate-400 prefix-symbol">${config.metode === 'nominal' ? 'Rp' : '%'}</span>
                            <input type="text" id="nilai_${jenis}" data-jenis="${jenis}"
                                value="${config.metode === 'nominal' ? formatRupiah(config.nilai) : config.nilai}"
                                class="w-full pl-8 pr-3 py-2 bg-white dark:bg-gray-800 border rounded-lg text-sm"
                                oninput="handleNilaiInput(this, '${jenis}')">
                        </div>
                    </div>
                </div>
            </div>
        `;
            }

            container.innerHTML = html;

            for (const jenis of selectedJeniss) {
                const startInput = document.getElementById(`cicilan_start_${jenis}`);
                const endInput = document.getElementById(`cicilan_end_${jenis}`);
                if (startInput) {
                    startInput.addEventListener('change', function() {
                        let val = parseInt(this.value);
                        const max = parseInt(this.max);
                        if (isNaN(val)) val = 1;
                        if (val < 1) val = 1;
                        if (val > max) val = max;
                        this.value = val;
                        konfigurasiPerJenis[jenis].cicilan_start = val;
                    });
                }
                if (endInput) {
                    endInput.addEventListener('change', function() {
                        let val = parseInt(this.value);
                        const max = parseInt(this.max);
                        if (isNaN(val)) val = 1;
                        if (val < 1) val = 1;
                        if (val > max) val = max;
                        this.value = val;
                        konfigurasiPerJenis[jenis].cicilan_end = val;
                    });
                }
            }
        };

        window.updateMetode = function(jenis) {
            const metodeSelect = document.getElementById(`metode_${jenis}`);
            const nilaiInput = document.getElementById(`nilai_${jenis}`);
            const metode = metodeSelect.value;
            konfigurasiPerJenis[jenis].metode = metode;

            const parent = nilaiInput.parentElement;

            // Hapus semua prefix yang ada
            const oldPrefixes = parent.querySelectorAll('.prefix-symbol');
            oldPrefixes.forEach(prefix => prefix.remove());

            // Buat prefix baru sesuai metode
            const span = document.createElement('span');
            span.className = 'absolute left-3 top-1/2 transform -translate-y-1/2 text-xs text-slate-400 prefix-symbol';

            if (metode === 'nominal') {
                span.innerText = 'Rp';
                nilaiInput.value = formatRupiah(konfigurasiPerJenis[jenis].nilai);
                nilaiInput.style.textAlign = 'right';
                nilaiInput.classList.add('font-mono');
                nilaiInput.classList.remove('text-left');
                nilaiInput.placeholder = '0';
            } else {
                span.innerText = '%';
                nilaiInput.value = konfigurasiPerJenis[jenis].nilai;
                nilaiInput.style.textAlign = 'left';
                nilaiInput.classList.remove('font-mono', 'text-right');
                nilaiInput.classList.add('text-left');
                nilaiInput.placeholder = '0';
            }

            parent.insertBefore(span, nilaiInput);
        };

        window.handleNilaiInput = function(input, jenis) {
            const metode = konfigurasiPerJenis[jenis].metode;
            if (metode === 'nominal') {
                let numericValue = parseInt(input.value.replace(/[^0-9]/g, '')) || 0;
                konfigurasiPerJenis[jenis].nilai = numericValue;
                input.value = formatRupiah(numericValue);
            } else {
                let numericValue = parseInt(input.value) || 0;
                if (numericValue > 100) numericValue = 100;
                if (numericValue < 0) numericValue = 0;
                konfigurasiPerJenis[jenis].nilai = numericValue;
                input.value = numericValue;
            }
        };

        function validatePotonganInput() {
            const selectedJeniss = Array.from(document.querySelectorAll('.jenis-checkbox:checked')).map(cb => cb.value);
            if (selectedJeniss.length === 0) {
                showPotonganError('Pilih minimal satu jenis biaya');
                return false;
            }

            const semesterStart = parseInt(document.getElementById('semesterStart').value);
            const semesterEnd = parseInt(document.getElementById('semesterEnd').value);
            if (semesterStart > semesterEnd) {
                showPotonganError('Semester mulai tidak boleh lebih besar dari semester sampai');
                return false;
            }

            for (const jenis of selectedJeniss) {
                const config = konfigurasiPerJenis[jenis];
                const maxCicilan = MAX_CICILAN[jenis];
                if (config.cicilan_start < 1 || config.cicilan_start > maxCicilan) {
                    showPotonganError(`${jenis}: Cicilan mulai harus antara 1-${maxCicilan}`);
                    return false;
                }
                if (config.cicilan_end < 1 || config.cicilan_end > maxCicilan) {
                    showPotonganError(`${jenis}: Cicilan sampai harus antara 1-${maxCicilan}`);
                    return false;
                }
                if (config.cicilan_start > config.cicilan_end) {
                    showPotonganError(`${jenis}: Cicilan mulai tidak boleh lebih dari cicilan sampai`);
                    return false;
                }
                if (!config.nilai || config.nilai <= 0) {
                    showPotonganError(`${jenis}: Masukkan nilai potongan`);
                    return false;
                }
                if (config.metode === 'persen' && config.nilai > 100) {
                    showPotonganError(`${jenis}: Persen tidak boleh lebih dari 100%`);
                    return false;
                }
            }
            return true;
        }

        function showPotonganError(msg) {
            const errorDiv = document.getElementById('potonganFleksibelError');
            errorDiv.textContent = msg;
            errorDiv.classList.remove('hidden');
            errorDiv.scrollIntoView({
                behavior: 'smooth',
                block: 'nearest'
            });
            setTimeout(() => errorDiv.classList.add('hidden'), 5000);
        }

        async function checkAvailableJenisWithDetails(mahasiswaIds) {
            try {
                const response = await fetch('{{ route('potongan-biaya.available-jenis') }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        mahasiswa_ids: mahasiswaIds
                    })
                });
                return await response.json();
            } catch (error) {
                console.error('Error:', error);
                return null;
            }
        }

        window.showPotonganFleksibelModal = async function() {
            const checked = document.querySelectorAll('.mahasiswa-checkbox:checked');
            if (checked.length === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Peringatan',
                    text: 'Pilih minimal 1 mahasiswa'
                });
                return;
            }

            Swal.fire({
                title: 'Memeriksa data...',
                text: 'Mohon tunggu',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => Swal.showLoading()
            });

            const mahasiswaIds = Array.from(checked).map(cb => cb.value);
            semuaMahasiswaTerpilih = mahasiswaIds;

            const data = await checkAvailableJenisWithDetails(mahasiswaIds);
            Swal.close();

            if (!data || data.available.length === 0) {
                Swal.fire({
                    icon: 'info',
                    title: 'Tidak Ada Data',
                    text: 'Tidak ada jenis biaya yang dapat dipotong'
                });
                return;
            }

            // Set availableJenisSet berdasarkan data dari server
            availableJenisSet.clear();
            data.available.forEach(j => availableJenisSet.add(j));

            // Cek apakah ada campuran UKT dengan SPB/SPP
            const hasUKT = availableJenisSet.has('UKT');
            const hasNonUKT = availableJenisSet.has('SPB') || availableJenisSet.has('SPP');

            if (hasUKT && hasNonUKT) {
                Swal.fire({
                    icon: 'error',
                    title: 'Tidak Dapat Diproses',
                    html: 'Mahasiswa yang dipilih memiliki jenis biaya yang berbeda (campuran UKT dengan SPB/SPP).<br><br><strong>Solusi:</strong><br>1. Pilih mahasiswa dengan jenis biaya yang sama<br>2. Atau lakukan potongan secara terpisah',
                    confirmButtonColor: '#f59e0b'
                });
                return;
            }

            // Render checkbox berdasarkan jenis yang tersedia
            renderJenisCheckboxes();

            // Reset konfigurasi
            konfigurasiPerJenis = {
                SPB: {
                    cicilan_start: 1,
                    cicilan_end: 48,
                    metode: 'nominal',
                    nilai: 0
                },
                SPP: {
                    cicilan_start: 1,
                    cicilan_end: 6,
                    metode: 'nominal',
                    nilai: 0
                },
                UKT: {
                    cicilan_start: 1,
                    cicilan_end: 6,
                    metode: 'nominal',
                    nilai: 0
                }
            };

            // Tampilkan info mahasiswa
            const infoDiv = document.getElementById('selectedMahasiswaInfo');
            const listDiv = document.getElementById('selectedMahasiswaList');
            let names = [];
            checked.forEach(cb => {
                const row = cb.closest('tr');
                const nama = row.querySelector('td:nth-child(3)')?.innerText || '';
                const nim = row.querySelector('td:nth-child(2)')?.innerText || '';
                names.push(`${nama} (${nim})`);
            });
            infoDiv.classList.remove('hidden');
            if (names.length <= 3) {
                listDiv.innerHTML = names.join('<br>');
            } else {
                listDiv.innerHTML =
                    `${names.length} mahasiswa dipilih:<br>${names.slice(0, 3).join('<br>')}<br><span class="text-green-500">+${names.length - 3} lainnya</span>`;
            }
            document.getElementById('selectedCountModal').textContent = checked.length;

            document.getElementById('jenisConfigContainer').innerHTML =
                '<div class="text-center text-slate-400 py-4 p-4 border-2 border-dashed rounded-xl">Pilih jenis biaya terlebih dahulu</div>';
            document.getElementById('semesterContainer').style.display = 'none';
            document.getElementById('potonganFleksibelError').classList.add('hidden');
            document.getElementById('potonganFleksibelModal').classList.remove('hidden');
            document.body.classList.add('modal-open');
            if (typeof lucide !== 'undefined') lucide.createIcons();
        };

        window.closePotonganFleksibelModal = function() {
            document.getElementById('potonganFleksibelModal').classList.add('hidden');
            document.body.classList.remove('modal-open');
        };

        window.closePotonganConfirmModal = function() {
            document.getElementById('potonganConfirmModal').classList.add('hidden');
        };

        window.showPotonganConfirmModal = async function() {
            if (!validatePotonganInput()) return;

            const selectedJeniss = Array.from(document.querySelectorAll('.jenis-checkbox:checked')).map(cb => cb
                .value);
            const semesterStart = document.getElementById('semesterStart').value;
            const semesterEnd = document.getElementById('semesterEnd').value;

            let semuaItems = [];
            let totalItemsSemua = 0;
            let totalPotonganSemua = 0;
            let summaryPerJenis = {};

            Swal.fire({
                title: 'Memproses...',
                text: 'Menghitung item',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => Swal.showLoading()
            });

            for (const jenis of selectedJeniss) {
                summaryPerJenis[jenis] = {
                    count: 0,
                    total: 0
                };
                const config = konfigurasiPerJenis[jenis];
                const nilai = config.metode === 'persen' ? config.nilai : config.nilai;

                try {
                    const response = await fetch('{{ route('potongan-biaya.summary-potongan') }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({
                            mahasiswa_ids: semuaMahasiswaTerpilih,
                            kriteria: {
                                jenis: [jenis],
                                semester_start: semesterStart,
                                semester_end: semesterEnd,
                                cicilan_start: config.cicilan_start,
                                cicilan_end: config.cicilan_end
                            },
                            metode: config.metode,
                            nilai: nilai
                        })
                    });
                    const data = await response.json();
                    if (data.items) {
                        data.items.forEach(item => {
                            semuaItems.push(item);
                            if (summaryPerJenis[item.jenis]) {
                                summaryPerJenis[item.jenis].count++;
                                summaryPerJenis[item.jenis].total += item.potongan;
                            }
                        });
                        totalItemsSemua += data.total_items;
                        totalPotonganSemua += data.total_potongan;
                    }
                } catch (error) {
                    console.error(error);
                }
            }

            Swal.close();

            if (totalItemsSemua === 0) {
                Swal.fire({
                    icon: 'info',
                    title: 'Tidak Ada Item',
                    text: 'Tidak ada item yang sesuai dengan kriteria'
                });
                return;
            }

            potonganData = {
                selectedJeniss,
                semester_start: semesterStart,
                semester_end: semesterEnd,
                konfigurasi: JSON.parse(JSON.stringify(konfigurasiPerJenis)),
                mahasiswa_ids: [...semuaMahasiswaTerpilih]
            };

            // Summary stats
            let statsHtml = '';
            const warnaStat = {
                SPB: 'blue',
                SPP: 'green',
                UKT: 'purple'
            };
            for (const [jenis, stat] of Object.entries(summaryPerJenis)) {
                if (stat.count > 0) {
                    statsHtml += `<div class="bg-${warnaStat[jenis]}-50 rounded-xl p-3 text-center">
                        <div class="text-2xl font-bold text-${warnaStat[jenis]}-600">${stat.count}</div>
                        <div class="text-xs text-slate-500">Item ${jenis}</div>
                        <div class="text-sm font-medium text-${warnaStat[jenis]}-600">Rp ${stat.total.toLocaleString('id-ID')}</div>
                    </div>`;
                }
            }
            statsHtml += `<div class="bg-amber-50 rounded-xl p-3 text-center">
                <div class="text-2xl font-bold text-amber-600">${totalItemsSemua}</div>
                <div class="text-xs text-slate-500">Total Item</div>
                <div class="text-sm font-medium text-amber-600">Rp ${totalPotonganSemua.toLocaleString('id-ID')}</div>
            </div>`;

            document.getElementById('summaryStats').innerHTML = statsHtml;
            document.getElementById('itemCountBadge').innerHTML = `${totalItemsSemua} item`;
            document.getElementById('potonganConfirmMessage').textContent =
                `Memberikan potongan kepada ${semuaMahasiswaTerpilih.length} mahasiswa`;

            let itemsHtml = '';
            semuaItems.forEach(item => {
                const warna = item.jenis === 'SPB' ? 'blue' : (item.jenis === 'SPP' ? 'green' : 'purple');
                itemsHtml += `
                    <div class="summary-item bg-white rounded-lg p-3 border-l-4 border-${warna}-500 shadow-sm">
                        <div class="flex flex-wrap justify-between items-start gap-2">
                            <div class="flex-1">
                                <div class="flex items-center gap-2 mb-1">
                                    <span class="px-2 py-0.5 text-xs rounded-full bg-${warna}-100 text-${warna}-700">${item.jenis}</span>
                                    <span class="text-xs text-slate-400">Cicilan ke-${item.nomor_cicilan} | Semester ${item.semester}</span>
                                </div>
                                <p class="font-medium text-sm">${escapeHtml(item.mahasiswa_nama)}</p>
                                <p class="text-xs text-slate-400">${item.mahasiswa_nim} • ${escapeHtml(item.komponen)}</p>
                            </div>
                            <div class="text-right">
                                <div class="text-xs text-slate-400 line-through">Rp ${item.total_asli.toLocaleString('id-ID')}</div>
                                <div class="text-sm font-bold text-green-600">Rp ${item.total_baru.toLocaleString('id-ID')}</div>
                                <div class="text-xs text-red-500">-Rp ${item.potongan.toLocaleString('id-ID')}</div>
                            </div>
                        </div>
                    </div>
                `;
            });

            document.getElementById('potonganSummaryList').innerHTML = itemsHtml;
            document.getElementById('potonganFleksibelModal').classList.add('hidden');
            document.getElementById('potonganConfirmModal').classList.remove('hidden');
            if (typeof lucide !== 'undefined') lucide.createIcons();
        };

        window.applyPotongan = function() {
            Swal.fire({
                title: 'Memproses...',
                text: 'Mohon tunggu',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => Swal.showLoading()
            });

            let promises = [];
            for (const jenis of potonganData.selectedJeniss) {
                const config = potonganData.konfigurasi[jenis];
                const nilai = config.metode === 'persen' ? config.nilai : config.nilai;
                promises.push(fetch('{{ route('potongan-biaya.apply') }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        mahasiswa_ids: potonganData.mahasiswa_ids,
                        kriteria: {
                            jenis: [jenis],
                            semester_start: potonganData.semester_start,
                            semester_end: potonganData.semester_end,
                            cicilan_start: config.cicilan_start,
                            cicilan_end: config.cicilan_end
                        },
                        metode: config.metode,
                        nilai: nilai
                    })
                }).then(res => res.json()));
            }

            Promise.all(promises).then(results => {
                Swal.close();
                document.getElementById('potonganConfirmModal').classList.add('hidden');
                document.getElementById('potonganFleksibelModal').classList.add('hidden');
                document.body.classList.remove('modal-open');

                let success = results.every(r => r.success);
                let messages = results.map(r => r.message).join('<br>');

                if (success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        html: messages,
                        timer: 3000
                    }).then(() => window.location.reload());
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal!',
                        html: messages
                    });
                }
            }).catch(error => {
                Swal.close();
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: error.message
                });
            });
        };

        // Detail Angsuran
        window.showAngsuranDetail = function(id) {
            const modal = document.getElementById('detailModal');
            const loading = document.getElementById('detailLoading');
            const dataDiv = document.getElementById('detailData');
            modal.classList.remove('hidden');
            loading.classList.remove('hidden');
            dataDiv.classList.add('hidden');

            fetch(`/potongan-biaya/detail/${id}`).then(res => res.json()).then(data => {
                loading.classList.add('hidden');
                if (data.error) {
                    dataDiv.innerHTML = `<div class="text-center text-red-500 py-4">${data.error}</div>`;
                } else {
                    document.getElementById('detailModalTitle').textContent =
                        `Detail - ${data.mahasiswa.nama} (${data.mahasiswa.nim})`;
                    let html = `<div class="flex gap-3 mb-4 p-3 bg-slate-50 rounded-xl">
                        <div><span class="text-xs">Total:</span><span class="font-bold text-amber-600">Rp ${data.total.toLocaleString()}</span></div>
                        <div class="w-px bg-slate-300"></div>
                        <div><span class="text-xs">Sisa:</span><span class="font-bold">Rp ${data.sisa.toLocaleString()}</span></div>
                    </div><div class="space-y-2 max-h-96 overflow-y-auto">`;
                    data.details.forEach(d => {
                        let warna = d.jenis === 'SPB' ? 'blue' : (d.jenis === 'SPP' ? 'green' :
                            'purple');
                        html += `<div class="p-3 bg-white rounded-lg border">
                            <div class="flex justify-between"><span class="font-medium">${escapeHtml(d.komponen)}</span><span class="px-2 py-0.5 text-xs rounded-full bg-${warna}-100 text-${warna}-700">${d.jenis}</span></div>
                            <div class="text-xs text-slate-400">${d.kode_biaya} | Semester ${d.semester || '-'} | Cicilan ke-${d.nomor_cicilan || '-'}</div>
                            <div class="flex justify-between mt-2"><span>Tagihan:</span><span>Rp ${d.total.toLocaleString()}</span></div>
                            ${d.potongan > 0 ? `<div class="flex justify-between text-red-500"><span>Potongan:</span><span>-Rp ${d.potongan.toLocaleString()}</span></div>` : ''}
                            <div class="flex justify-between"><span>Dibayar:</span><span class="text-green-600">Rp ${d.dibayar.toLocaleString()}</span></div>
                            <div class="flex justify-between font-medium"><span>Sisa:</span><span class="${d.sisa > 0 ? 'text-amber-600' : 'text-green-600'}">Rp ${d.sisa.toLocaleString()}</span></div>
                        </div>`;
                    });
                    html += `</div>`;
                    dataDiv.innerHTML = html;
                }
                dataDiv.classList.remove('hidden');
                if (typeof lucide !== 'undefined') lucide.createIcons();
            }).catch(e => {
                loading.classList.add('hidden');
                dataDiv.innerHTML = `<div class="text-center text-red-500 py-4">Error: ${e.message}</div>`;
                dataDiv.classList.remove('hidden');
            });
        };

        window.closeDetailModal = function() {
            document.getElementById('detailModal').classList.add('hidden');
        };

        // DOM Ready
        document.addEventListener('DOMContentLoaded', function() {
            if (typeof lucide !== 'undefined') lucide.createIcons();

            const selectAll = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('.mahasiswa-checkbox');
            const potonganBtn = document.getElementById('potonganBtn');
            const selectedCount = document.getElementById('selectedCount');

            function updateSelected() {
                const checked = document.querySelectorAll('.mahasiswa-checkbox:checked').length;
                selectedCount.textContent = checked + ' mahasiswa dipilih';
                potonganBtn.disabled = checked === 0;
                document.getElementById('selectedCountModal').textContent = checked;
            }

            if (selectAll) {
                selectAll.addEventListener('change', function() {
                    checkboxes.forEach(cb => cb.checked = this.checked);
                    updateSelected();
                });
            }
            checkboxes.forEach(cb => cb.addEventListener('change', updateSelected));
            window.clearSelection = function() {
                checkboxes.forEach(cb => cb.checked = false);
                if (selectAll) selectAll.checked = false;
                updateSelected();
            };
            updateSelected();
        });
    </script>
</x-app-layout>
