@extends('layouts.dashboard')

@section('title', 'Daftar Link - Selinku')

@section('content')
<div class="max-w-7xl mx-auto space-y-6">
    
    <!-- Header Section -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
            <h2 class="text-2xl font-bold text-slate-900">Daftar Link</h2>
            <p class="text-slate-500 mt-1">Kelola semua shortlink Anda di sini</p>
        </div>
        <a href="{{ route('dashboard') }}" class="inline-flex items-center gap-2 px-4 py-2.5 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors font-medium justify-center">
            <i class="fa-solid fa-plus"></i>
            Buat Link Baru
        </a>
    </div>

    <!-- Filter & Search -->
    <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-4">
        <form action="{{ route('shortlinks.index') }}" method="GET" class="flex flex-col md:flex-row gap-3">
            <div class="flex-1 relative">
                <i class="fa-solid fa-search absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"></i>
                <input type="text" name="search" value="{{ request('search') }}" placeholder="Cari..." 
                    class="w-full pl-10 pr-4 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 outline-none text-sm">
            </div>
            <div class="grid grid-cols-2 gap-3 md:flex">
                <select name="status" onchange="this.form.submit()" class="px-3 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 outline-none text-sm bg-white">
                    <option value="">Semua Status</option>
                    <option value="active" {{ request('status') == 'active' ? 'selected' : '' }}>Aktif</option>
                    <option value="inactive" {{ request('status') == 'inactive' ? 'selected' : '' }}>Nonaktif</option>
                </select>
                <select name="sort" onchange="this.form.submit()" class="px-3 py-2.5 border border-slate-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 outline-none text-sm bg-white">
                    <option value="latest" {{ request('sort', 'latest') == 'latest' ? 'selected' : '' }}>Terbaru</option>
                    <option value="oldest" {{ request('sort') == 'oldest' ? 'selected' : '' }}>Terlama</option>
                    <option value="most_clicks" {{ request('sort') == 'most_clicks' ? 'selected' : '' }}>Terpopuler</option>
                </select>
            </div>
        </form>
    </div>

    <!-- Links List (Responsive) -->
    
    <!-- Desktop Table View -->
    <div class="hidden md:block bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-slate-200">
                <thead class="bg-slate-50">
                    <tr>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider w-48">Short Link</th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider w-48">Judul</th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">URL Tujuan</th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider w-32">Klik</th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider w-24">Status</th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider w-32">Tanggal</th>
                        <th scope="col" class="px-4 py-3 text-right text-xs font-medium text-slate-500 uppercase tracking-wider w-32">Aksi</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-slate-200" id="linksTableDesktop">
                    @forelse($shortlinks as $link)
                        <tr class="hover:bg-slate-50 transition-colors link-item" data-link-id="{{ $link->id }}">
                            <td class="px-4 py-3 whitespace-nowrap">
                                <div class="flex items-center gap-2">
                                    <span class="text-slate-900 font-medium max-w-[140px] truncate" title="{{ $link->custom_alias ?: $link->short_code }}">{{ $link->custom_alias ?: $link->short_code }}</span>
                                    <button onclick="copyLink('{{ $link->getShortUrl() }}')" class="text-slate-400 hover:text-emerald-600 transition-colors shrink-0"><i class="fa-regular fa-copy text-sm"></i></button>
                                </div>
                            </td>
                            <td class="px-4 py-3"><div class="text-sm font-medium text-slate-900 truncate max-w-[150px]" title="{{ $link->title ?: '-' }}">{{ $link->title ?: '-' }}</div></td>
                            <td class="px-4 py-3"><div class="text-xs text-slate-500 truncate max-w-[200px]" title="{{ $link->original_url }}">{{ $link->original_url }}</div></td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <div class="flex flex-col">
                                    <span class="text-sm font-semibold text-slate-900">{{ number_format($link->total_clicks) }}</span>
                                    <span class="text-[10px] text-slate-500">{{ number_format($link->unique_clicks) }} unik</span>
                                </div>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                @if($link->is_active)
                                    <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800"><i class="fa-solid fa-circle text-[6px]"></i> Aktif</span>
                                @else
                                    <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-800"><i class="fa-solid fa-circle text-[6px]"></i> Nonaktif</span>
                                @endif
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap">
                                <div class="text-xs text-slate-900">{{ $link->created_at->format('d M Y') }}</div>
                                <div class="text-[10px] text-slate-400">{{ $link->created_at->format('H:i') }}</div>
                            </td>
                            <td class="px-4 py-3 whitespace-nowrap text-right text-sm font-medium">
                                <div class="flex items-center justify-end gap-1">
                                    <button onclick="openLinkDetails({{ $link->id }}, '{{ $link->custom_alias ?: $link->short_code }}', '{{ $link->original_url }}', {{ $link->total_clicks }}, {{ $link->unique_clicks_count }}, {{ $link->clicks_30_days_count }}, {{ $link->clicks_7_days_count }}, {{ $link->clicks_today_count }}, {{ $link->clicks_1_hour_count }}, '{{ $link->clicks->first() ? $link->clicks->first()->clicked_at->diffForHumans() : 'Belum pernah' }}')" class="p-1.5 text-slate-600 hover:text-emerald-600 hover:bg-emerald-50 rounded-lg transition-colors"><i class="fa-solid fa-chart-line text-sm"></i></button>
                                    <button onclick="editLink({{ $link->id }}, '{{ addslashes($link->title) }}', '{{ addslashes($link->original_url) }}', {{ $link->is_active ? 'true' : 'false' }})" class="p-1.5 text-slate-600 hover:text-emerald-600 hover:bg-emerald-50 rounded-lg transition-colors"><i class="fa-solid fa-pen text-sm"></i></button>
                                    <button onclick="deleteLink({{ $link->id }}, this)" class="p-1.5 text-slate-600 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"><i class="fa-solid fa-trash text-sm"></i></button>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="7" class="px-6 py-12 text-center text-slate-500">Belum ada link.</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

    <!-- Mobile Card View -->
    <div class="md:hidden space-y-4" id="linksListMobile">
        @forelse($shortlinks as $link)
        <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-4 link-item transition-all duration-300 relative overflow-hidden">
            <!-- Active Status Indicator Stripe -->
            <div class="absolute left-0 top-0 bottom-0 w-1 {{ $link->is_active ? 'bg-emerald-500' : 'bg-slate-300' }}"></div>
            
            <div class="pl-2">
                <div class="flex justify-between items-start mb-2">
                    <div class="flex items-center gap-2 max-w-[80%]">
                        <span class="text-lg font-medium text-slate-900 break-all pr-2">
                            {{ $link->custom_alias ?: $link->short_code }}
                        </span>
                        <button onclick="copyLink('{{ $link->getShortUrl() }}')" class="w-8 h-8 rounded-full bg-slate-50 flex items-center justify-center text-slate-400 hover:text-emerald-600 hover:bg-emerald-50 transition-colors shrink-0">
                            <i class="fa-regular fa-copy"></i>
                        </button>
                    </div>
                </div>

                <div class="mb-3">
                    <h3 class="font-medium text-slate-900 truncate pr-8">{{ $link->title ?: 'Tanpa Judul' }}</h3>
                    <div class="flex items-center gap-1 text-xs text-slate-500 mt-1">
                        <i class="fa-solid fa-link text-[10px] opacity-70"></i>
                        <p class="truncate flex-1">{{ $link->original_url }}</p>
                    </div>
                </div>

                <div class="flex items-center justify-between pt-3 border-t border-slate-100">
                    <div class="flex gap-3">
                        <div class="flex flex-col">
                            <span class="text-[10px] text-slate-400 uppercase font-semibold">Total Klik</span>
                            <span class="text-sm font-bold text-slate-800">{{ number_format($link->total_clicks) }}</span>
                        </div>
                        <div class="flex flex-col border-l border-slate-100 pl-3">
                            <span class="text-[10px] text-slate-400 uppercase font-semibold">Tanggal</span>
                            <span class="text-xs font-medium text-slate-600 py-0.5">{{ $link->created_at->format('d/m/y') }}</span>
                        </div>
                    </div>
                    
                    <div class="flex gap-1">
                        <button onclick="openLinkDetails({{ $link->id }}, '{{ $link->custom_alias ?: $link->short_code }}', '{{ $link->original_url }}', {{ $link->total_clicks }}, {{ $link->unique_clicks_count }}, {{ $link->clicks_30_days_count }}, {{ $link->clicks_7_days_count }}, {{ $link->clicks_today_count }}, {{ $link->clicks_1_hour_count }}, '{{ $link->clicks->first() ? $link->clicks->first()->clicked_at->diffForHumans() : 'Belum pernah' }}')" 
                            class="w-9 h-9 rounded-lg bg-slate-50 text-slate-600 flex items-center justify-center hover:bg-emerald-50 hover:text-emerald-600 transition-colors">
                            <i class="fa-solid fa-chart-line"></i>
                        </button>
                        <button onclick="editLink({{ $link->id }}, '{{ addslashes($link->title) }}', '{{ addslashes($link->original_url) }}', {{ $link->is_active ? 'true' : 'false' }})" 
                            class="w-9 h-9 rounded-lg bg-slate-50 text-slate-600 flex items-center justify-center hover:bg-emerald-50 hover:text-emerald-600 transition-colors">
                            <i class="fa-solid fa-pen"></i>
                        </button>
                        <button onclick="deleteLink({{ $link->id }}, this)" 
                            class="w-9 h-9 rounded-lg bg-slate-50 text-slate-600 flex items-center justify-center hover:bg-red-50 hover:text-red-600 transition-colors">
                            <i class="fa-solid fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
        @empty
        <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-8 text-center">
            <div class="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-4 text-slate-300">
                <i class="fa-solid fa-link-slash text-2xl"></i>
            </div>
            <p class="text-slate-500 font-medium">Belum ada link yang dibuat</p>
        </div>
        @endforelse
    </div>

    <!-- Pagination -->
    @if($shortlinks->hasPages())
        <div class="pt-4">
            {{ $shortlinks->links() }}
        </div>
    @endif

</div>

<!-- Link Details Modal (Same as before) -->
<div id="linkDetailsModal" class="fixed inset-0 z-50 hidden overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onclick="closeLinkDetails()"></div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="sm:flex sm:items-start">
                    <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-emerald-100 sm:mx-0 sm:h-10 sm:w-10">
                        <i class="fa-solid fa-chart-line text-emerald-600"></i>
                    </div>
                    <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
                        <h3 class="text-lg leading-6 font-medium text-slate-900" id="modalLinkTitle">Link Details</h3>
                        <div class="mt-2">
                            <p class="text-sm text-slate-500 break-all mb-4" id="modalOriginalUrl">...</p>
                            <div class="grid grid-cols-2 gap-4 mt-4">
                                <div class="bg-emerald-50 p-3 rounded-lg border border-emerald-100">
                                    <span class="block text-xs font-medium text-emerald-500 uppercase">Hari Ini</span>
                                    <span class="block text-xl font-bold text-emerald-700" id="modalClicksToday">0</span>
                                </div>
                                <div class="bg-slate-50 p-3 rounded-lg border border-slate-100">
                                    <span class="block text-xs font-medium text-slate-500 uppercase">7 Hari</span>
                                    <span class="block text-xl font-bold text-slate-700" id="modalClicks7Days">0</span>
                                </div>
                                <div class="bg-slate-50 p-3 rounded-lg border border-slate-100">
                                    <span class="block text-xs font-medium text-slate-500 uppercase">30 Hari</span>
                                    <span class="block text-xl font-bold text-slate-700" id="modalClicks30Days">0</span>
                                </div>
                                <div class="bg-green-50 p-3 rounded-lg border border-green-100">
                                    <span class="block text-xs font-medium text-green-600 uppercase">Total</span>
                                    <span class="block text-xl font-bold text-green-700" id="modalTotalClicks">0</span>
                                </div>
                            </div>
                            <div class="mt-4 pt-4 border-t border-slate-100">
                                <h4 class="text-xs font-semibold text-slate-500 uppercase mb-3">Sumber Terpopuler</h4>
                                <div id="modalReferrerList" class="space-y-2 max-h-40 overflow-y-auto pr-1"></div>
                                
                                <!-- Latest Referrer Only -->
                                <div class="mt-4 pt-4 border-t border-slate-100">
                                    <span class="block text-xs font-medium text-slate-500 uppercase mb-2">Sumber Terbaru</span>
                                    <div class="flex items-center gap-2">
                                        <i class="fa-regular fa-clock text-blue-500 text-sm"></i>
                                        <span class="text-sm font-semibold text-slate-800 truncate" id="modalLatestReferrer">-</span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Popular Stats (Device, OS, Country, City) -->
                            <div class="mt-4 pt-4 border-t border-slate-100">
                                <h4 class="text-xs font-semibold text-slate-600 uppercase mb-3">Statistik Populer (Sepanjang Masa)</h4>
                                <div class="grid grid-cols-2 gap-4">
                                    <!-- Device -->
                                    <div>
                                        <span class="block text-xs font-medium text-slate-500 uppercase mb-1">Perangkat</span>
                                        <div class="flex items-center gap-2">
                                            <i class="fa-solid fa-desktop text-emerald-500 text-sm"></i>
                                            <span class="text-sm font-semibold text-slate-800 truncate capitalize" id="modalTopDevice">-</span>
                                        </div>
                                    </div>
                                    
                                    <!-- OS -->
                                    <div>
                                        <span class="block text-xs font-medium text-slate-500 uppercase mb-1">Sistem Operasi</span>
                                        <div class="flex items-center gap-2">
                                            <i class="fa-brands fa-windows text-blue-500 text-sm"></i>
                                            <span class="text-sm font-semibold text-slate-800 truncate capitalize" id="modalTopOS">-</span>
                                        </div>
                                    </div>
                                    
                                    <!-- Country -->
                                    <div>
                                        <span class="block text-xs font-medium text-slate-500 uppercase mb-1">Negara</span>
                                        <div class="flex items-center gap-2">
                                            <i class="fa-solid fa-globe text-indigo-500 text-sm"></i>
                                            <span class="text-sm font-semibold text-slate-800 truncate capitalize" id="modalTopCountry">-</span>
                                        </div>
                                    </div>
                                    
                                    <!-- City -->
                                    <div>
                                        <span class="block text-xs font-medium text-slate-500 uppercase mb-1">Kota</span>
                                        <div class="flex items-center gap-2">
                                            <i class="fa-solid fa-map-marker-alt text-purple-500 text-sm"></i>
                                            <span class="text-sm font-semibold text-slate-800 truncate capitalize" id="modalTopCity">-</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mt-4 pt-2 text-xs text-slate-500 space-y-1">
                                <div id="modalLastClick"></div>
                                <div id="modalClicks1Hour" class="hidden text-slate-500"></div>
                            </div>

                            <div class="mt-6 pt-4 border-t border-slate-100 text-center">
                                <a id="modalDetailedAnalyticsBtn" href="#" class="text-emerald-600 hover:text-emerald-700 font-medium text-sm flex items-center justify-center gap-2">
                                    Rincian Selengkapnya <i class="fa-solid fa-arrow-right"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bg-slate-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button type="button" class="w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-slate-700 hover:bg-slate-50 focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 sm:w-auto sm:text-sm" onclick="closeLinkDetails()">Tutup</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Link Modal -->
<div id="editLinkModal" class="fixed inset-0 z-50 hidden overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" onclick="closeEditModal()"></div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6">
                <div class="sm:flex sm:items-start">
                    <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-emerald-100 sm:mx-0 sm:h-10 sm:w-10">
                         <i class="fa-solid fa-pen text-emerald-600"></i>
                    </div>
                    <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
                        <h3 class="text-lg leading-6 font-medium text-slate-900">Edit Link</h3>
                        <div class="mt-4 space-y-4">
                            <form id="editLinkForm">
                                <input type="hidden" id="editLinkId">
                                <div>
                                    <label for="editTitle" class="block text-sm font-medium text-slate-700">Judul (Opsional)</label>
                                    <input type="text" id="editTitle" class="mt-1 block w-full border border-slate-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-emerald-500 focus:border-emerald-500 sm:text-sm" placeholder="Contoh: Portofolio Saya">
                                </div>
                                <div>
                                    <label for="editOriginalUrl" class="block text-sm font-medium text-slate-700">URL Tujuan</label>
                                    <input type="url" id="editOriginalUrl" class="mt-1 block w-full border border-slate-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-emerald-500 focus:border-emerald-500 sm:text-sm" placeholder="https://..." required>
                                </div>
                                <div class="flex items-center justify-between pt-2">
                                    <span class="text-sm font-medium text-slate-700">Status Link (Aktif)</span>
                                    <label class="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" id="editIsActive" class="sr-only peer">
                                        <div class="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-emerald-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-emerald-600"></div>
                                    </label>
                                </div>
                                <div class="bg-blue-50 p-3 rounded-md mt-2">
                                     <p class="text-xs text-blue-700"><i class="fa-solid fa-info-circle mr-1"></i> Permalink (kode unik) tidak dapat diubah untuk menjaga integritas link.</p>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bg-slate-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button type="button" onclick="saveEditLink()" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-emerald-600 text-base font-medium text-white hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 sm:ml-3 sm:w-auto sm:text-sm">Simpan</button>
                <button type="button" onclick="closeEditModal()" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-slate-700 hover:bg-slate-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">Batal</button>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    // Search functionality handled server-side now

    // Open Stats Modal with Ajax
    function openLinkDetails(id, title, url, total, unique, d30, d7, today, c1h, last) {
        // Build Basic Info
        document.getElementById('modalLinkTitle').innerText = title;
        document.getElementById('modalOriginalUrl').innerText = url;
        document.getElementById('modalTotalClicks').innerText = total;
        document.getElementById('modalClicks30Days').innerText = d30;
        document.getElementById('modalClicks7Days').innerText = d7;
        document.getElementById('modalClicksToday').innerText = today;
        document.getElementById('modalLastClick').innerText = 'Terakhir diklik: ' + last;
        
        const c1hEl = document.getElementById('modalClicks1Hour');
        if (c1h > 0) {
            c1hEl.innerText = 'Klik dalam 1 jam: ' + c1h + ' kali';
            c1hEl.classList.remove('hidden');
        } else {
            c1hEl.classList.add('hidden');
        }

        // Set Detailed Analytics Link
        document.getElementById('modalDetailedAnalyticsBtn').href = "{{ route('analytics.data') }}?search=" + encodeURIComponent(title);

        // Show loading state for detailed stats
        const listContainer = document.getElementById('modalReferrerList');
        listContainer.innerHTML = '<p class="text-sm text-slate-400 text-center py-4"><i class="fa-solid fa-circle-notch fa-spin mr-2"></i>Memuat statistik detail...</p>';
        document.getElementById('modalLatestReferrer').innerText = 'Memuat...';

        ['modalTopDevice', 'modalTopOS', 'modalTopCountry', 'modalTopCity'].forEach(id => {
             document.getElementById(id).innerHTML = '-';
        });
        
        document.getElementById('linkDetailsModal').classList.remove('hidden');

        // Fetch Detailed Stats
        fetch(`/shortlinks/${id}/stats`, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            // Referrers
            listContainer.innerHTML = '';
            if (data.referrer_summary && data.referrer_summary.length > 0) {
                data.referrer_summary.forEach(item => {
                    const domain = item.source;
                    const count = item.count;
                    const htmlItem = `
                        <div class="flex justify-between items-center text-sm">
                            <div class="flex items-center gap-2">
                                <span class="text-slate-700 font-medium truncate max-w-[150px]">${domain}</span>
                            </div>
                            <span class="bg-slate-100 text-slate-600 px-2 py-0.5 rounded-full text-xs font-bold">${count} klik</span>
                        </div>`;
                    listContainer.insertAdjacentHTML('beforeend', htmlItem);
                });
            } else {
                listContainer.innerHTML = '<p class="text-sm text-slate-400 italic text-center">Belum ada data</p>';
            }

            // Other Stats
            document.getElementById('modalLatestReferrer').innerText = data.latest_referrer || '-';
            
            document.getElementById('modalTopDevice').innerHTML = (data.top_device && data.top_device !== '-') ? `${data.top_device} <span class="text-slate-400 font-normal text-xs ml-1">(${data.top_device_count} klik)</span>` : '-';
            document.getElementById('modalTopOS').innerHTML = (data.top_os && data.top_os !== '-') ? `${data.top_os} <span class="text-slate-400 font-normal text-xs ml-1">(${data.top_os_count} klik)</span>` : '-';
            document.getElementById('modalTopCountry').innerHTML = (data.top_country && data.top_country !== '-') ? `${data.top_country} <span class="text-slate-400 font-normal text-xs ml-1">(${data.top_country_count} klik)</span>` : '-';
            document.getElementById('modalTopCity').innerHTML = (data.top_city && data.top_city !== '-') ? `${data.top_city} <span class="text-slate-400 font-normal text-xs ml-1">(${data.top_city_count} klik)</span>` : '-';

        })
        .catch(err => {
            console.error(err);
            listContainer.innerHTML = '<p class="text-sm text-red-500 text-center">Gagal memuat detail</p>';
        });
    }

    function closeLinkDetails() {
        document.getElementById('linkDetailsModal').classList.add('hidden');
    }

    // Edit Link
    function editLink(id, title, url, isActive) {
        document.getElementById('editLinkId').value = id;
        document.getElementById('editTitle').value = title || '';
        document.getElementById('editOriginalUrl').value = url;
        document.getElementById('editIsActive').checked = isActive;
        document.getElementById('editLinkModal').classList.remove('hidden');
    }

    function closeEditModal() {
        document.getElementById('editLinkModal').classList.add('hidden');
    }

    function saveEditLink() {
        const id = document.getElementById('editLinkId').value;
        const title = document.getElementById('editTitle').value;
        const original_url = document.getElementById('editOriginalUrl').value;
        const is_active = document.getElementById('editIsActive').checked;

        if(!original_url) {
            showToast('URL Tujuan wajib diisi!');
            return;
        }

        fetch(`/shortlinks/${id}`, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                title: title,
                original_url: original_url,
                is_active: is_active
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast(data.message);
                closeEditModal();
                // Optional: Update DOM directly without reload
                setTimeout(() => location.reload(), 500); 
            } else {
                showToast('Gagal memperbarui link');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('Terjadi kesalahan');
        });
    }

    // Delete Link
    function deleteLink(id, button) {
        if (!confirm('Yakin hapus?')) return;

        fetch(`/shortlinks/${id}`, {
            method: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Find nearest item container (tr or div.link-item)
                const item = button.closest('tr') || button.closest('.link-item');
                if(item) {
                    item.style.opacity = '0';
                    setTimeout(() => {
                        item.remove();
                        // Check if empty
                         // (Logic simplified for responsive: reload if really needed or just ignore)
                    }, 300);
                }
                showToast(data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('Gagal menghapus');
        });
    }
</script>
@endpush
@endsection
