<x-app-layout>
    <x-slot name="header">
        <div>
            <h2 class="font-semibold text-lg text-gray-800 dark:text-gray-200 leading-tight">
                <i class="fas fa-heartbeat mr-2 text-purple-500"></i>DNS Health Check
            </h2>
            <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">
                Verifică propagarea DNS și starea înregistrărilor pentru domeniile tale
            </p>
        </div>
    </x-slot>

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

            {{-- Formular de verificare --}}
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6 mb-6">
                <form id="healthCheckForm" class="space-y-4">
                    @csrf
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                        {{-- Domeniu --}}
                        <div class="md:col-span-2">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                Domeniu
                            </label>
                            <div class="relative">
                                <input type="text" name="domain" id="domainInput"
                                    class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-indigo-500 focus:border-indigo-500 pr-10"
                                    placeholder="exemplu.ro sau alege din listă" required
                                    autocomplete="off">
                                <button type="button" id="dropdownToggle"
                                    class="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 p-1">
                                    <i class="fas fa-chevron-down"></i>
                                </button>
                                {{-- Dropdown lista domenii --}}
                                <div id="domainDropdown" class="hidden absolute z-50 left-0 right-0 mt-1 bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg shadow-lg max-h-60 overflow-y-auto">
                                    @if($zones->count() > 0)
                                        @foreach($zones as $zone)
                                            <button type="button"
                                                class="domain-option w-full text-left px-4 py-2.5 hover:bg-indigo-50 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 border-b border-gray-100 dark:border-gray-600 last:border-b-0 transition"
                                                data-domain="{{ $zone->domain }}">
                                                <i class="fas fa-globe text-indigo-500 mr-2"></i>
                                                {{ $zone->domain }}
                                            </button>
                                        @endforeach
                                    @else
                                        <div class="px-4 py-3 text-gray-500 dark:text-gray-400 text-sm">
                                            <i class="fas fa-info-circle mr-1"></i>
                                            Nu ai zone DNS. Poți introduce manual un domeniu.
                                        </div>
                                    @endif
                                </div>
                            </div>
                        </div>

                        {{-- Subdomen (opțional) --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                Subdomen <span class="text-gray-400">(opțional)</span>
                            </label>
                            <input type="text" name="name" id="nameInput"
                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-indigo-500 focus:border-indigo-500"
                                placeholder="www, mail, etc.">
                        </div>

                        {{-- Tip înregistrare --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                                Tip Înregistrare
                            </label>
                            <select name="record_type" id="recordType"
                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white focus:ring-indigo-500 focus:border-indigo-500">
                                <option value="A">A (IPv4)</option>
                                <option value="AAAA">AAAA (IPv6)</option>
                                <option value="MX">MX (Mail)</option>
                                <option value="NS">NS (Nameserver)</option>
                                <option value="TXT">TXT</option>
                                <option value="CNAME">CNAME</option>
                                <option value="SOA">SOA</option>
                            </select>
                        </div>
                    </div>

                    <div class="flex justify-end">
                        <button type="submit" id="checkButton"
                            class="inline-flex items-center px-6 py-2.5 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700 text-white font-medium rounded-lg transition shadow-lg hover:shadow-xl">
                            <i class="fas fa-search mr-2"></i>
                            Verifică Propagarea
                        </button>
                    </div>
                </form>
            </div>

            {{-- Rezultate --}}
            <div id="resultsContainer" class="hidden space-y-6">
                {{-- Sumar --}}
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div id="consistencyCard" class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                        <div class="flex items-center gap-4">
                            <div id="consistencyIcon" class="w-12 h-12 rounded-lg bg-gradient-to-br from-gray-400 to-gray-600 flex items-center justify-center flex-shrink-0">
                                <i class="fas fa-sync text-xl text-white"></i>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500 dark:text-gray-400">Consistență</p>
                                <p id="consistencyValue" class="text-2xl font-bold text-gray-900 dark:text-white">--</p>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                        <div class="flex items-center gap-4">
                            <div class="w-12 h-12 rounded-lg bg-gradient-to-br from-blue-500 to-blue-600 flex items-center justify-center flex-shrink-0">
                                <i class="fas fa-server text-xl text-white"></i>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500 dark:text-gray-400">Servere Verificate</p>
                                <p id="serversCount" class="text-2xl font-bold text-gray-900 dark:text-white">--</p>
                            </div>
                        </div>
                    </div>

                    <div id="propagationCard" class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                        <div class="flex items-center gap-4">
                            <div id="propagationIcon" class="w-12 h-12 rounded-lg bg-gradient-to-br from-green-500 to-green-600 flex items-center justify-center flex-shrink-0">
                                <i class="fas fa-check-circle text-xl text-white"></i>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500 dark:text-gray-400">Propagare</p>
                                <p id="propagationValue" class="text-2xl font-bold text-gray-900 dark:text-white">--</p>
                            </div>
                        </div>
                    </div>
                </div>

                {{-- Detalii per server --}}
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                        <i class="fas fa-list-alt text-indigo-500 mr-2"></i>
                        Rezultate Detaliate
                    </h3>
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead>
                                <tr class="text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                                    <th class="pb-3">Provider</th>
                                    <th class="pb-3">Server DNS</th>
                                    <th class="pb-3">Status</th>
                                    <th class="pb-3">Valori</th>
                                    <th class="pb-3">TTL</th>
                                    <th class="pb-3">Timp Răspuns</th>
                                </tr>
                            </thead>
                            <tbody id="resultsTable" class="divide-y divide-gray-200 dark:divide-gray-700">
                                {{-- Rezultatele vor fi populate prin JavaScript --}}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            {{-- Loading --}}
            <div id="loadingContainer" class="hidden">
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-12 text-center">
                    <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-indigo-100 dark:bg-indigo-900/50 mb-4">
                        <i class="fas fa-spinner fa-spin text-indigo-600 dark:text-indigo-400 text-2xl"></i>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-2">Verificare în curs...</h3>
                    <p class="text-gray-500 dark:text-gray-400">Interogăm serverele DNS din întreaga lume</p>
                </div>
            </div>

            {{-- Informații suplimentare --}}
            <div class="mt-6 bg-blue-50 dark:bg-blue-900/20 rounded-xl border border-blue-200 dark:border-blue-800 p-6">
                <h4 class="font-semibold text-blue-900 dark:text-blue-100 mb-2">
                    <i class="fas fa-info-circle mr-2"></i>Despre DNS Health Check
                </h4>
                <p class="text-sm text-blue-800 dark:text-blue-200 mb-3">
                    Acest instrument verifică propagarea DNS pe servere din întreaga lume. Propagarea completă poate dura până la 48 de ore, în funcție de TTL-ul setat.
                </p>
                {{-- Provideri DNS pe un singur rând --}}
                <div class="flex flex-wrap items-center gap-6 text-sm mt-1">
                    <div class="flex items-center gap-2">
                        <i class="fab fa-google text-blue-600 text-base"></i>
                        <span class="text-blue-800 dark:text-blue-200">Google DNS</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <i class="fas fa-cloud text-orange-500 text-base"></i>
                        <span class="text-blue-800 dark:text-blue-200">Cloudflare</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <i class="fas fa-shield-alt text-green-600 text-base"></i>
                        <span class="text-blue-800 dark:text-blue-200">OpenDNS</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <i class="fas fa-lock text-purple-600 text-base"></i>
                        <span class="text-blue-800 dark:text-blue-200">Quad9</span>
                    </div>
                    <div class="flex items-center gap-2">
                        <i class="fas fa-server text-gray-600 text-base"></i>
                        <span class="text-blue-800 dark:text-blue-200">Comodo</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const domainInput = document.getElementById('domainInput');
            const domainDropdown = document.getElementById('domainDropdown');
            const dropdownToggle = document.getElementById('dropdownToggle');
            const domainOptions = document.querySelectorAll('.domain-option');

            // Toggle dropdown când se apasă pe buton
            dropdownToggle.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                domainDropdown.classList.toggle('hidden');
            });

            // Afișează dropdown când se focusează input-ul
            domainInput.addEventListener('focus', function() {
                domainDropdown.classList.remove('hidden');
            });

            // Selectează domeniu din listă
            domainOptions.forEach(function(option) {
                option.addEventListener('click', function(e) {
                    e.preventDefault();
                    domainInput.value = this.dataset.domain;
                    domainDropdown.classList.add('hidden');
                    domainInput.focus();
                });
            });

            // Filtrează domeniile când se tastează
            domainInput.addEventListener('input', function() {
                const filter = this.value.toLowerCase();
                domainOptions.forEach(function(option) {
                    const domain = option.dataset.domain.toLowerCase();
                    if (domain.includes(filter)) {
                        option.classList.remove('hidden');
                    } else {
                        option.classList.add('hidden');
                    }
                });
                domainDropdown.classList.remove('hidden');
            });

            // Închide dropdown când se apasă în afară
            document.addEventListener('click', function(e) {
                if (!domainInput.contains(e.target) && !domainDropdown.contains(e.target) && !dropdownToggle.contains(e.target)) {
                    domainDropdown.classList.add('hidden');
                }
            });
        });

        // Submit formular
        document.getElementById('healthCheckForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const domain = document.getElementById('domainInput').value;
            const name = document.getElementById('nameInput').value;
            const recordType = document.getElementById('recordType').value;

            // Afișează loading
            document.getElementById('resultsContainer').classList.add('hidden');
            document.getElementById('loadingContainer').classList.remove('hidden');

            try {
                const response = await fetch('{{ route("dns-health-check.check") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        domain: domain,
                        name: name,
                        record_type: recordType
                    })
                });

                const data = await response.json();

                if (data.success) {
                    displayResults(data);
                } else {
                    alert('Eroare: ' + (data.error || 'Verificarea a eșuat'));
                }
            } catch (error) {
                console.error('Error:', error);
                alert('Eroare la verificare. Încercați din nou.');
            } finally {
                document.getElementById('loadingContainer').classList.add('hidden');
            }
        });

        // Afișează rezultatele
        function displayResults(data) {
            document.getElementById('resultsContainer').classList.remove('hidden');

            // Consistență
            const consistencyCard = document.getElementById('consistencyCard');
            const consistencyIcon = document.getElementById('consistencyIcon');
            const consistencyValue = document.getElementById('consistencyValue');

            if (data.consistency.status === 'consistent') {
                consistencyIcon.className = 'w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0 bg-gradient-to-br from-green-500 to-green-600';
                consistencyIcon.innerHTML = '<i class="fas fa-check text-xl text-white"></i>';
                consistencyValue.textContent = '100%';
            } else if (data.consistency.status === 'inconsistent') {
                consistencyIcon.className = 'w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0 bg-gradient-to-br from-amber-500 to-amber-600';
                consistencyIcon.innerHTML = '<i class="fas fa-sync text-xl text-white"></i>';
                consistencyValue.textContent = data.consistency.percentage + '%';
            } else {
                consistencyIcon.className = 'w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0 bg-gradient-to-br from-gray-500 to-gray-600';
                consistencyIcon.innerHTML = '<i class="fas fa-question text-xl text-white"></i>';
                consistencyValue.textContent = 'N/A';
            }

            // Servere
            document.getElementById('serversCount').textContent = data.results.length;

            // Propagare
            const propagationIcon = document.getElementById('propagationIcon');
            const propagationValue = document.getElementById('propagationValue');

            if (data.propagation.status === 'complete') {
                propagationIcon.className = 'w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0 bg-gradient-to-br from-green-500 to-green-600';
                propagationIcon.innerHTML = '<i class="fas fa-check-circle text-xl text-white"></i>';
                propagationValue.textContent = 'Completă';
            } else if (data.propagation.status === 'in_progress') {
                propagationIcon.className = 'w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0 bg-gradient-to-br from-amber-500 to-amber-600';
                propagationIcon.innerHTML = '<i class="fas fa-clock text-xl text-white"></i>';
                propagationValue.textContent = data.propagation.current_percentage + '%';
            } else {
                propagationIcon.className = 'w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0 bg-gradient-to-br from-gray-500 to-gray-600';
                propagationIcon.innerHTML = '<i class="fas fa-question-circle text-xl text-white"></i>';
                propagationValue.textContent = 'Necunoscut';
            }

            // Tabel rezultate
            const tbody = document.getElementById('resultsTable');
            tbody.innerHTML = '';

            data.results.forEach(result => {
                const row = document.createElement('tr');
                row.className = 'text-sm';

                let statusBadge = '';
                if (result.status === 'success') {
                    statusBadge = '<span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-green-500 text-white"><i class="fas fa-check mr-1"></i>OK</span>';
                } else if (result.status === 'no_records') {
                    statusBadge = '<span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-amber-500 text-white"><i class="fas fa-minus mr-1"></i>Gol</span>';
                } else {
                    statusBadge = '<span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-red-500 text-white"><i class="fas fa-times mr-1"></i>Eroare</span>';
                }

                row.innerHTML = `
                    <td class="py-3 text-gray-900 dark:text-white font-medium">${result.provider}</td>
                    <td class="py-3 text-gray-600 dark:text-gray-400 font-mono">${result.server}</td>
                    <td class="py-3">${statusBadge}</td>
                    <td class="py-3 text-gray-600 dark:text-gray-400 font-mono text-xs">${result.records.join('<br>') || '-'}</td>
                    <td class="py-3 text-gray-600 dark:text-gray-400">${result.ttl ? result.ttl + 's' : '-'}</td>
                    <td class="py-3 text-gray-600 dark:text-gray-400">${result.response_time ? result.response_time + 'ms' : '-'}</td>
                `;

                tbody.appendChild(row);
            });
        }

        // Închide dropdown când click în afară
        document.addEventListener('click', function(e) {
            if (!e.target.closest('#domainInput') && !e.target.closest('#domainDropdown')) {
                document.getElementById('domainDropdown').classList.add('hidden');
            }
        });
    </script>
    @endpush
</x-app-layout>
