<x-app-layout>
    <x-slot name="title">ONUs Rogue</x-slot>
    <x-slot name="breadcrumb">
        <span class="text-gray-400">ONUs No Autorizadas</span>
    </x-slot>

    <div class="mb-6">
        <h1 class="text-xl font-bold text-gray-900 dark:text-white">ONUs No Autorizadas
            <span class="text-yellow-500 ml-1">⚠</span>
        </h1>
        <p class="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
            Equipos conectados en la red que aún no han sido configurados
        </p>
    </div>

    {{-- Filter --}}
    <div class="card mb-5">
        <div class="card-body py-4">
            <div class="flex flex-wrap gap-3 items-end">
                <div>
                    <label class="label text-xs">Dispositivo OLT *</label>
                    <select id="deviceSelect" class="input text-sm py-1.5 min-w-56">
                        <option value="">— Seleccionar OLT —</option>
                        @foreach($devices as $device)
                            <option value="{{ $device->id }}"
                                    data-name="{{ $device->name }}"
                                    data-host="{{ $device->host }}">
                                {{ $device->name }} ({{ $device->host }})
                            </option>
                        @endforeach
                    </select>
                </div>
                <div>
                    <label class="label text-xs">Frame</label>
                    <input type="number" id="frame" value="1" min="1"
                           class="input text-sm py-1.5 w-20 font-mono">
                </div>
                <div>
                    <label class="label text-xs">Slot <span class="text-gray-400 font-normal">(opcional)</span></label>
                    <input type="number" id="slot" min="1"
                           class="input text-sm py-1.5 w-24 font-mono" placeholder="Todos">
                </div>
                <div>
                    <label class="label text-xs">Puerto <span class="text-gray-400 font-normal">(opcional)</span></label>
                    <input type="number" id="port" min="1"
                           class="input text-sm py-1.5 w-24 font-mono" placeholder="Todos">
                </div>
                <button onclick="queryRogue()" id="queryBtn"
                        class="btn btn-sm bg-yellow-500 hover:bg-yellow-400 text-white focus:ring-yellow-400">
                    <svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                              d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"/>
                    </svg>
                    Consultar OLT
                </button>
            </div>
        </div>
    </div>

    {{-- Error --}}
    <div id="errorBox" class="hidden alert-error mb-4">
        <svg class="w-5 h-5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
        </svg>
        <span class="text-sm" id="errorMsg"></span>
    </div>

    {{-- Loading --}}
    <div id="loadingBox" class="hidden card p-12 text-center mb-4">
        <div class="flex flex-col items-center gap-3">
            <svg class="w-8 h-8 animate-spin text-yellow-500" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
            </svg>
            <p class="text-sm text-gray-500 dark:text-gray-400">Consultando ONUs no autorizadas en la OLT...</p>
        </div>
    </div>

    {{-- Results --}}
    <div id="resultsBox" class="hidden card">
        <div class="card-header">
            <div class="flex items-center gap-3">
                <div class="w-8 h-8 rounded-lg bg-yellow-100 dark:bg-yellow-900/30 flex items-center justify-center">
                    <svg class="w-4 h-4 text-yellow-600 dark:text-yellow-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                              d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
                    </svg>
                </div>
                <div>
                    <span class="font-semibold text-gray-900 dark:text-white" id="resultDeviceName"></span>
                    <code class="text-xs text-gray-400 ml-2" id="resultDeviceHost"></code>
                </div>
            </div>
            <span id="resultBadge"></span>
        </div>

        {{-- Table --}}
        <div id="tableWrapper" class="hidden table-wrapper rounded-b-xl overflow-hidden">
            <table class="table">
                <thead>
                    <tr>
                        <th>Interfaz</th>
                        <th>ONU ID</th>
                        <th>Serial Number</th>
                        <th>Estado</th>
                        <th class="text-right">Acción</th>
                    </tr>
                </thead>
                <tbody id="rogueTableBody"></tbody>
            </table>
        </div>

        {{-- Empty --}}
        <div id="emptyResult" class="hidden p-16 text-center">
            <div class="flex flex-col items-center gap-3">
                <div class="w-16 h-16 rounded-full bg-accent-100 dark:bg-accent-900/30 flex items-center justify-center">
                    <svg class="w-8 h-8 text-accent-600 dark:text-accent-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                </div>
                <div>
                    <p class="font-semibold text-gray-700 dark:text-gray-300">Todo en orden</p>
                    <p class="text-sm text-gray-400 mt-1">No se encontraron ONUs no autorizadas.</p>
                </div>
            </div>
        </div>
    </div>

    {{-- Initial empty state --}}
    <div id="emptyState" class="card p-16 text-center">
        <div class="flex flex-col items-center gap-3 text-gray-400">
            <div class="w-16 h-16 rounded-full bg-gray-100 dark:bg-white/5 flex items-center justify-center">
                <svg class="w-8 h-8 opacity-50" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                          d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"/>
                </svg>
            </div>
            <p class="text-sm">Selecciona un dispositivo OLT y haz clic en <strong>"Consultar OLT"</strong></p>
        </div>
    </div>

    <script>
    const baseUrl    = '{{ url("/") }}';
    const csrfToken  = document.querySelector('meta[name="csrf-token"]').content;
    const createUrl  = '{{ route("onus.create") }}';

    function queryRogue() {
        const deviceId   = document.getElementById('deviceSelect').value;
        const deviceOpt  = document.querySelector(`#deviceSelect option[value="${deviceId}"]`);
        const frame      = document.getElementById('frame').value || 1;
        const slot       = document.getElementById('slot').value;
        const port       = document.getElementById('port').value;

        if (!deviceId) {
            alert('Selecciona un dispositivo OLT.');
            return;
        }

        // UI: hide all, show loader
        ['emptyState', 'errorBox', 'resultsBox'].forEach(id => document.getElementById(id).classList.add('hidden'));
        document.getElementById('loadingBox').classList.remove('hidden');
        document.getElementById('queryBtn').disabled = true;

        const body = { frame: parseInt(frame) };
        if (slot) body.slot = parseInt(slot);
        if (port) body.port = parseInt(port);

        fetch(`${baseUrl}/rogue/${deviceId}/query`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
            body: JSON.stringify(body),
        })
        .then(r => r.json())
        .then(data => {
            document.getElementById('loadingBox').classList.add('hidden');
            document.getElementById('queryBtn').disabled = false;

            if (!data.success) {
                document.getElementById('errorMsg').textContent = data.message;
                document.getElementById('errorBox').classList.remove('hidden');
                return;
            }

            // Header info
            document.getElementById('resultDeviceName').textContent = data.device.name;
            document.getElementById('resultDeviceHost').textContent = data.device.host;

            const onus = data.onus;

            // Badge
            const badge = document.getElementById('resultBadge');
            if (onus.length > 0) {
                badge.innerHTML = `<span class="badge bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400">${onus.length} no autorizada(s)</span>`;
            } else {
                badge.innerHTML = '<span class="badge-green">Sin rogue ONUs</span>';
            }

            // Table or empty
            if (onus.length > 0) {
                const tbody = document.getElementById('rogueTableBody');
                tbody.innerHTML = '';
                onus.forEach(r => {
                    const iface = (r.frame && r.slot && r.port)
                        ? `<code class="text-xs font-mono text-gray-500 dark:text-gray-400">gpon-olt_${r.frame}/${r.slot}/${r.port}</code>`
                        : '<span class="text-gray-400">—</span>';

                    // Build authorize URL
                    const params = new URLSearchParams({
                        device_id: data.device.id,
                        sn: r.sn,
                        frame: r.frame || frame,
                        ...(r.slot ? { slot: r.slot } : {}),
                        ...(r.port ? { port: r.port } : {}),
                    });

                    const tr = document.createElement('tr');
                    tr.className = 'hover:bg-yellow-50/50 dark:hover:bg-yellow-900/5';
                    tr.innerHTML = `
                        <td>${iface}</td>
                        <td><span class="badge-gray font-mono">${r.onu_id}</span></td>
                        <td><code class="text-sm font-mono font-bold text-yellow-700 dark:text-yellow-400 bg-yellow-50 dark:bg-yellow-900/20 px-2 py-0.5 rounded">${r.sn}</code></td>
                        <td><span class="badge-yellow">${r.state}</span></td>
                        <td class="text-right">
                            <a href="${createUrl}?${params}"
                               class="btn-accent btn-sm inline-flex items-center gap-1.5">
                                <svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                          d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                </svg>
                                Autorizar
                            </a>
                        </td>
                    `;
                    tbody.appendChild(tr);
                });
                document.getElementById('tableWrapper').classList.remove('hidden');
                document.getElementById('emptyResult').classList.add('hidden');
            } else {
                document.getElementById('tableWrapper').classList.add('hidden');
                document.getElementById('emptyResult').classList.remove('hidden');
            }

            document.getElementById('resultsBox').classList.remove('hidden');
        })
        .catch(err => {
            document.getElementById('loadingBox').classList.add('hidden');
            document.getElementById('queryBtn').disabled = false;
            document.getElementById('errorMsg').textContent = 'Error: ' + (err.message || 'Error desconocido');
            document.getElementById('errorBox').classList.remove('hidden');
        });
    }
    </script>
</x-app-layout>
