@extends('layouts.dashboard')

@section('title', 'Detail Analistik: ' . ($shortlink->custom_alias ?: $shortlink->short_code) . ' - Selinku')

@section('content')
<div class="max-w-7xl mx-auto space-y-10">
    
    <!-- Header -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
            <div class="flex items-center gap-2 mb-1">
                <a href="{{ route('shortlinks.index') }}" class="text-slate-500 hover:text-emerald-600 transition-colors">
                    <i class="fa-solid fa-arrow-left"></i>
                </a>
                <h2 class="text-2xl font-bold text-slate-900">Detail Analistik</h2>
            </div>
            <p class="text-slate-500 ml-6">Laporan lengkap untuk link <span class="font-semibold text-emerald-600">{{ $shortlink->custom_alias ?: $shortlink->short_code }}</span></p>
        </div>
        <div class="flex items-center gap-2">
            <a href="{{ $shortlink->original_url }}" target="_blank" class="inline-flex items-center gap-2 px-4 py-2 bg-white text-slate-700 border border-slate-300 rounded-lg hover:bg-slate-50 transition-colors font-medium text-sm">
                <i class="fa-solid fa-external-link-alt"></i>
                Buka URL Asli
            </a>
        </div>
    </div>

    <!-- Report Summary Card -->
    <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
        <div class="p-6 pb-3 border-b border-slate-100">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-bold text-slate-800">Laporan Aktivitas Link</h3>
                <div class="flex items-center gap-2">
                    <button onclick="openAnalyticsModal()" class="text-xs font-semibold text-white bg-emerald-600 hover:bg-emerald-700 px-3 py-1.5 rounded-lg transition-colors flex items-center gap-1.5 shadow-sm shadow-emerald-200">
                        <i class="fa-solid fa-chart-pie"></i> Analisis 30 Hari
                    </button>
                    <span class="text-xs font-medium text-slate-500 bg-slate-100 px-3 py-1.5 rounded-full">
                        <i class="fa-regular fa-clock mr-1"></i> Update: {{ now()->format('H:i') }}
                    </span>
                </div>
            </div>
            
            <!-- Removed cumulative summary text -->
        </div>

        <div class="bg-slate-50/50 p-6 pt-3">
            <div class="grid grid-cols-2 md:grid-cols-4 gap-6 md:divide-x md:divide-slate-200">
                <!-- Total -->
                <div class="flex flex-col md:px-4 first:pl-0">
                    <span class="text-xs font-semibold text-slate-500 uppercase tracking-widest mb-1">Total Trafik</span>
                    <span class="text-2xl font-bold text-slate-900">{{ number_format($shortlink->clicks->count()) }}</span>
                    <span class="text-xs text-slate-400 font-medium">Data total sepanjang masa</span>
                </div>

                <!-- Unique -->
                <div class="flex flex-col md:px-4">
                    <span class="text-xs font-semibold text-slate-500 uppercase tracking-widest mb-1">Unik</span>
                    <span class="text-2xl font-bold text-emerald-600">{{ number_format($shortlink->clicks->where('is_unique', true)->count()) }}</span>
                    <span class="text-xs text-slate-400 mt-1">Pengunjung baru</span>
                </div>

                <!-- Today -->
                <div class="flex flex-col md:px-4">
                    <span class="text-xs font-semibold text-slate-500 uppercase tracking-widest mb-1">Hari Ini</span>
                    <div class="flex items-center gap-2">
                        <span class="text-2xl font-bold text-blue-600">{{ number_format($shortlink->clicks->where('clicked_at', '>=', today())->count()) }}</span>
                        @if($shortlink->clicks->where('clicked_at', '>=', today())->count() > 0)
                        <span class="bg-blue-100 text-blue-600 text-[10px] px-1.5 py-0.5 rounded-full font-bold animate-pulse">Live</span>
                        @endif
                    </div>
                     <span class="text-xs text-slate-400 mt-1">Sejak 00:00</span>
                </div>

                <!-- Weekly -->
                <div class="flex flex-col md:px-4">
                    <span class="text-xs font-semibold text-slate-500 uppercase tracking-widest mb-1">Minggu Ini</span>
                    <span class="text-2xl font-bold text-purple-600">{{ number_format($shortlink->clicks->where('clicked_at', '>=', now()->subDays(6))->count()) }}</span>
                    <span class="text-xs text-slate-400 mt-1">7 hari terakhir</span>
                </div>
        </div>
    </div>

    </div>
    
    <!-- Charts Section -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Main Line Chart -->
        <div class="lg:col-span-2 bg-white p-6 rounded-xl shadow-sm border border-slate-200">
             <div class="flex items-center justify-between mb-6">
                <h3 class="text-lg font-semibold text-slate-800">Tren Klik (30 Hari)</h3>
            </div>
            <div class="h-80 relative">
                 <canvas id="clicksChart"></canvas>
            </div>
        </div>

        <!-- Top Referrers -->
        <div class="bg-white p-6 rounded-xl shadow-sm border border-slate-200 flex flex-col">
            <div class="mb-6">
                <h3 class="text-lg font-semibold text-slate-800">Sumber Trafik Teratas</h3>
                <span class="text-xs text-slate-400 font-medium">Data 30 hari terakhir</span>
            </div>
            <div class="flex-1 overflow-y-auto max-h-[320px] pr-2 space-y-4">
                @forelse($referrers as $ref)
                <div class="flex items-center justify-between p-3 rounded-lg bg-slate-50 hover:bg-slate-100 transition-colors">
                    <div class="flex items-center gap-3 overflow-hidden">
                        <div class="w-8 h-8 rounded-full bg-white border border-slate-200 flex items-center justify-center shrink-0 text-slate-400">
                            <i class="fa-solid fa-link text-xs"></i>
                        </div>
                        <div class="flex flex-col overflow-hidden">
                            <span class="text-sm font-medium text-slate-900 truncate" title="{{ $ref->referer_url ?: 'Direct / Unknown' }}">
                                {{ $ref->referer_domain ?: 'Direct / Unknown' }}
                            </span>
                            @if($ref->referer_url)
                                <span class="text-xs text-slate-500 truncate">{{ $ref->referer_url }}</span>
                            @endif
                        </div>
                    </div>
                    <span class="text-sm font-bold text-emerald-600 shrink-0">{{ number_format($ref->total) }}</span>
                </div>
                @empty
                <div class="text-center py-8 text-slate-400 text-sm">Belum ada data referer</div>
                @endforelse
            </div>
        </div>
    </div>

    <!-- Popular Stats Summary (Visual) -->
    <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-8">
        <h3 class="text-sm font-bold text-slate-500 uppercase tracking-wider mb-8">Statistik Populer (Sepanjang Masa)</h3>
        
        <div class="grid grid-cols-2 lg:grid-cols-4 gap-x-8 gap-y-10">
            <!-- Top Device -->
            <div>
                <span class="block text-[10px] sm:text-xs font-semibold text-slate-400 uppercase mb-2 sm:mb-3">Perangkat</span>
                <div class="flex items-center gap-3 sm:gap-4">
                    <div class="w-10 h-10 sm:w-12 sm:h-12 rounded-xl bg-emerald-50 flex items-center justify-center text-emerald-600 shadow-sm border border-emerald-100 shrink-0">
                        @php
                            $topDeviceType = $devices->first() ? strtolower($devices->first()->device_type) : 'desktop';
                            $deviceIconClass = 'fa-desktop';
                            if ($topDeviceType === 'mobile') $deviceIconClass = 'fa-mobile-alt';
                            elseif ($topDeviceType === 'tablet') $deviceIconClass = 'fa-tablet-alt';
                        @endphp
                        <i class="fa-solid {{ $deviceIconClass }} text-lg sm:text-xl"></i>
                    </div>
                    <div class="min-w-0">
                        <div class="font-bold text-slate-800 text-sm sm:text-lg capitalize leading-tight truncate">{{ $devices->first() ? $devices->first()->device_type : '-' }}</div>
                        <div class="text-[10px] sm:text-sm text-slate-500 font-medium">
                            {{ $devices->first() ? number_format($devices->first()->total) . ' Klik' : '0 Klik' }}
                        </div>
                    </div>
                </div>
            </div>

            <!-- Top OS -->
            <div>
                <span class="block text-[10px] sm:text-xs font-semibold text-slate-400 uppercase mb-2 sm:mb-3">Sistem Operasi</span>
                <div class="flex items-center gap-3 sm:gap-4">
                    <div class="w-10 h-10 sm:w-12 sm:h-12 rounded-xl bg-blue-50 flex items-center justify-center text-blue-600 shadow-sm border border-blue-100 shrink-0">
                        @php
                            $topOsName = $os_stats->first() ? strtolower($os_stats->first()->os) : '';
                            $osIconClass = 'fa-solid fa-microchip';
                            if (str_contains($topOsName, 'windows')) $osIconClass = 'fa-brands fa-windows';
                            elseif (str_contains($topOsName, 'android')) $osIconClass = 'fa-brands fa-android';
                            elseif (str_contains($topOsName, 'linux')) $osIconClass = 'fa-brands fa-linux';
                            elseif (str_contains($topOsName, 'ios') || str_contains($topOsName, 'mac')) $osIconClass = 'fa-brands fa-apple';
                            elseif (str_contains($topOsName, 'ubuntu')) $osIconClass = 'fa-brands fa-ubuntu';
                        @endphp
                        <i class="{{ $osIconClass }} text-lg sm:text-xl"></i>
                    </div>
                    <div class="min-w-0">
                        <div class="font-bold text-slate-800 text-sm sm:text-lg capitalize leading-tight truncate">{{ $os_stats->first() ? $os_stats->first()->os : '-' }}</div>
                        <div class="text-[10px] sm:text-sm text-slate-500 font-medium">
                             {{ $os_stats->first() ? number_format($os_stats->first()->total) . ' Klik' : '0 Klik' }}
                        </div>
                    </div>
                </div>
            </div>

            <!-- Top Country -->
            <div>
                <span class="block text-[10px] sm:text-xs font-semibold text-slate-400 uppercase mb-2 sm:mb-3">Negara</span>
                <div class="flex items-center gap-3 sm:gap-4">
                    <div class="w-10 h-10 sm:w-12 sm:h-12 rounded-xl bg-indigo-50 flex items-center justify-center text-indigo-600 shadow-sm border border-indigo-100 shrink-0">
                        <i class="fa-solid fa-globe text-lg sm:text-xl"></i>
                    </div>
                    <div class="min-w-0">
                        <div class="font-bold text-slate-800 text-sm sm:text-lg capitalize leading-tight truncate">{{ $countries->first() ? $countries->first()->country : '-' }}</div>
                        <div class="text-[10px] sm:text-sm text-slate-500 font-medium">
                             {{ $countries->first() ? number_format($countries->first()->total) . ' Klik' : '0 Klik' }}
                        </div>
                    </div>
                </div>
            </div>

            <!-- Top City -->
            <div>
                <span class="block text-[10px] sm:text-xs font-semibold text-slate-400 uppercase mb-2 sm:mb-3">Kota</span>
                <div class="flex items-center gap-3 sm:gap-4">
                    <div class="w-10 h-10 sm:w-12 sm:h-12 rounded-xl bg-purple-50 flex items-center justify-center text-purple-600 shadow-sm border border-purple-100 shrink-0">
                        <i class="fa-solid fa-map-marker-alt text-lg sm:text-xl"></i>
                    </div>
                    <div class="min-w-0">
                        <div class="font-bold text-slate-800 text-sm sm:text-lg capitalize leading-tight truncate cursor-help" title="{{ $cities->first() ? $cities->first()->city : '-' }}">{{ $cities->first() ? $cities->first()->city : '-' }}</div>
                        <div class="text-[10px] sm:text-sm text-slate-500 font-medium">
                             {{ $cities->first() ? number_format($cities->first()->total) . ' Klik' : '0 Klik' }}
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="mt-8 pt-6 border-t border-slate-100 flex flex-col gap-4 text-sm text-slate-500">
            <div class="bg-white border border-slate-200 rounded-lg p-4 text-slate-700 mt-2 space-y-2">
                <div class="flex items-start gap-2">
                     <i class="fa-solid fa-circle-info mt-1 text-indigo-500 shrink-0"></i>
                     <div>
                        {{ $periodLabel }}, link Anda banyak diakses melalui <strong>{{ $dominant7Days['source'] }}</strong>, dengan perangkat <strong class="capitalize">{{ $dominant7Days['device'] }}</strong>, dari <strong class="capitalize">{{ $dominant7Days['city'] }}, {{ $dominant7Days['country'] }}</strong>.
                     </div>
                </div>

                @if(!empty($insights))
                <div class="pt-2 border-t border-slate-100 flex flex-col gap-1.5 text-xs md:text-sm">
                    @if(isset($insights['os']))
                    <div class="flex items-start gap-2">
                        <i class="fa-solid fa-check text-emerald-500 mt-1 shrink-0"></i>
                        <span>{!! $insights['os'] !!}</span>
                    </div>
                    @endif
                     @if(isset($insights['device']))
                    <div class="flex items-start gap-2">
                        <i class="fa-solid fa-check text-emerald-500 mt-1 shrink-0"></i>
                        <span>{!! $insights['device'] !!}</span>
                    </div>
                    @endif
                     @if(isset($insights['location']))
                    <div class="flex items-start gap-2">
                        <i class="fa-solid fa-check text-emerald-500 mt-1 shrink-0"></i>
                        <span>{!! $insights['location'] !!}</span>
                    </div>
                    @endif
                    @if(isset($insights['peak_time']))
                    <div class="flex items-start gap-2">
                        <i class="fa-solid fa-check text-emerald-500 mt-1 shrink-0"></i>
                        <span>{!! $insights['peak_time'] !!}</span>
                    </div>
                    @endif
                </div>
                @endif


            </div>

            <div class="flex flex-col sm:flex-row gap-4 mt-2">
                <div>Terakhir diklik: <span class="font-medium text-slate-700">{{ $lastClick }}</span></div>
                @if($clicks1Hour > 0)
                <div class="hidden sm:block text-slate-300">|</div>
                <div>Klik dalam 1 jam terakhir: <span class="font-medium text-emerald-600">{{ $clicks1Hour }} kali</span></div>
                @endif
            </div>
        </div>
    </div>

    <!-- Charts Section -->




    <!-- Click History Table -->
    <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
        <div class="p-6 border-b border-slate-100 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <h3 class="font-bold text-slate-800">Klik Terbaru</h3>
            
            <!-- Search Form -->
            <form action="{{ route('analytics.data') }}" method="GET" class="relative">
                <input type="hidden" name="search" value="{{ $shortlink->custom_alias ?: $shortlink->short_code }}">
                <input type="text" name="q" value="{{ request('q') }}" placeholder="Cari IP, Lokasi, Sumber..." 
                       class="pl-9 pr-4 py-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-transparent w-full sm:w-64 transition-all">
                <i class="fa-solid fa-search absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-xs"></i>
                @if(request('q'))
                <a href="{{ route('analytics.data', ['search' => $shortlink->custom_alias ?: $shortlink->short_code]) }}" class="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600">
                    <i class="fa-solid fa-xmark"></i>
                </a>
                @endif
            </form>
        </div>
        
        <!-- Mobile View (Cards) -->
        <div class="md:hidden space-y-4 p-4">
            @forelse($clickHistory as $click)
            <div class="bg-white border border-slate-200 rounded-lg p-4 shadow-sm flex flex-col gap-3">
                <div class="flex items-center justify-between border-b border-slate-100 pb-2">
                    <div class="flex items-center gap-2">
                        <i class="fa-regular fa-clock text-slate-400 text-xs"></i>
                        <span class="text-xs font-medium text-slate-700">{{ $click->clicked_at->translatedFormat('d M Y, H:i') }}</span>
                    </div>
                    <span class="text-[10px] bg-slate-100 text-slate-500 px-2 py-0.5 rounded font-mono">{{ $click->ip_address }}</span>
                </div>
                
                <!-- Source -->
                <div class="flex items-start gap-3">
                     <div class="w-8 h-8 rounded bg-slate-50 flex items-center justify-center text-slate-400 shrink-0 border border-slate-100">
                        <i class="fa-solid fa-arrow-right-to-bracket text-xs"></i>
                    </div>
                    <div>
                         <span class="block text-[10px] uppercase text-slate-400 font-semibold mb-0.5">Sumber</span>
                         @if($click->referer_url)
                            <div class="font-medium text-sm text-slate-800 break-all leading-tight">
                                {{ parse_url($click->referer_url, PHP_URL_HOST) ?? 'Unknown' }}
                            </div>
                         @else
                            <div class="font-medium text-sm text-slate-800">Direct / Email / SMS</div>
                         @endif
                    </div>
                </div>
                
                <div class="grid grid-cols-2 gap-2 pt-1">
                    <!-- Device -->
                    <div class="flex items-center gap-2">
                         <div class="w-7 h-7 rounded bg-indigo-50 flex items-center justify-center text-indigo-500 shrink-0">
                            <i class="fa-solid fa-{{ $click->device_type === 'mobile' ? 'mobile-alt' : ($click->device_type === 'desktop' ? 'desktop' : 'tablet-alt') }} text-xs"></i>
                        </div>
                        <div class="flex flex-col">
                             <span class="text-[10px] text-slate-400 leading-none mb-0.5">Perangkat</span>
                             <span class="text-xs font-medium text-slate-700 capitalize">{{ $click->device_type }}</span>
                        </div>
                    </div>
                    
                    <!-- Location -->
                    <div class="flex items-center gap-2">
                         <div class="w-7 h-7 rounded bg-emerald-50 flex items-center justify-center text-emerald-500 shrink-0">
                            <i class="fa-solid fa-map-location-dot text-xs"></i>
                        </div>
                        <div class="flex flex-col">
                             <span class="text-[10px] text-slate-400 leading-none mb-0.5">Lokasi</span>
                             <span class="text-xs font-medium text-slate-700 capitalize truncate max-w-[100px] cursor-help" title="{{ $click->city && $click->city !== 'Unknown' ? $click->city : ($click->country ?: 'Unknown') }}">{{ $click->city && $click->city !== 'Unknown' ? $click->city : ($click->country ?: 'Unknown') }}</span>
                        </div>
                    </div>
                </div>
            </div>
            @empty
            <div class="text-center py-10 text-slate-400 italic text-sm bg-slate-50 rounded-lg">
                Belum ada data klik terbaru.
            </div>
            @endforelse
        </div>

        <!-- Desktop View (Table) -->
        <div class="hidden md:block overflow-x-auto">
            <table class="w-full text-left text-sm text-slate-600">
                <thead class="bg-slate-50 text-xs uppercase font-semibold text-slate-500">
                    <tr>
                        <th class="px-6 py-4">Waktu</th>
                        <th class="px-6 py-4">IP Address</th>
                        <th class="px-6 py-4">Sumber</th>
                        <th class="px-6 py-4">Perangkat</th>
                        <th class="px-6 py-4">Lokasi</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    @forelse($clickHistory as $click)
                    <tr class="hover:bg-slate-50 transition-colors">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="font-medium text-slate-900">{{ $click->clicked_at->translatedFormat('d M Y') }}</div>
                            <div class="text-xs text-slate-500">{{ $click->clicked_at->format('H:i') }}</div>
                        </td>
                        <td class="px-6 py-4 font-mono text-xs text-slate-500">
                             {{ $click->ip_address }}
                        </td>
                        <td class="px-6 py-4">
                            @if($click->referer_url)
                                <div class="flex items-center gap-2 max-w-[200px]">
                                    <div class="w-6 h-6 rounded bg-slate-100 flex items-center justify-center text-slate-400 shrink-0">
                                        <i class="fa-solid fa-link text-xs"></i>
                                    </div>
                                    <span class="truncate" title="{{ $click->referer_url }}">
                                        {{ parse_url($click->referer_url, PHP_URL_HOST) ?? 'Unknown' }}
                                    </span>
                                </div>
                            @else
                                <div class="flex items-center gap-2">
                                    <div class="w-6 h-6 rounded bg-slate-100 flex items-center justify-center text-slate-400 shrink-0">
                                        <i class="fa-solid fa-turn-up text-xs"></i>
                                    </div>
                                    <span>Direct / Email / SMS</span>
                                </div>
                            @endif
                        </td>
                        <td class="px-6 py-4">
                            <div class="flex flex-col gap-1">
                                <div class="flex items-center gap-2">
                                    <i class="fa-solid fa-{{ $click->device_type === 'mobile' ? 'mobile-alt' : ($click->device_type === 'desktop' ? 'desktop' : 'tablet-alt') }} w-4 text-center text-slate-400"></i>
                                    <span class="capitalize text-slate-900">{{ $click->device_type }}</span>
                                </div>
                                <div class="flex items-center gap-2 text-xs text-slate-500 ml-6">
                                    <span class="capitalize">{{ $click->os }}</span>
                                    <span>•</span>
                                    <span class="capitalize">{{ $click->browser }}</span>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4">
                            <div class="flex flex-col gap-1">
                                <div class="flex items-center gap-2">
                                    <span class="capitalize text-slate-900 font-medium">{{ $click->country ?: 'Unknown' }}</span>
                                </div>
                                @if($click->city && $click->city !== 'Unknown')
                                <div class="flex items-center gap-1 text-xs text-slate-500 ml-0.5">
                                    <i class="fa-solid fa-location-dot text-[10px] text-slate-300"></i>
                                    <span class="capitalize">{{ $click->city }}</span>
                                </div>
                                @endif
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="5" class="px-6 py-10 text-center text-slate-400 italic">
                            Belum ada data klik terbaru.
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        
        @if($clickHistory->hasPages())
        <div class="px-6 py-4 border-t border-slate-100">
            {{ $clickHistory->links() }}
        </div>
        @endif
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    // Chart Setup
    const ctx = document.getElementById('clicksChart').getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: {!! json_encode($labels) !!},
            datasets: [{
                label: 'Klik',
                data: {!! json_encode($chartData) !!},
                borderColor: '#059669',
                backgroundColor: 'rgba(5, 150, 105, 0.1)',
                borderWidth: 2,
                tension: 0.3,
                fill: true,
                pointBackgroundColor: '#fff',
                pointBorderColor: '#059669',
                pointBorderWidth: 2,
                pointRadius: 4,
                pointHoverRadius: 6
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: { borderDash: [2, 2], drawBorder: false }
                },
                x: {
                    grid: { display: false }
                }
            }
        }
    });

    // Modal Logic
    const modal = document.getElementById('analyticsModal');
    const carouselTrack = document.getElementById('carouselTrack');
    let currentSlide = 0;
    const totalSlides = 9;

    function openAnalyticsModal() {
        modal.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }

    function closeAnalyticsModal() {
        modal.classList.add('hidden');
        document.body.style.overflow = 'auto';
    }

    function nextSlide() {
        currentSlide = (currentSlide + 1) % totalSlides;
        updateCarousel();
    }

    function prevSlide() {
        currentSlide = (currentSlide - 1 + totalSlides) % totalSlides;
        updateCarousel();
    }

    function updateCarousel() {
        carouselTrack.style.transform = `translateX(-${currentSlide * 100}%)`;
    }

    // Close on click outside
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            closeAnalyticsModal();
        }
    });
</script>
@endpush

<!-- Analytics Modal -->
<div id="analyticsModal" class="hidden fixed inset-0 z-50 overflow-y-auto bg-slate-900/50 backdrop-blur-sm flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-2xl overflow-hidden relative">
        <!-- Close Button -->
        <button onclick="closeAnalyticsModal()" class="absolute top-4 right-4 text-slate-400 hover:text-slate-600 z-10 p-2">
            <i class="fa-solid fa-xmark text-xl"></i>
        </button>

        <!-- Carousel Content -->
        <div class="relative">
            <!-- Slides Container -->
            <div class="overflow-hidden">
                <div id="carouselTrack" class="flex transition-transform duration-500 ease-in-out">
                    
                    <!-- Slide 1: Trend 30 Days (Opening) -->
                    <div class="w-full shrink-0 p-8 h-96 flex flex-col items-center justify-center text-center">
                        <div class="w-14 h-14 rounded-2xl bg-indigo-100 flex items-center justify-center text-indigo-600 mb-6 mx-auto">
                            <i class="fa-solid fa-trophy text-2xl"></i>
                        </div>
                        
                        <div class="max-w-xl mx-auto">
                            <h3 class="text-lg font-bold text-slate-800 leading-relaxed">
                                {!! $trendMessage30Days !!}
                            </h3>
                        </div>
                    </div>

                    <!-- Slide 2: Detailed Breakdown -->
                    <div class="w-full shrink-0 p-8 h-96 flex flex-col items-center justify-center text-center">
                         <div class="w-14 h-14 rounded-2xl bg-emerald-100 flex items-center justify-center text-emerald-600 mb-6 mx-auto">
                            <i class="fa-solid fa-list-check text-2xl"></i>
                        </div>
                        <h3 class="text-xl font-bold text-slate-800 mb-2">Rincian Performa</h3>
                         <p class="text-xs text-slate-500 mb-6">Distribusi audiens berdasarkan kategori utama.</p>
                        
                        <div class="flex flex-col gap-3 w-full max-w-md mx-auto text-left">
                            @forelse($insights30Days as $insight)
                            <div class="flex items-center gap-3 p-3 bg-white border border-slate-200 rounded-lg shadow-sm">
                                <i class="fa-solid fa-check-circle text-emerald-500 text-sm"></i>
                                <span class="text-slate-700 font-medium text-xs sm:text-sm">{!! $insight !!}</span>
                            </div>
                            @empty
                            <div class="text-center text-slate-400 italic text-xs">Belum ada data mendalam untuk ditampilkan.</div>
                            @endforelse
                        </div>
                    </div>

                    <!-- Slide 3: Comparison & Growth -->
                    <div class="w-full shrink-0 p-8 h-96 flex flex-col items-center justify-center text-center bg-gradient-to-br from-indigo-50 to-white">
                         <div class="w-14 h-14 rounded-2xl bg-indigo-600 flex items-center justify-center text-white mb-6 mx-auto shadow-lg shadow-indigo-200">
                            <i class="fa-solid fa-chart-line text-2xl"></i>
                        </div>
                        <h3 class="text-xl font-bold text-slate-800 mb-4">Pertumbuhan Trafik</h3>
                        
                        <div class="max-w-lg mx-auto bg-white p-6 rounded-xl border border-indigo-100 shadow-sm relative group/hint">
                             <i class="fa-solid fa-quote-left absolute top-4 left-4 text-indigo-100 text-2xl -z-10"></i>
                             
                             <!-- Calculation Hint -->
                             <div class="absolute top-2 right-2">
                                <div class="relative group/tooltip">
                                    <i class="fa-regular fa-circle-question text-slate-300 hover:text-indigo-400 cursor-help"></i>
                                    <div class="hidden group-hover/tooltip:block absolute bottom-full right-0 mb-2 w-56 p-2.5 bg-slate-800 text-white text-[10px] leading-tight rounded-lg shadow-xl z-30">
                                        Angka ini didapat dari membandingkan <strong>rata-rata klik harian minggu ini</strong> (7 hari terakhir) dibandingkan <strong>rata-rata harian bulan ini</strong> (30 hari terakhir).
                                        <div class="absolute top-full right-1 w-2 h-2 bg-slate-800 rotate-45 -translate-y-1"></div>
                                    </div>
                                </div>
                             </div>

                             <p class="text-slate-700 text-sm leading-relaxed pr-6">
                                {!! $comparison30Days !!}
                            </p>
                        </div>
                    </div>

                    <!-- Slide 4: Top Sources (Standalone) -->
                    <div class="w-full shrink-0 p-8 h-96 flex flex-col items-center justify-center text-center">
                         <div class="w-14 h-14 rounded-2xl bg-orange-100 flex items-center justify-center text-orange-600 mb-6 mx-auto">
                            <i class="fa-solid fa-share-nodes text-2xl"></i>
                        </div>
                        <h3 class="text-xl font-bold text-slate-800 mb-2">Sumber Trafik Populer</h3>
                         <p class="text-xs text-slate-500 mb-6">Analisis 30 hari terakhir.</p>
                        
                        <div class="w-full max-w-md mx-auto">
                            <!-- Top Sources List -->
                            <div class="bg-slate-50 rounded-xl p-4 border border-slate-100 text-left">
                                <span class="text-[10px] font-bold text-slate-400 uppercase mb-2 block tracking-wider">Top 3 Sumber Trafik</span>
                                <div class="space-y-2">
                                    @forelse($top3Sources30 as $idx => $src)
                                    <div class="flex items-center justify-between text-xs">
                                        <div class="flex items-center gap-2">
                                            <span class="w-5 h-5 rounded-full bg-white border border-slate-200 flex items-center justify-center text-xs font-bold text-slate-500 shadow-sm">{{ $idx + 1 }}</span>
                                            <span class="font-medium text-slate-700 truncate max-w-[150px]">{{ $src['name'] }}</span>
                                        </div>
                                        <span class="font-bold text-slate-900">{{ number_format($src['total']) }}</span>
                                    </div>
                                    @empty
                                    <div class="text-slate-400 text-xs italic">Belum ada data sumber.</div>
                                    @endforelse
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Slide New: Popular Click Time -->
                    <div class="w-full shrink-0 p-8 h-96 flex flex-col items-center justify-center text-center">
                         <div class="w-14 h-14 rounded-2xl bg-amber-100 flex items-center justify-center text-amber-600 mb-6 mx-auto">
                            <i class="fa-solid fa-clock-rotate-left text-2xl"></i>
                        </div>
                        <h3 class="text-xl font-bold text-slate-800 mb-2">Waktu Klik Populer</h3>
                         <p class="text-xs text-slate-500 mb-4">Perbandingan waktu aktif audiens.</p>
                        
                        <div class="w-full max-w-sm mx-auto space-y-3">
                            <div class="grid grid-cols-2 gap-3">
                                <div class="bg-slate-50 rounded-lg p-3 border border-slate-100">
                                    <span class="block text-[10px] uppercase text-slate-400 font-semibold mb-1">30 Hari Terakhir</span>
                                    <span class="font-bold text-slate-800 text-sm">{{ $peakHour30Text }}</span>
                                </div>
                                <div class="bg-amber-50 rounded-lg p-3 border border-amber-100">
                                    <span class="block text-[10px] uppercase text-amber-600 font-semibold mb-1">7 Hari Terakhir</span>
                                    <span class="font-bold text-slate-800 text-sm">{{ $peakHour7Text }}</span>
                                </div>
                            </div>
                             
                            <div class="bg-amber-50/50 rounded-xl p-4 border border-amber-100 text-left relative">
                                <i class="fa-solid fa-lightbulb absolute top-4 right-4 text-amber-200 text-xl"></i>
                                <span class="text-[10px] font-bold text-amber-600 uppercase mb-1 block">Rekomendasi Waktu</span>
                                <p class="text-slate-700 text-xs leading-relaxed">
                                    {!! $timeRecommendation !!}
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- Slide 6: Location Analysis (Cities) -->
                    <div class="w-full shrink-0 p-8 h-96 flex flex-col items-center justify-center text-center">
                         <div class="w-14 h-14 rounded-2xl bg-sky-100 flex items-center justify-center text-sky-600 mb-6 mx-auto">
                            <i class="fa-solid fa-map-location-dot text-2xl"></i>
                        </div>
                        <h3 class="text-xl font-bold text-slate-800 mb-2">Analisis Kota</h3>
                         <p class="text-xs text-slate-500 mb-6">Distribusi kota asal audiens Anda.</p>
                        
                        <div class="w-full max-w-sm mx-auto space-y-4">
                             <!-- Top 3 Cities List (30D) -->
                            <div class="bg-slate-50 rounded-xl p-3 border border-slate-100 text-left">
                                <span class="text-[10px] font-bold text-slate-400 uppercase mb-2 block tracking-wider">Top 3 Kota (30 Hari)</span>
                                <div class="space-y-2">
                                    @forelse($top3Cities30 as $idx => $city)
                                    <div class="flex items-center justify-between text-xs">
                                        <div class="flex items-center gap-2">
                                            <span class="w-5 h-5 rounded-full bg-white border border-slate-200 flex items-center justify-center text-xs font-bold text-slate-500 shadow-sm">{{ $idx + 1 }}</span>
                                            <span class="font-medium text-slate-700 truncate max-w-[150px]">{{ $city->city }}</span>
                                        </div>
                                        <span class="font-bold text-slate-900">{{ number_format($city->total) }}</span>
                                    </div>
                                    @empty
                                    <div class="text-slate-400 text-xs italic">Belum ada data kota.</div>
                                    @endforelse
                                </div>
                            </div>

                            <!-- Weekly & Daily Winners -->
                            <div class="grid grid-cols-2 gap-3">
                                <div class="bg-sky-50 rounded-xl p-3 border border-sky-100 relative overflow-hidden">
                                     <div class="absolute -right-2 -top-2 text-sky-100/50 text-4xl">
                                        <i class="fa-solid fa-trophy"></i>
                                    </div>
                                    <span class="block text-[10px] uppercase text-sky-600 font-bold mb-1 relative z-10">Juara Minggu Ini</span>
                                    <span class="block font-bold text-slate-800 text-sm relative z-10 truncate">{{ $topCityWeekly ? $topCityWeekly->city : '-' }}</span>
                                </div>
                                <div class="bg-indigo-50 rounded-xl p-3 border border-indigo-100 relative overflow-hidden">
                                    <span class="block text-[10px] uppercase text-indigo-600 font-bold mb-1 relative z-10">Juara Hari Ini</span>
                                    <span class="block font-bold text-slate-800 text-sm relative z-10 truncate">{{ $topCityDaily ? $topCityDaily->city : '-' }}</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Slide 7: Country Analysis (New) -->
                    <div class="w-full shrink-0 p-8 h-96 flex flex-col items-center justify-center text-center">
                         <div class="w-14 h-14 rounded-2xl bg-teal-100 flex items-center justify-center text-teal-600 mb-6 mx-auto">
                            <i class="fa-solid fa-earth-americas text-2xl"></i>
                        </div>
                        <h3 class="text-xl font-bold text-slate-800 mb-2">Berdasarkan Negara</h3>
                         <p class="text-xs text-slate-500 mb-6">Sebaran negara asal pengunjung.</p>
                        
                        <div class="w-full max-w-sm mx-auto space-y-4">
                             <!-- Top 3 Countries List (30D) -->
                            <div class="bg-slate-50 rounded-xl p-3 border border-slate-100 text-left">
                                <span class="text-[10px] font-bold text-slate-400 uppercase mb-2 block tracking-wider">Top 3 Negara (30 Hari)</span>
                                <div class="space-y-2">
                                    @forelse($top3Countries30 as $idx => $country)
                                    <div class="flex items-center justify-between text-xs">
                                        <div class="flex items-center gap-2">
                                            <span class="w-5 h-5 rounded-full bg-white border border-slate-200 flex items-center justify-center text-xs font-bold text-slate-500 shadow-sm">{{ $idx + 1 }}</span>
                                            <span class="font-medium text-slate-700 truncate max-w-[150px]">{{ $country->country }}</span>
                                        </div>
                                        <span class="font-bold text-slate-900">{{ number_format($country->total) }}</span>
                                    </div>
                                    @empty
                                    <div class="text-slate-400 text-xs italic">Belum ada data negara.</div>
                                    @endforelse
                                </div>
                            </div>

                             <!-- Weekly Country Winner -->
                             <div class="bg-teal-50 rounded-xl p-4 border border-teal-100 flex items-center justify-between">
                                <div>
                                    <span class="block text-[10px] uppercase text-teal-600 font-bold mb-1">Negara Terpopuler (Minggu Ini)</span>
                                    <span class="block font-bold text-slate-800 text-sm">{{ $topCountryWeekly ? $topCountryWeekly->country : '-' }}</span>
                                </div>
                                <i class="fa-solid fa-flag text-teal-200 text-xl"></i>
                            </div>
                        </div>
                    </div>

                    <!-- Slide 8: Last 24 Hours (Moved Down) -->
                    <div class="w-full shrink-0 p-8 h-96 flex flex-col items-center justify-center text-center bg-slate-900 text-white">
                         <div class="w-14 h-14 rounded-2xl bg-slate-800 flex items-center justify-center text-emerald-400 mb-6 mx-auto border border-slate-700">
                            <i class="fa-solid fa-bolt text-2xl"></i>
                        </div>
                        <h3 class="text-xl font-bold text-white mb-2">Insight 24 Jam Terakhir</h3>
                         <p class="text-xs text-slate-400 mb-6 max-w-lg mx-auto">Ringkasan aktivitas real-time sejak pukul 00:00 WIB hari ini.</p>
                        
                        @if($last24HStats)
                        <div class="bg-slate-800/50 backdrop-blur rounded-xl border border-slate-700 p-6 max-w-xl mx-auto text-left relative overflow-hidden">
                             <div class="absolute top-0 right-0 p-4 opacity-10">
                                 <i class="fa-solid fa-clock text-4xl text-white"></i>
                             </div>
                             <p class="text-slate-200 leading-relaxed text-sm sm:text-base">
                                 Waktu klik terbanyak tercatat pada pukul <strong class="text-emerald-400">{{ $last24HStats['peak_hour'] }}</strong>. 
                                 Akses didominasi oleh pengguna <strong class="text-emerald-400 capitalize">{{ $last24HStats['device'] }}</strong> 
                                 menggunakan sistem operasi <strong class="text-emerald-400 capitalize">{{ $last24HStats['os'] }}</strong>, 
                                 yang datang dari sumber <strong class="text-emerald-400">{{ $last24HStats['source'] }}</strong>.
                             </p>
                        </div>
                        @else
                        <div class="bg-slate-800/50 rounded-xl border border-slate-700 p-8 max-w-md mx-auto text-slate-400 italic text-sm">
                            Belum ada cukup data interaksi untuk hari ini (sejak 00:00).
                        </div>
                        @endif
                    </div>

                    <!-- Slide 9: Recommendation (New) -->
                    <div class="w-full shrink-0 p-8 h-96 flex flex-col items-center justify-center text-center bg-gradient-to-br from-purple-50 to-white">
                        <div class="flex items-center justify-center gap-3 mb-6">
                             <div class="w-10 h-10 rounded-xl bg-purple-600 flex items-center justify-center text-white shadow-lg shadow-purple-200">
                                <i class="fa-solid fa-wand-magic-sparkles text-lg"></i>
                            </div>
                            <h3 class="text-xl font-bold text-slate-800">Rekomendasi</h3>
                        </div>
                        
                        <div class="max-w-lg mx-auto bg-white p-6 rounded-xl border border-purple-100 shadow-sm relative">
                             <p class="text-slate-700 text-sm leading-relaxed">
                                {!! $finalRecommendation !!}
                            </p>
                        </div>
                    </div>

                </div>
            </div>

            <!-- Navigation Controls -->
            <button onclick="prevSlide()" class="absolute left-4 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full bg-white shadow-md border border-slate-200 flex items-center justify-center text-slate-600 hover:text-indigo-600 hover:bg-slate-50 transition-colors z-20">
                <i class="fa-solid fa-chevron-left"></i>
            </button>
            <button onclick="nextSlide()" class="absolute right-4 top-1/2 -translate-y-1/2 w-10 h-10 rounded-full bg-white shadow-md border border-slate-200 flex items-center justify-center text-slate-600 hover:text-indigo-600 hover:bg-slate-50 transition-colors z-20">
                <i class="fa-solid fa-chevron-right"></i>
            </button>
            
            <!-- Indicators -->
             <div class="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2 z-20">
                <div class="w-2 h-2 rounded-full bg-slate-300 transition-colors" id="dot-0"></div>
                <div class="w-2 h-2 rounded-full bg-slate-300 transition-colors" id="dot-1"></div>
                <div class="w-2 h-2 rounded-full bg-slate-300 transition-colors" id="dot-2"></div>
                <div class="w-2 h-2 rounded-full bg-slate-300 transition-colors" id="dot-3"></div>
                <div class="w-2 h-2 rounded-full bg-slate-300 transition-colors" id="dot-4"></div>
                <div class="w-2 h-2 rounded-full bg-slate-300 transition-colors" id="dot-5"></div>
                <div class="w-2 h-2 rounded-full bg-slate-300 transition-colors" id="dot-6"></div>
                <div class="w-2 h-2 rounded-full bg-slate-300 transition-colors" id="dot-7"></div>
                <div class="w-2 h-2 rounded-full bg-slate-300 transition-colors" id="dot-8"></div>
            </div>
        </div>
    </div>
</div>
@endsection
