<x-app-layout>
    <x-slot name="title">Buscar ONU</x-slot>
    <x-slot name="breadcrumb">
        <span class="text-gray-400">Buscar ONU por Serial Number</span>
    </x-slot>

    <div class="mb-6">
        <h1 class="text-xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
            <svg class="w-5 h-5 text-primary-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
            </svg>
            Buscar ONU por Serial Number
        </h1>
        <p class="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
            Localiza una ONU en cualquier puerto de la OLT ingresando su número de serie
        </p>
    </div>

    {{-- Search form --}}
    <div class="card mb-5">
        <div class="card-body py-5">
            <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 }}">{{ $device->name }} ({{ $device->host }})</option>
                        @endforeach
                    </select>
                </div>
                <div class="flex-1 min-w-64">
                    <label class="label text-xs">Serial Number *</label>
                    <div class="relative">
                        <svg class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                        </svg>
                        <input type="text" id="snInput" placeholder="Ej: ZTEGDA1966EA"
                               class="input text-sm py-1.5 pl-9 w-full font-mono uppercase"
                               maxlength="20" onkeydown="if(event.key==='Enter') doSearch()">
                    </div>
                </div>
                <button onclick="doSearch()" id="searchBtn" class="btn-primary btn-sm flex items-center gap-2">
                    <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                    </svg>
                    Buscar
                </button>
            </div>
            <p class="text-xs text-gray-400 mt-3 flex items-center gap-1">
                <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="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                La busqueda escanea todos los puertos de la OLT. Puede tomar hasta 2 minutos.
            </p>
        </div>
    </div>

    {{-- Loading --}}
    <div id="searchLoading" class="hidden card p-16 text-center mb-5">
        <div class="flex flex-col items-center gap-3">
            <svg class="w-8 h-8 animate-spin text-primary-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">Buscando ONU en la OLT...</p>
            <p class="text-xs text-gray-400">Escaneando todos los slots y puertos. Esto puede tomar un momento.</p>
        </div>
    </div>

    {{-- Error --}}
    <div id="searchError" class="hidden mb-5">
        <div class="alert-red">
            <svg class="w-4 h-4 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 id="searchErrorMsg"></span>
        </div>
    </div>

    {{-- Not found --}}
    <div id="notFound" class="hidden card p-12 text-center mb-5">
        <div class="flex flex-col items-center gap-3 text-gray-400">
            <svg class="w-12 h-12 opacity-30" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            <p class="text-sm font-medium text-gray-500 dark:text-gray-400">ONU no encontrada</p>
            <p class="text-xs text-gray-400" id="notFoundMsg"></p>
        </div>
    </div>

    {{-- Result --}}
    <div id="resultCard" class="hidden">
        {{-- Location header --}}
        <div class="card mb-4">
            <div class="card-body py-5">
                <div class="flex items-center justify-between flex-wrap gap-3">
                    <div>
                        <div class="text-xs text-gray-400 mb-1">ONU encontrada en</div>
                        <div class="text-2xl font-bold font-mono text-primary-600 dark:text-primary-400" id="resLocation"></div>
                    </div>
                    <div class="flex items-center gap-2">
                        <span id="resTimestamp" class="text-xs text-gray-400 font-mono"></span>
                        <span id="resPhaseBadge"></span>
                    </div>
                </div>
            </div>
        </div>

        {{-- Detail grid --}}
        <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 mb-5">
            <div class="card p-4">
                <div class="text-xs text-gray-400 mb-1">Tipo</div>
                <div class="text-sm font-bold text-gray-900 dark:text-white" id="resType">—</div>
            </div>
            <div class="card p-4">
                <div class="text-xs text-gray-400 mb-1">Serial Number</div>
                <div class="text-sm font-bold text-gray-900 dark:text-white font-mono" id="resSN">—</div>
            </div>
            <div class="card p-4">
                <div class="text-xs text-gray-400 mb-1">Admin</div>
                <div class="text-sm font-bold" id="resAdmin">—</div>
            </div>
            <div class="card p-4">
                <div class="text-xs text-gray-400 mb-1">Estado</div>
                <div class="text-sm font-bold" id="resPhase">—</div>
            </div>
            <div class="card p-4">
                <div class="text-xs text-gray-400 mb-1">OLT Rx (Potencia)</div>
                <div class="text-sm font-bold font-mono" id="resPower">—</div>
            </div>
        </div>
    </div>

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

    async function doSearch() {
        const deviceId = document.getElementById('deviceSelect').value;
        const sn       = document.getElementById('snInput').value.trim();

        if (!deviceId) { alert('Selecciona un dispositivo OLT'); return; }
        if (!sn || sn.length < 4) { alert('Ingresa un Serial Number válido (mínimo 4 caracteres)'); return; }

        // UI reset
        ['searchError', 'notFound', 'resultCard'].forEach(id => document.getElementById(id).classList.add('hidden'));
        document.getElementById('searchLoading').classList.remove('hidden');
        document.getElementById('searchBtn').disabled = true;

        try {
            const resp = await fetch(`${baseUrl}/onu-search/${deviceId}/search`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
                body: JSON.stringify({ serial_number: sn })
            });
            const data = await resp.json();

            document.getElementById('searchLoading').classList.add('hidden');

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

            if (!data.found) {
                document.getElementById('notFound').classList.remove('hidden');
                document.getElementById('notFoundMsg').textContent =
                    `El SN "${sn.toUpperCase()}" no fue encontrado en ningún puerto de esta OLT.`;
                return;
            }

            // Show result
            const onu = data.onu;
            document.getElementById('resLocation').textContent =
                `gpon-olt_${onu.frame}/${onu.slot}/${onu.port}:${onu.onu_id}`;
            document.getElementById('resType').textContent = onu.type || '—';
            document.getElementById('resSN').textContent = onu.sn || '—';

            // Admin
            const adminEl = document.getElementById('resAdmin');
            if (onu.admin === 'enable') {
                adminEl.innerHTML = '<span class="text-accent-600 dark:text-accent-400">Enable</span>';
            } else {
                adminEl.innerHTML = `<span class="text-red-500">${onu.admin}</span>`;
            }

            // Phase
            const phaseEl = document.getElementById('resPhase');
            const badgeEl = document.getElementById('resPhaseBadge');
            if (onu.phase === 'working') {
                phaseEl.innerHTML = '<span class="text-accent-600 dark:text-accent-400">Working</span>';
                badgeEl.innerHTML = '<span class="badge-green"><span class="w-1.5 h-1.5 rounded-full bg-accent-500 animate-pulse-slow"></span> Online</span>';
            } else {
                phaseEl.innerHTML = `<span class="text-red-500">${onu.phase}</span>`;
                badgeEl.innerHTML = `<span class="badge-red">${onu.phase}</span>`;
            }

            // Power
            const powerEl = document.getElementById('resPower');
            if (onu.olt_rx) {
                const val = parseFloat(onu.olt_rx);
                let cls = 'text-accent-600 dark:text-accent-400';
                if (val < -28) cls = 'text-red-500';
                else if (val < -25) cls = 'text-yellow-500';
                powerEl.innerHTML = `<span class="${cls}">${onu.olt_rx} dBm</span>`;
            } else {
                powerEl.innerHTML = '<span class="text-gray-400">N/A</span>';
            }

            // Timestamp
            document.getElementById('resTimestamp').textContent =
                new Date().toLocaleString('es-SV', { day: '2-digit', month: '2-digit', year: '2-digit', hour: 'numeric', minute: '2-digit', hour12: true });

            document.getElementById('resultCard').classList.remove('hidden');
        } catch(e) {
            document.getElementById('searchLoading').classList.add('hidden');
            document.getElementById('searchError').classList.remove('hidden');
            document.getElementById('searchErrorMsg').textContent = 'Error: ' + (e.message || '');
        } finally {
            document.getElementById('searchBtn').disabled = false;
        }
    }
    </script>
</x-app-layout>
