<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>{{ $nameServer->name }}
                </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">Dashboard</a>
                    <span class="mx-2">/</span>
                    <a href="{{ route('admin.dashboard') }}" class="text-blue-600 dark:text-blue-400 hover:underline">Admin</a>
                    <span class="mx-2">/</span>
                    <a href="{{ route('admin.nameservers.index') }}" class="text-blue-600 dark:text-blue-400 hover:underline">Name Servers</a>
                    <span class="mx-2">/</span>
                    <span>{{ $nameServer->name }}</span>
                </p>
            </div>
            <div class="flex items-center space-x-3">
                <!-- Sincronizează Zone - Buton Rapid -->
                <form action="{{ route('admin.nameservers.sync-zones', $nameServer) }}" method="POST" class="inline">
                    @csrf
                    <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition" title="Sincronizează zonele cu PowerDNS">
                        <i class="fas fa-sync mr-2"></i>Sincronizează
                    </button>
                </form>

                <!-- Dropdown Acțiuni -->
                <div class="relative" x-data="{ open: false }">
                    <button @click="open = !open" @click.away="open = false" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition inline-flex items-center">
                        <i class="fas fa-cog mr-2"></i>Acțiuni
                        <i class="fas fa-chevron-down ml-2 text-xs"></i>
                    </button>
                    <div x-show="open"
                         x-transition:enter="transition ease-out duration-100"
                         x-transition:enter-start="transform opacity-0 scale-95"
                         x-transition:enter-end="transform opacity-100 scale-100"
                         x-transition:leave="transition ease-in duration-75"
                         x-transition:leave-start="transform opacity-100 scale-100"
                         x-transition:leave-end="transform opacity-0 scale-95"
                         class="absolute right-0 mt-2 w-64 rounded-xl shadow-xl bg-white dark:bg-gray-800 ring-1 ring-black/5 dark:ring-white/10 z-50 overflow-hidden"
                         style="display: none;">

                        <!-- Header -->
                        <div class="px-4 py-3 bg-gray-50 dark:bg-gray-900/50 border-b border-gray-200 dark:border-gray-700">
                            <p class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wider">Acțiuni Server</p>
                        </div>

                        <div class="py-2">
                            <!-- Verifică Status -->
                            <form action="{{ route('admin.nameservers.check-health', $nameServer) }}" method="POST">
                                @csrf
                                <button type="submit" class="w-full text-left px-4 py-3 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center group transition-colors">
                                    <span class="flex items-center justify-center w-8 h-8 rounded-lg bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400 mr-3 group-hover:scale-110 transition-transform">
                                        <i class="fas fa-heartbeat"></i>
                                    </span>
                                    <span>
                                        <span class="block font-medium">Verifică Status</span>
                                        <span class="block text-xs text-gray-500 dark:text-gray-400">Testează conexiunea API</span>
                                    </span>
                                </button>
                            </form>

                            <!-- Editează Server -->
                            <a href="{{ route('admin.nameservers.edit', $nameServer) }}" class="w-full text-left px-4 py-3 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center group transition-colors">
                                <span class="flex items-center justify-center w-8 h-8 rounded-lg bg-indigo-100 dark:bg-indigo-900/30 text-indigo-600 dark:text-indigo-400 mr-3 group-hover:scale-110 transition-transform">
                                    <i class="fas fa-edit"></i>
                                </span>
                                <span>
                                    <span class="block font-medium">Editează Server</span>
                                    <span class="block text-xs text-gray-500 dark:text-gray-400">Modifică configurația</span>
                                </span>
                            </a>

                            <!-- Toggle Activ/Inactiv -->
                            <form action="{{ route('admin.nameservers.toggle-active', $nameServer) }}" method="POST">
                                @csrf
                                <button type="submit" class="w-full text-left px-4 py-3 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center group transition-colors">
                                    <span class="flex items-center justify-center w-8 h-8 rounded-lg {{ $nameServer->is_active ? 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-600 dark:text-yellow-400' : 'bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400' }} mr-3 group-hover:scale-110 transition-transform">
                                        <i class="fas {{ $nameServer->is_active ? 'fa-pause' : 'fa-play' }}"></i>
                                    </span>
                                    <span>
                                        <span class="block font-medium">{{ $nameServer->is_active ? 'Dezactivează' : 'Activează' }}</span>
                                        <span class="block text-xs text-gray-500 dark:text-gray-400">{{ $nameServer->is_active ? 'Oprește serverul temporar' : 'Pornește serverul' }}</span>
                                    </span>
                                </button>
                            </form>
                        </div>

                        <!-- Zona Periculoasă -->
                        <div class="border-t border-gray-200 dark:border-gray-700">
                            <div class="py-2">
                                <button type="button" onclick="openDeleteModal()" class="w-full text-left px-4 py-3 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 flex items-center group transition-colors">
                                    <span class="flex items-center justify-center w-8 h-8 rounded-lg bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400 mr-3 group-hover:scale-110 transition-transform">
                                        <i class="fas fa-trash-alt"></i>
                                    </span>
                                    <span>
                                        <span class="block font-medium">Șterge Server</span>
                                        <span class="block text-xs text-red-500/70 dark:text-red-400/70">Acțiune ireversibilă</span>
                                    </span>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <a href="{{ route('admin.nameservers.index') }}" class="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200" title="Înapoi la Name Servers">
                    <i class="fas fa-arrow-left"></i>
                </a>
            </div>
        </div>
    </x-slot>

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

            <!-- Status Card -->
            <div class="bg-gradient-to-r {{ $nameServer->isOnline() ? 'from-green-500 to-emerald-600' : 'from-red-500 to-rose-600' }} rounded-lg shadow-lg p-6 text-white">
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <i class="fas {{ $nameServer->status_icon }} text-4xl mr-4"></i>
                        <div>
                            <h3 class="text-2xl font-bold">{{ ucfirst($nameServer->status) }}</h3>
                            <p class="text-white/90">{{ $nameServer->hostname }}</p>
                        </div>
                    </div>
                    <div class="text-right">
                        @if($nameServer->response_time_ms)
                            <p class="text-3xl font-bold">{{ $nameServer->response_time_ms }}ms</p>
                            <p class="text-white/90 text-sm">Response Time</p>
                        @endif
                    </div>
                </div>
            </div>

            <!-- Statistici -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-500 dark:text-gray-400">Zone DNS</p>
                            <p class="text-2xl font-bold text-gray-900 dark:text-white">{{ $stats['zones_count'] }}</p>
                            @if($stats['zones_limit'])
                                <p class="text-xs text-gray-500">din {{ $stats['zones_limit'] }}</p>
                            @endif
                        </div>
                        <i class="fas fa-database text-3xl text-blue-500"></i>
                    </div>
                    @if($stats['zones_limit'])
                        <div class="mt-3">
                            <div class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                                <div class="bg-blue-600 h-2 rounded-full" style="width: {{ min($stats['usage_percentage'], 100) }}%"></div>
                            </div>
                            <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ $stats['usage_percentage'] }}% utilizat</p>
                        </div>
                    @endif
                </div>

                <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-500 dark:text-gray-400">Status</p>
                            <p class="text-2xl font-bold {{ $nameServer->isOnline() ? 'text-green-600' : 'text-red-600' }}">
                                {{ ucfirst($stats['status']) }}
                            </p>
                            @if($stats['last_check'])
                                <p class="text-xs text-gray-500">{{ $stats['last_check'] }}</p>
                            @endif
                        </div>
                        <i class="fas fa-heartbeat text-3xl {{ $nameServer->isOnline() ? 'text-green-500' : 'text-red-500' }}"></i>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-500 dark:text-gray-400">Uptime</p>
                            <p class="text-2xl font-bold text-gray-900 dark:text-white">{{ $stats['uptime_percentage'] }}%</p>
                            <p class="text-xs text-gray-500">Disponibilitate</p>
                        </div>
                        <i class="fas fa-chart-line text-3xl text-purple-500"></i>
                    </div>
                </div>

                <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-500 dark:text-gray-400">Capacitate</p>
                            <p class="text-2xl font-bold text-gray-900 dark:text-white">
                                {{ $stats['can_accept_zones'] ? 'Disponibil' : 'Plin' }}
                            </p>
                            <p class="text-xs text-gray-500">Zone noi</p>
                        </div>
                        <i class="fas fa-check-circle text-3xl {{ $stats['can_accept_zones'] ? 'text-green-500' : 'text-gray-400' }}"></i>
                    </div>
                </div>
            </div>

            <!-- Grafice Statistici -->
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow">
                <div class="p-6">
                    <div class="flex items-center justify-between mb-6">
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white">
                            <i class="fas fa-chart-line text-blue-500 mr-2"></i>
                            Statistici & Performanță
                        </h3>
                        <div class="flex space-x-2">
                            <button type="button" onclick="switchPeriod('24h')" id="btn-24h" class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm transition hover:bg-blue-700">24h</button>
                            <button type="button" onclick="switchPeriod('7d')" id="btn-7d" class="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg text-sm transition hover:bg-gray-300 dark:hover:bg-gray-600">7 zile</button>
                            <button type="button" onclick="switchPeriod('30d')" id="btn-30d" class="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg text-sm transition hover:bg-gray-300 dark:hover:bg-gray-600">30 zile</button>
                            <button type="button" onclick="switchPeriod('1y')" id="btn-1y" class="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg text-sm transition hover:bg-gray-300 dark:hover:bg-gray-600">1 an</button>
                        </div>
                    </div>

                    <!-- Statistici Cards - se actualizează dinamic -->
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6" id="statsCards">
                        <!-- Uptime -->
                        <div class="bg-gradient-to-r from-green-500 to-green-600 rounded-xl p-5 shadow-lg">
                            <div class="flex items-center justify-between mb-3">
                                <span class="text-xs font-semibold text-green-100 uppercase tracking-wider">Uptime</span>
                                <div class="w-10 h-10 rounded-lg bg-white/20 flex items-center justify-center">
                                    <i class="fas fa-check-circle text-white text-lg"></i>
                                </div>
                            </div>
                            <p class="text-3xl font-bold text-white" id="stat-uptime">{{ $extendedStats['24h']['uptime'] }}%</p>
                            <p class="text-sm text-green-100 mt-1">Disponibilitate</p>
                        </div>

                        <!-- Response Time Mediu -->
                        <div class="bg-gradient-to-r from-blue-500 to-blue-600 rounded-xl p-5 shadow-lg">
                            <div class="flex items-center justify-between mb-3">
                                <span class="text-xs font-semibold text-blue-100 uppercase tracking-wider">Mediu</span>
                                <div class="w-10 h-10 rounded-lg bg-white/20 flex items-center justify-center">
                                    <i class="fas fa-tachometer-alt text-white text-lg"></i>
                                </div>
                            </div>
                            <p class="text-3xl font-bold text-white" id="stat-avg">{{ $extendedStats['24h']['avg_response'] }}ms</p>
                            <div class="flex items-center mt-1">
                                <span id="stat-trend" class="text-sm font-medium {{ $extendedStats['24h']['trend'] <= 0 ? 'text-green-200' : 'text-red-200' }}">
                                    @if($extendedStats['24h']['trend'] != 0)
                                        <i class="fas fa-{{ $extendedStats['24h']['trend'] < 0 ? 'arrow-down' : 'arrow-up' }} mr-1"></i>{{ abs($extendedStats['24h']['trend']) }}%
                                    @else
                                        <i class="fas fa-minus mr-1"></i>stabil
                                    @endif
                                </span>
                            </div>
                        </div>

                        <!-- Response Time Min/Max -->
                        <div class="bg-gradient-to-r from-purple-500 to-purple-600 rounded-xl p-5 shadow-lg">
                            <div class="flex items-center justify-between mb-3">
                                <span class="text-xs font-semibold text-purple-100 uppercase tracking-wider">Min / Max</span>
                                <div class="w-10 h-10 rounded-lg bg-white/20 flex items-center justify-center">
                                    <i class="fas fa-arrows-alt-v text-white text-lg"></i>
                                </div>
                            </div>
                            <p class="text-2xl font-bold text-white">
                                <span id="stat-min">{{ $extendedStats['24h']['min_response'] }}</span>
                                <span class="text-lg font-normal text-purple-200 mx-1">/</span>
                                <span id="stat-max">{{ $extendedStats['24h']['max_response'] }}</span>
                                <span class="text-lg font-normal text-purple-200">ms</span>
                            </p>
                            <p class="text-sm text-purple-100 mt-1">Interval răspuns</p>
                        </div>

                        <!-- Total Verificări -->
                        <div class="bg-gradient-to-r from-orange-500 to-orange-600 rounded-xl p-5 shadow-lg">
                            <div class="flex items-center justify-between mb-3">
                                <span class="text-xs font-semibold text-orange-100 uppercase tracking-wider">Verificări</span>
                                <div class="w-10 h-10 rounded-lg bg-white/20 flex items-center justify-center">
                                    <i class="fas fa-sync text-white text-lg"></i>
                                </div>
                            </div>
                            <p class="text-3xl font-bold text-white" id="stat-checks">{{ number_format($extendedStats['24h']['total_checks']) }}</p>
                            <p class="text-sm text-orange-100 mt-1">Health checks</p>
                        </div>
                    </div>

                    <!-- Grafic Response Time cu threshold -->
                    <div class="mb-8">
                        <div class="flex items-center justify-between mb-4">
                            <h4 class="text-md font-semibold text-gray-900 dark:text-white">Response Time (ms)</h4>
                            <div class="flex items-center text-xs text-gray-500 dark:text-gray-400">
                                <span class="w-3 h-0.5 bg-red-500 mr-1"></span>
                                <span>Threshold 500ms</span>
                            </div>
                        </div>
                        <div class="bg-white dark:bg-white rounded-lg p-4">
                            <canvas id="responseTimeChart" height="80"></canvas>
                        </div>
                    </div>

                    <!-- Grafic Uptime pe zile -->
                    <div class="mb-8">
                        <h4 class="text-md font-semibold text-gray-900 dark:text-white mb-4">
                            <i class="fas fa-chart-area text-green-500 mr-2"></i>Disponibilitate (%)
                        </h4>
                        <div class="bg-white dark:bg-white rounded-lg p-4">
                            <canvas id="uptimeChart" height="60"></canvas>
                        </div>
                    </div>

                    <!-- Grafic Zone DNS -->
                    <div>
                        <h4 class="text-md font-semibold text-gray-900 dark:text-white mb-4">Zone DNS</h4>
                        <div class="bg-white dark:bg-white rounded-lg p-4">
                            <canvas id="zonesChart" height="80"></canvas>
                        </div>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Coloana 1 - Informații Generale -->
                <div class="space-y-6">
                    <!-- Detalii Generale -->
                    <div class="bg-white dark:bg-gray-800 rounded-lg shadow">
                        <div class="p-6">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                                <i class="fas fa-info-circle text-blue-500 mr-2"></i>
                                Informații Generale
                            </h3>
                            <div class="space-y-4">
                                <div>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">Hostname</p>
                                    <p class="font-medium text-gray-900 dark:text-white">{{ $nameServer->hostname }}</p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">IP Address (IPv4)</p>
                                    <p class="font-medium text-gray-900 dark:text-white font-mono">{{ $nameServer->ip_address }}</p>
                                </div>
                                @if($nameServer->ipv6_address)
                                    <div>
                                        <p class="text-sm text-gray-500 dark:text-gray-400">IP Address (IPv6)</p>
                                        <p class="font-medium text-gray-900 dark:text-white font-mono text-xs">{{ $nameServer->ipv6_address }}</p>
                                    </div>
                                @endif
                                <div>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">Prioritate</p>
                                    <p class="font-medium text-gray-900 dark:text-white">{{ $nameServer->priority }}</p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">Weight</p>
                                    <p class="font-medium text-gray-900 dark:text-white">{{ $nameServer->weight }}</p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">Server Primar</p>
                                    <p class="font-medium text-gray-900 dark:text-white">
                                        @if($nameServer->is_primary)
                                            <span class="text-green-600"><i class="fas fa-check-circle mr-1"></i>Da</span>
                                        @else
                                            <span class="text-gray-500"><i class="fas fa-times-circle mr-1"></i>Nu</span>
                                        @endif
                                    </p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">Stare</p>
                                    <p class="font-medium">
                                        @if($nameServer->is_active)
                                            <span class="text-green-600"><i class="fas fa-check-circle mr-1"></i>Activ</span>
                                        @else
                                            <span class="text-red-600"><i class="fas fa-times-circle mr-1"></i>Inactiv</span>
                                        @endif
                                    </p>
                                </div>
                                <div class="pt-3 mt-3 border-t border-gray-200 dark:border-gray-700">
                                    <p class="text-sm text-gray-500 dark:text-gray-400">Creat la</p>
                                    <p class="font-medium text-gray-900 dark:text-white text-sm">{{ $nameServer->created_at->format('d.m.Y H:i') }}</p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">Ultima actualizare</p>
                                    <p class="font-medium text-gray-900 dark:text-white text-sm">{{ $nameServer->updated_at->format('d.m.Y H:i') }}</p>
                                </div>
                                @if($nameServer->last_check_at)
                                <div>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">Ultima verificare</p>
                                    <p class="font-medium text-gray-900 dark:text-white text-sm">{{ $nameServer->last_check_at->format('d.m.Y H:i') }}</p>
                                </div>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Coloana 2 - API Configuration -->
                <div class="space-y-6">
                    <!-- API Configuration -->
                    <div class="bg-white dark:bg-gray-800 rounded-lg shadow">
                        <div class="p-6">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                                <i class="fas fa-plug text-green-500 mr-2"></i>
                                Configurare API
                            </h3>
                            <div class="space-y-4">
                                <div>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">API URL</p>
                                    <p class="font-medium text-gray-900 dark:text-white font-mono text-sm break-all">{{ $nameServer->full_api_url }}</p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">Tip API</p>
                                    <p class="font-medium text-gray-900 dark:text-white">{{ strtoupper($nameServer->api_type) }}</p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">Port</p>
                                    <p class="font-medium text-gray-900 dark:text-white">{{ $nameServer->api_port }}</p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">Server ID</p>
                                    <p class="font-medium text-gray-900 dark:text-white">{{ $nameServer->server_id }}</p>
                                </div>
                                @if($nameServer->api_key)
                                    <div>
                                        <p class="text-sm text-gray-500 dark:text-gray-400">API Key</p>
                                        <p class="font-medium text-gray-900 dark:text-white font-mono text-xs">{{ str_repeat('•', 20) }}{{ substr($nameServer->api_key, -4) }}</p>
                                    </div>
                                @endif
                                @if($nameServer->web_port)
                                    <div>
                                        <p class="text-sm text-gray-500 dark:text-gray-400">Web Port (Query Logs)</p>
                                        <p class="font-medium text-gray-900 dark:text-white">{{ $nameServer->web_port }}</p>
                                    </div>
                                @endif
                                @if($nameServer->cloudflare_account_id)
                                    <div>
                                        <p class="text-sm text-gray-500 dark:text-gray-400">Cloudflare Account ID</p>
                                        <p class="font-medium text-gray-900 dark:text-white font-mono text-xs">{{ $nameServer->cloudflare_account_id }}</p>
                                    </div>
                                @endif
                            </div>
                            <div class="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
                                <button type="button" onclick="testConnection()" id="testConnectionBtn" class="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg transition">
                                    <i class="fas fa-plug mr-2"></i>Test Conexiune API
                                </button>
                                <!-- Rezultat Test Conexiune -->
                                <div id="testConnectionResult" class="hidden mt-4 p-4 rounded-lg"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Zone DNS Asociate -->
                    <div class="bg-white dark:bg-gray-800 rounded-lg shadow">
                        <div class="p-6">
                            <div class="flex items-center justify-between mb-4">
                                <h3 class="text-lg font-semibold text-gray-900 dark:text-white">
                                    <i class="fas fa-database text-purple-500 mr-2"></i>
                                    Zone DNS (<span id="zonesVisibleCount">{{ $totalLocalZones }}</span>{{ $powerDNSZones->count() > 0 ? ' + ' . $powerDNSZones->count() . ' PowerDNS' : '' }})
                                </h3>
                            </div>

                            <!-- Căutare Zone (Live Search) -->
                            <div class="mb-4 relative">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <i class="fas fa-search text-gray-400"></i>
                                </div>
                                <input type="text" id="zoneSearchInput"
                                    placeholder="Caută domeniu..."
                                    class="w-full pl-10 pr-10 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                <button type="button" id="clearZoneSearch" class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hidden">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>

                            @if($localZones->count() > 0 || $powerDNSZones->count() > 0)
                                <div class="space-y-2 max-h-80 overflow-y-auto" id="zonesContainer">
                                    {{-- Zone din baza de date locală --}}
                                    @foreach($localZones as $zone)
                                        <div class="zone-item flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-900 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition" data-domain="{{ strtolower($zone->domain) }}">
                                            <div class="flex-1">
                                                <div class="flex items-center gap-2">
                                                    <p class="font-medium text-gray-900 dark:text-white text-sm zone-domain">{{ $zone->domain }}</p>
                                                    @if($zone->dnssec_enabled)
                                                        <span class="px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded">DNSSEC</span>
                                                    @endif
                                                    @if(!$zone->is_active)
                                                        <span class="px-2 py-0.5 text-xs bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 rounded">Inactiv</span>
                                                    @endif
                                                </div>
                                                <div class="flex items-center gap-2 mt-1">
                                                    <p class="text-xs text-gray-500 dark:text-gray-400">{{ $zone->type }}</p>
                                                    @if($zone->user)
                                                        <span class="text-xs text-gray-400">•</span>
                                                        <p class="text-xs text-gray-500 dark:text-gray-400">{{ $zone->user->name }}</p>
                                                    @endif
                                                </div>
                                            </div>
                                            <a href="{{ route('dns-zones.show', $zone) }}" class="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300">
                                                <i class="fas fa-arrow-right"></i>
                                            </a>
                                        </div>
                                    @endforeach

                                    {{-- Zone doar în PowerDNS --}}
                                    @foreach($powerDNSZones as $zone)
                                        <div class="zone-item flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-900 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition border-l-4 border-green-500" data-domain="{{ strtolower($zone->domain) }}">
                                            <div class="flex-1">
                                                <div class="flex items-center gap-2">
                                                    <p class="font-medium text-gray-900 dark:text-white text-sm zone-domain">{{ $zone->domain }}</p>
                                                    <span class="px-2 py-0.5 text-xs bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-200 rounded">PowerDNS Only</span>
                                                </div>
                                                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ $zone->type }}</p>
                                            </div>
                                            <a href="{{ route('dns-zones.show', $zone->domain) }}" class="text-green-600 hover:text-green-800 dark:text-green-400 dark:hover:text-green-300" title="Vezi în PowerDNS">
                                                <i class="fas fa-external-link-alt"></i>
                                            </a>
                                        </div>
                                    @endforeach
                                </div>

                                <!-- Mesaj când nu sunt rezultate -->
                                <div id="noZonesFound" class="hidden text-center py-6">
                                    <i class="fas fa-search text-gray-400 dark:text-gray-600 text-3xl mb-2"></i>
                                    <p class="text-gray-500 dark:text-gray-400 text-sm">Nu s-au găsit zone pentru căutarea ta</p>
                                </div>

                                {{-- Paginare --}}
                                @if($localZones->hasPages())
                                    <div class="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
                                        {{ $localZones->appends(['zone_search' => $zoneSearch])->links() }}
                                    </div>
                                @endif
                            @else
                                <div class="text-center py-8">
                                    <i class="fas fa-database text-gray-400 dark:text-gray-600 text-4xl mb-3"></i>
                                    <p class="text-gray-500 dark:text-gray-400 text-sm">
                                        @if($zoneSearch)
                                            Nu s-au găsit zone pentru "{{ $zoneSearch }}"
                                        @else
                                            Nu există zone DNS asociate acestui server
                                        @endif
                                    </p>
                                </div>
                            @endif
                        </div>
                    </div>

                    <!-- Statistici DNSSEC -->
                    <div class="bg-white dark:bg-gray-800 rounded-lg shadow">
                        <div class="p-6">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                                <i class="fas fa-shield-alt text-blue-500 mr-2"></i>
                                Statistici DNSSEC
                            </h3>
                            <div class="space-y-3">
                                <div class="flex items-center justify-between">
                                    <span class="text-sm text-gray-500 dark:text-gray-400">Zone cu DNSSEC activ</span>
                                    <span class="font-medium text-green-600 dark:text-green-400">{{ $dnssecStats['dnssec_enabled'] }}</span>
                                </div>
                                <div class="flex items-center justify-between">
                                    <span class="text-sm text-gray-500 dark:text-gray-400">Zone fără DNSSEC</span>
                                    <span class="font-medium text-gray-600 dark:text-gray-400">{{ $dnssecStats['dnssec_disabled'] }}</span>
                                </div>
                                <div class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-3 mt-2">
                                    <div class="bg-blue-600 h-3 rounded-full" style="width: {{ $dnssecStats['dnssec_percentage'] }}%"></div>
                                </div>
                                <p class="text-xs text-center text-gray-500 dark:text-gray-400">{{ $dnssecStats['dnssec_percentage'] }}% din zone au DNSSEC activ</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Coloana 3 - Locație & Acțiuni -->
                <div class="space-y-6">
                    <!-- Locație -->
                    <div class="bg-white dark:bg-gray-800 rounded-lg shadow">
                        <div class="p-6">
                            <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                                <i class="fas fa-globe text-purple-500 mr-2"></i>
                                Locație
                            </h3>
                            <div class="space-y-3">
                                @if($nameServer->city || $nameServer->country_code)
                                    <div>
                                        <p class="text-sm text-gray-500 dark:text-gray-400">Oraș / Țară</p>
                                        <p class="font-medium text-gray-900 dark:text-white">{{ $nameServer->location }}</p>
                                    </div>
                                @endif
                                @if($nameServer->region)
                                    <div>
                                        <p class="text-sm text-gray-500 dark:text-gray-400">Regiune</p>
                                        <p class="font-medium text-gray-900 dark:text-white">{{ $nameServer->region }}</p>
                                    </div>
                                @endif
                                @if($nameServer->provider)
                                    <div>
                                        <p class="text-sm text-gray-500 dark:text-gray-400">Provider</p>
                                        <p class="font-medium text-gray-900 dark:text-white">{{ $nameServer->provider }}</p>
                                    </div>
                                @endif
                                @if($nameServer->datacenter)
                                    <div>
                                        <p class="text-sm text-gray-500 dark:text-gray-400">Datacenter</p>
                                        <p class="font-medium text-gray-900 dark:text-white">{{ $nameServer->datacenter }}</p>
                                    </div>
                                @endif
                                @if($nameServer->latitude && $nameServer->longitude)
                                    <div>
                                        <p class="text-sm text-gray-500 dark:text-gray-400">Coordonate</p>
                                        <p class="font-medium text-gray-900 dark:text-white text-sm">
                                            {{ $nameServer->latitude }}, {{ $nameServer->longitude }}
                                        </p>
                                    </div>
                                @endif
                            </div>
                        </div>
                    </div>

                    <!-- Descriere & Note -->
                    @if($nameServer->description || $nameServer->notes)
                        <div class="bg-white dark:bg-gray-800 rounded-lg shadow">
                            <div class="p-6">
                                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                                    <i class="fas fa-sticky-note text-yellow-500 mr-2"></i>
                                    Note
                                </h3>
                                @if($nameServer->description)
                                    <div class="mb-3">
                                        <p class="text-sm text-gray-500 dark:text-gray-400 mb-1">Descriere:</p>
                                        <p class="text-sm text-gray-900 dark:text-white">{{ $nameServer->description }}</p>
                                    </div>
                                @endif
                                @if($nameServer->notes)
                                    <div>
                                        <p class="text-sm text-gray-500 dark:text-gray-400 mb-1">Note Administrative:</p>
                                        <p class="text-sm text-gray-900 dark:text-white">{{ $nameServer->notes }}</p>
                                    </div>
                                @endif
                            </div>
                        </div>
                    @endif
                </div>
            </div>

            <!-- Istoric Incidente (full width) -->
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow">
                <div class="p-6">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white">
                            <i class="fas fa-exclamation-triangle text-orange-500 mr-2"></i>
                            Istoric Incidente (ultimele 30 zile)
                        </h3>
                        <span class="px-3 py-1 text-sm rounded-full {{ $incidentHistory->count() > 0 ? 'bg-orange-100 dark:bg-orange-900/30 text-orange-700 dark:text-orange-300' : 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300' }}">
                            {{ $incidentHistory->count() }} {{ $incidentHistory->count() == 1 ? 'incident' : 'incidente' }}
                        </span>
                    </div>

                    @if($incidentHistory->count() > 0)
                        <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-900">
                                    <tr>
                                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Data/Ora</th>
                                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Status</th>
                                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Response Time</th>
                                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Eroare</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                                    @foreach($incidentHistory as $incident)
                                        <tr class="hover:bg-gray-50 dark:hover:bg-gray-700">
                                            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-900 dark:text-white">
                                                {{ $incident['date'] }}
                                            </td>
                                            <td class="px-4 py-3 whitespace-nowrap">
                                                @if($incident['status'] === 'offline')
                                                    <span class="px-2 py-1 text-xs rounded-full bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-300">
                                                        <i class="fas fa-times-circle mr-1"></i>Offline
                                                    </span>
                                                @else
                                                    <span class="px-2 py-1 text-xs rounded-full bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-300">
                                                        <i class="fas fa-exclamation-triangle mr-1"></i>Degraded
                                                    </span>
                                                @endif
                                            </td>
                                            <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400">
                                                {{ $incident['response_time'] ? $incident['response_time'] . 'ms' : '-' }}
                                            </td>
                                            <td class="px-4 py-3 text-sm text-gray-600 dark:text-gray-400 max-w-md truncate" title="{{ $incident['error'] }}">
                                                {{ $incident['error'] ?: '-' }}
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    @else
                        <div class="text-center py-8">
                            <i class="fas fa-check-circle text-green-500 text-4xl mb-3"></i>
                            <p class="text-gray-500 dark:text-gray-400">Nu au existat incidente în ultimele 30 de zile</p>
                            <p class="text-sm text-green-600 dark:text-green-400 mt-1">Serverul funcționează excelent! 🎉</p>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@2.2.1/dist/chartjs-plugin-annotation.min.js"></script>
    <script>
        // Date pentru grafice
        const chartData = {
            '24h': @json($chartData24h ?? []),
            '7d': @json($chartData7days ?? []),
            '30d': @json($chartData30days ?? []),
            '1y': @json($chartData1year ?? [])
        };

        // Date pentru statistici extinse
        const extendedStats = @json($extendedStats ?? []);

        // Date pentru uptime chart
        const uptimeByDay = @json($uptimeByDay ?? []);

        // Threshold response time
        const responseTimeThreshold = {{ $nameServer->response_time_threshold ?? 500 }};

        console.log('=== Name Server Charts Debug ===');
        console.log('Chart Data:', chartData);
        console.log('Extended Stats:', extendedStats);
        console.log('Uptime By Day:', uptimeByDay);

        let currentPeriod = '24h';
        let responseTimeChart = null;
        let zonesChart = null;
        let uptimeChart = null;

        // Configurare Chart.js - mereu fundal alb deci folosim culori închise
        const isDark = document.documentElement.classList.contains('dark');
        // Graficele au fundal alb mereu, deci folosim culori pentru light mode
        const textColor = '#374151';  // gray-700
        const gridColor = '#e5e7eb';  // gray-200

        // Actualizare statistici cards
        function updateStatsCards(period) {
            const stats = extendedStats[period];
            if (!stats) return;

            document.getElementById('stat-uptime').textContent = stats.uptime + '%';
            document.getElementById('stat-avg').textContent = stats.avg_response + 'ms';
            document.getElementById('stat-min').textContent = stats.min_response;
            document.getElementById('stat-max').textContent = stats.max_response;
            document.getElementById('stat-checks').textContent = stats.total_checks.toLocaleString();

            // Update trend - folosim culori mai deschise pentru cardurile colorate
            const trendEl = document.getElementById('stat-trend');
            if (stats.trend !== 0) {
                const isPositive = stats.trend > 0;
                trendEl.className = 'text-sm font-medium ' + (isPositive ? 'text-red-200' : 'text-green-200');
                trendEl.innerHTML = '<i class="fas fa-arrow-' + (isPositive ? 'up' : 'down') + ' mr-1"></i>' + Math.abs(stats.trend) + '%';
            } else {
                trendEl.className = 'text-sm font-medium text-blue-200';
                trendEl.innerHTML = '<i class="fas fa-minus mr-1"></i>stabil';
            }
        }

        // Inițializare grafice
        function initCharts() {
            const ctx1 = document.getElementById('responseTimeChart').getContext('2d');
            const ctx2 = document.getElementById('zonesChart').getContext('2d');
            const ctx3 = document.getElementById('uptimeChart').getContext('2d');

            // Grafic Response Time cu threshold line
            responseTimeChart = new Chart(ctx1, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Response Time (ms)',
                        data: [],
                        borderColor: 'rgb(59, 130, 246)',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        tension: 0.4,
                        fill: true,
                        pointRadius: 2,
                        pointHoverRadius: 5
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            backgroundColor: isDark ? '#1f2937' : '#ffffff',
                            titleColor: textColor,
                            bodyColor: textColor,
                            borderColor: gridColor,
                            borderWidth: 1
                        },
                        annotation: {
                            annotations: {
                                thresholdLine: {
                                    type: 'line',
                                    yMin: responseTimeThreshold,
                                    yMax: responseTimeThreshold,
                                    borderColor: 'rgba(239, 68, 68, 0.8)',
                                    borderWidth: 2,
                                    borderDash: [5, 5],
                                    label: {
                                        display: true,
                                        content: `Threshold (${responseTimeThreshold}ms)`,
                                        backgroundColor: 'rgba(239, 68, 68, 0.8)',
                                        color: 'white',
                                        font: { size: 10 },
                                        position: 'end'
                                    }
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: { color: textColor },
                            grid: { color: gridColor }
                        },
                        x: {
                            ticks: {
                                color: textColor,
                                maxRotation: 45,
                                minRotation: 45
                            },
                            grid: { color: gridColor }
                        }
                    }
                }
            });

            // Grafic Zone DNS
            zonesChart = new Chart(ctx2, {
                type: 'bar',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Zone DNS',
                        data: [],
                        backgroundColor: 'rgba(147, 51, 234, 0.6)',
                        borderColor: 'rgb(147, 51, 234)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            backgroundColor: isDark ? '#1f2937' : '#ffffff',
                            titleColor: textColor,
                            bodyColor: textColor,
                            borderColor: gridColor,
                            borderWidth: 1
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                color: textColor,
                                stepSize: 1
                            },
                            grid: { color: gridColor }
                        },
                        x: {
                            ticks: {
                                color: textColor,
                                maxRotation: 45,
                                minRotation: 45
                            },
                            grid: { color: gridColor }
                        }
                    }
                }
            });

            // Grafic Uptime pe zile
            uptimeChart = new Chart(ctx3, {
                type: 'bar',
                data: {
                    labels: uptimeByDay.map(d => d.date),
                    datasets: [{
                        label: 'Uptime %',
                        data: uptimeByDay.map(d => d.total_checks > 0 ? ((d.online_checks / d.total_checks) * 100).toFixed(1) : 0),
                        backgroundColor: uptimeByDay.map(d => {
                            const uptime = d.total_checks > 0 ? (d.online_checks / d.total_checks) * 100 : 0;
                            if (uptime >= 99.9) return 'rgba(34, 197, 94, 0.8)';
                            if (uptime >= 99) return 'rgba(34, 197, 94, 0.6)';
                            if (uptime >= 95) return 'rgba(234, 179, 8, 0.6)';
                            return 'rgba(239, 68, 68, 0.6)';
                        }),
                        borderColor: uptimeByDay.map(d => {
                            const uptime = d.total_checks > 0 ? (d.online_checks / d.total_checks) * 100 : 0;
                            if (uptime >= 99.9) return 'rgb(34, 197, 94)';
                            if (uptime >= 99) return 'rgb(34, 197, 94)';
                            if (uptime >= 95) return 'rgb(234, 179, 8)';
                            return 'rgb(239, 68, 68)';
                        }),
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            backgroundColor: isDark ? '#1f2937' : '#ffffff',
                            titleColor: textColor,
                            bodyColor: textColor,
                            borderColor: gridColor,
                            borderWidth: 1,
                            callbacks: {
                                label: function(context) {
                                    return `Uptime: ${context.raw}%`;
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            ticks: {
                                color: textColor,
                                callback: function(value) {
                                    return value + '%';
                                }
                            },
                            grid: { color: gridColor }
                        },
                        x: {
                            ticks: {
                                color: textColor,
                                maxRotation: 45,
                                minRotation: 45
                            },
                            grid: { color: gridColor }
                        }
                    }
                }
            });

            // Încarcă datele inițiale
            updateCharts('24h');
        }

        // Actualizare grafice
        function updateCharts(period) {
            const data = chartData[period] || [];

            console.log(`Updating charts for period: ${period}, data points: ${data.length}`);

            if (!responseTimeChart || !zonesChart) {
                console.error('Charts not initialized!');
                return;
            }

            // Extrage labels și date
            let labels, responseData, zonesData;

            if (data.length === 0) {
                console.warn(`No data for period: ${period}`);
                labels = [];
                responseData = [];
                zonesData = [];
            } else {
                if (period === '24h') {
                    labels = data.map(d => d.time || '');
                    responseData = data.map(d => d.response_time || 0);
                    zonesData = data.map(d => d.zones || 0);
                } else {
                    labels = data.map(d => d.date || '');
                    responseData = data.map(d => d.avg_response || 0);
                    zonesData = data.map(d => d.avg_zones || 0);
                }
            }

            console.log(`Labels: ${labels.length}, Response: ${responseData.length}, Zones: ${zonesData.length}`);

            // Actualizare Response Time Chart
            responseTimeChart.data.labels = labels;
            responseTimeChart.data.datasets[0].data = responseData;
            responseTimeChart.update('none'); // No animation for faster update

            // Actualizare Zones Chart
            zonesChart.data.labels = labels;
            zonesChart.data.datasets[0].data = zonesData;
            zonesChart.update('none');

            console.log('Charts updated successfully');
        }

        // Switch perioada
        function switchPeriod(period) {
            currentPeriod = period;
            updateCharts(period);
            updateStatsCards(period);

            // Update butoane
            document.querySelectorAll('[id^="btn-"]').forEach(btn => {
                btn.classList.remove('bg-blue-600', 'text-white');
                btn.classList.add('bg-gray-200', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300');
            });

            const activeBtn = document.getElementById('btn-' + period);
            activeBtn.classList.remove('bg-gray-200', 'dark:bg-gray-700', 'text-gray-700', 'dark:text-gray-300');
            activeBtn.classList.add('bg-blue-600', 'text-white');
        }

        // Inițializare la încărcarea paginii
        document.addEventListener('DOMContentLoaded', function() {
            initCharts();
        });

        // Modal Ștergere cu cod de confirmare
        let currentDeleteCode = null;

        function generateDeleteCode() {
            const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
            let code = '';
            for (let i = 0; i < 6; i++) {
                code += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            return code;
        }

        function openDeleteModal() {
            currentDeleteCode = generateDeleteCode();

            const codeDisplay = document.getElementById('deleteConfirmCode');
            const input = document.getElementById('deleteCodeInput');
            const errorEl = document.getElementById('deleteCodeError');
            const button = document.getElementById('deleteServerButton');

            // Dacă există câmpul de cod (serverul nu are zone)
            if (codeDisplay && input) {
                codeDisplay.textContent = currentDeleteCode;
                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 tracking-widest';

                if (errorEl) errorEl.classList.add('hidden');
                if (button) {
                    button.disabled = true;
                    button.className = 'w-full inline-flex justify-center items-center rounded-lg border border-transparent shadow-sm px-4 py-2.5 bg-gray-400 text-base font-medium text-white cursor-not-allowed sm:w-auto transition';
                }

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

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

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

        function validateDeleteCode() {
            const input = document.getElementById('deleteCodeInput');
            const button = document.getElementById('deleteServerButton');
            const error = document.getElementById('deleteCodeError');

            if (!input || !button) return;

            const inputValue = input.value.trim().toUpperCase();

            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 tracking-widest';
                if (error) error.classList.add('hidden');
                button.disabled = true;
                button.className = 'w-full inline-flex justify-center items-center rounded-lg border border-transparent shadow-sm px-4 py-2.5 bg-gray-400 text-base font-medium text-white cursor-not-allowed sm:w-auto 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 tracking-widest';
                if (error) error.classList.add('hidden');
                button.disabled = false;
                button.className = 'w-full inline-flex justify-center items-center rounded-lg border border-transparent shadow-sm px-4 py-2.5 bg-red-600 hover:bg-red-700 text-base font-medium text-white focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:w-auto 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 tracking-widest';
                if (error) error.classList.remove('hidden');
                button.disabled = true;
                button.className = 'w-full inline-flex justify-center items-center rounded-lg border border-transparent shadow-sm px-4 py-2.5 bg-gray-400 text-base font-medium text-white cursor-not-allowed sm:w-auto transition';
            }
        }

        function confirmDeleteServer() {
            const input = document.getElementById('deleteCodeInput');
            const form = document.getElementById('deleteServerForm');
            if (!input || !form) return;

            const inputValue = input.value.trim().toUpperCase();
            if (inputValue === currentDeleteCode) {
                form.submit();
            }
        }

        // Test Conexiune cu feedback vizual
        function testConnection() {
            const btn = document.getElementById('testConnectionBtn');
            const resultDiv = document.getElementById('testConnectionResult');

            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Se testează...';
            resultDiv.classList.add('hidden');

            fetch('{{ route("admin.nameservers.test", $nameServer) }}', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                resultDiv.classList.remove('hidden');
                if (data.success) {
                    resultDiv.className = 'mt-4 p-4 rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800';
                    resultDiv.innerHTML = `
                        <div class="flex items-center text-green-700 dark:text-green-300">
                            <i class="fas fa-check-circle text-xl mr-3"></i>
                            <div>
                                <p class="font-medium">${data.message}</p>
                                ${data.response_time ? `<p class="text-sm">Timp răspuns: ${Math.round(data.response_time * 1000)}ms</p>` : ''}
                            </div>
                        </div>
                    `;
                } else {
                    resultDiv.className = 'mt-4 p-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800';
                    resultDiv.innerHTML = `
                        <div class="flex items-center text-red-700 dark:text-red-300">
                            <i class="fas fa-times-circle text-xl mr-3"></i>
                            <div>
                                <p class="font-medium">${data.message}</p>
                                ${data.error ? `<p class="text-sm text-red-600 dark:text-red-400">${data.error}</p>` : ''}
                            </div>
                        </div>
                    `;
                }
            })
            .catch(error => {
                resultDiv.classList.remove('hidden');
                resultDiv.className = 'mt-4 p-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800';
                resultDiv.innerHTML = `
                    <div class="flex items-center text-red-700 dark:text-red-300">
                        <i class="fas fa-exclamation-triangle text-xl mr-3"></i>
                        <p class="font-medium">Eroare la testare: ${error.message}</p>
                    </div>
                `;
            })
            .finally(() => {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-plug mr-2"></i>Test Conexiune API';
            });
        }

        // Căutare AJAX zone DNS
        const zoneSearchInput = document.getElementById('zoneSearchInput');
        const clearZoneSearchBtn = document.getElementById('clearZoneSearch');
        const zonesContainer = document.getElementById('zonesContainer');
        const noZonesFound = document.getElementById('noZonesFound');
        const zonesVisibleCount = document.getElementById('zonesVisibleCount');
        const searchUrl = '{{ route("admin.nameservers.search-zones", $nameServer) }}';
        let searchTimeout = null;
        let originalZonesHtml = zonesContainer ? zonesContainer.innerHTML : '';

        if (zoneSearchInput) {
            zoneSearchInput.addEventListener('input', function() {
                const searchTerm = this.value.trim();

                // Afișează/ascunde butonul X
                if (searchTerm.length > 0) {
                    clearZoneSearchBtn.classList.remove('hidden');
                } else {
                    clearZoneSearchBtn.classList.add('hidden');
                    // Restaurează lista originală
                    zonesContainer.innerHTML = originalZonesHtml;
                    zonesContainer.classList.remove('hidden');
                    noZonesFound.classList.add('hidden');
                    zonesVisibleCount.textContent = '{{ $totalLocalZones }}';
                    return;
                }

                // Debounce - așteaptă 300ms după ultima tastare
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    performZoneSearch(searchTerm);
                }, 300);
            });

            // Buton clear
            clearZoneSearchBtn.addEventListener('click', function() {
                zoneSearchInput.value = '';
                clearZoneSearchBtn.classList.add('hidden');
                // Restaurează lista originală
                zonesContainer.innerHTML = originalZonesHtml;
                zonesContainer.classList.remove('hidden');
                noZonesFound.classList.add('hidden');
                zonesVisibleCount.textContent = '{{ $totalLocalZones }}';
                zoneSearchInput.focus();
            });
        }

        function performZoneSearch(query) {
            // Afișează loading
            zonesContainer.innerHTML = `
                <div class="flex items-center justify-center py-8">
                    <i class="fas fa-spinner fa-spin text-blue-500 text-2xl mr-3"></i>
                    <span class="text-gray-500 dark:text-gray-400">Se caută...</span>
                </div>
            `;
            zonesContainer.classList.remove('hidden');
            noZonesFound.classList.add('hidden');

            fetch(`${searchUrl}?q=${encodeURIComponent(query)}`, {
                headers: {
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                // Actualizează counter
                zonesVisibleCount.textContent = data.total;

                if (data.zones.length === 0) {
                    zonesContainer.classList.add('hidden');
                    noZonesFound.classList.remove('hidden');
                } else {
                    zonesContainer.classList.remove('hidden');
                    noZonesFound.classList.add('hidden');

                    // Construiește HTML pentru rezultate
                    let html = '';
                    data.zones.forEach(zone => {
                        html += `
                            <div class="zone-item flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-900 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition" data-domain="${zone.domain.toLowerCase()}">
                                <div class="flex-1">
                                    <div class="flex items-center gap-2">
                                        <p class="font-medium text-gray-900 dark:text-white text-sm">${zone.domain}</p>
                                        ${zone.dnssec_enabled ? '<span class="px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded">DNSSEC</span>' : ''}
                                        ${!zone.is_active ? '<span class="px-2 py-0.5 text-xs bg-red-100 dark:bg-red-900 text-red-800 dark:text-red-200 rounded">Inactiv</span>' : ''}
                                    </div>
                                    <div class="flex items-center gap-2 mt-1">
                                        <p class="text-xs text-gray-500 dark:text-gray-400">${zone.type}</p>
                                        ${zone.user_name ? `<span class="text-xs text-gray-400">•</span><p class="text-xs text-gray-500 dark:text-gray-400">${zone.user_name}</p>` : ''}
                                    </div>
                                </div>
                                <a href="${zone.url}" class="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300">
                                    <i class="fas fa-arrow-right"></i>
                                </a>
                            </div>
                        `;
                    });

                    // Adaugă mesaj dacă sunt mai multe rezultate
                    if (data.has_more) {
                        html += `
                            <div class="text-center py-2 text-sm text-gray-500 dark:text-gray-400">
                                <i class="fas fa-info-circle mr-1"></i>
                                Se afișează ${data.showing} din ${data.total} rezultate. Refinați căutarea pentru rezultate mai precise.
                            </div>
                        `;
                    }

                    zonesContainer.innerHTML = html;
                }
            })
            .catch(error => {
                console.error('Eroare căutare zone:', error);
                zonesContainer.innerHTML = `
                    <div class="text-center py-6 text-red-500">
                        <i class="fas fa-exclamation-triangle text-2xl mb-2"></i>
                        <p>Eroare la căutare. Încearcă din nou.</p>
                    </div>
                `;
            });
        }
    </script>
    @endpush

    <!-- Modal Confirmare Ștergere cu Cod -->
    <div id="deleteModal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4" aria-labelledby="modal-title" role="dialog" aria-modal="true">
        <!-- Overlay - mai vizibil -->
        <div class="fixed inset-0 bg-black/70 dark:bg-black/80 backdrop-blur-sm transition-opacity" onclick="closeDeleteModal()"></div>

        <!-- Modal - centrat, mai lat -->
        <div class="relative bg-white dark:bg-gray-800 rounded-2xl shadow-2xl w-full max-w-xl transform transition-all" onclick="event.stopPropagation()">
            <!-- Header -->
            <div class="px-6 py-5 border-b border-gray-200 dark:border-gray-700">
                <div class="flex items-center">
                    <div class="flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-xl bg-amber-400 shadow-md">
                        <i class="fas fa-exclamation-triangle text-amber-900 text-xl"></i>
                    </div>
                    <div class="ml-4 flex-1">
                        <h3 class="text-xl font-bold text-gray-900 dark:text-white" id="modal-title">
                            Șterge NameServer
                        </h3>
                        <p class="text-red-500 dark:text-red-400 text-sm mt-0.5 font-medium">Acțiune ireversibilă</p>
                    </div>
                    <button onclick="closeDeleteModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
            </div>

            <!-- Content -->
            <div class="px-6 py-6">
                <p class="text-gray-700 dark:text-gray-300 mb-4 text-center">
                    Ești sigur că vrei să ștergi serverul<br>
                    <strong class="text-red-600 dark:text-red-400 text-lg">{{ $nameServer->name }}</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 text-center">
                        <i class="fas fa-info-circle mr-2"></i>
                        Toate statisticile și datele asociate vor fi șterse permanent!
                    </p>
                </div>

                @if($nameServer->dnsZones->count() > 0)
                    <div class="bg-orange-50 dark:bg-orange-900/20 border-2 border-orange-300 dark:border-orange-700 rounded-lg p-4">
                        <p class="text-sm text-orange-800 dark:text-orange-200 text-center">
                            <i class="fas fa-server mr-2"></i>
                            <strong>Atenție:</strong> Acest server are <strong>{{ $nameServer->dnsZones->count() }}</strong> zone DNS asociate.<br>
                            Nu poate fi șters până când toate zonele nu sunt mutate pe alt server.
                        </p>
                    </div>
                @else
                    <!-- Confirmation Code Section -->
                    <div class="mb-2">
                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3 text-center">
                            Pentru a confirma, introdu codul
                            <strong id="deleteConfirmCode" class="inline-block px-3 py-1 bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300 rounded-lg border border-blue-300 dark:border-blue-700 text-lg font-mono tracking-widest"></strong>
                        </label>
                        <input
                            type="text"
                            id="deleteCodeInput"
                            placeholder="Introdu codul"
                            class="w-full px-4 py-3 bg-white dark:bg-gray-700 border-2 border-gray-300 dark:border-gray-600 rounded-xl 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-red-500 transition text-center font-mono text-xl tracking-widest"
                            autocomplete="off"
                            oninput="validateDeleteCode()"
                            style="text-transform: uppercase;"
                        >
                        <p id="deleteCodeError" class="hidden text-sm text-red-600 dark:text-red-400 mt-2 text-center">
                            <i class="fas fa-times-circle mr-1"></i>
                            Codul introdus nu este corect!
                        </p>
                    </div>
                @endif
            </div>

            <!-- Footer -->
            <div class="bg-gray-50 dark:bg-gray-900/50 px-6 py-4 rounded-b-2xl flex flex-row gap-3">
                <button type="button" onclick="closeDeleteModal()" class="flex-1 inline-flex justify-center items-center rounded-xl border-2 border-gray-300 dark:border-gray-600 shadow-sm px-4 py-3 bg-white dark:bg-gray-800 text-base font-semibold text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition">
                    Anulează
                </button>
                @if($nameServer->dnsZones->count() == 0)
                    <form id="deleteServerForm" action="{{ route('admin.nameservers.destroy', $nameServer) }}" method="POST" class="flex-1">
                        @csrf
                        @method('DELETE')
                        <button type="button" id="deleteServerButton" onclick="confirmDeleteServer()" disabled class="w-full inline-flex justify-center items-center rounded-xl border border-transparent shadow-sm px-4 py-3 bg-gray-400 text-base font-semibold text-white cursor-not-allowed transition">
                            <i class="fas fa-trash-alt mr-2"></i>
                            Șterge definitiv
                        </button>
                    </form>
                @else
                    <button type="button" disabled class="flex-1 inline-flex justify-center items-center rounded-xl border border-transparent shadow-sm px-4 py-3 bg-gray-400 text-base font-semibold text-white cursor-not-allowed">
                        <i class="fas fa-ban mr-2"></i>
                        Nu se poate șterge
                    </button>
                @endif
            </div>
        </div>
    </div>
</x-app-layout>
