@extends('layouts.app')

@section('title', 'Pendaftaran Ekstrakurikuler')

@section('content')
<style>
*, *::before, *::after { box-sizing: border-box; }

.excul-wrap {
    max-width: 1200px;
    margin: 0 auto;
}

.page-header {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 16px;
    margin-bottom: 24px;
}

.page-header__left h1 {
    font-family: 'DM Serif Display', serif;
    font-size: 28px;
    color: #1C1B18;
    margin: 0 0 4px;
    letter-spacing: -0.02em;
    line-height: 1.15;
}

.page-header__left p {
    font-size: 13px;
    color: rgba(0,0,0,0.42);
    margin: 0;
}

.page-header__badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 14px;
    background: #FFF7ED;
    border: 0.5px solid #FED7AA;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    color: #9A3412;
    letter-spacing: 0.02em;
}

.page-header__badge .dot {
    width: 7px; height: 7px;
    border-radius: 50%;
    background: #F97316;
    animation: pulse-dot 1.8s ease-in-out infinite;
    flex-shrink: 0;
}

@keyframes pulse-dot {
    0%,100% { opacity:1; transform:scale(1); }
    50%      { opacity:.4; transform:scale(.8); }
}

.stat-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    margin-bottom: 20px;
}

.stat-card {
    background: #fff;
    border: 0.5px solid rgba(0,0,0,0.09);
    border-radius: 10px;
    padding: 16px 20px;
    display: flex;
    align-items: center;
    gap: 14px;
}

.stat-card__icon {
    width: 38px; height: 38px;
    border-radius: 8px;
    display: flex; align-items: center; justify-content: center;
    font-size: 16px;
    flex-shrink: 0;
}

.stat-card__icon--orange { background: #FFF7ED; }
.stat-card__icon--green  { background: #F0FDF4; }
.stat-card__icon--red    { background: #FFF5F5; }

.stat-card__val {
    font-size: 22px;
    font-weight: 700;
    color: #1C1B18;
    line-height: 1;
    margin-bottom: 3px;
    letter-spacing: -0.02em;
}

.stat-card__lbl {
    font-size: 12px;
    color: rgba(0,0,0,0.45);
    font-weight: 500;
}

.filter-card {
    background: #fff;
    border: 0.5px solid rgba(0,0,0,0.09);
    border-radius: 12px;
    padding: 16px 20px 0;
    margin-bottom: 20px;
}

.filter-row {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
    margin-bottom: 16px;
}

.filter-input, .filter-select {
    padding: 9px 13px;
    border: 0.5px solid rgba(0,0,0,0.15);
    border-radius: 8px;
    font-size: 13.5px;
    color: #1C1B18;
    background: #fff;
    transition: border-color .15s;
    outline: none;
}

.filter-input  { flex: 1; min-width: 200px; }
.filter-select { min-width: 160px; cursor: pointer; }

.filter-input:focus, .filter-select:focus {
    border-color: rgba(0,0,0,0.35);
}

.btn-search {
    padding: 9px 20px;
    background: #1C1B18;
    color: #fff;
    border: none;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    white-space: nowrap;
    transition: background .15s;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.btn-search:hover { background: #333; }

.btn-reset {
    padding: 9px 16px;
    border: 0.5px solid rgba(0,0,0,0.15);
    border-radius: 8px;
    background: transparent;
    color: rgba(0,0,0,0.55);
    text-decoration: none;
    font-size: 13px;
    font-weight: 500;
    white-space: nowrap;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    transition: background .15s;
}

.btn-reset:hover { background: #F8F7F4; color: #1C1B18; }

.chips {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin: 0 0 14px;
}

.chip {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 3px 10px;
    background: #F0F0EC;
    border-radius: 20px;
    font-size: 12px;
    color: #1C1B18;
    font-weight: 500;
}

.chip span { color: rgba(0,0,0,0.45); font-weight: 400; }

.tab-nav {
    display: flex;
    gap: 2px;
    border-top: 0.5px solid rgba(0,0,0,0.07);
}

.tab-link {
    padding: 11px 18px;
    border: none;
    background: transparent;
    color: rgba(0,0,0,0.5);
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    border-top: 2px solid transparent;
    margin-top: -0.5px;
    transition: all .15s;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.tab-link:hover  { color: #1C1B18; }
.tab-link.active { color: #1C1B18; border-top-color: #1C1B18; }

.tab-count {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 18px;
    height: 18px;
    padding: 0 5px;
    border-radius: 9px;
    font-size: 11px;
    font-weight: 600;
    background: rgba(0,0,0,0.07);
    color: rgba(0,0,0,0.55);
}

.tab-link.active .tab-count {
    background: #1C1B18;
    color: #fff;
}

.tab-count--orange { background: #FFF7ED; color: #9A3412; }
.tab-link.active .tab-count--orange { background: #F97316; color: #fff; }

.table-card {
    background: #fff;
    border: 0.5px solid rgba(0,0,0,0.09);
    border-radius: 12px;
    overflow: hidden;
}

.table-wrap { overflow-x: auto; }

table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13.5px;
}

thead th {
    background: #F8F7F4;
    padding: 11px 16px;
    text-align: left;
    font-size: 11px;
    font-weight: 600;
    letter-spacing: 0.06em;
    text-transform: uppercase;
    color: rgba(0,0,0,0.45);
    border-bottom: 0.5px solid rgba(0,0,0,0.09);
    white-space: nowrap;
}

tbody td {
    padding: 13px 16px;
    border-bottom: 0.5px solid rgba(0,0,0,0.05);
    vertical-align: middle;
}

tbody tr:last-child td { border-bottom: none; }
tbody tr:hover { background: #FAFAF8; }

.cell-siswa__name {
    font-weight: 600;
    color: #1C1B18;
    white-space: nowrap;
}

.cell-siswa__meta {
    font-size: 12px;
    color: rgba(0,0,0,0.45);
    margin-top: 2px;
    white-space: nowrap;
}

.cell-excul__name { font-weight: 500; color: #1C1B18; }

.cell-date {
    color: rgba(0,0,0,0.55);
    white-space: nowrap;
    font-size: 13px;
}

.cell-ket {
    font-size: 12.5px;
    color: rgba(0,0,0,0.6);
    max-width: 200px;
}

.badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 11.5px;
    font-weight: 600;
    letter-spacing: 0.02em;
    white-space: nowrap;
}

.badge .dot {
    width: 5px; height: 5px;
    border-radius: 50%;
    flex-shrink: 0;
}

.badge--pending  { background: #FFF7ED; color: #9A3412; }
.badge--pending .dot { background: #F97316; animation: pulse-dot 1.8s ease-in-out infinite; }
.badge--approved { background: #F0FDF4; color: #14532D; }
.badge--approved .dot { background: #22C55E; }
.badge--rejected { background: #FFF5F5; color: #7F1D1D; }
.badge--rejected .dot { background: #EF4444; }
.badge--exited   { background: #F8F8F6; color: rgba(0,0,0,0.5); }
.badge--exited .dot { background: rgba(0,0,0,0.25); }

.quota-wrap { display: flex; flex-direction: column; gap: 3px; min-width: 80px; }
.quota-bar-track {
    height: 4px;
    background: rgba(0,0,0,0.07);
    border-radius: 2px;
    overflow: hidden;
}
.quota-bar-fill { height: 100%; border-radius: 2px; transition: width .3s ease; }
.quota-bar-fill--ok   { background: #22C55E; }
.quota-bar-fill--mid  { background: #F59E0B; }
.quota-bar-fill--full { background: #EF4444; }
.quota-label { font-size: 11px; color: rgba(0,0,0,0.45); font-weight: 500; }

.action-cell { text-align: right; white-space: nowrap; }

.btn-approve, .btn-reject, .btn-detail {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 7px 13px;
    border-radius: 7px;
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
    border: none;
    transition: all .15s;
    white-space: nowrap;
}

.btn-approve {
    background: #F0FDF4;
    color: #15803D;
    border: 0.5px solid #BBF7D0;
}
.btn-approve:hover:not(:disabled) {
    background: #22C55E; color: #fff; border-color: #22C55E;
}

.btn-reject {
    background: #FFF5F5;
    color: #DC2626;
    border: 0.5px solid #FECACA;
}
.btn-reject:hover:not(:disabled) {
    background: #EF4444; color: #fff; border-color: #EF4444;
}

.btn-detail {
    background: #F8F7F4;
    color: #1C1B18;
    border: 0.5px solid rgba(0,0,0,0.1);
    text-decoration: none;
}
.btn-detail:hover { background: #1C1B18; color: #fff; border-color: #1C1B18; }

.btn-approve:disabled, .btn-reject:disabled {
    opacity: .5; cursor: not-allowed; pointer-events: none;
}

.empty-state { text-align: center; padding: 64px 24px; }
.empty-icon {
    width: 52px; height: 52px;
    border-radius: 12px;
    background: #F8F7F4;
    display: flex; align-items: center; justify-content: center;
    margin: 0 auto 16px;
    font-size: 22px;
}
.empty-state h3 { font-size: 15px; font-weight: 600; color: #1C1B18; margin: 0 0 6px; }
.empty-state p  { font-size: 13px; color: rgba(0,0,0,0.42); margin: 0 auto; max-width: 320px; line-height: 1.6; }

.pagination {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 14px 20px;
    border-top: 0.5px solid rgba(0,0,0,0.07);
    gap: 12px;
    flex-wrap: wrap;
}
.pagination__info { font-size: 12.5px; color: rgba(0,0,0,0.45); }
.pagination__links { display: flex; gap: 4px; flex-wrap: wrap; }
.pagination__links a,
.pagination__links span {
    display: inline-flex; align-items: center; justify-content: center;
    min-width: 32px; height: 32px; padding: 0 10px;
    border-radius: 6px; border: 0.5px solid rgba(0,0,0,0.1);
    background: #fff; text-decoration: none; color: #1C1B18;
    font-size: 12.5px; font-weight: 500; transition: all .12s;
}
.pagination__links a:hover       { background: #F8F7F4; border-color: rgba(0,0,0,0.2); }
.pagination__links span.active   { background: #1C1B18; color: #fff; border-color: #1C1B18; }
.pagination__links span.disabled { opacity: .35; cursor: not-allowed; }

.modal-backdrop {
    position: fixed; inset: 0;
    background: rgba(0,0,0,0.35);
    z-index: 1000;
    display: none; align-items: center; justify-content: center;
    padding: 20px;
}
.modal-backdrop.open { display: flex; }

.modal {
    background: #fff; border-radius: 14px; padding: 28px;
    width: 100%; max-width: 420px;
    box-shadow: 0 20px 60px rgba(0,0,0,0.15);
}
.modal h3 { font-size: 16px; font-weight: 700; color: #1C1B18; margin: 0 0 6px; }
.modal p  { font-size: 13px; color: rgba(0,0,0,0.5); margin: 0 0 18px; line-height: 1.55; }
.modal textarea {
    width: 100%; padding: 10px 13px;
    border: 0.5px solid rgba(0,0,0,0.18); border-radius: 8px;
    font-size: 13.5px; color: #1C1B18; resize: vertical; min-height: 90px;
    font-family: inherit; transition: border-color .15s; outline: none; background: #FAFAF8;
}
.modal textarea:focus { border-color: rgba(0,0,0,0.4); background: #fff; }
.modal-actions { display: flex; gap: 10px; margin-top: 18px; justify-content: flex-end; }
.modal-cancel {
    padding: 9px 18px; border: 0.5px solid rgba(0,0,0,0.15); border-radius: 8px;
    background: transparent; font-size: 13px; font-weight: 600;
    color: rgba(0,0,0,0.6); cursor: pointer; transition: background .12s;
}
.modal-cancel:hover { background: #F8F7F4; color: #1C1B18; }
.modal-confirm-reject {
    padding: 9px 18px; border: none; border-radius: 8px;
    background: #EF4444; color: #fff; font-size: 13px; font-weight: 600;
    cursor: pointer; transition: background .12s;
    display: inline-flex; align-items: center; gap: 6px;
}
.modal-confirm-reject:hover    { background: #DC2626; }
.modal-confirm-reject:disabled { opacity: .6; cursor: not-allowed; }

.toast-wrap {
    position: fixed; bottom: 24px; right: 24px; z-index: 2000;
    display: flex; flex-direction: column; gap: 8px; pointer-events: none;
}
.toast {
    padding: 12px 18px; border-radius: 10px; font-size: 13.5px; font-weight: 500;
    color: #fff; box-shadow: 0 4px 20px rgba(0,0,0,0.2);
    display: flex; align-items: center; gap: 10px;
    pointer-events: auto; animation: toast-in .25s ease forwards; max-width: 320px;
}
.toast--ok  { background: #16A34A; }
.toast--err { background: #DC2626; }

@keyframes toast-in  { from { opacity:0; transform:translateY(8px); } to { opacity:1; transform:translateY(0); } }
@keyframes toast-out { from { opacity:1; transform:translateY(0); } to { opacity:0; transform:translateY(8px); } }
.toast.fading { animation: toast-out .25s ease forwards; }

tr.processing td { opacity: .45; pointer-events: none; }

@media (max-width: 768px) {
    .stat-row { grid-template-columns: 1fr 1fr; }
    .stat-row .stat-card:last-child { grid-column: span 2; }
    .page-header { flex-direction: column; align-items: flex-start; }
    .filter-input { min-width: 100%; }
    thead th:nth-child(5), thead th:nth-child(6),
    tbody td:nth-child(5), tbody td:nth-child(6) { display: none; }
}
@media (max-width: 540px) {
    .stat-row { grid-template-columns: 1fr; }
    .stat-row .stat-card:last-child { grid-column: span 1; }
}
</style>

@php
    use App\Enums\IzinStatus;

    $totalPending  = $totalPending  ?? 0;
    $totalApproved = $totalApproved ?? 0;
    $totalRejected = $totalRejected ?? 0;
    $currentStatus = $currentStatus ?? '';
    $search        = $search        ?? '';
    $kel           = $kel           ?? '';
    $tanggal       = $tanggal       ?? '';

    // Hanya isi yang tidak kosong agar URL bersih
    $filterParams = array_filter([
        'search'  => $search,
        'kel'     => $kel,
        'tanggal' => $tanggal,
    ], fn($v) => $v !== '' && $v !== null);

    // URL tab — disiapkan di PHP, render pakai {!! !!} agar & tidak di-escape
    $urlAll      = route('index', $filterParams);
    $urlPending  = route('index', array_merge(['status' => 'pending'],  $filterParams));
    $urlApproved = route('index', array_merge(['status' => 'approved'], $filterParams));
    $urlRejected = route('index', array_merge(['status' => 'rejected'], $filterParams));
    $urlReset    = route('index', $currentStatus ? ['status' => $currentStatus] : []);
    $urlFormAction = route('index');
@endphp

<div class="excul-wrap">

    {{-- Page Header --}}
    <div class="page-header">
        <div class="page-header__left">
            <h1>Pendaftaran Ekskul</h1>
            <p>Setujui atau tolak permohonan ekstrakurikuler siswa</p>
        </div>
        @if($totalPending > 0)
            <div class="page-header__badge">
                <span class="dot"></span>
                {{ $totalPending }} menunggu persetujuan
            </div>
        @endif
    </div>

    {{-- Stat Row --}}
    <div class="stat-row">
        <div class="stat-card">
            <div class="stat-card__icon stat-card__icon--orange">🕐</div>
            <div>
                <div class="stat-card__val">{{ number_format($totalPending) }}</div>
                <div class="stat-card__lbl">Menunggu</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card__icon stat-card__icon--green">✓</div>
            <div>
                <div class="stat-card__val">{{ number_format($totalApproved) }}</div>
                <div class="stat-card__lbl">Disetujui</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card__icon stat-card__icon--red">✕</div>
            <div>
                <div class="stat-card__val">{{ number_format($totalRejected) }}</div>
                <div class="stat-card__lbl">Ditolak</div>
            </div>
        </div>
    </div>

    {{-- Filter + Tabs --}}
    <div class="filter-card">
        <form method="GET" action="{!! $urlFormAction !!}" id="filter-form">
            @if($currentStatus)
                <input type="hidden" name="status" value="{{ $currentStatus }}">
            @endif

            <div class="filter-row">
                <input
                    type="text"
                    name="search"
                    class="filter-input"
                    placeholder="Cari nama siswa atau NIS…"
                    value="{{ $search }}"
                    autocomplete="off"
                >
                <input
                    type="text"
                    name="kel"
                    class="filter-select"
                    placeholder="Kelas"
                    value="{{ $kel }}"
                    autocomplete="off"
                    style="min-width:140px; width:auto;"
                >
                <input
                    type="date"
                    name="tanggal"
                    class="filter-select"
                    value="{{ $tanggal }}"
                    style="min-width:150px; width:auto;"
                >
                <button type="submit" class="btn-search">
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
                        <circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
                    </svg>
                    Cari
                </button>
                @if($search || $kel || $tanggal)
                    <a href="{!! $urlReset !!}" class="btn-reset">
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
                            <path d="M18 6 6 18M6 6l12 12"/>
                        </svg>
                        Reset
                    </a>
                @endif
            </div>
        </form>

        {{-- Active Chips --}}
        @if($search || $kel || $tanggal)
            <div class="chips">
                @if($search)
                    <div class="chip">Pencarian <span>"{{ $search }}"</span></div>
                @endif
                @if($kel)
                    <div class="chip">Kelas <span>{{ $kel }}</span></div>
                @endif
                @if($tanggal)
                    <div class="chip">
                        Tanggal <span>{{ \Carbon\Carbon::parse($tanggal)->translatedFormat('d M Y') }}</span>
                    </div>
                @endif
            </div>
        @endif

        {{-- Tabs — {!! !!} wajib agar & tidak jadi &amp; --}}
        <div class="tab-nav">
            <a href="{!! $urlAll !!}" class="tab-link {{ $currentStatus === '' ? 'active' : '' }}">
                Semua
                <span class="tab-count">{{ $totalPending + $totalApproved + $totalRejected }}</span>
            </a>
            <a href="{!! $urlPending !!}" class="tab-link {{ $currentStatus === 'pending' ? 'active' : '' }}">
                Menunggu
                @if($totalPending > 0)
                    <span class="tab-count tab-count--orange">{{ $totalPending }}</span>
                @endif
            </a>
            <a href="{!! $urlApproved !!}" class="tab-link {{ $currentStatus === 'approved' ? 'active' : '' }}">
                Disetujui
                <span class="tab-count">{{ $totalApproved }}</span>
            </a>
            <a href="{!! $urlRejected !!}" class="tab-link {{ $currentStatus === 'rejected' ? 'active' : '' }}">
                Ditolak
                <span class="tab-count">{{ $totalRejected }}</span>
            </a>
        </div>
    </div>

    {{-- Bulk Action Bar --}}
    <div
        id="bulk-action-bar"
        style="display:none; padding:16px 20px; background:#F8F7F4; border:0.5px solid rgba(0,0,0,0.09); border-radius:8px; margin-bottom:20px; gap:12px; align-items:center; flex-wrap:wrap;"
    >
        <span id="bulk-selected-count" style="font-size:13px; color:rgba(0,0,0,0.55); font-weight:500;">0 terpilih</span>
        <button class="btn-approve" onclick="doBulkApprove()" style="margin:0;">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
                <polyline points="20 6 9 17 4 12"/>
            </svg>
            Setujui Terpilih
        </button>
        <button class="btn-reject" onclick="openBulkRejectModal()" style="margin:0;">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
                <path d="M18 6 6 18M6 6l12 12"/>
            </svg>
            Tolak Terpilih
        </button>
    </div>

    {{-- Table Card --}}
    <div class="table-card">
        @if($izins->count() > 0)
            <div class="table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th style="width:36px">
                                <input type="checkbox" id="select-all" onclick="toggleSelectAll(this)">
                            </th>
                            <th>Siswa</th>
                            <th>Ekstrakurikuler</th>
                            <th>Kuota</th>
                            <th>Tgl. Daftar</th>
                            <th>Keterangan</th>
                            <th>Status</th>
                            <th style="text-align:right">Aksi</th>
                        </tr>
                    </thead>
                    <tbody id="tabel-body">
                        @foreach($izins as $item)
                            @php
                                $status = $item->sta instanceof IzinStatus
                                    ? $item->sta
                                    : IzinStatus::from((int) $item->sta);

                                $isPending  = $status === IzinStatus::PENDING;
                                $siswa      = $item->siswa;
                                $kelas      = $item->kelas;
                                $quota      = (int) ($kelas?->qty ?? 0);
                                $terdaftar  = (int) ($item->registered_count ?? 0);
                                $quotaPct   = $quota > 0 ? min(100, round($terdaftar / $quota * 100)) : 0;
                                $quotaClass = $quotaPct >= 100 ? 'full' : ($quotaPct >= 75 ? 'mid' : 'ok');
                            @endphp

                            <tr id="row-{{ $item->id }}" data-sta="{{ $status->value }}">

                                <td style="text-align:center">
                                    @if($isPending)
                                        <input
                                            type="checkbox"
                                            class="row-checkbox"
                                            value="{{ $item->id }}"
                                            onchange="updateSelectAllCheckbox()"
                                        >
                                    @endif
                                </td>

                                <td>
                                    <div class="cell-siswa__name">{{ $siswa?->namlen ?? '—' }}</div>
                                    <div class="cell-siswa__meta">
                                        @if($siswa?->nis) NIS {{ $siswa->nis }} @endif
                                        @if($kelas?->nam)
                                            @if($siswa?->nis) · @endif
                                            {{ $kelas->nam }}
                                        @endif
                                    </div>
                                </td>

                                <td>
                                    <div class="cell-excul__name">{{ $kelas?->nam ?? '—' }}</div>
                                </td>

                                <td>
                                    @if($quota > 0)
                                        <div class="quota-wrap">
                                            <div class="quota-label">{{ $terdaftar }}/{{ $quota }}</div>
                                            <div class="quota-bar-track">
                                                <div class="quota-bar-fill quota-bar-fill--{{ $quotaClass }}"
                                                     style="width:{{ $quotaPct }}%"></div>
                                            </div>
                                        </div>
                                    @else
                                        <span style="font-size:12px; color:rgba(0,0,0,0.35);">Tak terbatas</span>
                                    @endif
                                </td>

                                <td class="cell-date">
                                    {{ $item->tgl
                                        ? \Carbon\Carbon::parse($item->tgl)->translatedFormat('d M Y')
                                        : '—' }}
                                </td>

                                <td class="cell-ket" title="{{ $item->ket ?? '' }}">
                                    {{ \Illuminate\Support\Str::limit($item->ket ?? '—', 48) }}
                                </td>

                                <td>
                                    <span class="badge {{ $status->badgeClass() }}">
                                        <span class="dot"></span>
                                        {{ $status->label() }}
                                    </span>
                                </td>

                                <td class="action-cell">
                                    @if($isPending)
                                        <button
                                            class="btn-approve"
                                            onclick="doApprove({{ $item->id }}, this)"
                                            style="margin-right:5px;"
                                        >
                                            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
                                                <polyline points="20 6 9 17 4 12"/>
                                            </svg>
                                            Setujui
                                        </button>
                                        <button
                                            class="btn-reject"
                                            onclick="openRejectModal({{ $item->id }})"
                                        >
                                            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
                                                <path d="M18 6 6 18M6 6l12 12"/>
                                            </svg>
                                            Tolak
                                        </button>
                                    @endif
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>

            {{-- Pagination --}}
            @if($izins->hasPages())
                @php
                    $pgParams = array_filter([
                        'search'  => $search,
                        'kel'     => $kel,
                        'tanggal' => $tanggal,
                        'status'  => $currentStatus,
                    ], fn($v) => $v !== '' && $v !== null);
                    $qs = http_build_query($pgParams);
                @endphp
                <div class="pagination">
                    <div class="pagination__info">
                        Menampilkan
                        <strong>{{ $izins->firstItem() }}–{{ $izins->lastItem() }}</strong>
                        dari <strong>{{ $izins->total() }}</strong> data
                    </div>
                    <div class="pagination__links">
                        @if($izins->onFirstPage())
                            <span class="disabled">←</span>
                        @else
                            <a href="{!! $izins->previousPageUrl() . ($qs ? '&'.$qs : '') !!}">←</a>
                        @endif

                        @foreach($izins->getUrlRange(1, $izins->lastPage()) as $page => $url)
                            @if(abs($page - $izins->currentPage()) <= 2 || $page === 1 || $page === $izins->lastPage())
                                @if($page == $izins->currentPage())
                                    <span class="active">{{ $page }}</span>
                                @else
                                    <a href="{!! $url . ($qs ? '&'.$qs : '') !!}">{{ $page }}</a>
                                @endif
                            @elseif(abs($page - $izins->currentPage()) === 3)
                                <span class="disabled" style="border:none;background:none;padding:0 4px">…</span>
                            @endif
                        @endforeach

                        @if($izins->hasMorePages())
                            <a href="{!! $izins->nextPageUrl() . ($qs ? '&'.$qs : '') !!}">→</a>
                        @else
                            <span class="disabled">→</span>
                        @endif
                    </div>
                </div>
            @endif

        @else
            <div class="empty-state">
                <div class="empty-icon">📋</div>
                <h3>
                    @if($currentStatus === 'pending')      Tidak ada yang menunggu
                    @elseif($currentStatus === 'approved') Belum ada yang disetujui
                    @elseif($currentStatus === 'rejected') Belum ada yang ditolak
                    @else                                  Tidak ada data
                    @endif
                </h3>
                <p>
                    @if($search || $kel || $tanggal)
                        Tidak ditemukan pendaftaran yang cocok dengan filter aktif.
                        <a href="{!! route('index') !!}" style="color:#1C1B18;font-weight:600;">Reset filter</a>
                    @elseif($currentStatus === 'pending')
                        Semua pendaftaran sudah diproses.
                    @else
                        Belum ada pendaftaran ekstrakurikuler masuk.
                    @endif
                </p>
            </div>
        @endif
    </div>

</div>{{-- /.excul-wrap --}}

{{-- Reject Modal --}}
<div class="modal-backdrop" id="reject-modal" onclick="closeRejectModal(event)">
    <div class="modal" role="dialog" aria-modal="true" aria-labelledby="modal-title">
        <h3 id="modal-title">Tolak pendaftaran</h3>
        <p>Isi alasan penolakan agar siswa tahu apa yang perlu diperbaiki. Boleh dikosongkan.</p>
        <textarea id="reject-reason" placeholder="Contoh: Kuota kelas penuh, coba bulan depan…" maxlength="500"></textarea>
        <div style="text-align:right; margin-top:4px;">
            <span id="reason-counter" style="font-size:11px; color:rgba(0,0,0,0.35);">0/500</span>
        </div>
        <div class="modal-actions">
            <button class="modal-cancel" onclick="closeRejectModal()">Batal</button>
            <button class="modal-confirm-reject" id="modal-confirm-btn" onclick="submitReject()">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
                    <path d="M18 6 6 18M6 6l12 12"/>
                </svg>
                <span id="modal-confirm-text">Tolak pendaftaran</span>
            </button>
        </div>
    </div>
</div>

{{-- Toast --}}
<div class="toast-wrap" id="toast-wrap" aria-live="polite"></div>

<script>
const CSRF_TOKEN   = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
const STA_PENDING  = {{ IzinStatus::PENDING->value }};
const STA_APPROVED = {{ IzinStatus::APPROVED->value }};
const STA_REJECTED = {{ IzinStatus::REJECTED->value }};

let rejectTargetId = null;
let rejectMode     = 'single';
let rejectBulkIds  = [];

// ── Toast ─────────────────────────────────────────
function showToast(msg, type = 'ok') {
    const wrap  = document.getElementById('toast-wrap');
    const toast = document.createElement('div');
    toast.className = `toast toast--${type}`;
    const icon = type === 'ok'
        ? `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg>`
        : `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M18 6 6 18M6 6l12 12"/></svg>`;
    toast.innerHTML = icon + msg;
    wrap.appendChild(toast);
    setTimeout(() => {
        toast.classList.add('fading');
        toast.addEventListener('animationend', () => toast.remove(), { once: true });
    }, 3200);
}

// ── Approve Single ────────────────────────────────
async function doApprove(id, btn) {
    if (!confirm('Setujui pendaftaran ini?')) return;

    const row = document.getElementById(`row-${id}`);
    row.classList.add('processing');
    btn.disabled    = true;
    btn.textContent = '…';

    try {
        const res  = await fetch(`/excul/${id}/approve`, {
            method : 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF_TOKEN, 'Accept': 'application/json' },
        });
        const json = await res.json();

        if (!res.ok) {
            showToast(json.message ?? 'Gagal menyetujui.', 'err');
            row.classList.remove('processing');
            btn.disabled = false;
            btn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> Setujui`;
            return;
        }

        updateRowStatus(row, STA_APPROVED);
        updateStatCounter('pending',  -1);
        updateStatCounter('approved', +1);
        showToast('Pendaftaran berhasil disetujui.');
    } catch {
        showToast('Gagal menghubungi server.', 'err');
        row.classList.remove('processing');
        btn.disabled = false;
        btn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> Setujui`;
    }
}

// ── Reject Modal ──────────────────────────────────
function openRejectModal(id) {
    rejectTargetId = id;
    rejectMode     = 'single';
    resetModal('Tolak pendaftaran');
    document.getElementById('reject-modal').classList.add('open');
    setTimeout(() => document.getElementById('reject-reason').focus(), 80);
}

function openBulkRejectModal() {
    const selected = getSelectedIds();
    if (selected.length === 0) { showToast('Pilih minimal satu pendaftaran.', 'err'); return; }
    rejectBulkIds = selected;
    rejectMode    = 'bulk';
    resetModal(`Tolak ${selected.length} pendaftaran`);
    document.getElementById('reject-modal').classList.add('open');
    setTimeout(() => document.getElementById('reject-reason').focus(), 80);
}

function resetModal(label) {
    document.getElementById('reject-reason').value        = '';
    document.getElementById('reason-counter').textContent = '0/500';
    document.getElementById('modal-confirm-text').textContent = label;
    document.getElementById('modal-confirm-btn').disabled = false;
}

function closeRejectModal(e) {
    if (e && e.target !== document.getElementById('reject-modal')) return;
    document.getElementById('reject-modal').classList.remove('open');
    rejectTargetId = null;
}

document.addEventListener('keydown', e => {
    if (e.key === 'Escape') document.getElementById('reject-modal').classList.remove('open');
});

document.getElementById('reject-reason').addEventListener('input', function () {
    document.getElementById('reason-counter').textContent = `${this.value.length}/500`;
});

async function submitReject() {
    const alasan     = document.getElementById('reject-reason').value.trim();
    const confirmBtn = document.getElementById('modal-confirm-btn');
    confirmBtn.disabled    = true;
    confirmBtn.textContent = '…';

    if (rejectMode === 'single') {
        await rejectSingle(rejectTargetId, alasan);
    } else {
        await rejectBulk(rejectBulkIds, alasan);
    }

    document.getElementById('reject-modal').classList.remove('open');
    rejectTargetId = null;
    rejectBulkIds  = [];
}

async function rejectSingle(id, alasan) {
    const row = document.getElementById(`row-${id}`);
    row.classList.add('processing');
    try {
        const res  = await fetch(`/excul/${id}/reject`, {
            method : 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF_TOKEN, 'Accept': 'application/json' },
            body   : JSON.stringify({ alasan }),
        });
        const json = await res.json();
        if (!res.ok) {
            showToast(json.message ?? 'Gagal menolak.', 'err');
            row.classList.remove('processing');
        } else {
            updateRowStatus(row, STA_REJECTED);
            updateStatCounter('pending',  -1);
            updateStatCounter('rejected', +1);
            showToast('Pendaftaran berhasil ditolak.');
        }
    } catch {
        showToast('Gagal menghubungi server.', 'err');
        row.classList.remove('processing');
    }
}

// ── Bulk ──────────────────────────────────────────
async function doBulkApprove() {
    const selected = getSelectedIds();
    if (selected.length === 0) { showToast('Pilih minimal satu pendaftaran.', 'err'); return; }
    if (!confirm(`Setujui ${selected.length} pendaftaran?`)) return;

    selected.forEach(id => document.getElementById(`row-${id}`)?.classList.add('processing'));

    let ok = 0;
    for (const id of selected) {
        try {
            const res = await fetch(`/excul/${id}/approve`, {
                method : 'PATCH',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF_TOKEN, 'Accept': 'application/json' },
            });
            if (res.ok) { updateRowStatus(document.getElementById(`row-${id}`), STA_APPROVED); ok++; }
        } catch { /* lanjut */ }
    }

    updateStatCounter('pending',  -ok);
    updateStatCounter('approved', +ok);
    showToast(`${ok}/${selected.length} pendaftaran disetujui.`);
    resetSelectAll();
}

async function rejectBulk(ids, alasan) {
    ids.forEach(id => document.getElementById(`row-${id}`)?.classList.add('processing'));

    let ok = 0;
    for (const id of ids) {
        try {
            const res = await fetch(`/excul/${id}/reject`, {
                method : 'PATCH',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF_TOKEN, 'Accept': 'application/json' },
                body   : JSON.stringify({ alasan }),
            });
            if (res.ok) { updateRowStatus(document.getElementById(`row-${id}`), STA_REJECTED); ok++; }
        } catch { /* lanjut */ }
    }

    updateStatCounter('pending',  -ok);
    updateStatCounter('rejected', +ok);
    showToast(`${ok}/${ids.length} pendaftaran ditolak.`);
    resetSelectAll();
}

// ── DOM Helpers ───────────────────────────────────
function updateRowStatus(row, newSta) {
    if (!row) return;
    row.setAttribute('data-sta', newSta);
    row.classList.remove('processing');

    const badge = row.querySelector('.badge');
    if (badge) {
        const approved   = newSta === STA_APPROVED;
        badge.className  = `badge ${approved ? 'badge--approved' : 'badge--rejected'}`;
        badge.innerHTML  = `<span class="dot"></span>${approved ? 'Disetujui' : 'Ditolak'}`;
    }

    // Hapus checkbox & tombol aksi
    const cb = row.querySelector('.row-checkbox');
    if (cb) cb.remove();
    row.querySelectorAll('.btn-approve, .btn-reject').forEach(b => b.remove());
}

function updateStatCounter(type, delta) {
    const idx = { pending: 0, approved: 1, rejected: 2 }[type] ?? -1;
    if (idx < 0) return;
    const val = document.querySelectorAll('.stat-card')[idx]?.querySelector('.stat-card__val');
    if (!val) return;
    const cur = parseInt(val.textContent.replace(/\D/g, '')) || 0;
    val.textContent = Math.max(0, cur + delta).toLocaleString('id-ID');
}

function toggleSelectAll(cb) {
    document.querySelectorAll('.row-checkbox').forEach(c => c.checked = cb.checked);
    updateBulkActionBar();
}

function updateSelectAllCheckbox() {
    const total   = document.querySelectorAll('.row-checkbox').length;
    const checked = document.querySelectorAll('.row-checkbox:checked').length;
    const sa      = document.getElementById('select-all');
    sa.checked       = total > 0 && checked === total;
    sa.indeterminate = checked > 0 && checked < total;
    updateBulkActionBar();
}

function updateBulkActionBar() {
    const count = getSelectedIds().length;
    document.getElementById('bulk-selected-count').textContent = `${count} terpilih`;
    document.getElementById('bulk-action-bar').style.display   = count > 0 ? 'flex' : 'none';
}

function getSelectedIds() {
    return Array.from(document.querySelectorAll('.row-checkbox:checked')).map(cb => parseInt(cb.value));
}

function resetSelectAll() {
    const sa = document.getElementById('select-all');
    if (sa) { sa.checked = false; sa.indeterminate = false; }
    updateBulkActionBar();
}
</script>

@endsection