<x-app-layout>
    <x-slot name="header">
        <div class="flex justify-between items-center">
            <div>
                <h2 class="font-semibold text-lg text-gray-800 dark:text-gray-200 leading-tight">
                    <i class="fas fa-tachometer-alt mr-2"></i>@trans_db('my_dns_zones', 'dns_zones', 'My DNS Zones')
                </h2>
                <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">
                    <a href="{{ route('dashboard') }}" class="text-blue-600 dark:text-blue-400 hover:underline">{{ __('menu.dashboard') }}</a>
                    <span class="mx-2">/</span>
                    <span>@trans_db('my_dns_zones', 'dns_zones', 'DNS Zones')</span>
                </p>
            </div>
            <div class="flex items-center gap-3">
                @if(Auth::user()->canPerformDnsOperations())
                    <a href="{{ route('dns-zones.create') }}" class="inline-flex items-center px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold rounded-lg transition">
                        <i class="fas fa-plus mr-2"></i>@trans_db('add_dns_zone', 'dns_zones', 'Add DNS Zone')
                    </a>
                @else
                    <button disabled class="inline-flex items-center px-4 py-2 bg-gray-400 text-gray-200 font-semibold rounded-lg cursor-not-allowed opacity-60">
                        <i class="fas fa-ban mr-2"></i>@trans_db('limit_reached', 'dns_zones', 'Limită Atinsă')
                    </button>
                @endif
                <a href="{{ route('dashboard') }}" class="inline-flex items-center justify-center w-10 h-10 text-gray-600 dark:text-gray-400 hover:text-indigo-600 dark:hover:text-indigo-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition" title="@trans_db('back_to_dashboard', 'dns_zones', 'Înapoi la Dashboard')">
                    <i class="fas fa-arrow-left"></i>
                </a>
            </div>
        </div>
    </x-slot>

    <div class="py-12">
        <div class="px-6 lg:px-8">
            <!-- Stats Cards -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
                <!-- Card 1: Plan Curent -->
                <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                    <div class="p-6">
                        <div class="flex items-center justify-between mb-4">
                            <div class="flex items-center">
                                <div class="flex items-center justify-center w-12 h-12 rounded-full bg-gradient-to-br from-purple-400 to-indigo-600 shadow-lg">
                                    <i class="fas fa-crown text-white text-xl"></i>
                                </div>
                                <div class="ml-4">
                                    <h4 class="text-sm font-medium text-gray-600 dark:text-gray-400">@trans_db('current_plan', 'dashboard', 'Plan Curent')</h4>
                                    <p class="text-2xl font-bold text-gray-900 dark:text-gray-100">
                                        @if(Auth::user()->role === 'admin')
                                            @trans_db('administrator', 'dashboard', 'Administrator')
                                        @elseif(Auth::user()->role === 'reseller')
                                            {{ Auth::user()->resellerPlan?->name ?? 'Reseller' }}
                                        @else
                                            {{ Auth::user()->plan?->name ?? trans_db('free', 'dashboard', 'Gratuit') }}
                                        @endif
                                    </p>
                                </div>
                            </div>
                        </div>
                        @if(Auth::user()->plan_expires_at && Auth::user()->role !== 'admin')
                            <p class="text-sm text-gray-600 dark:text-gray-400">
                                @trans_db('expires', 'dashboard', 'Expiră'): <strong>{{ Auth::user()->plan_expires_at->format('d M Y') }}</strong>
                            </p>
                        @else
                            <p class="text-sm text-green-600 dark:text-green-400 font-semibold">@trans_db('no_expiry', 'dashboard', 'Fără dată expirare')</p>
                        @endif
                    </div>
                </div>

                <!-- Card 2: Zone DNS -->
                <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                    <div class="p-6">
                        <div class="flex items-center justify-between mb-4">
                            <div class="flex items-center">
                                <div class="flex items-center justify-center w-12 h-12 rounded-full bg-gradient-to-br from-blue-400 to-blue-600 shadow-lg">
                                    <i class="fas fa-globe text-white text-xl"></i>
                                </div>
                                <div class="ml-4">
                                    <h4 class="text-sm font-medium text-gray-600 dark:text-gray-400">@trans_db('zone_dns', 'dns_zones', 'Zone DNS')</h4>
                                    <p class="text-2xl font-bold text-gray-900 dark:text-gray-100">
                                        @if(Auth::user()->role === 'admin')
                                            {{ $zones->total() }} / ∞
                                        @elseif(Auth::user()->role === 'reseller')
                                            {{ $zones->total() }} / {{ Auth::user()->resellerPlan?->dns_zones_per_client ?? 'N/A' }}
                                        @else
                                            {{ $zones->total() }} / {{ Auth::user()->plan?->dns_zones_limit ?? 0 }}
                                        @endif
                                    </p>
                                </div>
                            </div>
                        </div>
                        @if(Auth::user()->role !== 'admin')
                            <div class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                                @php
                                    $zonesCount = $zones->total();
                                    if(Auth::user()->role === 'reseller') {
                                        $zonesLimit = Auth::user()->resellerPlan?->dns_zones_per_client ?? 1;
                                    } else {
                                        $zonesLimit = Auth::user()->plan?->dns_zones_limit ?? 1;
                                    }
                                    $zonesPercent = $zonesLimit > 0 ? min(($zonesCount / $zonesLimit) * 100, 100) : 0;
                                @endphp
                                <div class="bg-blue-600 dark:bg-blue-400 h-2 rounded-full" style="width: {{ $zonesPercent }}%"></div>
                            </div>
                        @else
                            <p class="text-sm text-green-600 dark:text-green-400 font-semibold">Unlimited</p>
                        @endif
                    </div>
                </div>

                <!-- Card 3: Înregistrări DNS -->
                <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                    <div class="p-6">
                        <div class="flex items-center justify-between mb-4">
                            <div class="flex items-center">
                                <div class="flex items-center justify-center w-12 h-12 rounded-full bg-gradient-to-br from-green-400 to-green-600 shadow-lg">
                                    <i class="fas fa-network-wired text-white text-xl"></i>
                                </div>
                                <div class="ml-4">
                                    <h4 class="text-sm font-medium text-gray-600 dark:text-gray-400">Înregistrări DNS</h4>
                                    <p class="text-2xl font-bold text-gray-900 dark:text-gray-100">
                                        @php
                                            $recordsCount = Auth::user()->getTotalRecordsCount();
                                        @endphp
                                        @if(Auth::user()->role === 'admin')
                                            {{ $recordsCount }} / ∞
                                        @elseif(Auth::user()->role === 'reseller')
                                            {{ $recordsCount }} / {{ Auth::user()->resellerPlan?->subdomains_per_client ?? 'N/A' }}
                                        @else
                                            {{ $recordsCount }} / {{ Auth::user()->plan?->subdomains_limit ?? 0 }}
                                        @endif
                                    </p>
                                </div>
                            </div>
                        </div>
                        @if(Auth::user()->role !== 'admin')
                            <div class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                                @php
                                    if(Auth::user()->role === 'reseller') {
                                        $recordsLimit = Auth::user()->resellerPlan?->subdomains_per_client ?? 1;
                                    } else {
                                        $recordsLimit = Auth::user()->plan?->subdomains_limit ?? 1;
                                    }
                                    $recordsPercent = $recordsLimit > 0 ? min(($recordsCount / $recordsLimit) * 100, 100) : 0;
                                @endphp
                                <div class="bg-green-600 dark:bg-green-400 h-2 rounded-full" style="width: {{ $recordsPercent }}%"></div>
                            </div>
                        @else
                            <p class="text-sm text-green-600 dark:text-green-400 font-semibold">Unlimited</p>
                        @endif
                    </div>
                </div>

                <!-- Card 4: Nameservere Alocate -->
                <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                    <div class="p-6">
                        @php
                            $user = Auth::user();
                            $nameserversList = [];

                            if ($user->isAdmin()) {
                                // Admin vede toate nameserverele active
                                $nameserversList = \App\Models\Nameserver::active()->pluck('hostname')->toArray();
                            } elseif ($user->role === 'reseller' && $user->resellerPlan) {
                                // Reseller vede nameserverele din planul său reseller
                                $allowedIds = $user->resellerPlan->getAllowedNameServers();
                                $nameserversList = \App\Models\Nameserver::whereIn('id', $allowedIds)
                                    ->where('is_active', true)
                                    ->pluck('hostname')
                                    ->toArray();
                            } elseif ($user->reseller_id && $user->reseller && $user->reseller->resellerPlan) {
                                // Client al unui reseller - vede nameserverele din planul resellerului
                                $allowedIds = $user->reseller->resellerPlan->getAllowedNameServers();
                                $nameserversList = \App\Models\Nameserver::whereIn('id', $allowedIds)
                                    ->where('is_active', true)
                                    ->pluck('hostname')
                                    ->toArray();
                            } elseif ($user->plan) {
                                // Client normal cu plan propriu
                                $allowedIds = $user->plan->getAllowedNameServers();
                                $nameserversList = \App\Models\Nameserver::whereIn('id', $allowedIds)
                                    ->where('is_active', true)
                                    ->pluck('hostname')
                                    ->toArray();
                            }
                            $totalNS = count($nameserversList);
                        @endphp

                        <!-- Header -->
                        <div class="flex items-center justify-between mb-2">
                            <div class="flex items-center">
                                <div class="flex items-center justify-center w-12 h-12 rounded-full bg-gradient-to-br from-purple-400 to-purple-600 shadow-lg">
                                    <i class="fas fa-server text-white text-xl"></i>
                                </div>
                                <div class="ml-4">
                                    <h4 class="text-sm font-medium text-gray-600 dark:text-gray-400">NSuri Alocate</h4>
                                </div>
                            </div>

                            <!-- Navigation Arrows (doar dacă sunt mai mult de 2 NS) -->
                            @if($totalNS > 2)
                                <div class="flex items-center gap-2">
                                    <button onclick="prevNS()" class="text-gray-400 dark:text-gray-500 hover:text-purple-600 dark:hover:text-purple-400 transition text-xs" title="Anterior">
                                        <i class="fas fa-chevron-left"></i>
                                    </button>
                                    <div id="nsIndicators" class="flex gap-1">
                                        @foreach(array_chunk($nameserversList, 2) as $index => $chunk)
                                            <div class="ns-indicator w-1 h-1 rounded-full bg-gray-300 dark:bg-gray-600 transition {{ $index === 0 ? 'bg-purple-600 dark:bg-purple-400' : '' }}"></div>
                                        @endforeach
                                    </div>
                                    <button onclick="nextNS()" class="text-gray-400 dark:text-gray-500 hover:text-purple-600 dark:hover:text-purple-400 transition text-xs" title="Următor">
                                        <i class="fas fa-chevron-right"></i>
                                    </button>
                                </div>
                            @endif
                        </div>

                        <!-- Carousel Container -->
                        @if($totalNS > 0)
                            <div class="ml-16 overflow-hidden">
                                <div id="nsCarousel" class="flex transition-transform duration-300 ease-in-out">
                                    @foreach(array_chunk($nameserversList, 2) as $chunkIndex => $chunk)
                                        <div class="w-full flex-shrink-0 space-y-0.5">
                                            @foreach($chunk as $hostname)
                                                <p class="text-xs font-mono text-gray-700 dark:text-gray-300">{{ $hostname }}</p>
                                            @endforeach
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        @else
                            <p class="ml-16 text-xs text-gray-500 dark:text-gray-400">Nu există nameservere alocate</p>
                        @endif
                    </div>
                </div>
            </div>

            <!-- DNS Zones List -->
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6">
                    <div class="flex flex-wrap items-center justify-between gap-4 mb-4">
                        <div class="flex flex-wrap items-center gap-4">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">Zone DNS</h3>

                            <!-- Search Box -->
                            <form action="{{ route('dns-zones.index') }}" method="GET" class="relative w-64" id="searchForm">
                                <input type="text"
                                       name="search"
                                       id="zoneSearch"
                                       value="{{ request('search') }}"
                                       placeholder="Caută zone..."
                                       class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 focus:border-indigo-500 dark:focus:border-indigo-600 focus:ring-indigo-500 dark:focus:ring-indigo-600 pl-3 pr-10 py-2 text-sm"
                                       autocomplete="off">
                                <!-- Hidden fields for filters -->
                                <input type="hidden" name="status" id="hiddenStatus" value="{{ request('status') }}">
                                <input type="hidden" name="dnssec" id="hiddenDnssec" value="{{ request('dnssec') }}">
                                <input type="hidden" name="period" id="hiddenPeriod" value="{{ request('period') }}">
                                <input type="hidden" name="sort" id="hiddenSort" value="{{ request('sort', 'newest') }}">
                                @if(request('search'))
                                    <a href="{{ route('dns-zones.index', array_filter(['status' => request('status'), 'dnssec' => request('dnssec'), 'period' => request('period'), 'sort' => request('sort')])) }}" class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                                        <i class="fas fa-times"></i>
                                    </a>
                                @endif
                            </form>

                            <!-- Filter Toggle Button -->
                            <button onclick="toggleFilters()" class="inline-flex items-center px-3 py-2 text-sm font-medium rounded-lg border transition
                                {{ request('status') || request('dnssec') || request('period') ? 'bg-indigo-50 dark:bg-indigo-900/20 border-indigo-300 dark:border-indigo-700 text-indigo-700 dark:text-indigo-300' : 'bg-white dark:bg-gray-700 border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600' }}">
                                <i class="fas fa-filter mr-2"></i>
                                Filtre
                                @if(request('status') || request('dnssec') || request('period'))
                                    <span class="ml-2 px-1.5 py-0.5 text-xs bg-indigo-600 text-white rounded-full">
                                        {{ collect([request('status'), request('dnssec'), request('period')])->filter()->count() }}
                                    </span>
                                @endif
                            </button>

                            <!-- View Toggle Buttons -->
                            <div class="flex items-center border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden">
                                <button onclick="setViewMode('table')" id="viewTableBtn"
                                        class="px-3 py-2 text-sm font-medium transition {{ request('view', 'table') === 'table' ? 'bg-indigo-600 text-white' : 'bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600' }}"
                                        title="Vedere tabel">
                                    <i class="fas fa-list"></i>
                                </button>
                                <button onclick="setViewMode('cards')" id="viewCardsBtn"
                                        class="px-3 py-2 text-sm font-medium transition {{ request('view', 'table') === 'cards' ? 'bg-indigo-600 text-white' : 'bg-white dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600' }}"
                                        title="Vedere carduri">
                                    <i class="fas fa-th-large"></i>
                                </button>
                            </div>
                        </div>

                        <!-- Export Button -->
                        <div class="relative">
                            <button onclick="toggleZoneExportMenu()" id="zoneExportBtn" class="inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition">
                                <i class="fas fa-download mr-2"></i>
                                Export
                                <i class="fas fa-chevron-down ml-2"></i>
                            </button>
                            <div id="zoneExportMenu" class="hidden absolute right-0 mt-2 w-48 bg-white dark:bg-gray-700 rounded-lg shadow-lg z-50 border border-gray-200 dark:border-gray-600">
                                <a href="{{ route('dns-zones.export-list', array_merge(['format' => 'txt'], request()->only(['search', 'status', 'dnssec', 'period']))) }}" class="w-full text-left block px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-t-lg">
                                    <i class="fas fa-file-alt mr-2"></i>Export TXT
                                </a>
                                <a href="{{ route('dns-zones.export-list', array_merge(['format' => 'html'], request()->only(['search', 'status', 'dnssec', 'period']))) }}" class="w-full text-left block px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600">
                                    <i class="fas fa-globe mr-2"></i>Export HTML
                                </a>
                                <a href="{{ route('dns-zones.export-list', array_merge(['format' => 'csv'], request()->only(['search', 'status', 'dnssec', 'period']))) }}" class="w-full text-left block px-4 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-b-lg">
                                    <i class="fas fa-file-excel mr-2"></i>Export CSV
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Advanced Filters Panel -->
                    <div id="filtersPanel" class="{{ request('status') || request('dnssec') || request('period') ? '' : 'hidden' }} mb-4 p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg border border-gray-200 dark:border-gray-600">
                        <div class="flex flex-wrap items-end gap-4">
                            <!-- Status Filter -->
                            <div class="min-w-[140px]">
                                <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Status</label>
                                <select id="filterStatus" onchange="applyFilters()" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 text-sm py-2">
                                    <option value="">Toate</option>
                                    <option value="active" {{ request('status') == 'active' ? 'selected' : '' }}>Activ</option>
                                    <option value="inactive" {{ request('status') == 'inactive' ? 'selected' : '' }}>Inactiv</option>
                                    <option value="suspended" {{ request('status') == 'suspended' ? 'selected' : '' }}>Suspendat</option>
                                </select>
                            </div>

                            <!-- DNSSEC Filter -->
                            <div class="min-w-[140px]">
                                <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">DNSSEC</label>
                                <select id="filterDnssec" onchange="applyFilters()" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 text-sm py-2">
                                    <option value="">Toate</option>
                                    <option value="enabled" {{ request('dnssec') == 'enabled' ? 'selected' : '' }}>Activat</option>
                                    <option value="disabled" {{ request('dnssec') == 'disabled' ? 'selected' : '' }}>Dezactivat</option>
                                </select>
                            </div>

                            <!-- Period Filter -->
                            <div class="min-w-[160px]">
                                <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Perioadă creare</label>
                                <select id="filterPeriod" onchange="applyFilters()" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 text-sm py-2">
                                    <option value="">Oricând</option>
                                    <option value="today" {{ request('period') == 'today' ? 'selected' : '' }}>Azi</option>
                                    <option value="week" {{ request('period') == 'week' ? 'selected' : '' }}>Ultima săptămână</option>
                                    <option value="month" {{ request('period') == 'month' ? 'selected' : '' }}>Ultima lună</option>
                                    <option value="quarter" {{ request('period') == 'quarter' ? 'selected' : '' }}>Ultimele 3 luni</option>
                                    <option value="year" {{ request('period') == 'year' ? 'selected' : '' }}>Ultimul an</option>
                                </select>
                            </div>

                            <!-- Sort Filter -->
                            <div class="min-w-[160px]">
                                <label class="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Sortare</label>
                                <select id="filterSort" onchange="applyFilters()" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 text-sm py-2">
                                    <option value="newest" {{ request('sort', 'newest') == 'newest' ? 'selected' : '' }}>Cele mai noi</option>
                                    <option value="oldest" {{ request('sort') == 'oldest' ? 'selected' : '' }}>Cele mai vechi</option>
                                    <option value="domain_asc" {{ request('sort') == 'domain_asc' ? 'selected' : '' }}>Domeniu A-Z</option>
                                    <option value="domain_desc" {{ request('sort') == 'domain_desc' ? 'selected' : '' }}>Domeniu Z-A</option>
                                    <option value="records_desc" {{ request('sort') == 'records_desc' ? 'selected' : '' }}>Recorduri (multe→puține)</option>
                                    <option value="records_asc" {{ request('sort') == 'records_asc' ? 'selected' : '' }}>Recorduri (puține→multe)</option>
                                </select>
                            </div>

                            <!-- Clear Filters -->
                            @if(request('status') || request('dnssec') || request('period') || request('sort') != 'newest')
                                <a href="{{ route('dns-zones.index', ['search' => request('search')]) }}" class="inline-flex items-center px-3 py-2 text-sm text-red-600 dark:text-red-400 hover:text-red-800 dark:hover:text-red-300 transition">
                                    <i class="fas fa-times-circle mr-1"></i>
                                    Resetează filtrele
                                </a>
                            @endif
                        </div>

                        <!-- Active Filters Tags -->
                        @if(request('status') || request('dnssec') || request('period'))
                            <div class="mt-3 flex flex-wrap gap-2">
                                @if(request('status'))
                                    <span class="inline-flex items-center px-2 py-1 text-xs bg-indigo-100 dark:bg-indigo-900/40 text-indigo-700 dark:text-indigo-300 rounded-full">
                                        Status: {{ request('status') == 'active' ? 'Activ' : (request('status') == 'inactive' ? 'Inactiv' : 'Suspendat') }}
                                        <a href="{{ route('dns-zones.index', array_merge(request()->except('status'), [])) }}" class="ml-1 hover:text-indigo-900 dark:hover:text-indigo-100">×</a>
                                    </span>
                                @endif
                                @if(request('dnssec'))
                                    <span class="inline-flex items-center px-2 py-1 text-xs bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-300 rounded-full">
                                        DNSSEC: {{ request('dnssec') == 'enabled' ? 'Activat' : 'Dezactivat' }}
                                        <a href="{{ route('dns-zones.index', array_merge(request()->except('dnssec'), [])) }}" class="ml-1 hover:text-green-900 dark:hover:text-green-100">×</a>
                                    </span>
                                @endif
                                @if(request('period'))
                                    @php
                                        $periodLabels = ['today' => 'Azi', 'week' => 'Ultima săptămână', 'month' => 'Ultima lună', 'quarter' => 'Ultimele 3 luni', 'year' => 'Ultimul an'];
                                    @endphp
                                    <span class="inline-flex items-center px-2 py-1 text-xs bg-yellow-100 dark:bg-yellow-900/40 text-yellow-700 dark:text-yellow-300 rounded-full">
                                        Perioadă: {{ $periodLabels[request('period')] ?? request('period') }}
                                        <a href="{{ route('dns-zones.index', array_merge(request()->except('period'), [])) }}" class="ml-1 hover:text-yellow-900 dark:hover:text-yellow-100">×</a>
                                    </span>
                                @endif
                            </div>
                        @endif
                    </div>

                    @if($zones->count() > 0)
                        <!-- Bulk Actions Bar (hidden by default) -->
                        <div id="bulkActionsBar" class="hidden mb-4 p-4 bg-indigo-50 dark:bg-indigo-900/20 border border-indigo-200 dark:border-indigo-800 rounded-lg">
                            <div class="flex flex-wrap items-center justify-between gap-4">
                                <div class="flex items-center gap-2">
                                    <span class="text-sm font-medium text-indigo-700 dark:text-indigo-300">
                                        <i class="fas fa-check-square mr-1"></i>
                                        <span id="selectedCount">0</span> zone selectate
                                    </span>
                                    <button onclick="clearSelection()" class="text-xs text-indigo-600 dark:text-indigo-400 hover:underline">
                                        Deselectează tot
                                    </button>
                                </div>
                                <div class="flex flex-wrap items-center gap-2">
                                    <button onclick="bulkActivate()" class="inline-flex items-center px-3 py-1.5 bg-green-600 hover:bg-green-700 text-white text-sm font-medium rounded-lg transition">
                                        <i class="fas fa-toggle-on mr-1.5"></i>Activează
                                    </button>
                                    <button onclick="bulkDeactivate()" class="inline-flex items-center px-3 py-1.5 bg-yellow-600 hover:bg-yellow-700 text-white text-sm font-medium rounded-lg transition">
                                        <i class="fas fa-toggle-off mr-1.5"></i>Dezactivează
                                    </button>
                                    <button onclick="bulkResync()" class="inline-flex items-center px-3 py-1.5 bg-purple-600 hover:bg-purple-700 text-white text-sm font-medium rounded-lg transition">
                                        <i class="fas fa-sync-alt mr-1.5"></i>Sincronizează
                                    </button>
                                    <button onclick="openBulkDeleteModal()" class="inline-flex items-center px-3 py-1.5 bg-red-600 hover:bg-red-700 text-white text-sm font-medium rounded-lg transition">
                                        <i class="fas fa-trash mr-1.5"></i>Șterge
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Table View -->
                        <div id="tableView" class="{{ request('view', 'table') === 'table' ? '' : 'hidden' }}">
                            <div class="overflow-x-auto">
                                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                                    <thead class="bg-gray-50 dark:bg-gray-700">
                                    <tr>
                                        <th class="px-4 py-3 text-center w-12">
                                            <input type="checkbox" id="selectAll" onchange="toggleSelectAll()"
                                                   class="w-4 h-4 text-indigo-600 bg-gray-100 dark:bg-gray-700 border-gray-300 dark:border-gray-600 rounded focus:ring-indigo-500 cursor-pointer">
                                        </th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                            DOMENIU
                                        </th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider hidden md:table-cell">
                                            NAMESERVER(E)
                                        </th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider hidden lg:table-cell">
                                            DATA
                                        </th>
                                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                            STATUS
                                        </th>
                                        <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                            ACȚIUNI
                                        </th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                                    @foreach($zones as $zone)
                                        @php
                                            $isPowerDnsOnly = isset($zone->is_powerdns_only) && $zone->is_powerdns_only;
                                            $zoneId = $isPowerDnsOnly ? null : $zone->id;
                                        @endphp
                                        <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/50 transition {{ $isPowerDnsOnly ? 'bg-green-50 dark:bg-green-900/20' : '' }}" data-zone-id="{{ $zoneId }}">
                                            <td class="px-4 py-4 text-center">
                                                @if(!$isPowerDnsOnly)
                                                    <input type="checkbox" class="zone-checkbox w-4 h-4 text-indigo-600 bg-gray-100 dark:bg-gray-700 border-gray-300 dark:border-gray-600 rounded focus:ring-indigo-500 cursor-pointer"
                                                           data-zone-id="{{ $zone->id }}"
                                                           data-zone-domain="{{ $zone->domain }}"
                                                           onchange="updateBulkSelection()">
                                                @else
                                                    <span class="text-gray-400" title="Zona PowerDNS nu poate fi selectată">
                                                        <i class="fas fa-lock text-xs"></i>
                                                    </span>
                                                @endif
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap">
                                                <div class="flex items-center group relative">
                                                    <div class="w-10 h-10 rounded-full bg-gradient-to-br {{ $isPowerDnsOnly ? 'from-green-400 to-emerald-600' : 'from-blue-400 to-indigo-600' }} flex items-center justify-center">
                                                        <i class="fas {{ $isPowerDnsOnly ? 'fa-server' : 'fa-globe' }} text-white text-sm"></i>
                                                    </div>
                                                    <div class="ml-3">
                                                        <div class="text-base font-semibold">
                                                            <a href="{{ route('dns-zones.show', $zone->domain) }}" class="text-gray-900 dark:text-gray-100 hover:text-indigo-600 dark:hover:text-indigo-400 transition">
                                                                {{ $zone->domain }}
                                                            </a>
                                                        </div>
                                                        <div class="text-xs text-gray-500 dark:text-gray-400">
                                                            @php
                                                                $recordCount = $isPowerDnsOnly
                                                                    ? count($zone->powerdns_data['rrsets'] ?? [])
                                                                    : $zone->records()->count();
                                                            @endphp
                                                            {{ $recordCount }} {{ $recordCount === 1 ? 'înregistrare' : 'înregistrări' }}
                                                            @if(Auth::user()->role === 'admin')
                                                                · {{ $zone->user->name }}
                                                            @endif
                                                        </div>
                                                    </div>

                                                    <!-- Quick Stats Tooltip -->
                                                    @if(!$isPowerDnsOnly)
                                                        {{-- Pentru primele 2 rânduri, tooltip-ul apare jos; pentru restul, sus --}}
                                                        @if($loop->index < 2)
                                                        <div class="absolute left-0 top-full mt-2 hidden group-hover:block z-[100] w-64">
                                                            <div class="bg-gray-900 dark:bg-gray-700 text-white text-xs rounded-lg shadow-lg p-3">
                                                                <div class="absolute left-4 top-0 transform -translate-y-full">
                                                                    <div class="border-8 border-transparent border-b-gray-900 dark:border-b-gray-700"></div>
                                                                </div>
                                                                <div class="font-semibold mb-2 pb-2 border-b border-gray-700 dark:border-gray-600">
                                                                    <i class="fas fa-chart-bar mr-1"></i> {{ $zone->domain }}
                                                                </div>
                                                                <div class="space-y-1.5">
                                                                    <div class="flex justify-between">
                                                                        <span class="text-gray-400">Înregistrări:</span>
                                                                        <span class="font-medium">{{ $recordCount }}</span>
                                                                    </div>
                                                                    <div class="flex justify-between">
                                                                        <span class="text-gray-400">Status:</span>
                                                                        <span class="font-medium tooltip-status {{ $zone->is_active ? 'text-green-400' : 'text-red-400' }}">
                                                                            {{ $zone->is_active ? 'Activ' : 'Inactiv' }}
                                                                        </span>
                                                                    </div>
                                                                    <div class="flex justify-between">
                                                                        <span class="text-gray-400">DNSSEC:</span>
                                                                        <span class="font-medium {{ $zone->dnssec_enabled ? 'text-green-400' : 'text-gray-400' }}">
                                                                            {{ $zone->dnssec_enabled ? 'Activat' : 'Dezactivat' }}
                                                                        </span>
                                                                    </div>
                                                                    <div class="flex justify-between">
                                                                        <span class="text-gray-400">Creat:</span>
                                                                        <span class="font-medium">{{ $zone->created_at->format('d.m.Y') }}</span>
                                                                    </div>
                                                                    @if($zone->updated_at && $zone->updated_at != $zone->created_at)
                                                                        <div class="flex justify-between">
                                                                            <span class="text-gray-400">Modificat:</span>
                                                                            <span class="font-medium">{{ $zone->updated_at->diffForHumans() }}</span>
                                                                        </div>
                                                                    @endif
                                                                </div>
                                                            </div>
                                                        </div>
                                                        @else
                                                        <div class="absolute left-0 bottom-full mb-2 hidden group-hover:block z-[100] w-64">
                                                            <div class="bg-gray-900 dark:bg-gray-700 text-white text-xs rounded-lg shadow-lg p-3">
                                                                <div class="font-semibold mb-2 pb-2 border-b border-gray-700 dark:border-gray-600">
                                                                    <i class="fas fa-chart-bar mr-1"></i> {{ $zone->domain }}
                                                                </div>
                                                                <div class="space-y-1.5">
                                                                    <div class="flex justify-between">
                                                                        <span class="text-gray-400">Înregistrări:</span>
                                                                        <span class="font-medium">{{ $recordCount }}</span>
                                                                    </div>
                                                                    <div class="flex justify-between">
                                                                        <span class="text-gray-400">Status:</span>
                                                                        <span class="font-medium tooltip-status {{ $zone->is_active ? 'text-green-400' : 'text-red-400' }}">
                                                                            {{ $zone->is_active ? 'Activ' : 'Inactiv' }}
                                                                        </span>
                                                                    </div>
                                                                    <div class="flex justify-between">
                                                                        <span class="text-gray-400">DNSSEC:</span>
                                                                        <span class="font-medium {{ $zone->dnssec_enabled ? 'text-green-400' : 'text-gray-400' }}">
                                                                            {{ $zone->dnssec_enabled ? 'Activat' : 'Dezactivat' }}
                                                                        </span>
                                                                    </div>
                                                                    <div class="flex justify-between">
                                                                        <span class="text-gray-400">Creat:</span>
                                                                        <span class="font-medium">{{ $zone->created_at->format('d.m.Y') }}</span>
                                                                    </div>
                                                                    @if($zone->updated_at && $zone->updated_at != $zone->created_at)
                                                                        <div class="flex justify-between">
                                                                            <span class="text-gray-400">Modificat:</span>
                                                                            <span class="font-medium">{{ $zone->updated_at->diffForHumans() }}</span>
                                                                        </div>
                                                                    @endif
                                                                </div>
                                                                <div class="absolute left-4 bottom-0 transform translate-y-full">
                                                                    <div class="border-8 border-transparent border-t-gray-900 dark:border-t-gray-700"></div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        @endif
                                                    @endif
                                                </div>
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap hidden md:table-cell">
                                                @php
                                                    // Obține nameserverele atribuite din planul utilizatorului
                                                    $nameservers = [];
                                                    $user = $zone->user;

                                                    // Pentru admin, afișează toate nameserverele active
                                                    if ($user->isAdmin()) {
                                                        $allowedNsIds = \App\Models\NameServer::where('is_active', true)->pluck('id')->toArray();
                                                    } else {
                                                        // Pentru utilizatori normali, obține nameserverele permise din plan
                                                        $plan = $user->plan ?? $user->resellerPlan;
                                                        $allowedNsIds = $plan ? $plan->allowed_nameservers : [];
                                                    }

                                                    // Obține nameserverele efectiv
                                                    if (!empty($allowedNsIds)) {
                                                        $nameserverModels = \App\Models\NameServer::whereIn('id', $allowedNsIds)->get();
                                                        foreach ($nameserverModels as $ns) {
                                                            $nameservers[] = $ns->hostname;
                                                        }
                                                    }

                                                    $nsCount = count($nameservers);
                                                    $nameserversJson = json_encode($nameservers);
                                                @endphp

                                                @if($nsCount > 0)
                                                    <div class="flex items-center space-x-2">
                                                        <div class="ns-carousel-{{ $zone->id }}" data-ns-count="{{ $nsCount }}">
                                                            @foreach($nameservers as $ns)
                                                                <div class="ns-item inline-flex items-center px-2.5 py-1 text-xs font-semibold rounded-lg bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 border border-blue-200 dark:border-blue-800" style="{{ $loop->first ? '' : 'display: none;' }}">
                                                                    {{ $ns }}
                                                                </div>
                                                            @endforeach
                                                        </div>
                                                        <!-- Copy Nameservers Button -->
                                                        <button type="button"
                                                                onclick="copyNameservers({{ $nameserversJson }}, this)"
                                                                class="inline-flex items-center justify-center w-6 h-6 rounded text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 transition"
                                                                title="Copiază toate nameserverele">
                                                            <i class="fas fa-copy text-xs"></i>
                                                        </button>
                                                    </div>
                                                @else
                                                    <span class="text-xs text-gray-400">-</span>
                                                @endif
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300 hidden lg:table-cell">
                                                <div class="flex flex-col">
                                                    <span class="font-medium">{{ $zone->created_at->format('d.m.Y') }}</span>
                                                    <span class="text-xs text-gray-500 dark:text-gray-400">{{ $zone->created_at->format('H:i') }}</span>
                                                </div>
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap">
                                                <div class="flex flex-col space-y-1">
                                                    @if($zone->is_active)
                                                        <span class="px-3 py-1.5 inline-flex items-center text-xs font-semibold rounded-lg bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 border border-green-200 dark:border-green-800" id="status-badge-{{ $zone->id }}">
                                                            <span class="w-1.5 h-1.5 bg-green-500 rounded-full mr-2 status-dot"></span>
                                                            Activ
                                                        </span>
                                                    @else
                                                        <span class="px-3 py-1.5 inline-flex items-center text-xs font-semibold rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-gray-600" id="status-badge-{{ $zone->id }}">
                                                            <span class="w-1.5 h-1.5 bg-gray-400 rounded-full mr-2 status-dot"></span>
                                                            Inactiv
                                                        </span>
                                                    @endif

                                                    <!-- Health Check Indicator -->
                                                    @if(!$isPowerDnsOnly && $zone->sync_to_powerdns && $zone->powerdns_zone_id)
                                                        @php
                                                            // Verifică numărul de nameservere active care au zona
                                                            $syncedNsCount = \App\Models\NameServer::where('is_active', true)
                                                                ->where('status', 'online')
                                                                ->count();
                                                        @endphp
                                                        <span class="inline-flex items-center text-xs text-green-600 dark:text-green-400" title="Sincronizat cu {{ $syncedNsCount }} nameservere">
                                                            <i class="fas fa-check-circle mr-1"></i>
                                                            Sync <span class="text-gray-400 ml-1">({{ $syncedNsCount }}NS)</span>
                                                        </span>
                                                    @elseif(!$isPowerDnsOnly && !$zone->sync_to_powerdns)
                                                        <span class="inline-flex items-center text-xs text-yellow-600 dark:text-yellow-400" title="Sincronizare PowerDNS dezactivată">
                                                            <i class="fas fa-exclamation-triangle mr-1"></i>
                                                            Local
                                                        </span>
                                                    @elseif(!$isPowerDnsOnly && !$zone->powerdns_zone_id)
                                                        <span class="inline-flex items-center text-xs text-red-600 dark:text-red-400" title="Zona nu este creată în PowerDNS">
                                                            <i class="fas fa-times-circle mr-1"></i>
                                                            Nu e sync
                                                        </span>
                                                    @endif
                                                </div>
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                                <div class="flex items-center justify-center space-x-1.5">
                                                    @if(isset($zone->is_powerdns_only) && $zone->is_powerdns_only)
                                                        {{-- PowerDNS only zone actions --}}
                                                        <a href="{{ route('dns-zones.show', $zone->domain) }}" class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-green-50 dark:bg-green-900/20 text-green-600 dark:text-green-400 hover:bg-green-100 dark:hover:bg-green-900/40 border border-green-200 dark:border-green-800 transition" title="Vizualizează în PowerDNS">
                                                            <i class="fas fa-eye"></i>
                                                        </a>
                                                        @if(in_array($zone->powerdns_assignment->access_level, ['full', 'records_only']))
                                                            <a href="{{ route('powerdns.user.records', $zone->powerdns_data['name']) }}" class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-900/40 border border-blue-200 dark:border-blue-800 transition" title="Gestionează înregistrări">
                                                                <i class="fas fa-edit"></i>
                                                            </a>
                                                        @endif
                                                        <span class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-gray-50 dark:bg-gray-700 text-gray-400 dark:text-gray-500 border border-gray-200 dark:border-gray-600 cursor-not-allowed" title="Nu se poate șterge - zona PowerDNS atribuită">
                                                            <i class="fas fa-lock"></i>
                                                        </span>
                                                    @else
                                                        {{-- Standard local zone actions --}}
                                                        <a href="{{ route('dns-zones.show', $zone->domain) }}" class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-indigo-50 dark:bg-indigo-900/20 text-indigo-600 dark:text-indigo-400 hover:bg-indigo-100 dark:hover:bg-indigo-900/40 border border-indigo-200 dark:border-indigo-800 transition" title="Vizualizează">
                                                            <i class="fas fa-eye"></i>
                                                        </a>
                                                        @if(auth()->user()->isAdmin())
                                                            <a href="{{ route('dns-zones.edit', $zone) }}" class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-900/40 border border-blue-200 dark:border-blue-800 transition" title="Editează">
                                                                <i class="fas fa-edit"></i>
                                                            </a>
                                                        @else
                                                            <span class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-gray-50 dark:bg-gray-700 text-gray-400 dark:text-gray-500 border border-gray-200 dark:border-gray-600 cursor-not-allowed" title="Editare dezactivată">
                                                                <i class="fas fa-edit"></i>
                                                            </span>
                                                        @endif
                                                        @if($zone->nameServer)
                                                            <form action="{{ route('dns-zones.resync', $zone) }}" method="POST" class="hidden" id="resyncForm{{ $zone->id }}">
                                                                @csrf
                                                            </form>
                                                            <button type="button" onclick="openResyncModal({{ $zone->id }}, '{{ addslashes($zone->domain) }}')" class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 hover:bg-purple-100 dark:hover:bg-purple-900/40 border border-purple-200 dark:border-purple-800 transition" title="Sincronizează">
                                                                <i class="fas fa-sync-alt"></i>
                                                            </button>
                                                        @endif
                                                        <!-- Toggle Active Button (AJAX) -->
                                                        <button type="button"
                                                                id="toggle-btn-{{ $zone->id }}"
                                                                onclick="toggleZoneStatus({{ $zone->id }}, '{{ addslashes($zone->domain) }}')"
                                                                class="inline-flex items-center justify-center w-9 h-9 rounded-lg {{ $zone->is_active ? 'bg-green-50 dark:bg-green-900/20 text-green-600 dark:text-green-400 hover:bg-green-100 dark:hover:bg-green-900/40 border-green-200 dark:border-green-800' : 'bg-gray-50 dark:bg-gray-700 text-gray-400 dark:text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-600 border-gray-200 dark:border-gray-600' }} border transition"
                                                                title="{{ $zone->is_active ? 'Dezactivează' : 'Activează' }}"
                                                                data-active="{{ $zone->is_active ? '1' : '0' }}">
                                                            <i class="fas {{ $zone->is_active ? 'fa-toggle-on' : 'fa-toggle-off' }}" id="toggle-icon-{{ $zone->id }}"></i>
                                                        </button>
                                                        <form id="delete-zone-form-{{ $zone->id }}" action="{{ route('dns-zones.destroy', $zone) }}" method="POST" class="inline">
                                                            @csrf
                                                            @method('DELETE')
                                                        </form>
                                                        <button type="button" onclick="openDeleteModal({{ $zone->id }}, '{{ addslashes($zone->domain) }}')" class="inline-flex items-center justify-center w-9 h-9 rounded-lg bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 hover:bg-red-100 dark:hover:bg-red-900/40 border border-red-200 dark:border-red-800 transition" title="Șterge">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    @endif
                                                </div>
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                            </div>
                        </div>
                        <!-- End Table View -->

                        <!-- Cards View -->
                        <div id="cardsView" class="{{ request('view', 'table') === 'cards' ? '' : 'hidden' }}">
                            <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                                @foreach($zones as $zone)
                                    @php
                                        $isPowerDnsOnly = isset($zone->is_powerdns_only) && $zone->is_powerdns_only;
                                        $recordCount = $isPowerDnsOnly
                                            ? count($zone->powerdns_data['rrsets'] ?? [])
                                            : $zone->records()->count();

                                        // Get nameservers for copy
                                        $nsUser = $zone->user;
                                        if ($nsUser->isAdmin()) {
                                            $nsAllowedIds = \App\Models\NameServer::where('is_active', true)->pluck('id')->toArray();
                                        } else {
                                            $nsPlan = $nsUser->plan ?? $nsUser->resellerPlan;
                                            $nsAllowedIds = $nsPlan ? $nsPlan->allowed_nameservers : [];
                                        }
                                        $cardNameservers = [];
                                        if (!empty($nsAllowedIds)) {
                                            $nsModels = \App\Models\NameServer::whereIn('id', $nsAllowedIds)->get();
                                            foreach ($nsModels as $ns) {
                                                $cardNameservers[] = $ns->hostname;
                                            }
                                        }
                                    @endphp
                                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-md border border-gray-200 dark:border-gray-700 overflow-hidden hover:shadow-lg transition-shadow">
                                        <!-- Card Header -->
                                        <div class="p-4 bg-gradient-to-r {{ $isPowerDnsOnly ? 'from-green-50 to-emerald-50 dark:from-green-900/20 dark:to-emerald-900/20' : 'from-indigo-50 to-blue-50 dark:from-indigo-900/20 dark:to-blue-900/20' }} border-b border-gray-200 dark:border-gray-700">
                                            <div class="flex items-center justify-between">
                                                <div class="flex items-center space-x-3">
                                                    @if(!$isPowerDnsOnly)
                                                        <input type="checkbox"
                                                               class="zone-checkbox w-4 h-4 text-indigo-600 bg-gray-100 dark:bg-gray-700 border-gray-300 dark:border-gray-600 rounded focus:ring-indigo-500 cursor-pointer"
                                                               value="{{ $zone->id }}"
                                                               data-zone-domain="{{ $zone->domain }}"
                                                               onchange="updateBulkSelection()">
                                                    @endif
                                                    <div class="w-10 h-10 rounded-full bg-gradient-to-br {{ $isPowerDnsOnly ? 'from-green-400 to-emerald-600' : 'from-blue-400 to-indigo-600' }} flex items-center justify-center">
                                                        <i class="fas {{ $isPowerDnsOnly ? 'fa-server' : 'fa-globe' }} text-white text-sm"></i>
                                                    </div>
                                                    <div>
                                                        <a href="{{ route('dns-zones.show', $zone->domain) }}"
                                                           class="font-bold text-gray-900 dark:text-gray-100 hover:text-indigo-600 dark:hover:text-indigo-400 transition">
                                                            {{ $zone->domain }}
                                                        </a>
                                                        @if(Auth::user()->role === 'admin')
                                                            <p class="text-xs text-gray-500 dark:text-gray-400">{{ $zone->user->name }}</p>
                                                        @endif
                                                    </div>
                                                </div>
                                                <span class="px-2 py-1 text-xs font-semibold rounded-full {{ $zone->is_active ? 'bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-300' : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400' }}">
                                                    {{ $zone->is_active ? 'Activ' : 'Inactiv' }}
                                                </span>
                                            </div>
                                        </div>

                                        <!-- Card Body -->
                                        <div class="p-4 space-y-3">
                                            <div class="grid grid-cols-2 gap-3 text-sm">
                                                <div class="flex items-center text-gray-600 dark:text-gray-400">
                                                    <i class="fas fa-database w-4 text-center mr-2"></i>
                                                    <span>{{ $recordCount }} înregistrări</span>
                                                </div>
                                                <div class="flex items-center text-gray-600 dark:text-gray-400">
                                                    <i class="fas fa-calendar w-4 text-center mr-2"></i>
                                                    <span>{{ $zone->created_at->format('d.m.Y') }}</span>
                                                </div>
                                                <div class="flex items-center {{ $zone->dnssec_enabled ? 'text-green-600 dark:text-green-400' : 'text-gray-400 dark:text-gray-500' }}">
                                                    <i class="fas fa-shield-alt w-4 text-center mr-2"></i>
                                                    <span>DNSSEC {{ $zone->dnssec_enabled ? 'Activ' : 'Inactiv' }}</span>
                                                </div>
                                                @if(!$isPowerDnsOnly && $zone->sync_to_powerdns && $zone->powerdns_zone_id)
                                                    <div class="flex items-center text-green-600 dark:text-green-400">
                                                        <i class="fas fa-check-circle w-4 text-center mr-2"></i>
                                                        <span>Sincronizat</span>
                                                    </div>
                                                @elseif(!$isPowerDnsOnly && !$zone->sync_to_powerdns)
                                                    <div class="flex items-center text-yellow-600 dark:text-yellow-400">
                                                        <i class="fas fa-exclamation-triangle w-4 text-center mr-2"></i>
                                                        <span>Local</span>
                                                    </div>
                                                @endif
                                            </div>

                                            @if(count($cardNameservers) > 0)
                                                <div class="pt-2 border-t border-gray-100 dark:border-gray-700">
                                                    <div class="flex items-center justify-between">
                                                        <span class="text-xs text-gray-500 dark:text-gray-400">Nameservere:</span>
                                                        <button type="button"
                                                                onclick="copyNameservers({{ json_encode($cardNameservers) }}, this)"
                                                                class="text-xs text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 transition"
                                                                title="Copiază nameserverele">
                                                            <i class="fas fa-copy"></i>
                                                        </button>
                                                    </div>
                                                    <div class="mt-1 flex flex-wrap gap-1">
                                                        @foreach(array_slice($cardNameservers, 0, 2) as $ns)
                                                            <span class="px-2 py-0.5 text-xs bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300 rounded">
                                                                {{ $ns }}
                                                            </span>
                                                        @endforeach
                                                        @if(count($cardNameservers) > 2)
                                                            <span class="px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400 rounded">
                                                                +{{ count($cardNameservers) - 2 }}
                                                            </span>
                                                        @endif
                                                    </div>
                                                </div>
                                            @endif
                                        </div>

                                        <!-- Card Footer (Actions) -->
                                        <div class="px-4 py-3 bg-gray-50 dark:bg-gray-700/50 border-t border-gray-200 dark:border-gray-700 flex items-center justify-between">
                                            <div class="flex items-center space-x-2">
                                                <a href="{{ route('dns-zones.show', $zone->domain) }}"
                                                   class="inline-flex items-center px-2.5 py-1.5 text-xs font-medium rounded bg-indigo-100 dark:bg-indigo-900/30 text-indigo-700 dark:text-indigo-300 hover:bg-indigo-200 dark:hover:bg-indigo-900/50 transition">
                                                    <i class="fas fa-eye mr-1"></i>Vezi
                                                </a>
                                                @if(!$isPowerDnsOnly)
                                                    <a href="{{ route('dns-zones.edit', $zone) }}"
                                                       class="inline-flex items-center px-2.5 py-1.5 text-xs font-medium rounded bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 hover:bg-blue-200 dark:hover:bg-blue-900/50 transition">
                                                        <i class="fas fa-edit mr-1"></i>Editează
                                                    </a>
                                                @endif
                                            </div>
                                            @if(!$isPowerDnsOnly)
                                                <div class="flex items-center space-x-1">
                                                    <button type="button"
                                                            id="toggle-btn-card-{{ $zone->id }}"
                                                            onclick="toggleZoneStatus({{ $zone->id }}, '{{ addslashes($zone->domain) }}')"
                                                            class="p-1.5 rounded {{ $zone->is_active ? 'text-green-600 dark:text-green-400 hover:bg-green-100 dark:hover:bg-green-900/30' : 'text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600' }} transition"
                                                            title="{{ $zone->is_active ? 'Dezactivează' : 'Activează' }}"
                                                            data-active="{{ $zone->is_active ? '1' : '0' }}">
                                                        <i class="fas {{ $zone->is_active ? 'fa-toggle-on' : 'fa-toggle-off' }}" id="toggle-icon-card-{{ $zone->id }}"></i>
                                                    </button>
                                                    <button type="button"
                                                            onclick="openDeleteModal({{ $zone->id }}, '{{ addslashes($zone->domain) }}')"
                                                            class="p-1.5 rounded text-red-500 hover:bg-red-100 dark:hover:bg-red-900/30 transition"
                                                            title="Șterge">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            @endif
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        </div>
                        <!-- End Cards View -->

                        <!-- Pagination -->
                        <div class="mt-4">
                            {{ $zones->links() }}
                        </div>
                    @else
                        <div class="text-center py-12">
                            <i class="fas fa-globe text-gray-400 dark:text-gray-600 text-6xl mb-4"></i>
                            <h3 class="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-2">{{ __('No records found') }}</h3>
                            <p class="text-gray-600 dark:text-gray-400 mb-6">Încă nu ai nicio zonă DNS. Creează prima ta zonă DNS acum!</p>
                            @if(Auth::user()->canPerformDnsOperations())
                                <a href="{{ route('dns-zones.create') }}" class="inline-flex items-center px-6 py-3 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold rounded-lg transition">
                                    <i class="fas fa-plus mr-2"></i>
                                    {{ __('Add DNS Zone') }}
                                </a>
                            @else
                                <button disabled class="inline-flex items-center px-6 py-3 bg-gray-400 text-gray-200 font-semibold rounded-lg cursor-not-allowed opacity-60">
                                    <i class="fas fa-ban mr-2"></i>
                                    Limită Query-uri Atinsă
                                </button>
                            @endif
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Confirmare Ștergere -->
    <div id="deleteModal" class="hidden fixed inset-0 bg-black bg-opacity-50 dark:bg-opacity-70 z-50 flex items-center justify-center p-4" onclick="if(event.target === this) closeDeleteModal()">
        <div class="relative w-full max-w-lg max-h-[85vh] overflow-y-auto bg-white dark:bg-gray-800 rounded-lg shadow-xl" onclick="event.stopPropagation()" style="max-width: min(32rem, 98vw);">
            <div class="p-6">
                <!-- Header -->
                <div class="flex items-center justify-between pb-4 border-b border-gray-200 dark:border-gray-700">
                    <h3 class="text-xl font-semibold text-gray-900 dark:text-gray-100">
                        <i class="fas fa-exclamation-triangle text-red-600 dark:text-red-400 mr-2"></i>
                        Confirmare Ștergere
                    </h3>
                    <button onclick="closeDeleteModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition">
                        <i class="fas fa-times text-2xl"></i>
                    </button>
                </div>

                <!-- Content -->
                <div class="py-6">
                    <div class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mb-4">
                        <p class="text-sm text-red-800 dark:text-red-200">
                            <i class="fas fa-exclamation-circle mr-2"></i>
                            <strong>Atenție!</strong> Această acțiune este ireversibilă!
                        </p>
                    </div>

                    <p class="text-gray-700 dark:text-gray-300 mb-4">
                        Ești sigur că vrei să ștergi zona DNS <strong id="deleteZoneName" class="text-red-600 dark:text-red-400"></strong>?
                    </p>

                    <div class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 mb-4">
                        <p class="text-sm text-yellow-800 dark:text-yellow-200">
                            <i class="fas fa-info-circle mr-2"></i>
                            Toate înregistrările DNS asociate vor fi șterse permanent!
                        </p>
                    </div>

                    <!-- Confirmation Code Section -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Pentru a confirma, introdu codul <strong id="deleteConfirmCode" class="px-2 py-1 bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300 rounded border border-blue-300 dark:border-blue-700 text-lg font-mono"></strong> în câmpul de mai jos:
                        </label>
                        <input
                            type="text"
                            id="deleteCodeInput"
                            placeholder="Introdu codul de confirmare"
                            class="w-full px-4 py-2.5 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-red-500 dark:focus:ring-red-400 focus:border-transparent transition text-center font-mono text-lg"
                            autocomplete="off"
                            oninput="validateDeleteCode()"
                        >
                        <p id="deleteCodeError" class="hidden text-sm text-red-600 dark:text-red-400 mt-2">
                            <i class="fas fa-times-circle mr-1"></i>
                            Codul introdus nu este corect!
                        </p>
                    </div>
                </div>

                <!-- Footer -->
                <div class="flex items-center justify-end space-x-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                    <button onclick="closeDeleteModal()" class="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600 transition">
                        <i class="fas fa-times mr-2"></i>
                        Anulează
                    </button>
                    <button id="deleteZoneButton" onclick="confirmDelete()" disabled class="px-4 py-2 bg-gray-400 dark:bg-gray-600 text-gray-200 dark:text-gray-400 rounded-lg cursor-not-allowed transition">
                        <i class="fas fa-trash mr-2"></i>
                        Șterge Zona
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Confirmare Sincronizare -->
    <div id="resyncModal" class="hidden fixed inset-0 bg-black bg-opacity-50 dark:bg-opacity-70 z-50 flex items-center justify-center p-4" onclick="if(event.target === this) closeResyncModal()">
        <div class="relative w-full max-w-lg max-h-[85vh] overflow-y-auto bg-white dark:bg-gray-800 rounded-lg shadow-xl" onclick="event.stopPropagation()" style="max-width: min(32rem, 98vw);">
            <div class="p-6">
                <!-- Header -->
                <div class="flex items-center justify-between pb-4 border-b border-gray-200 dark:border-gray-700">
                    <h3 class="text-xl font-semibold text-gray-900 dark:text-gray-100">
                        <i class="fas fa-sync-alt text-purple-600 dark:text-purple-400 mr-2"></i>
                        Confirmare Sincronizare
                    </h3>
                    <button onclick="closeResyncModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition">
                        <i class="fas fa-times text-2xl"></i>
                    </button>
                </div>

                <!-- Content -->
                <div class="py-6">
                    <div class="bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-800 rounded-lg p-4 mb-4">
                        <p class="text-sm text-purple-800 dark:text-purple-200">
                            <i class="fas fa-info-circle mr-2"></i>
                            <strong>Informație:</strong> Zona va fi sincronizată pe toate name server-ele permise în planul tău.
                        </p>
                    </div>

                    <p class="text-gray-700 dark:text-gray-300 mb-4">
                        Ești sigur că vrei să sincronizezi zona DNS <strong id="resyncZoneName" class="text-purple-600 dark:text-purple-400"></strong>?
                    </p>

                    <div class="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
                        <p class="text-sm text-blue-800 dark:text-blue-200">
                            <i class="fas fa-server mr-2"></i>
                            Sincronizarea va actualiza configurația DNS pe toate name server-ele active din planul tău.
                        </p>
                    </div>
                </div>

                <!-- Footer -->
                <div class="flex items-center justify-end space-x-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                    <button onclick="closeResyncModal()" class="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600 transition">
                        <i class="fas fa-times mr-2"></i>
                        Anulează
                    </button>
                    <button onclick="confirmResync()" class="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition">
                        <i class="fas fa-sync-alt mr-2"></i>
                        Sincronizează
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Bulk Delete -->
    <div id="bulkDeleteModal" class="hidden fixed inset-0 bg-black bg-opacity-50 dark:bg-opacity-70 z-50 flex items-center justify-center p-4" onclick="if(event.target === this) closeBulkDeleteModal()">
        <div class="relative w-full max-w-lg max-h-[85vh] overflow-y-auto bg-white dark:bg-gray-800 rounded-lg shadow-xl" onclick="event.stopPropagation()" style="max-width: min(32rem, 98vw);">
            <div class="p-6">
                <!-- Header -->
                <div class="flex items-center justify-between pb-4 border-b border-gray-200 dark:border-gray-700">
                    <h3 class="text-xl font-semibold text-gray-900 dark:text-gray-100">
                        <i class="fas fa-exclamation-triangle text-red-600 dark:text-red-400 mr-2"></i>
                        Ștergere Zone Multiple
                    </h3>
                    <button onclick="closeBulkDeleteModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition">
                        <i class="fas fa-times text-2xl"></i>
                    </button>
                </div>

                <!-- Content -->
                <div class="py-6">
                    <div class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mb-4">
                        <p class="text-sm text-red-800 dark:text-red-200">
                            <i class="fas fa-exclamation-circle mr-2"></i>
                            <strong>Atenție!</strong> Această acțiune este ireversibilă!
                        </p>
                    </div>

                    <p class="text-gray-700 dark:text-gray-300 mb-4">
                        Ești sigur că vrei să ștergi <strong id="bulkDeleteCount" class="text-red-600 dark:text-red-400">0</strong> zone DNS?
                    </p>

                    <div class="max-h-40 overflow-y-auto mb-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg p-3">
                        <ul id="bulkDeleteList" class="text-sm text-gray-600 dark:text-gray-300 space-y-1">
                        </ul>
                    </div>

                    <div class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 mb-4">
                        <p class="text-sm text-yellow-800 dark:text-yellow-200">
                            <i class="fas fa-info-circle mr-2"></i>
                            Toate înregistrările DNS asociate vor fi șterse permanent!
                        </p>
                    </div>

                    <!-- Confirmation Code Section -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                            Pentru a confirma, introdu codul <strong id="bulkDeleteConfirmCode" class="px-2 py-1 bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300 rounded border border-blue-300 dark:border-blue-700 text-lg font-mono"></strong>:
                        </label>
                        <input
                            type="text"
                            id="bulkDeleteCodeInput"
                            placeholder="Introdu codul de confirmare"
                            class="w-full px-4 py-2.5 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-red-500 dark:focus:ring-red-400 focus:border-transparent transition text-center font-mono text-lg"
                            autocomplete="off"
                            oninput="validateBulkDeleteCode()"
                        >
                    </div>
                </div>

                <!-- Footer -->
                <div class="flex items-center justify-end space-x-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                    <button onclick="closeBulkDeleteModal()" class="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600 transition">
                        <i class="fas fa-times mr-2"></i>
                        Anulează
                    </button>
                    <button id="bulkDeleteButton" onclick="confirmBulkDelete()" disabled class="px-4 py-2 bg-gray-400 dark:bg-gray-600 text-gray-200 dark:text-gray-400 rounded-lg cursor-not-allowed transition">
                        <i class="fas fa-trash mr-2"></i>
                        Șterge Zonele
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bulk Actions Forms -->
    <form id="bulkActionForm" method="POST" class="hidden">
        @csrf
        <input type="hidden" name="zone_ids" id="bulkZoneIds">
        <input type="hidden" name="action" id="bulkActionType">
    </form>

    <script>
        let currentDeleteZoneId = null;
        let currentResyncZoneId = null;
        let currentDeleteCode = null;
        let bulkDeleteCode = null;
        let selectedZones = new Map(); // Map of zoneId -> zoneDomain

        function openDeleteModal(zoneId, zoneName) {
            currentDeleteZoneId = zoneId;
            // Generate random 5-digit code
            currentDeleteCode = Math.floor(10000 + Math.random() * 90000).toString();

            // Update modal content
            document.getElementById('deleteZoneName').textContent = zoneName;
            document.getElementById('deleteConfirmCode').textContent = currentDeleteCode;

            // Reset input and button
            const input = document.getElementById('deleteCodeInput');
            input.value = '';
            input.className = 'w-full px-4 py-2.5 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-red-500 dark:focus:ring-red-400 focus:border-transparent transition text-center font-mono text-lg';

            document.getElementById('deleteCodeError').classList.add('hidden');
            document.getElementById('deleteZoneButton').disabled = true;
            document.getElementById('deleteZoneButton').className = 'px-4 py-2 bg-gray-400 dark:bg-gray-600 text-gray-200 dark:text-gray-400 rounded-lg cursor-not-allowed transition';

            document.getElementById('deleteModal').classList.remove('hidden');

            // Focus on input after modal opens
            setTimeout(() => input.focus(), 100);
        }

        function closeDeleteModal() {
            document.getElementById('deleteModal').classList.add('hidden');
            currentDeleteZoneId = null;
            currentDeleteCode = null;
        }

        function validateDeleteCode() {
            const input = document.getElementById('deleteCodeInput');
            const button = document.getElementById('deleteZoneButton');
            const error = document.getElementById('deleteCodeError');
            const inputValue = input.value.trim();

            if (inputValue === '') {
                // Empty - neutral state
                input.className = 'w-full px-4 py-2.5 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-red-500 dark:focus:ring-red-400 focus:border-transparent transition text-center font-mono text-lg';
                error.classList.add('hidden');
                button.disabled = true;
                button.className = 'px-4 py-2 bg-gray-400 dark:bg-gray-600 text-gray-200 dark:text-gray-400 rounded-lg cursor-not-allowed transition';
            } else if (inputValue === currentDeleteCode) {
                // Correct code - green state
                input.className = 'w-full px-4 py-2.5 bg-white dark:bg-gray-700 border-2 border-green-500 dark:border-green-400 rounded-lg text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-green-500 dark:focus:ring-green-400 transition text-center font-mono text-lg';
                error.classList.add('hidden');
                button.disabled = false;
                button.className = 'px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition cursor-pointer';
            } else {
                // Wrong code - red state
                input.className = 'w-full px-4 py-2.5 bg-white dark:bg-gray-700 border-2 border-red-500 dark:border-red-400 rounded-lg text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-red-500 dark:focus:ring-red-400 transition text-center font-mono text-lg';
                error.classList.remove('hidden');
                button.disabled = true;
                button.className = 'px-4 py-2 bg-gray-400 dark:bg-gray-600 text-gray-200 dark:text-gray-400 rounded-lg cursor-not-allowed transition';
            }
        }

        function confirmDelete() {
            if (currentDeleteZoneId && document.getElementById('deleteCodeInput').value.trim() === currentDeleteCode) {
                document.getElementById('delete-zone-form-' + currentDeleteZoneId).submit();
            }
        }

        function openResyncModal(zoneId, zoneName) {
            currentResyncZoneId = zoneId;
            document.getElementById('resyncZoneName').textContent = zoneName;
            document.getElementById('resyncModal').classList.remove('hidden');
        }

        function closeResyncModal() {
            document.getElementById('resyncModal').classList.add('hidden');
            currentResyncZoneId = null;
        }

        function confirmResync() {
            if (currentResyncZoneId) {
                document.getElementById('resyncForm' + currentResyncZoneId).submit();
            }
        }

        // Închide modalurile cu tasta Escape
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                closeDeleteModal();
                closeResyncModal();
            }
        });

        // Carousel pentru nameservere în stats cards
        const nsCarousel = document.getElementById('nsCarousel');
        const nsIndicators = document.querySelectorAll('.ns-indicator');
        const totalNSSlides = nsIndicators.length;
        let currentNSSlide = 0;

        function updateNSCarousel() {
            if (!nsCarousel) return;

            nsCarousel.style.transform = `translateX(-${currentNSSlide * 100}%)`;

            // Update indicators
            nsIndicators.forEach((indicator, index) => {
                if (index === currentNSSlide) {
                    indicator.classList.add('bg-purple-600', 'dark:bg-purple-400');
                    indicator.classList.remove('bg-gray-300', 'dark:bg-gray-600');
                } else {
                    indicator.classList.remove('bg-purple-600', 'dark:bg-purple-400');
                    indicator.classList.add('bg-gray-300', 'dark:bg-gray-600');
                }
            });
        }

        function nextNS() {
            currentNSSlide = (currentNSSlide + 1) % totalNSSlides;
            updateNSCarousel();
        }

        function prevNS() {
            currentNSSlide = (currentNSSlide - 1 + totalNSSlides) % totalNSSlides;
            updateNSCarousel();
        }

        // Carousel pentru nameservere în tabelul de zone
        document.addEventListener('DOMContentLoaded', function() {
            // Găsește toate carousel-urile de nameservere din tabel
            const carousels = document.querySelectorAll('[class^="ns-carousel-"]');

            carousels.forEach(carousel => {
                const nsCount = parseInt(carousel.getAttribute('data-ns-count'));

                // Doar dacă sunt mai multe nameservere, pornește carousel-ul
                if (nsCount > 1) {
                    const items = carousel.querySelectorAll('.ns-item');
                    let currentIndex = 0;

                    // Rotește nameserverele la fiecare 3 secunde
                    setInterval(() => {
                        // Ascunde item-ul curent
                        items[currentIndex].style.display = 'none';

                        // Treci la următorul index
                        currentIndex = (currentIndex + 1) % nsCount;

                        // Afișează noul item
                        items[currentIndex].style.display = '';
                    }, 3000); // 3 secunde
                }
            });
        });

        // Search submits on enter or debounced after typing
        const searchInput = document.getElementById('zoneSearch');
        let searchTimeout;
        searchInput?.addEventListener('input', function(e) {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                this.form.submit();
            }, 800); // Submit after 800ms of no typing
        });

        // Export menu toggle
        function toggleZoneExportMenu() {
            const menu = document.getElementById('zoneExportMenu');
            menu.classList.toggle('hidden');
        }

        // Close export menu when clicking outside
        document.addEventListener('click', function(event) {
            const exportBtn = document.getElementById('zoneExportBtn');
            const exportMenu = document.getElementById('zoneExportMenu');

            if (exportBtn && exportMenu && !exportBtn.contains(event.target) && !exportMenu.contains(event.target)) {
                exportMenu.classList.add('hidden');
            }
        });

        // ========== BULK OPERATIONS ==========

        // Toggle select all checkboxes
        function toggleSelectAll() {
            const selectAllCheckbox = document.getElementById('selectAll');
            const checkboxes = document.querySelectorAll('.zone-checkbox');

            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
                const zoneId = checkbox.getAttribute('data-zone-id');
                const zoneDomain = checkbox.getAttribute('data-zone-domain');

                if (selectAllCheckbox.checked) {
                    selectedZones.set(zoneId, zoneDomain);
                } else {
                    selectedZones.delete(zoneId);
                }
            });

            updateBulkActionsBar();
        }

        // Update bulk selection when individual checkbox changes
        function updateBulkSelection() {
            const checkboxes = document.querySelectorAll('.zone-checkbox');
            const selectAllCheckbox = document.getElementById('selectAll');

            selectedZones.clear();
            let checkedCount = 0;

            checkboxes.forEach(checkbox => {
                if (checkbox.checked) {
                    checkedCount++;
                    const zoneId = checkbox.getAttribute('data-zone-id');
                    const zoneDomain = checkbox.getAttribute('data-zone-domain');
                    selectedZones.set(zoneId, zoneDomain);
                }
            });

            // Update select all checkbox state
            selectAllCheckbox.checked = checkedCount === checkboxes.length && checkboxes.length > 0;
            selectAllCheckbox.indeterminate = checkedCount > 0 && checkedCount < checkboxes.length;

            updateBulkActionsBar();
        }

        // Show/hide bulk actions bar
        function updateBulkActionsBar() {
            const bar = document.getElementById('bulkActionsBar');
            const countSpan = document.getElementById('selectedCount');

            countSpan.textContent = selectedZones.size;

            if (selectedZones.size > 0) {
                bar.classList.remove('hidden');
            } else {
                bar.classList.add('hidden');
            }
        }

        // Clear all selections
        function clearSelection() {
            const checkboxes = document.querySelectorAll('.zone-checkbox');
            const selectAllCheckbox = document.getElementById('selectAll');

            checkboxes.forEach(checkbox => checkbox.checked = false);
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = false;
            selectedZones.clear();
            updateBulkActionsBar();
        }

        // Bulk activate zones
        function bulkActivate() {
            if (selectedZones.size === 0) return;

            if (confirm(`Ești sigur că vrei să activezi ${selectedZones.size} zone?`)) {
                submitBulkAction('activate');
            }
        }

        // Bulk deactivate zones
        function bulkDeactivate() {
            if (selectedZones.size === 0) return;

            if (confirm(`Ești sigur că vrei să dezactivezi ${selectedZones.size} zone?`)) {
                submitBulkAction('deactivate');
            }
        }

        // Bulk resync zones
        function bulkResync() {
            if (selectedZones.size === 0) return;

            if (confirm(`Ești sigur că vrei să sincronizezi ${selectedZones.size} zone cu PowerDNS?`)) {
                submitBulkAction('resync');
            }
        }

        // Open bulk delete modal
        function openBulkDeleteModal() {
            if (selectedZones.size === 0) return;

            bulkDeleteCode = Math.floor(10000 + Math.random() * 90000).toString();

            document.getElementById('bulkDeleteCount').textContent = selectedZones.size;
            document.getElementById('bulkDeleteConfirmCode').textContent = bulkDeleteCode;

            // Populate zone list
            const listEl = document.getElementById('bulkDeleteList');
            listEl.innerHTML = '';
            selectedZones.forEach((domain, id) => {
                const li = document.createElement('li');
                li.innerHTML = `<i class="fas fa-globe text-red-500 mr-2"></i>${domain}`;
                listEl.appendChild(li);
            });

            // Reset input
            const input = document.getElementById('bulkDeleteCodeInput');
            input.value = '';
            document.getElementById('bulkDeleteButton').disabled = true;
            document.getElementById('bulkDeleteButton').className = 'px-4 py-2 bg-gray-400 dark:bg-gray-600 text-gray-200 dark:text-gray-400 rounded-lg cursor-not-allowed transition';

            document.getElementById('bulkDeleteModal').classList.remove('hidden');
            setTimeout(() => input.focus(), 100);
        }

        function closeBulkDeleteModal() {
            document.getElementById('bulkDeleteModal').classList.add('hidden');
            bulkDeleteCode = null;
        }

        function validateBulkDeleteCode() {
            const input = document.getElementById('bulkDeleteCodeInput');
            const button = document.getElementById('bulkDeleteButton');

            if (input.value.trim() === bulkDeleteCode) {
                input.className = 'w-full px-4 py-2.5 bg-white dark:bg-gray-700 border-2 border-green-500 dark:border-green-400 rounded-lg text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-green-500 dark:focus:ring-green-400 transition text-center font-mono text-lg';
                button.disabled = false;
                button.className = 'px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition';
            } else {
                input.className = 'w-full px-4 py-2.5 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-red-500 dark:focus:ring-red-400 transition text-center font-mono text-lg';
                button.disabled = true;
                button.className = 'px-4 py-2 bg-gray-400 dark:bg-gray-600 text-gray-200 dark:text-gray-400 rounded-lg cursor-not-allowed transition';
            }
        }

        function confirmBulkDelete() {
            if (bulkDeleteCode && document.getElementById('bulkDeleteCodeInput').value.trim() === bulkDeleteCode) {
                submitBulkAction('delete');
            }
        }

        // Submit bulk action form
        function submitBulkAction(action) {
            const form = document.getElementById('bulkActionForm');
            const zoneIds = Array.from(selectedZones.keys());

            document.getElementById('bulkZoneIds').value = JSON.stringify(zoneIds);
            document.getElementById('bulkActionType').value = action;

            form.action = '{{ route("dns-zones.bulk-action") }}';
            form.submit();
        }

        // Update escape key handler to include bulk delete modal
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                closeDeleteModal();
                closeResyncModal();
                closeBulkDeleteModal();
            }
        });

        // ========== FILTER FUNCTIONS ==========

        // Toggle filters panel visibility
        function toggleFilters() {
            const panel = document.getElementById('filtersPanel');
            panel.classList.toggle('hidden');
        }

        // Apply filters by submitting the form
        function applyFilters() {
            const form = document.getElementById('searchForm');

            // Update hidden fields with current filter values
            document.getElementById('hiddenStatus').value = document.getElementById('filterStatus').value;
            document.getElementById('hiddenDnssec').value = document.getElementById('filterDnssec').value;
            document.getElementById('hiddenPeriod').value = document.getElementById('filterPeriod').value;
            document.getElementById('hiddenSort').value = document.getElementById('filterSort').value;

            form.submit();
        }

        // ========== VIEW MODE FUNCTIONS ==========

        function setViewMode(mode) {
            const tableView = document.getElementById('tableView');
            const cardsView = document.getElementById('cardsView');
            const tableBtn = document.getElementById('viewTableBtn');
            const cardsBtn = document.getElementById('viewCardsBtn');

            if (mode === 'table') {
                tableView.classList.remove('hidden');
                cardsView.classList.add('hidden');
                tableBtn.classList.add('bg-indigo-600', 'text-white');
                tableBtn.classList.remove('bg-white', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300');
                cardsBtn.classList.remove('bg-indigo-600', 'text-white');
                cardsBtn.classList.add('bg-white', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300');
            } else {
                tableView.classList.add('hidden');
                cardsView.classList.remove('hidden');
                cardsBtn.classList.add('bg-indigo-600', 'text-white');
                cardsBtn.classList.remove('bg-white', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300');
                tableBtn.classList.remove('bg-indigo-600', 'text-white');
                tableBtn.classList.add('bg-white', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300');
            }

            // Save preference to localStorage
            localStorage.setItem('dnsZonesViewMode', mode);

            // Update URL without page reload (optional, for persistence)
            const url = new URL(window.location);
            url.searchParams.set('view', mode);
            window.history.replaceState({}, '', url);
        }

        // Restore view mode from localStorage on page load
        document.addEventListener('DOMContentLoaded', function() {
            const savedMode = localStorage.getItem('dnsZonesViewMode');
            const urlParams = new URLSearchParams(window.location.search);
            const urlMode = urlParams.get('view');

            // Priority: URL > localStorage > default (table)
            if (urlMode && (urlMode === 'table' || urlMode === 'cards')) {
                setViewMode(urlMode);
            } else if (savedMode && (savedMode === 'table' || savedMode === 'cards')) {
                setViewMode(savedMode);
            }
        });

        // Keyboard shortcut for search focus
        document.addEventListener('keydown', function(event) {
            // Press '/' to focus search
            if (event.key === '/' && !['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement.tagName)) {
                event.preventDefault();
                document.getElementById('zoneSearch').focus();
            }
            // Press 'f' to toggle filters
            if (event.key === 'f' && !['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement.tagName)) {
                event.preventDefault();
                toggleFilters();
            }
            // Press 'v' to toggle view mode
            if (event.key === 'v' && !['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement.tagName)) {
                event.preventDefault();
                const currentMode = localStorage.getItem('dnsZonesViewMode') || 'table';
                setViewMode(currentMode === 'table' ? 'cards' : 'table');
            }
        });

        // ========== TOGGLE ZONE STATUS (AJAX) ==========

        async function toggleZoneStatus(zoneId, domain) {
            const btn = document.getElementById('toggle-btn-' + zoneId);
            const icon = document.getElementById('toggle-icon-' + zoneId);
            const currentActive = btn.dataset.active === '1';

            // Disable button and show loading
            btn.disabled = true;
            const originalIcon = icon.className;
            icon.className = 'fas fa-spinner fa-spin';

            try {
                // Use domain instead of ID for route model binding
                const response = await fetch(`{{ url('dns-zones') }}/${encodeURIComponent(domain)}/toggle-active`, {
                    method: 'PATCH',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });

                const data = await response.json();

                if (data.success) {
                    const isActive = data.is_active;

                    // Update button styling
                    if (isActive) {
                        btn.className = 'inline-flex items-center justify-center w-9 h-9 rounded-lg bg-green-50 dark:bg-green-900/20 text-green-600 dark:text-green-400 hover:bg-green-100 dark:hover:bg-green-900/40 border-green-200 dark:border-green-800 border transition';
                        icon.className = 'fas fa-toggle-on';
                        btn.title = 'Dezactivează';
                    } else {
                        btn.className = 'inline-flex items-center justify-center w-9 h-9 rounded-lg bg-gray-50 dark:bg-gray-700 text-gray-400 dark:text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-600 border-gray-200 dark:border-gray-600 border transition';
                        icon.className = 'fas fa-toggle-off';
                        btn.title = 'Activează';
                    }

                    btn.dataset.active = isActive ? '1' : '0';

                    // Update the status badge in the table
                    const statusBadge = document.getElementById('status-badge-' + zoneId);
                    if (statusBadge) {
                        if (isActive) {
                            statusBadge.className = 'px-3 py-1.5 inline-flex items-center text-xs font-semibold rounded-lg bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 border border-green-200 dark:border-green-800';
                            statusBadge.innerHTML = '<span class="w-1.5 h-1.5 bg-green-500 rounded-full mr-2 status-dot"></span>Activ';
                        } else {
                            statusBadge.className = 'px-3 py-1.5 inline-flex items-center text-xs font-semibold rounded-lg bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-gray-600';
                            statusBadge.innerHTML = '<span class="w-1.5 h-1.5 bg-gray-400 rounded-full mr-2 status-dot"></span>Inactiv';
                        }
                    }

                    // Update the Quick Stats tooltip status if exists
                    const row = btn.closest('tr');
                    if (row) {
                        const tooltipStatus = row.querySelector('.tooltip-status');
                        if (tooltipStatus) {
                            tooltipStatus.textContent = isActive ? 'Activ' : 'Inactiv';
                            tooltipStatus.className = 'font-medium tooltip-status ' + (isActive ? 'text-green-400' : 'text-red-400');
                        }
                    }

                    // Show success toast
                    showToast(data.message, 'success');
                } else {
                    icon.className = originalIcon;
                    showToast(data.message || 'Eroare la schimbarea statusului', 'error');
                }
            } catch (error) {
                console.error('Toggle error:', error);
                icon.className = originalIcon;
                showToast('Eroare la comunicarea cu serverul', 'error');
            } finally {
                btn.disabled = false;
            }
        }

        // Toast notification function
        function showToast(message, type = 'info') {
            // Remove existing toasts
            const existingToasts = document.querySelectorAll('.toast-notification');
            existingToasts.forEach(t => t.remove());

            const toast = document.createElement('div');
            toast.className = `toast-notification fixed bottom-4 right-4 px-4 py-3 rounded-lg shadow-lg z-50 flex items-center space-x-2 transform translate-y-0 opacity-100 transition-all duration-300`;

            if (type === 'success') {
                toast.classList.add('bg-green-500', 'text-white');
                toast.innerHTML = `<i class="fas fa-check-circle"></i><span>${message}</span>`;
            } else if (type === 'error') {
                toast.classList.add('bg-red-500', 'text-white');
                toast.innerHTML = `<i class="fas fa-times-circle"></i><span>${message}</span>`;
            } else {
                toast.classList.add('bg-blue-500', 'text-white');
                toast.innerHTML = `<i class="fas fa-info-circle"></i><span>${message}</span>`;
            }

            document.body.appendChild(toast);

            // Auto-remove after 4 seconds
            setTimeout(() => {
                toast.classList.add('opacity-0', 'translate-y-2');
                setTimeout(() => toast.remove(), 300);
            }, 4000);
        }

        // ========== COPY NAMESERVERS ==========

        async function copyNameservers(nameservers, button) {
            const text = nameservers.join('\n');

            try {
                await navigator.clipboard.writeText(text);

                // Show success feedback on button
                const icon = button.querySelector('i');
                const originalClass = icon.className;
                icon.className = 'fas fa-check text-xs text-green-500';

                setTimeout(() => {
                    icon.className = originalClass;
                }, 1500);

                showToast(`${nameservers.length} nameservere copiate în clipboard`, 'success');
            } catch (err) {
                // Fallback for older browsers
                const textarea = document.createElement('textarea');
                textarea.value = text;
                textarea.style.position = 'fixed';
                textarea.style.opacity = '0';
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);

                showToast(`${nameservers.length} nameservere copiate în clipboard`, 'success');
            }
        }
    </script>
</x-app-layout>
