<x-app-layout>
    <x-slot name="header">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-1">
            <h2 class="font-semibold text-lg leading-tight text-white">
                <i class="fas fa-users mr-2 opacity-80"></i>
                Daftar Pasien yang Ditangani
            </h2>
            <span class="text-sm text-teal-100 opacity-80">
                <i class="fas fa-calendar-day mr-1"></i>
                {{ now()->isoFormat('dddd, D MMMM YYYY') }}
            </span>
        </div>
    </x-slot>

    @push('styles')
    {{-- DataTables CSS sudah di-load di app.blade.php (v2.3.7) --}}

    <style>
        /* ═══════════════════════════════════════════
           STAT CARDS
        ═══════════════════════════════════════════ */
        .stat-card {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1.25rem 1.5rem;
            border-radius: 1rem;
            background: #fff;
            border: 1px solid #f1f5f9;
            box-shadow: 0 1px 4px rgba(0,0,0,.05);
            transition: box-shadow .2s, transform .2s;
        }
        .dark .stat-card {
            background: #1e293b;
            border-color: #334155;
        }
        .stat-card:hover {
            box-shadow: 0 4px 16px rgba(0,0,0,.08);
            transform: translateY(-2px);
        }
        .stat-icon {
            width: 3rem;
            height: 3rem;
            border-radius: .875rem;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            font-size: 1.125rem;
            color: #fff;
            box-shadow: 0 4px 10px rgba(0,0,0,.12);
        }
        .stat-label {
            font-size: .75rem;
            font-weight: 600;
            color: #94a3b8;
            text-transform: uppercase;
            letter-spacing: .05em;
        }
        .stat-value {
            font-size: 1.75rem;
            font-weight: 800;
            color: #0f172a;
            line-height: 1;
            margin-top: .25rem;
        }
        .dark .stat-value { color: #f1f5f9; }

        /* ═══════════════════════════════════════════
           CONTROL BAR
        ═══════════════════════════════════════════ */
        .ctrl-card {
            background: #fff;
            border: 1px solid #f1f5f9;
            border-radius: 1rem;
            padding: 1rem 1.25rem;
            box-shadow: 0 1px 4px rgba(0,0,0,.04);
        }
        .dark .ctrl-card {
            background: #1e293b;
            border-color: #334155;
        }
        .ctrl-input {
            height: 2.5rem;
            padding: 0 .875rem;
            border: 1.5px solid #e2e8f0;
            border-radius: .625rem;
            font-size: .875rem;
            background: #f8fafc;
            color: #0f172a;
            outline: none;
            transition: border-color .2s, box-shadow .2s, background .2s;
        }
        .dark .ctrl-input {
            background: #0f172a;
            border-color: #334155;
            color: #f1f5f9;
        }
        .ctrl-input:focus {
            border-color: #14b8a6;
            box-shadow: 0 0 0 3px rgba(20,184,166,.15);
            background: #fff;
        }
        .dark .ctrl-input:focus { background: #1e293b; }

        /* ═══════════════════════════════════════════
           TABLE CARD
        ═══════════════════════════════════════════ */
        .table-card {
            background: #fff;
            border: 1px solid #f1f5f9;
            border-radius: 1rem;
            box-shadow: 0 1px 4px rgba(0,0,0,.04);
            overflow: hidden;
        }
        .dark .table-card {
            background: #1e293b;
            border-color: #334155;
        }
        .table-card-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: .875rem 1.25rem;
            border-bottom: 1px solid #f1f5f9;
            background: #f8fafc;
        }
        .dark .table-card-header {
            background: #0f172a;
            border-bottom-color: #334155;
        }



        /* ═══════════════════════════════════════════
           BADGES & AVATAR
        ═══════════════════════════════════════════ */
        .avatar-circle {
            background: linear-gradient(135deg, #14b8a6, #0d9488);
            width: 2.375rem;
            height: 2.375rem;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            color: #fff;
            font-size: .875rem;
            font-weight: 700;
            box-shadow: 0 2px 6px rgba(20,184,166,.3);
        }

        .badge {
            display: inline-flex;
            align-items: center;
            gap: .375rem;
            padding: .2rem .65rem;
            border-radius: 99px;
            font-size: .72rem;
            font-weight: 700;
            white-space: nowrap;
        }
        .badge-dot {
            width: .45rem;
            height: .45rem;
            border-radius: 50%;
            flex-shrink: 0;
        }
        .badge-aktif  { background: rgba(20,184,166,.12); color: #0d9488; }
        .badge-selesai{ background: rgba(100,116,139,.1);  color: #475569; }
        .badge-rujuk  { background: rgba(249,115,22,.12);  color: #ea580c; }
        .badge-dot-aktif   { background: #10b981; }
        .badge-dot-selesai { background: #94a3b8; }
        .badge-dot-rujuk   { background: #f97316; }
        .dark .badge-aktif  { background: rgba(20,184,166,.18); color: #2dd4bf; }
        .dark .badge-selesai{ background: rgba(148,163,184,.1); color: #94a3b8; }
        .dark .badge-rujuk  { background: rgba(249,115,22,.18); color: #fb923c; }

        /* Row action buttons */
        .row-btn {
            display: inline-flex;
            align-items: center;
            gap: .375rem;
            padding: .35rem .75rem;
            border-radius: .5rem;
            font-size: .75rem;
            font-weight: 600;
            white-space: nowrap;
            transition: background .15s, transform .1s;
            text-decoration: none;
        }
        .row-btn:active { transform: scale(.95); }
        .row-btn-teal  { background: rgba(20,184,166,.1); color: #0d9488; }
        .row-btn-teal:hover { background: rgba(20,184,166,.2); }
        .row-btn-blue  { background: rgba(59,130,246,.1); color: #3b82f6; }
        .row-btn-blue:hover { background: rgba(59,130,246,.2); }
        .dark .row-btn-teal { color: #2dd4bf; }
        .dark .row-btn-blue { color: #60a5fa; }

        /* Filter pill */
        .filter-pill {
            display: inline-flex;
            align-items: center;
            gap: .375rem;
            padding: .2rem .7rem;
            border-radius: 99px;
            font-size: .75rem;
            font-weight: 600;
            background: rgba(20,184,166,.1);
            color: #0d9488;
        }
        .dark .filter-pill { color: #2dd4bf; background: rgba(20,184,166,.15); }
        .filter-pill button { line-height: 1; }

        /* Empty state */
        .empty-state {
            padding: 4rem 1rem;
            text-align: center;
        }

        /* Mobile responsive adjustments */
        @media (max-width: 640px) {
            .stat-card { padding: 1rem; }
            .stat-value { font-size: 1.5rem; }
            .stat-icon { width: 2.5rem; height: 2.5rem; font-size: 1rem; border-radius: .75rem; }
            #tabelPasien thead th,
            #tabelPasien tbody td { padding: .625rem .75rem; }
        }
    </style>
    @endpush

    <div class="py-6 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto space-y-5">

        {{-- ══ STAT CARDS ══ --}}
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">

            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg,#3b82f6,#2563eb);">
                    <i class="fas fa-users"></i>
                </div>
                <div>
                    <p class="stat-label">Total Pasien</p>
                    <p class="stat-value">{{ $stats['total'] }}</p>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg,#14b8a6,#0d9488);">
                    <i class="fas fa-heartbeat"></i>
                </div>
                <div>
                    <p class="stat-label">Pasien Aktif</p>
                    <p class="stat-value">{{ $stats['aktif'] }}</p>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon" style="background: linear-gradient(135deg,#f59e0b,#d97706);">
                    <i class="fas fa-calendar-check"></i>
                </div>
                <div>
                    <p class="stat-label">Kontrol Hari Ini</p>
                    <p class="stat-value">{{ $stats['kontrol_hari_ini'] }}</p>
                </div>
            </div>

        </div>

        {{-- ══ FILTER & CONTROL BAR ══ --}}
        <div class="ctrl-card">
            <div class="flex flex-col sm:flex-row gap-3 items-stretch sm:items-center flex-wrap">

                {{-- Search --}}
                <div class="relative flex-1 min-w-[200px]">
                    <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-sm pointer-events-none"></i>
                    <input type="text" id="searchInput"
                           placeholder="Cari nama, no. rekam medis, NIK..."
                           class="ctrl-input w-full pl-9">
                </div>

                {{-- Status Filter --}}
                <select id="statusFilter" class="ctrl-input min-w-[145px]">
                    <option value="">Semua Status</option>
                    <option value="Aktif">Aktif</option>
                    <option value="Selesai">Selesai</option>
                    <option value="Rujuk">Rujuk</option>
                </select>

                {{-- Kontrol Filter --}}
                <select id="kontrolFilter" class="ctrl-input min-w-[155px]">
                    <option value="">Semua Jadwal</option>
                    <option value="hari-ini">Kontrol Hari Ini</option>
                    <option value="belum">Belum Dijadwalkan</option>
                </select>

                {{-- Reset --}}
                <button id="btnReset"
                        class="h-10 px-4 rounded-lg text-sm font-medium border border-slate-200 dark:border-slate-700 text-slate-500 dark:text-slate-400 hover:border-teal-400 hover:text-teal-600 dark:hover:text-teal-400 transition-colors flex-shrink-0 flex items-center gap-1.5">
                    <i class="fas fa-rotate-right text-sm"></i>
                    <span>Reset</span>
                </button>

            </div>

            {{-- Active filter pills --}}
            <div id="filterPills" class="mt-3 flex flex-wrap gap-2 hidden"></div>
        </div>

        {{-- ══ TABLE CARD ══ --}}
        <div class="table-card">

            {{-- Table header bar --}}
            <div class="table-card-header">
                <div class="flex items-center gap-2.5">
                    <div class="w-7 h-7 rounded-lg flex items-center justify-center"
                         style="background: rgba(20,184,166,.12);">
                        <i class="fas fa-table-list text-[11px]" style="color:#14b8a6;"></i>
                    </div>
                    <span class="text-sm font-semibold text-slate-700 dark:text-slate-200">Daftar Pasien</span>
                </div>

            </div>

            {{-- Scrollable table --}}
            <div class="overflow-x-auto">
                <table id="tabelPasien" class="min-w-full" style="width:100%">
                    <thead>
                        <tr>
                            <th class="w-10 text-center">#</th>
                            <th>Pasien</th>
                            <th>Diagnosis</th>
                            <th>Kontrol Berikutnya</th>
                            <th>Status</th>
                            <th class="text-center" style="width:130px;">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($pasien as $index => $item)
                            @php
                                $isKontrolHariIni = $item->tanggal_kontrol_berikutnya &&
                                    \Carbon\Carbon::parse($item->tanggal_kontrol_berikutnya)->isToday();
                                $badgeClass = match($item->status_penanganan) {
                                    'AKTIF'   => 'badge-aktif',
                                    'SELESAI' => 'badge-selesai',
                                    'RUJUK'   => 'badge-rujuk',
                                    default   => 'badge-selesai',
                                };
                                $dotClass = match($item->status_penanganan) {
                                    'AKTIF'   => 'badge-dot-aktif',
                                    'SELESAI' => 'badge-dot-selesai',
                                    'RUJUK'   => 'badge-dot-rujuk',
                                    default   => 'badge-dot-selesai',
                                };
                                $statusLabel = match($item->status_penanganan) {
                                    'AKTIF'   => 'Aktif',
                                    'SELESAI' => 'Selesai',
                                    'RUJUK'   => 'Rujuk',
                                    default   => $item->status_penanganan,
                                };
                                $initial = strtoupper(substr($item->pasien->nama_lengkap ?? 'P', 0, 1));
                            @endphp
                            <tr class="{{ $isKontrolHariIni ? 'kontrol-hari-ini' : '' }}">

                                {{-- No --}}
                                <td class="text-center">
                                    <span class="text-xs text-slate-400 font-mono">
                                        {{ $pasien->firstItem() + $index }}
                                    </span>
                                </td>

                                {{-- Pasien --}}
                                <td>
                                    <div class="flex items-center gap-3">
                                        <div class="avatar-circle">{{ $initial }}</div>
                                        <div class="min-w-0">
                                            <p class="font-semibold text-slate-800 dark:text-slate-100 text-sm leading-tight truncate max-w-[160px] sm:max-w-none">
                                                {{ $item->pasien->nama_lengkap ?? 'N/A' }}
                                            </p>
                                            <p class="text-xs text-slate-400 mt-0.5 font-mono">
                                                {{ $item->pasien->no_rekam_medis ?? '-' }}
                                            </p>
                                            @if($item->pasien->no_telepon ?? false)
                                            <p class="text-xs text-slate-400">
                                                <i class="fas fa-phone text-[9px] mr-1"></i>{{ $item->pasien->no_telepon }}
                                            </p>
                                            @endif
                                        </div>
                                    </div>
                                </td>

                                {{-- Diagnosis --}}
                                <td>
                                    @if($item->diagnosis_utama)
                                        <p class="text-sm text-slate-700 dark:text-slate-300 leading-snug max-w-[200px]" title="{{ $item->diagnosis_utama }}">
                                            {{ Str::limit($item->diagnosis_utama, 45) }}
                                        </p>
                                    @else
                                        <span class="text-xs text-slate-400 italic">Belum ada diagnosis</span>
                                    @endif
                                </td>

                                {{-- Kontrol Berikutnya --}}
                                <td>
                                    @if($item->tanggal_kontrol_berikutnya)
                                        @php $tgl = \Carbon\Carbon::parse($item->tanggal_kontrol_berikutnya); @endphp
                                        @if($isKontrolHariIni)
                                            <span class="badge badge-aktif">
                                                <span class="badge-dot badge-dot-aktif animate-pulse"></span>
                                                Hari Ini
                                            </span>
                                        @else
                                            <div>
                                                <p class="text-sm font-semibold text-slate-700 dark:text-slate-200">
                                                    {{ $tgl->format('d M Y') }}
                                                </p>
                                                <p class="text-xs text-slate-400 mt-0.5">{{ $tgl->diffForHumans() }}</p>
                                            </div>
                                        @endif
                                    @else
                                        <span class="text-xs text-slate-400 italic">Belum dijadwalkan</span>
                                    @endif
                                </td>

                                {{-- Status --}}
                                <td>
                                    <span class="badge {{ $badgeClass }}">
                                        <span class="badge-dot {{ $dotClass }} {{ $item->status_penanganan === 'AKTIF' ? 'animate-pulse' : '' }}"></span>
                                        {{ $statusLabel }}
                                    </span>
                                </td>

                                {{-- Aksi --}}
                                <td>
                                    <div class="flex items-center justify-center gap-1.5">
                                        <a href="{{ route('dokter.pasien.detail', $item->pasien_id) }}"
                                           class="row-btn row-btn-teal" title="Lihat Detail">
                                            <i class="fas fa-eye text-[11px]"></i>
                                            <span class="hidden sm:inline">Detail</span>
                                        </a>
                                        <a href="{{ route('dokter.pasien.update-penanganan', $item->pasien_id) }}"
                                           class="row-btn row-btn-blue" title="Update Penanganan">
                                            <i class="fas fa-pen-to-square text-[11px]"></i>
                                            <span class="hidden sm:inline">Update</span>
                                        </a>
                                    </div>
                                </td>

                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>

            {{-- Empty state --}}
            @if($pasien->count() === 0)
            <div class="empty-state">
                <div class="w-16 h-16 rounded-2xl mx-auto flex items-center justify-center mb-4"
                     style="background:rgba(20,184,166,.08);">
                    <i class="fas fa-user-slash text-2xl" style="color:#14b8a6;"></i>
                </div>
                <p class="font-semibold text-slate-700 dark:text-slate-200 text-base">Tidak ada pasien ditemukan</p>
                <p class="text-slate-400 text-sm mt-1">
                    @if(request('search'))
                        Tidak ditemukan hasil untuk pencarian <strong>"{{ request('search') }}"</strong>.
                    @else
                        Anda belum memiliki pasien yang ditangani saat ini.
                    @endif
                </p>
            </div>
            @endif

        </div>

    </div>{{-- end page --}}

    @push('scripts')
    {{-- DataTables JS --}}
    {{-- DataTables JS sudah di-load di app.blade.php (v2.3.7) --}}
    <script>
    $(document).ready(function () {

        // ── Init DataTable ────────────────────────────────────────────
        const dt = $('#tabelPasien').DataTable({
            responsive: true,
            pageLength: 25,
            ordering: true,
            language: window.dtLangId,
            columnDefs: [
                { targets: [0, 5], orderable: false },
                { targets: 0, width: '48px', className: 'text-center' },
                { targets: 5, className: 'text-center' },
            ],
        });

        // ── Custom Search ─────────────────────────────────────────────
        $('#searchInput').on('keyup', function () {
            dt.search(this.value).draw();
            updatePills();
        });

        // ── Custom column filters ─────────────────────────────────────
        $.fn.dataTable.ext.search.push(function (settings, data) {
            if (settings.nTable.id !== 'tabelPasien') return true;
            const status  = $('#statusFilter').val();
            const kontrol = $('#kontrolFilter').val();

            if (status && !data[4].includes(status)) return false;

            if (kontrol === 'hari-ini' && !data[3].includes('Hari Ini')) return false;
            if (kontrol === 'belum'    && !data[3].includes('Belum dijadwalkan')) return false;

            return true;
        });

        $('#statusFilter, #kontrolFilter').on('change', function () {
            dt.draw();
            updatePills();
        });


        // ── Reset ─────────────────────────────────────────────────────
        $('#btnReset').on('click', function () {
            $('#searchInput').val('');
            $('#statusFilter, #kontrolFilter').val('');
            dt.search('').draw();
            updatePills();
        });

        // ── Filter pills ──────────────────────────────────────────────
        function updatePills() {
            const q  = $('#searchInput').val();
            const st = $('#statusFilter').val();
            const ko = $('#kontrolFilter').val();
            const pills = [];

            if (q)  pills.push({ label: `Cari: "${q}"`,  id: 'q' });
            if (st) pills.push({ label: `Status: ${st}`, id: 'st' });
            if (ko) pills.push({ label: `Jadwal: ${ ko === 'hari-ini' ? 'Hari Ini' : 'Belum Dijadwalkan' }`, id: 'ko' });

            const $pills = $('#filterPills');
            if (!pills.length) { $pills.addClass('hidden').empty(); return; }
            $pills.removeClass('hidden').empty();
            pills.forEach(p => {
                $pills.append(`
                    <span class="filter-pill">
                        ${p.label}
                        <button onclick="clearPill('${p.id}')" class="ml-0.5 hover:opacity-70 focus:outline-none" title="Hapus filter">
                            <i class="fas fa-xmark text-[10px]"></i>
                        </button>
                    </span>
                `);
            });
        }

        window.clearPill = function (id) {
            if (id === 'q')  { $('#searchInput').val(''); dt.search('').draw(); }
            if (id === 'st') { $('#statusFilter').val(''); dt.draw(); }
            if (id === 'ko') { $('#kontrolFilter').val(''); dt.draw(); }
            updatePills();
        };

    });
    </script>
    @endpush

</x-app-layout>