@extends('layouts.anggota')

@section('content')
<!-- Google Fonts & Tailwind CSS -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght=400;600;700;800;900&display=swap" rel="stylesheet">
<script src="https://cdn.tailwindcss.com"></script>

<style>
    .font-minimalis {
        font-family: 'Inter', sans-serif;
    }
    .text-hitam-pekat { color: #0f172a; }
    .text-biru-gelap { color: #0b2265; }
    .bg-biru-gelap { background-color: #0b2265; }
    ::-webkit-scrollbar {
        width: 5px;
    }
    ::-webkit-scrollbar-track {
        background: #f1f5f9;
    }
    ::-webkit-scrollbar-thumb {
        background: #cbd5e1;
        border-radius: 4px;
    }
    .tab-active {
        border-color: #0b2265;
        color: #0b2265;
        font-weight: 700;
    }
</style>

<div class="font-minimalis min-h-screen py-8 px-4 sm:px-6 lg:px-8 bg-[#f8fafc]">
    <div class="max-w-7xl mx-auto space-y-8">
        
      <!-- HEADER UTAMA DASHBOARD - PUSTAKA NAWASENA BAKORWIL III MALANG -->
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center border-b border-slate-200 pb-5 gap-4">
            <div>
                <h1 class="text-xl font-black text-hitam-pekat tracking-tight flex items-center gap-2">
                    <span class="w-2 h-6 bg-biru-gelap rounded-full inline-block"></span>
                    Statistik & Analitik Data Terpadu
                </h1>
                <div class="flex items-center gap-1.5 mt-0.5">
                    <span class="text-xs font-extrabold text-blue-700 bg-blue-50 px-1.5 py-0.5 rounded border border-blue-100 uppercase tracking-wide">Pustaka Nawasena</span>
                </div>
            </div>
    
        </div>

        <!-- ================= BAGIAN 1: RINGKASAN EKSEKUTIF TERPADU ================= -->
        <div class="grid grid-cols-2 gap-4 lg:grid-cols-4">
            <!-- Total Koleksi Buku Fisik -->
            <div class="bg-white rounded-xl p-5 border border-slate-200/80 shadow-sm flex flex-col justify-between">
                <div>
                    <p class="text-xs font-bold text-slate-400 uppercase tracking-wider">Total Koleksi Fisik</p>
                    <h3 class="text-3xl font-black text-hitam-pekat tracking-tight mt-1">{{ $totalBuku }}</h3>
                </div>
                <div class="mt-4 pt-3 border-t border-slate-100 flex justify-between items-center text-[11px] text-slate-400">
                    <span>Eksemplar di rak</span>
                </div>
            </div>

            <!-- Total Anggota -->
            <div class="bg-white rounded-xl p-5 border border-slate-200/80 shadow-sm flex flex-col justify-between">
                <div>
                    <p class="text-xs font-bold text-slate-400 uppercase tracking-wider">Total Anggota</p>
                    <h3 class="text-3xl font-black text-hitam-pekat tracking-tight mt-1">{{ $totalAnggota }}</h3>
                </div>
                <div class="mt-4 pt-3 border-t border-slate-100 flex justify-between items-center text-[11px] text-slate-400">
                    <span>Pemegang Kartu Aktif</span>
                </div>
            </div>

            <!-- Total Dipinjam -->
            <div class="bg-white rounded-xl p-5 border border-slate-200/80 shadow-sm flex flex-col justify-between">
                <div>
                    <p class="text-xs font-bold text-slate-400 uppercase tracking-wider">Sedang Dipinjam</p>
                    <h3 class="text-3xl font-black text-biru-gelap tracking-tight mt-1">{{ $totalPeminjaman }}</h3>
                </div>
                <div class="mt-4 pt-3 border-t border-slate-100 flex justify-between items-center text-[11px]">
                    <span class="text-blue-600 font-semibold">Bawa pulang aktif</span>
                    <span class="font-bold text-rose-600">{{ $totalTerlambat ?? 0 }} Terlambat</span>
                </div>
            </div>

            <!-- Total Dikembalikan -->
            <div class="bg-white rounded-xl p-5 border border-slate-200/80 shadow-sm flex flex-col justify-between">
                <div>
                    <p class="text-xs font-bold text-slate-400 uppercase tracking-wider">Selesai Kembali</p>
                    <h3 class="text-3xl font-black text-slate-700 tracking-tight mt-1">{{ $totalPengembalian }}</h3>
                </div>
                <div class="mt-4 pt-3 border-t border-slate-100 flex justify-between items-center text-[11px]">
                    <span class="text-emerald-600 font-semibold">Riwayat sirkulasi</span>
                </div>
            </div>
        </div>

        <!-- ================= BAGIAN 2: SIRKULASI UTAMA & SEBARAN GEOGRAFIS ================= -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Tren Peminjaman Buku Fisik Bulanan -->
            <div class="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden lg:col-span-2">
                <div class="p-5 border-b border-slate-100 bg-white">
                    <h4 class="text-xs font-extrabold text-biru-gelap uppercase tracking-widest">
                        Tren Sirkulasi & Peminjaman Buku Fisik
                    </h4>
                </div>
                <div class="p-6 bg-white">
                    <div class="relative w-full h-[350px]">
                        <canvas id="chartPeminjaman"></canvas>
                    </div>
                </div>
            </div>

            <!-- KONTEN SEBARAN GEOGRAFIS MODERN & PROFESIONAL -->
            <div class="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden lg:col-span-1 flex flex-col justify-between">
                <!-- Header Kontainer -->
                <div class="p-5 border-b border-slate-100 flex justify-between items-center bg-white">
                    <div>
                        <h4 class="text-xs font-extrabold text-[#0b2265] uppercase tracking-wider">Sebaran Wilayah Anggota</h4>
                        <p class="text-[10px] text-slate-400 font-medium mt-0.5">Analisis spasial demografi kartu aktif</p>
                    </div>
                    <span class="bg-slate-50 text-[#0b2265] text-[10px] font-bold px-2.5 py-1 rounded-md border border-slate-100 font-mono">
                        {{ count($wilayahLabels) }} Cakupan
                    </span>
                </div>
                
                @php
                    $totalSeluruhWilayah = array_sum($wilayahData) ?: 1;
                @endphp

                <!-- Area Visualisasi Grafik & Legenda Makro -->
                <div class="p-5 flex flex-col justify-center items-center flex-1 space-y-5">
                    <!-- Canvas Chart Pie -->
                    <div class="relative w-full h-[180px] flex justify-center">
                        <canvas id="chartWilayahSpasial"></canvas>
                    </div>

                    <!-- Tabel Legenda Data Formal -->
                    <div class="w-full border border-slate-100 rounded-lg overflow-hidden bg-slate-50/50">
                        <div class="max-h-[135px] overflow-y-auto divide-y divide-slate-100 text-[11px]">
                            @foreach($wilayahLabels as $index => $label)
                            @php
                                $persentase = round(($wilayahData[$index] / $totalSeluruhWilayah) * 100);
                            @endphp
                            <div class="flex justify-between items-center p-2.5 hover:bg-white transition-colors">
                                <div class="flex items-center gap-2 truncate max-w-[65%]">
                                    <span class="w-2 h-2 rounded-full shrink-0 opacity-80" id="legend-marker-{{ $index }}"></span>
                                    <span class="font-semibold text-slate-700 truncate">{{ $label }}</span>
                                </div>
                                <div class="flex items-center gap-3 font-mono">
                                    <span class="text-slate-900 font-bold">{{ number_format($wilayahData[$index]) }} <span class="text-[9px] text-slate-400 font-normal">org</span></span>
                                    <span class="text-slate-300 font-medium">|</span>
                                    <span class="text-[#0b2265] font-black min-w-[30px] text-right">{{ $persentase }}%</span>
                                </div>
                            </div>
                            @endforeach
                        </div>
                    </div>
                </div>

                <!-- Catatan Kaki Khusus Komponen -->
                <div class="p-4 bg-slate-50/70 border-t border-slate-100 flex items-center gap-2">
                    <svg class="w-3.5 h-3.5 text-slate-400 shrink-0" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m9-.75a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 3.75h.008v.008H12v-.008Z" />
                    </svg>
                    <p class="text-[10px] text-slate-400 leading-normal font-medium">
                        Standardisasi kode wilayah berdasarkan pendaftaran regional basis data Perpusnas.
                    </p>
                </div>
            </div>
        </div>

        <!-- ================= BAGIAN 3: PORTAL INFORMASI SEKTORAL ================= -->
        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 border-b border-slate-200 pb-2">
            <div class="flex border-b border-transparent space-x-6 font-semibold text-sm text-slate-500 overflow-x-auto w-full sm:w-auto">
                <button onclick="switchTab('tab-pengunjung')" id="btn-tab-pengunjung" class="pb-3 border-b-2 tab-active transition-all whitespace-nowrap">Aktivitas Portal Digital</button>
                <button onclick="switchTab('tab-keanggotaan')" id="btn-tab-keanggotaan" class="pb-3 border-b-2 border-transparent hover:text-slate-800 transition-all whitespace-nowrap">Keanggotaan & Demografi</button>
                <button onclick="switchTab('tab-koleksi')" id="btn-tab-koleksi" class="pb-3 border-b-2 border-transparent hover:text-slate-800 transition-all whitespace-nowrap">Koleksi Klasifikasi DDC</button>
            </div>
        </div>

        <!-- KONTEN TAB METRIK -->
        <div id="tab-content-area" class="mt-4">
            <!-- PANEL 1: AKSES PORTAL DIGITAL -->
            <div id="tab-pengunjung" class="tab-panel space-y-6">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div class="bg-white p-5 rounded-xl border border-slate-200/80 shadow-sm">
                        <span class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Aktivitas Hari Ini</span>
                        <div class="flex items-baseline space-x-2 mt-1">
                            <span class="text-2xl font-black text-hitam-pekat">{{ $userHariIni ?? 0 }}</span>
                            <span class="text-[11px] font-semibold text-emerald-600">Log Akses</span>
                        </div>
                    </div>
                    <div class="bg-white p-5 rounded-xl border border-slate-200/80 shadow-sm">
                        <span class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Log Sistem Bulan Ini</span>
                        <div class="flex items-baseline space-x-2 mt-1">
                            <span class="text-2xl font-black text-hitam-pekat">{{ $userBulanIni ?? 0 }}</span>
                            <span class="text-[11px] text-slate-400 font-medium">Total Sesi Aktif</span>
                        </div>
                    </div>
                    <div class="bg-white p-5 rounded-xl border border-slate-200/80 shadow-sm">
                        <span class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Total Akumulasi Log</span>
                        <div class="flex items-baseline space-x-2 mt-1">
                            <span class="text-2xl font-black text-biru-gelap">{{ $userTahunIni ?? 0 }}</span>
                            <span class="text-[11px] text-slate-400 font-medium">Sistem Terpadu</span>
                        </div>
                    </div>
                </div>
                <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
                    <h4 class="text-xs font-extrabold text-biru-gelap uppercase tracking-widest mb-4">Grafik Log Aktivitas Sistem Informasi (Berdasarkan Rentang Waktu)</h4>
                    <div class="h-[240px] relative"><canvas id="chartKunjunganTren"></canvas></div>
                </div>
            </div>

            <!-- PANEL 2: KEANGGOTAAN -->
            <div id="tab-keanggotaan" class="tab-panel hidden space-y-6">
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm flex flex-col justify-between">
                        <div>
                            <h4 class="text-xs font-extrabold text-biru-gelap uppercase tracking-widest mb-4">Rasio Anggota (Gender)</h4>
                            <div class="h-[180px] relative flex justify-center"><canvas id="chartGender"></canvas></div>
                        </div>
                    </div>
                    <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm lg:col-span-2">
                        <h4 class="text-xs font-extrabold text-biru-gelap uppercase tracking-widest mb-4">Data Grafik Anggota</h4>
                        <div class="h-[180px] relative"><canvas id="chartDataAnggota"></canvas></div>
                    </div>
                </div>
            </div>

            <!-- PANEL 3: KOLEKSI & KLASIFIKASI DDC -->
            <div id="tab-koleksi" class="tab-panel hidden space-y-6">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
                        <h4 class="text-xs font-extrabold text-biru-gelap uppercase tracking-widest mb-4">Koleksi Berdasarkan Subjek Klasifikasi DDC (Fisik)</h4>
                        <div class="h-[240px] relative"><canvas id="chartKlasifikasiKoleksi"></canvas></div>
                    </div>
                    <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
                        <h4 class="text-xs font-extrabold text-biru-gelap uppercase tracking-widest mb-4">Jenis Buku Fisik Paling Sering Dipinjam</h4>
                        <div class="h-[240px] relative"><canvas id="chartKoleksiTerpopuler"></canvas></div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

<!-- Script Chart.js Terintegrasi -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    function switchTab(tabId) {
        document.querySelectorAll('.tab-panel').forEach(panel => panel.classList.add('hidden'));
        document.getElementById(tabId).classList.remove('hidden');
        
        document.querySelectorAll('button[id^="btn-tab-"]').forEach(btn => {
            btn.classList.remove('tab-active');
            btn.classList.add('border-transparent', 'text-slate-500');
        });
        document.getElementById('btn-' + tabId).classList.add('tab-active');
    }

    document.addEventListener("DOMContentLoaded", function() {
        
        // --- 1. Chart Peminjaman Bulanan ---
        const ctxPeminjaman = document.getElementById('chartPeminjaman').getContext('2d');
        new Chart(ctxPeminjaman, {
            type: 'bar',
            data: {
                labels: {!! json_encode($bulanLabels) !!},
                datasets: [{
                    label: 'Volume Peminjaman Buku',
                    data: {!! json_encode($dataPeminjaman) !!},
                    backgroundColor: '#0b2265', 
                    hoverBackgroundColor: '#0f172a', 
                    borderRadius: 4, 
                    barThickness: 20, 
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: { backgroundColor: '#0f172a', padding: 10, cornerRadius: 4 }
                },
                scales: {
                    x: { grid: { display: false }, ticks: { font: { family: 'Inter', size: 11, weight: '600' }, color: '#64748b' } },
                    y: { beginAtZero: true, grid: { color: '#f1f5f9' }, ticks: { font: { family: 'Inter', size: 11 }, color: '#64748b', stepSize: 1 } }
                }
            }
        });

        // --- 2. Chart Demografi Gender ---
        new Chart(document.getElementById('chartGender').getContext('2d'), {
            type: 'doughnut',
            data: {
                labels: ['Laki-laki', 'Perempuan'],
                datasets: [{ 
                    data: [{{ $genderLaki }}, {{ $genderPerempuan }}], 
                    backgroundColor: ['#0b2265', '#cbd5e1'], 
                    borderWidth: 0 
                }]
            },
            options: { 
                responsive: true, 
                maintainAspectRatio: false, 
                cutout: '75%', 
                plugins: { 
                    legend: { 
                        position: 'bottom', 
                        labels: { 
                            boxWidth: 12, 
                            font: { family: 'Inter', size: 11 },
                            generateLabels: function(chart) {
                                const data = chart.data;
                                if (data.labels.length && data.datasets.length) {
                                    return data.labels.map(function(label, i) {
                                        const value = data.datasets[0].data[i];
                                        return {
                                            text: label + ': ' + value + ' orang',
                                            fillStyle: data.datasets[0].backgroundColor[i],
                                            strokeStyle: data.datasets[0].backgroundColor[i],
                                            lineWidth: 0,
                                            hidden: isNaN(value),
                                            index: i
                                        };
                                    });
                                }
                                return [];
                            }
                        } 
                    } 
                } 
            }
        });

        // --- 2b. Chart Sebaran Wilayah Spasial (New Perpusnas Standard) ---
        const warnaPaletWilayah = [
            '#0b2265', '#0ea5e9', '#38bdf8', '#7dd3fc', '#94a3b8', 
            '#475569', '#1e293b', '#cbd5e1', '#e2e8f0', '#f1f5f9'
        ];

        new Chart(document.getElementById('chartWilayahSpasial').getContext('2d'), {
            type: 'pie',
            data: {
                labels: {!! json_encode($wilayahLabels) !!},
                datasets: [{
                    data: {!! json_encode($wilayahData) !!},
                    backgroundColor: warnaPaletWilayah,
                    borderWidth: 2,
                    borderColor: '#ffffff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: '#0f172a',
                        titleFont: { family: 'Inter', size: 11, weight: 'bold' },
                        bodyFont: { family: 'Inter', size: 11 },
                        padding: 10,
                        cornerRadius: 6
                    }
                }
            }
        });

        // Sinkronisasi warna indikator di tabel legenda custom
        {!! json_encode($wilayahLabels) !!}.forEach((label, index) => {
            const marker = document.getElementById(`legend-marker-${index}`);
            if(marker) {
                marker.style.backgroundColor = warnaPaletWilayah[index % warnaPaletWilayah.length];
            }
        });

        // --- 3. Chart Tren Log Aktivitas Portal Sistem ---
        new Chart(document.getElementById('chartKunjunganTren').getContext('2d'), {
            type: 'line',
            data: {
                labels: {!! json_encode($bulanLabels) !!}, 
                datasets: [
                    { 
                        label: 'Total Pendaftaran Akun (users.created_at)', 
                        data: {!! json_encode($chartUsersCreatedAt ?? []) !!}, 
                        borderColor: '#0b2265', 
                        backgroundColor: 'rgba(11,34,101,0.05)', 
                        fill: true, 
                        tension: 0.3, 
                        borderWidth: 2, 
                        pointRadius: 4 
                    }
                ]
            },
            options: { 
                responsive: true, 
                maintainAspectRatio: false, 
                plugins: { 
                    legend: { 
                        position: 'bottom', 
                        labels: { font: { family: 'Inter', size: 11 } } 
                    } 
                },
                scales: {
                    y: { beginAtZero: true }
                }
            }
        });

        // --- 4. Data Grafik Anggota ---
        new Chart(document.getElementById('chartDataAnggota').getContext('2d'), {
            type: 'line',
            data: {
                labels: {!! json_encode($bulanLabels) !!},
                datasets: [{ 
                    label: 'Registrasi Profil Anggota (anggota.created_at)', 
                    data: {!! json_encode($chartAnggotaCreatedAt ?? []) !!}, 
                    backgroundColor: 'rgba(14,165,233,0.05)', 
                    borderColor: '#0ea5e9', 
                    fill: true, 
                    tension: 0.2,
                    pointRadius: 4
                }]
            },
            options: { 
                responsive: true, 
                maintainAspectRatio: false, 
                plugins: { 
                    legend: { 
                        position: 'bottom',
                        labels: { font: { family: 'Inter', size: 11 } }
                    } 
                },
                scales: {
                    y: { beginAtZero: true }
                }
            }
        });

        // --- 5. Chart Klasifikasi Subjek DDC ---
        new Chart(document.getElementById('chartKlasifikasiKoleksi').getContext('2d'), {
            type: 'bar',
            data: {
                labels: ['Karya Umum', 'Filsafat', 'Agama', 'Sosial', 'Bahasa', 'Sains', 'Teknologi', 'Seni', 'Sastra', 'Sejarah'],
                datasets: [{ data: [20, 14, 45, 38, 25, 52, 60, 18, 49, 33], backgroundColor: '#475569', borderRadius: 3 }]
            },
            options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } } }
        });

        // --- 6. Chart Jenis Buku Terpopuler ---
        new Chart(document.getElementById('chartKoleksiTerpopuler').getContext('2d'), {
            type: 'radar',
            data: {
                labels: ['Buku Teks', 'Koleksi Umum', 'Fiksi / Sastra', 'Majalah Fisik', 'Kamus / Referensi'],
                datasets: [{ label: 'Tingkat Sirkulasi', data: [85, 70, 90, 45, 30], backgroundColor: 'rgba(14,165,233,0.15)', borderColor: '#0ea5e9', borderWidth: 2 }]
            },
            options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } } }
        });
    });
</script>
@endsection