<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-link mr-2 text-orange-500"></i>Conectează la Cloudflare
                </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('cloudflare.index') }}" class="text-blue-600 dark:text-blue-400 hover:underline">Cloudflare</a>
                    <span class="mx-2">/</span>
                    <span>Conectează {{ $zone->domain }}</span>
                </p>
            </div>
            <a href="{{ route('dns-zones.show', $zone->domain) }}" class="inline-flex items-center justify-center w-10 h-10 text-gray-600 dark:text-gray-400 hover:text-indigo-600 dark:hover:text-indigo-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition" title="Înapoi la zonă">
                <i class="fas fa-arrow-left"></i>
            </a>
        </div>
    </x-slot>

    <div class="py-12">
        <div class="px-6 lg:px-8">
            <div class="max-w-2xl mx-auto">

                @if($existingLink)
                    <div class="bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-4 rounded mb-6 dark:bg-yellow-900/30 dark:border-yellow-600 dark:text-yellow-300">
                        <p class="font-bold"><i class="fas fa-exclamation-circle mr-2"></i>Această zonă este deja conectată!</p>
                        <p class="mt-2">Zona <strong>{{ $zone->domain }}</strong> este deja conectată la Cloudflare.</p>
                        <a href="{{ route('cloudflare.zones.show', $existingLink) }}" class="inline-flex items-center mt-3 text-yellow-800 dark:text-yellow-200 underline">
                            <i class="fas fa-arrow-right mr-2"></i>Vezi detaliile conexiunii
                        </a>
                    </div>
                @endif

                <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                    <div class="p-6">
                        <div class="mb-6 flex items-center">
                            <div class="flex-shrink-0 bg-orange-100 dark:bg-orange-900/30 p-3 rounded-lg">
                                <i class="fas fa-cloud text-orange-500 text-2xl"></i>
                            </div>
                            <div class="ml-4">
                                <h3 class="text-lg font-semibold text-gray-900 dark:text-white">{{ $zone->domain }}</h3>
                                <p class="text-sm text-gray-500 dark:text-gray-400">Conectează această zonă la Cloudflare</p>
                            </div>
                        </div>

                        @if($credentials->isEmpty())
                            <div class="text-center py-8 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg">
                                <i class="fas fa-key text-gray-400 text-4xl mb-4"></i>
                                <p class="text-gray-500 dark:text-gray-400 mb-4">Nu ai niciun credential Cloudflare configurat.</p>
                                <a href="{{ route('cloudflare.credentials.create') }}" class="inline-flex items-center px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white text-sm font-medium rounded-lg transition">
                                    <i class="fas fa-plus mr-2"></i>Adaugă credential
                                </a>
                            </div>
                        @else
                            <form action="{{ route('cloudflare.zones.link.store', $zone) }}" method="POST" id="linkForm">
                                @csrf

                                <!-- Select Credential -->
                                <div class="mb-6">
                                    <label for="credential_id" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Selectează Credential
                                    </label>
                                    <select name="credential_id" id="credential_id"
                                        class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-orange-500 focus:ring-orange-500"
                                        required onchange="loadCloudflareZones()">
                                        <option value="">-- Alege un credential --</option>
                                        @foreach($credentials as $credential)
                                            <option value="{{ $credential->id }}" {{ old('credential_id') == $credential->id ? 'selected' : '' }}>
                                                {{ $credential->name }}
                                                @if(!$credential->is_verified) (Neverificat) @endif
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('credential_id')
                                        <p class="mt-1 text-sm text-red-600 dark:text-red-400">{{ $message }}</p>
                                    @enderror
                                </div>

                                <!-- Select Cloudflare Zone -->
                                <div class="mb-6">
                                    <label for="cloudflare_zone_id" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Selectează Zona din Cloudflare
                                    </label>
                                    <select name="cloudflare_zone_id" id="cloudflare_zone_id"
                                        class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-orange-500 focus:ring-orange-500"
                                        required disabled>
                                        <option value="">-- Selectează mai întâi un credential --</option>
                                    </select>
                                    <div id="zonesLoading" class="hidden mt-2 text-sm text-gray-500 dark:text-gray-400">
                                        <i class="fas fa-spinner fa-spin mr-2"></i>Se încarcă zonele...
                                    </div>
                                    <div id="zonesError" class="hidden mt-2 text-sm text-red-600 dark:text-red-400"></div>
                                    @error('cloudflare_zone_id')
                                        <p class="mt-1 text-sm text-red-600 dark:text-red-400">{{ $message }}</p>
                                    @enderror
                                </div>

                                <!-- Sync Direction -->
                                <div class="mb-6">
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                        Direcția de Sincronizare
                                    </label>
                                    <div class="space-y-3">
                                        <label class="flex items-start p-3 border dark:border-gray-600 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700">
                                            <input type="radio" name="sync_direction" value="to_cloudflare" class="mt-1" {{ old('sync_direction', 'to_cloudflare') == 'to_cloudflare' ? 'checked' : '' }}>
                                            <div class="ml-3">
                                                <span class="font-medium text-gray-900 dark:text-white">
                                                    <i class="fas fa-arrow-right text-orange-500 mr-2"></i>Către Cloudflare
                                                </span>
                                                <p class="text-sm text-gray-500 dark:text-gray-400">Record-urile din sistem vor fi sincronizate în Cloudflare</p>
                                            </div>
                                        </label>
                                        <label class="flex items-start p-3 border dark:border-gray-600 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700">
                                            <input type="radio" name="sync_direction" value="from_cloudflare" class="mt-1" {{ old('sync_direction') == 'from_cloudflare' ? 'checked' : '' }}>
                                            <div class="ml-3">
                                                <span class="font-medium text-gray-900 dark:text-white">
                                                    <i class="fas fa-arrow-left text-blue-500 mr-2"></i>De la Cloudflare
                                                </span>
                                                <p class="text-sm text-gray-500 dark:text-gray-400">Record-urile din Cloudflare vor fi importate în sistem</p>
                                            </div>
                                        </label>
                                        <label class="flex items-start p-3 border dark:border-gray-600 rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700">
                                            <input type="radio" name="sync_direction" value="bidirectional" class="mt-1" {{ old('sync_direction') == 'bidirectional' ? 'checked' : '' }}>
                                            <div class="ml-3">
                                                <span class="font-medium text-gray-900 dark:text-white">
                                                    <i class="fas fa-arrows-alt-h text-purple-500 mr-2"></i>Bidirecțional
                                                </span>
                                                <p class="text-sm text-gray-500 dark:text-gray-400">Sincronizare în ambele direcții (modificările locale și din Cloudflare)</p>
                                            </div>
                                        </label>
                                    </div>
                                    @error('sync_direction')
                                        <p class="mt-1 text-sm text-red-600 dark:text-red-400">{{ $message }}</p>
                                    @enderror
                                </div>

                                <!-- Auto Sync Option -->
                                <div class="mb-6">
                                    <label class="flex items-center">
                                        <input type="checkbox" name="auto_sync" value="1" class="rounded border-gray-300 dark:border-gray-600 text-orange-600 focus:ring-orange-500" {{ old('auto_sync', true) ? 'checked' : '' }}>
                                        <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">
                                            Sincronizare automată la modificări
                                        </span>
                                    </label>
                                    <p class="mt-1 ml-6 text-xs text-gray-500 dark:text-gray-400">
                                        Când este activată, modificările vor fi sincronizate automat conform direcției selectate
                                    </p>
                                </div>

                                <!-- Submit -->
                                <div class="flex justify-end gap-3 pt-4 border-t dark:border-gray-700">
                                    <a href="{{ route('dns-zones.show', $zone->domain) }}" class="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition">
                                        Anulează
                                    </a>
                                    <button type="submit" class="px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white rounded-lg transition">
                                        <i class="fas fa-link mr-2"></i>Conectează Zona
                                    </button>
                                </div>
                            </form>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        async function loadCloudflareZones() {
            const credentialId = document.getElementById('credential_id').value;
            const zoneSelect = document.getElementById('cloudflare_zone_id');
            const loading = document.getElementById('zonesLoading');
            const error = document.getElementById('zonesError');

            if (!credentialId) {
                zoneSelect.innerHTML = '<option value="">-- Selectează mai întâi un credential --</option>';
                zoneSelect.disabled = true;
                return;
            }

            // Show loading
            loading.classList.remove('hidden');
            error.classList.add('hidden');
            zoneSelect.disabled = true;
            zoneSelect.innerHTML = '<option value="">Se încarcă...</option>';

            try {
                const response = await fetch(`{{ route('cloudflare.api.zones') }}?credential_id=${credentialId}`);
                const data = await response.json();

                if (data.success) {
                    if (data.zones.length === 0) {
                        zoneSelect.innerHTML = '<option value="">Nu există zone disponibile</option>';
                    } else {
                        let options = '<option value="">-- Selectează zona --</option>';
                        const targetDomain = '{{ $zone->domain }}'.toLowerCase();

                        data.zones.forEach(zone => {
                            const selected = zone.name.toLowerCase() === targetDomain ? 'selected' : '';
                            options += `<option value="${zone.id}" ${selected}>${zone.name} (${zone.status})</option>`;
                        });
                        zoneSelect.innerHTML = options;
                        zoneSelect.disabled = false;
                    }
                } else {
                    throw new Error(data.error || 'Eroare necunoscută');
                }
            } catch (e) {
                error.textContent = 'Eroare la încărcarea zonelor: ' + e.message;
                error.classList.remove('hidden');
                zoneSelect.innerHTML = '<option value="">Eroare - vezi mesajul de mai jos</option>';
            } finally {
                loading.classList.add('hidden');
            }
        }
    </script>
</x-app-layout>
