<?php if (isset($component)) { $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54 = $attributes; } ?>
<?php $component = App\View\Components\AppLayout::resolve([] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('app-layout'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\App\View\Components\AppLayout::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes([]); ?>
     <?php $__env->slot('title', null, []); ?> Estado ONUs <?php $__env->endSlot(); ?>
     <?php $__env->slot('breadcrumb', null, []); ?> 
        <span class="text-gray-400">Estado ONUs</span>
     <?php $__env->endSlot(); ?>

    <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="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
            </svg>
            Estado de ONUs
        </h1>
        <p class="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
            Consulta el estado de todas las ONUs en un puerto GPON
        </p>
    </div>

    
    <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" onchange="onDeviceChange()">
                        <option value="">— Seleccionar OLT —</option>
                        <?php $__currentLoopData = $devices; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $device): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($device->id); ?>"><?php echo e($device->name); ?> (<?php echo e($device->host); ?>)</option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </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 *</label>
                    <select id="slotSelect" class="input text-sm py-1.5 w-28 font-mono" onchange="onSlotChange()" disabled>
                        <option value="">—</option>
                    </select>
                </div>
            </div>

            
            <div id="slotLoading" class="hidden mt-3">
                <div class="flex items-center gap-2 text-xs text-gray-400">
                    <svg class="w-3.5 h-3.5 animate-spin" 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>
                    Consultando slots de la OLT...
                </div>
            </div>
        </div>
    </div>

    
    <div id="portsGrid" class="hidden mb-5">
        <div class="flex items-center justify-between mb-3">
            <h2 class="text-sm font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                <svg class="w-4 h-4 text-primary-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"/>
                </svg>
                Tarjeta <span id="slotLabel" class="font-mono text-primary-600 dark:text-primary-400"></span> — Puertos PON
            </h2>
            <span class="text-xs text-gray-400">Click en un puerto para ver detalle</span>
        </div>
        <div id="portsContainer" class="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-2"></div>
    </div>

    
    <?php if(auth()->user()->isAdmin()): ?>
    <div id="enablePonCard" class="hidden mb-5">
        <div class="card">
            <div class="card-header cursor-pointer select-none" onclick="document.getElementById('enablePonBody').classList.toggle('hidden')">
                <h3 class="text-sm font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                    <svg class="w-4 h-4 text-yellow-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
                    </svg>
                    Habilitar Puerto PON
                </h3>
                <svg class="w-4 h-4 text-gray-400 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                </svg>
            </div>
            <div id="enablePonBody" class="hidden">
                <div class="px-5 pb-5">
                    <p class="text-xs text-gray-500 dark:text-gray-400 mb-4">
                        Selecciona los puertos PON a habilitar. Se ejecutará <code class="text-xs bg-gray-100 dark:bg-white/10 px-1.5 py-0.5 rounded">no shutdown</code> en la interfaz gpon-olt.
                    </p>
                    <div id="enablePonGrid" class="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-2 mb-4"></div>
                    <div class="flex items-center gap-3">
                        <button onclick="enableSelectedPons()" id="enablePonBtn"
                                class="btn-primary btn-sm flex items-center gap-2" disabled>
                            <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="M13 10V3L4 14h7v7l9-11h-7z"/>
                            </svg>
                            Habilitar seleccionados
                        </button>
                        <span id="enablePonStatus" class="text-xs text-gray-400"></span>
                    </div>
                    <div id="enablePonResults" class="mt-3 space-y-1 hidden"></div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    
    <div id="portsLoading" class="hidden card p-12 text-center mb-5">
        <div class="flex flex-col items-center gap-3">
            <svg class="w-7 h-7 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">Consultando estado de los 16 puertos PON...</p>
            <p class="text-xs text-gray-400">Esto puede tomar varios segundos</p>
        </div>
    </div>

    
    <div id="statsRow" class="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-5 hidden">
        <div class="card p-4 flex items-center gap-3">
            <div class="w-10 h-10 rounded-xl bg-primary-100 dark:bg-primary-900/30 flex items-center justify-center">
                <svg class="w-5 h-5 text-primary-600 dark:text-primary-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 3H5a2 2 0 00-2 2v4m6-6h10a2 2 0 012 2v4M9 3v18"/>
                </svg>
            </div>
            <div>
                <div class="text-2xl font-bold text-gray-900 dark:text-white font-mono" id="statTotal">0</div>
                <div class="text-xs text-gray-400">Total ONUs</div>
            </div>
        </div>
        <div class="card p-4 flex items-center gap-3">
            <div class="w-10 h-10 rounded-xl bg-accent-100 dark:bg-accent-900/30 flex items-center justify-center">
                <span class="w-3 h-3 rounded-full bg-accent-500 animate-pulse-slow"></span>
            </div>
            <div>
                <div class="text-2xl font-bold text-accent-600 dark:text-accent-400 font-mono" id="statOnline">0</div>
                <div class="text-xs text-gray-400">Online</div>
            </div>
        </div>
        <div class="card p-4 flex items-center gap-3">
            <div class="w-10 h-10 rounded-xl bg-red-100 dark:bg-red-900/30 flex items-center justify-center">
                <span class="w-3 h-3 rounded-full bg-red-400"></span>
            </div>
            <div>
                <div class="text-2xl font-bold text-red-500 font-mono" id="statOffline">0</div>
                <div class="text-xs text-gray-400">Offline</div>
            </div>
        </div>
    </div>

    
    <div id="filterRow" class="hidden mb-4">
        <div class="flex flex-wrap gap-3 items-center">
            <div class="relative flex-1 min-w-48 max-w-sm">
                <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="searchInput" placeholder="Buscar por ONU #, SN o tipo..."
                       class="input text-sm py-1.5 pl-9 w-full" oninput="filterTable()">
            </div>
            <select id="stateFilter" class="input text-sm py-1.5 w-40" onchange="filterTable()">
                <option value="">Todos los estados</option>
                <option value="working">Online</option>
                <option value="offline">Offline</option>
            </select>
            <span class="text-xs text-gray-400 font-mono" id="portLabel"></span>
            <span class="text-xs text-gray-400 font-mono hidden" id="queryTimestamp"></span>
        </div>
    </div>

    
    <div id="tableCard" class="hidden card">
        <div class="card-header">
            <h3 class="text-sm font-semibold text-gray-900 dark:text-white">Lista de ONUs</h3>
            <div class="flex items-center gap-2">
                <span class="badge-purple" id="tableCount">0 ONUs</span>
                
                <div class="relative" id="shareMenuWrapper">
                    <button onclick="toggleShareMenu()" id="shareBtn"
                            class="flex items-center gap-1.5 text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200
                                   border border-gray-200 dark:border-white/10 hover:border-gray-300 dark:hover:border-white/20
                                   px-2.5 py-1 rounded-md transition-colors">
                        <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.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z"/>
                        </svg>
                        Compartir
                        <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                        </svg>
                    </button>
                    <div id="shareMenu"
                         class="hidden absolute right-0 top-full mt-1 z-20 w-52
                                bg-white dark:bg-surface-900 rounded-xl shadow-xl
                                border border-gray-200 dark:border-white/10 overflow-hidden">
                        <button onclick="copyData()" class="w-full flex items-center gap-2.5 px-3 py-2.5
                                text-xs text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-white/5 transition-colors">
                            <svg class="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="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                            </svg>
                            Copiar al portapapeles
                        </button>
                        <button onclick="shareWhatsApp()" class="w-full flex items-center gap-2.5 px-3 py-2.5
                                text-xs text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-white/5 transition-colors">
                            <svg class="w-4 h-4 text-accent-500" viewBox="0 0 24 24" fill="currentColor">
                                <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
                            </svg>
                            Enviar por WhatsApp
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <div class="table-wrapper rounded-b-xl overflow-hidden">
            <table class="table">
                <thead>
                    <tr>
                        <th>ONU #</th>
                        <th>Tipo</th>
                        <th>Serial Number</th>
                        <th>Admin</th>
                        <th>Estado</th>
                        <th class="text-center">Detalle</th>
                        <?php if(auth()->user()->isAdmin()): ?>
                        <th class="text-center">Acciones</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody id="statusTableBody">
                </tbody>
            </table>
        </div>
    </div>

    
    
    <div id="statusLoading" class="hidden card p-16 text-center">
        <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">Consultando estado de ONUs...</p>
            <p class="text-xs text-gray-400">Esto puede tomar varios segundos</p>
        </div>
    </div>

    
    <div id="statusError" class="hidden alert-error">
        <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="statusErrorMsg"></span>
    </div>

    
    <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="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                </svg>
            </div>
            <p class="text-sm">Selecciona un <strong>OLT</strong> y un <strong>slot</strong> para ver los puertos PON</p>
        </div>
    </div>

    
    <div id="detailModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 hidden"
         onclick="if(event.target===this) closeDetailModal()">
        <div class="absolute inset-0 bg-black/50 backdrop-blur-sm"></div>
        <div class="relative bg-white dark:bg-surface-800 rounded-2xl shadow-2xl w-full max-w-lg
                    border border-gray-200 dark:border-white/10 overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-100 dark:border-white/5 flex items-center justify-between">
                <h3 class="text-sm font-bold text-gray-900 dark:text-white flex items-center gap-2">
                    <svg class="w-4 h-4 text-primary-500" 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>
                    Detalle ONU <span id="detailOnuId" class="font-mono text-primary-600 dark:text-primary-400"></span>
                </h3>
                <button onclick="closeDetailModal()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200">
                    <svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>
            <div id="detailLoading" class="p-8 text-center hidden">
                <svg class="w-6 h-6 animate-spin text-primary-500 mx-auto" 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-xs text-gray-400 mt-2">Consultando OLT...</p>
            </div>
            <div id="detailContent" class="px-6 py-4 space-y-2 hidden">
                <div class="grid grid-cols-2 gap-3">
                    <div class="bg-gray-50 dark:bg-white/5 rounded-lg p-3">
                        <div class="text-xs text-gray-400 mb-0.5">Nombre / Descripción</div>
                        <div class="text-sm font-medium text-gray-900 dark:text-white" id="detailName">—</div>
                    </div>
                    <div class="bg-gray-50 dark:bg-white/5 rounded-lg p-3">
                        <div class="text-xs text-gray-400 mb-0.5">Distancia</div>
                        <div class="text-sm font-medium text-gray-900 dark:text-white font-mono" id="detailDistance">—</div>
                    </div>
                    <div class="bg-gray-50 dark:bg-white/5 rounded-lg p-3">
                        <div class="text-xs text-gray-400 mb-0.5">Tiempo Online</div>
                        <div class="text-sm font-medium text-gray-900 dark:text-white font-mono" id="detailDuration">—</div>
                    </div>
                    <div class="bg-gray-50 dark:bg-white/5 rounded-lg p-3">
                        <div class="text-xs text-gray-400 mb-0.5">Serial Number</div>
                        <div class="text-sm font-medium text-gray-900 dark:text-white font-mono" id="detailSN">—</div>
                    </div>
                </div>
            </div>
            <div id="detailError" class="px-6 py-4 hidden">
                <div class="alert-red text-xs" id="detailErrorMsg"></div>
            </div>
            <div class="px-6 py-3 border-t border-gray-100 dark:border-white/5 flex justify-end">
                <button onclick="closeDetailModal()" class="btn-ghost btn-sm text-xs">Cerrar</button>
            </div>
        </div>
    </div>

    
    <?php if(auth()->user()->isAdmin()): ?>
    <div id="deleteModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 hidden"
         onclick="if(event.target===this) closeDeleteModal()">
        <div class="absolute inset-0 bg-black/60 backdrop-blur-sm"></div>
        <div id="deletePanel"
             class="relative w-full max-w-md rounded-2xl shadow-2xl
                    bg-white dark:bg-surface-850
                    border border-gray-200/80 dark:border-white/5
                    transform transition-all duration-200 scale-95 opacity-0">
            <div class="flex items-start gap-4 p-6">
                <div class="w-12 h-12 rounded-xl bg-red-100 dark:bg-red-900/30 flex items-center justify-center flex-shrink-0">
                    <svg class="w-6 h-6 text-red-600 dark:text-red-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                              d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                    </svg>
                </div>
                <div class="flex-1 min-w-0">
                    <h3 class="text-base font-semibold text-gray-900 dark:text-white leading-snug">Eliminar ONU</h3>
                    <p class="mt-1.5 text-sm text-gray-600 dark:text-gray-400 leading-relaxed">
                        Esta accion eliminara la ONU de la OLT. <strong class="text-red-500">El cliente perdera el servicio inmediatamente.</strong>
                    </p>

                    
                    <div class="mt-3 rounded-lg bg-gray-50 dark:bg-black/30 border border-gray-200 dark:border-white/5 p-3 space-y-1.5">
                        <div class="flex items-center gap-2 text-xs">
                            <span class="text-gray-400 w-16">ONU #</span>
                            <span class="font-mono font-bold text-gray-900 dark:text-white" id="delOnuId"></span>
                        </div>
                        <div class="flex items-center gap-2 text-xs">
                            <span class="text-gray-400 w-16">SN</span>
                            <span class="font-mono text-gray-600 dark:text-gray-300" id="delOnuSn"></span>
                        </div>
                        <div class="flex items-center gap-2 text-xs">
                            <span class="text-gray-400 w-16">Puerto</span>
                            <span class="font-mono text-gray-600 dark:text-gray-300" id="delOnuPort"></span>
                        </div>
                    </div>

                    
                    <div class="mt-3">
                        <label class="text-xs text-gray-500 dark:text-gray-400">
                            Escribe el numero de ONU (<span class="font-mono font-bold text-red-500" id="delConfirmHint"></span>) para confirmar:
                        </label>
                        <input type="text" id="deleteConfirmInput"
                               class="input text-sm py-1.5 w-full mt-1 font-mono"
                               placeholder="Numero de ONU"
                               oninput="checkDeleteConfirm()">
                    </div>
                </div>
            </div>
            <div class="flex items-center justify-end gap-2 px-6 py-4 border-t border-gray-100 dark:border-white/5">
                <button onclick="closeDeleteModal()" class="btn-ghost btn-sm">Cancelar</button>
                <button id="deleteConfirmBtn" onclick="executeDelete()" disabled
                        class="btn btn-sm bg-red-600 hover:bg-red-500 text-white focus:ring-red-400 disabled:opacity-40 disabled:cursor-not-allowed">
                    <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                    </svg>
                    Eliminar ONU
                </button>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <script>
    const baseUrl = '<?php echo e(url("/")); ?>';
    const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
    const isAdmin = <?php echo e(auth()->user()->isAdmin() ? 'true' : 'false'); ?>;
    let lastStatusData = [];

    // ---- Cascading selectors ----
    function onDeviceChange() {
        const deviceId = document.getElementById('deviceSelect').value;
        const slotSel  = document.getElementById('slotSelect');

        slotSel.innerHTML = '<option value="">—</option>';
        slotSel.disabled = true;
        selectedPort = null;

        // Hide everything
        ['portsGrid', 'portsLoading', 'statsRow', 'filterRow', 'tableCard', 'statusError', 'statusLoading'].forEach(id =>
            document.getElementById(id).classList.add('hidden'));
        document.getElementById('emptyState').classList.remove('hidden');

        if (!deviceId) return;

        document.getElementById('slotLoading').classList.remove('hidden');

        fetch(`${baseUrl}/onu-status/${deviceId}/slots`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
        })
        .then(r => r.json())
        .then(data => {
            document.getElementById('slotLoading').classList.add('hidden');
            if (!data.success) return;

            slotSel.innerHTML = '<option value="">— Slot —</option>';
            data.slots.forEach(s => {
                const opt = document.createElement('option');
                opt.value = s.slot;
                opt.textContent = `Slot ${s.slot}`;
                slotSel.appendChild(opt);
            });
            slotSel.disabled = false;
        })
        .catch(() => document.getElementById('slotLoading').classList.add('hidden'));
    }

    let selectedPort = null;

    function onSlotChange() {
        const slot = document.getElementById('slotSelect').value;

        // Hide detail sections
        ['statsRow', 'filterRow', 'tableCard', 'statusError'].forEach(id =>
            document.getElementById(id).classList.add('hidden'));
        document.getElementById('portsGrid').classList.add('hidden');
        const epCard = document.getElementById('enablePonCard');
        if (epCard) epCard.classList.add('hidden');
        selectedPort = null;

        if (!slot) return;

        document.getElementById('slotLabel').textContent = `Slot ${slot}`;
        fetchPortsSummary();
    }

    function fetchPortsSummary() {
        const deviceId = document.getElementById('deviceSelect').value;
        const frame    = document.getElementById('frame').value || 1;
        const slot     = document.getElementById('slotSelect').value;

        if (!deviceId || !slot) return;

        document.getElementById('portsGrid').classList.add('hidden');
        document.getElementById('emptyState').classList.add('hidden');
        document.getElementById('portsLoading').classList.remove('hidden');

        fetch(`${baseUrl}/onu-status/${deviceId}/ports-summary`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
            body: JSON.stringify({ frame: parseInt(frame), slot: parseInt(slot) })
        })
        .then(r => r.json())
        .then(data => {
            document.getElementById('portsLoading').classList.add('hidden');

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

            buildPortsGrid(data.ports);
            document.getElementById('portsGrid').classList.remove('hidden');
            buildEnablePonGrid();
            const epCard = document.getElementById('enablePonCard');
            if (epCard) epCard.classList.remove('hidden');
        })
        .catch(err => {
            document.getElementById('portsLoading').classList.add('hidden');
            document.getElementById('statusError').classList.remove('hidden');
            document.getElementById('statusErrorMsg').textContent = 'Error: ' + (err.message || '');
        });
    }

    function buildPortsGrid(ports) {
        const container = document.getElementById('portsContainer');
        container.innerHTML = '';

        ports.forEach(p => {
            const hasOnus = p.total > 0;
            const allOnline = hasOnus && p.online === p.total;
            const allOffline = hasOnus && p.offline === p.total;

            let borderClass = 'border-gray-200 dark:border-white/10';
            let bgHover = 'hover:border-gray-300 dark:hover:border-white/20';
            if (hasOnus && allOnline) {
                borderClass = 'border-accent-200 dark:border-accent-800/50';
                bgHover = 'hover:border-accent-400 dark:hover:border-accent-600';
            } else if (hasOnus && allOffline) {
                borderClass = 'border-red-200 dark:border-red-800/50';
                bgHover = 'hover:border-red-400 dark:hover:border-red-600';
            } else if (hasOnus) {
                borderClass = 'border-yellow-200 dark:border-yellow-800/50';
                bgHover = 'hover:border-yellow-400 dark:hover:border-yellow-600';
            }

            const card = document.createElement('div');
            card.className = `card p-3 border ${borderClass} ${bgHover} cursor-pointer transition-all hover:shadow-md group`;
            card.onclick = () => selectPort(p.port);

            card.innerHTML = `
                <div class="flex items-center justify-between mb-2">
                    <span class="text-xs font-bold text-gray-900 dark:text-white font-mono">PON ${p.port}</span>
                    ${hasOnus
                        ? `<span class="w-2 h-2 rounded-full ${allOnline ? 'bg-accent-500 animate-pulse-slow' : allOffline ? 'bg-red-400' : 'bg-yellow-400'}"></span>`
                        : '<span class="w-2 h-2 rounded-full bg-gray-300 dark:bg-gray-600"></span>'}
                </div>
                <div class="text-lg font-bold font-mono text-gray-900 dark:text-white">${p.total}</div>
                <div class="text-xs text-gray-400 mb-1.5">ONUs</div>
                ${hasOnus ? `
                <div class="flex gap-2 text-xs">
                    <span class="text-accent-600 dark:text-accent-400 font-medium">${p.online}<span class="text-gray-400 font-normal"> on</span></span>
                    <span class="text-red-500 font-medium">${p.offline}<span class="text-gray-400 font-normal"> off</span></span>
                </div>
                <div class="mt-1.5 h-1 rounded-full bg-gray-100 dark:bg-white/10 overflow-hidden">
                    <div class="h-full rounded-full bg-accent-500" style="width: ${p.total > 0 ? (p.online / p.total * 100) : 0}%"></div>
                </div>
                ` : '<div class="text-xs text-gray-400">Sin ONUs</div>'}
            `;

            container.appendChild(card);
        });
    }

    // ---- Enable PON ----
    let ponSelection = new Set();

    function buildEnablePonGrid() {
        const grid = document.getElementById('enablePonGrid');
        if (!grid) return;
        grid.innerHTML = '';
        ponSelection.clear();
        updateEnableBtn();

        for (let i = 1; i <= 16; i++) {
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'card p-2.5 border border-gray-200 dark:border-white/10 hover:border-primary-400 dark:hover:border-primary-500 cursor-pointer transition-all text-center';
            btn.dataset.port = i;
            btn.innerHTML = `
                <div class="text-xs font-bold font-mono text-gray-700 dark:text-gray-300">PON ${i}</div>
                <div class="mt-1">
                    <span class="pon-check hidden text-primary-500">
                        <svg class="w-4 h-4 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"/>
                        </svg>
                    </span>
                    <span class="pon-uncheck text-gray-300 dark:text-gray-600">
                        <svg class="w-4 h-4 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 6v12m6-6H6"/>
                        </svg>
                    </span>
                </div>
            `;
            btn.onclick = () => togglePonSelect(btn, i);
            grid.appendChild(btn);
        }
    }

    function togglePonSelect(btn, port) {
        if (ponSelection.has(port)) {
            ponSelection.delete(port);
            btn.classList.remove('ring-2', 'ring-primary-500', 'border-primary-400');
            btn.querySelector('.pon-check').classList.add('hidden');
            btn.querySelector('.pon-uncheck').classList.remove('hidden');
        } else {
            ponSelection.add(port);
            btn.classList.add('ring-2', 'ring-primary-500', 'border-primary-400');
            btn.querySelector('.pon-check').classList.remove('hidden');
            btn.querySelector('.pon-uncheck').classList.add('hidden');
        }
        updateEnableBtn();
    }

    function updateEnableBtn() {
        const btn = document.getElementById('enablePonBtn');
        if (!btn) return;
        btn.disabled = ponSelection.size === 0;
        btn.textContent = ponSelection.size > 0
            ? `Habilitar ${ponSelection.size} puerto${ponSelection.size > 1 ? 's' : ''}`
            : 'Habilitar seleccionados';
    }

    async function enableSelectedPons() {
        const deviceId = document.getElementById('deviceSelect').value;
        const frame    = document.getElementById('frame').value || 1;
        const slot     = document.getElementById('slotSelect').value;
        const ports    = [...ponSelection].sort((a, b) => a - b);

        if (!deviceId || !slot || ports.length === 0) return;

        const btn = document.getElementById('enablePonBtn');
        const statusEl = document.getElementById('enablePonStatus');
        const resultsEl = document.getElementById('enablePonResults');

        btn.disabled = true;
        btn.innerHTML = '<svg class="w-4 h-4 animate-spin" 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> Procesando...';
        resultsEl.innerHTML = '';
        resultsEl.classList.remove('hidden');

        let ok = 0, fail = 0;

        for (const port of ports) {
            statusEl.textContent = `Habilitando PON ${port} de ${ports.length}...`;
            try {
                const resp = await fetch(`${baseUrl}/onu-status/${deviceId}/enable-pon`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
                    body: JSON.stringify({ frame: parseInt(frame), slot: parseInt(slot), port: parseInt(port) })
                });
                const data = await resp.json();

                const div = document.createElement('div');
                if (data.success) {
                    ok++;
                    div.className = 'flex items-center gap-2 text-xs text-accent-600 dark:text-accent-400';
                    div.innerHTML = `<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.5" d="M5 13l4 4L19 7"/></svg> PON ${port}: ${data.message}`;
                } else {
                    fail++;
                    div.className = 'flex items-center gap-2 text-xs text-red-500';
                    div.innerHTML = `<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.5" d="M6 18L18 6M6 6l12 12"/></svg> PON ${port}: ${data.message}`;
                }
                resultsEl.appendChild(div);
            } catch (e) {
                fail++;
                const div = document.createElement('div');
                div.className = 'flex items-center gap-2 text-xs text-red-500';
                div.innerHTML = `<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.5" d="M6 18L18 6M6 6l12 12"/></svg> PON ${port}: Error de conexión`;
                resultsEl.appendChild(div);
            }
        }

        statusEl.textContent = `Completado: ${ok} exitoso${ok !== 1 ? 's' : ''}, ${fail} error${fail !== 1 ? 'es' : ''}`;
        btn.innerHTML = `<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="M13 10V3L4 14h7v7l9-11h-7z"/></svg> Habilitar seleccionados`;
        btn.disabled = false;
        ponSelection.clear();
        buildEnablePonGrid();
    }

    function selectPort(port) {
        selectedPort = port;

        // Highlight selected card
        document.querySelectorAll('#portsContainer > div').forEach((card, i) => {
            if (i + 1 === port) {
                card.classList.add('ring-2', 'ring-primary-500', 'dark:ring-primary-400');
            } else {
                card.classList.remove('ring-2', 'ring-primary-500', 'dark:ring-primary-400');
            }
        });

        fetchOnuStatus();
    }

    // ---- State helpers ----
    function phaseHtml(phase) {
        if (phase === 'working') return '<span class="badge-green"><span class="w-1 h-1 rounded-full bg-accent-500 animate-pulse-slow"></span> Online</span>';
        if (phase === 'DyingGasp') return '<span class="badge-yellow">DyingGasp</span>';
        if (phase === 'LOS') return '<span class="badge-red">LOS</span>';
        if (phase === 'unknown') return '<span class="badge-gray">Desconocido</span>';
        return '<span class="badge-red">' + phase + '</span>';
    }

    function adminHtml(admin) {
        if (admin === 'enable') return '<span class="text-accent-600 dark:text-accent-400 text-xs font-medium">Enable</span>';
        if (admin === 'disable') return '<span class="text-red-500 text-xs font-medium">Disable</span>';
        return '<span class="text-gray-400 text-xs">' + admin + '</span>';
    }

    // ---- Build table ----
    function buildTable(onus) {
        const tbody = document.getElementById('statusTableBody');
        tbody.innerHTML = '';

        onus.forEach(onu => {
            const tr = document.createElement('tr');
            tr.dataset.search = `${onu.onu_id} ${onu.sn} ${onu.type}`.toLowerCase();
            tr.dataset.phase = onu.phase;

            let actionCol = '';
            if (isAdmin) {
                actionCol = `
                    <td class="text-center">
                        <button onclick="openDeleteModal(${onu.onu_id}, '${onu.sn}')"
                                class="inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium
                                       text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20
                                       border border-red-200 dark:border-red-800/50 transition-colors"
                                title="Eliminar ONU ${onu.onu_id}">
                            <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                      d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                            </svg>
                            Eliminar
                        </button>
                    </td>`;
            }

            tr.innerHTML = `
                <td><span class="badge-gray font-mono">${onu.onu_id}</span></td>
                <td><span class="text-sm text-gray-700 dark:text-gray-300">${onu.type}</span></td>
                <td><span class="font-mono text-xs text-gray-600 dark:text-gray-400">${onu.sn}</span></td>
                <td>${adminHtml(onu.admin)}</td>
                <td>${phaseHtml(onu.phase)}</td>
                <td class="text-center">
                    <button onclick="fetchOnuDetail(${onu.onu_id})"
                            class="inline-flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium
                                   text-primary-600 dark:text-primary-400 hover:bg-primary-50 dark:hover:bg-primary-900/20
                                   border border-primary-200 dark:border-primary-800/50 transition-colors"
                            id="detailBtn_${onu.onu_id}">
                        <svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                        </svg>
                        Ver
                    </button>
                </td>
                ${actionCol}
            `;

            tbody.appendChild(tr);
        });
    }

    // ---- Filter ----
    function filterTable() {
        const search = document.getElementById('searchInput').value.toLowerCase();
        const stateFilter = document.getElementById('stateFilter').value;
        const rows = document.querySelectorAll('#statusTableBody tr');

        rows.forEach(row => {
            const matchSearch = !search || row.dataset.search.includes(search);
            let matchState = true;
            if (stateFilter === 'working') matchState = row.dataset.phase === 'working';
            else if (stateFilter === 'offline') matchState = row.dataset.phase !== 'working';

            row.style.display = (matchSearch && matchState) ? '' : 'none';
        });
    }

    // ---- Copy MAC ----
    function copyMac(el, mac) {
        navigator.clipboard.writeText(mac).then(() => {
            const orig = el.textContent;
            el.textContent = 'Copiado!';
            el.classList.add('text-accent-500');
            setTimeout(() => { el.textContent = orig; el.classList.remove('text-accent-500'); }, 1500);
        });
    }

    // ---- Share ----
    function buildShareText() {
        const port  = document.getElementById('portLabel').textContent || '';
        const date  = new Date().toLocaleString('es-SV', { day: '2-digit', month: '2-digit', year: '2-digit', hour: 'numeric', minute: '2-digit', hour12: true });
        const total = document.getElementById('statTotal').textContent;
        const online= document.getElementById('statOnline').textContent;
        const offline=document.getElementById('statOffline').textContent;

        const rows = lastStatusData.map(onu => {
            const st = onu.phase === 'working' ? '✅' : '❌';
            return `ONU ${onu.onu_id}: ${st} ${onu.sn} | ${onu.type}`;
        }).join('\n');

        return `📋 Estado ONUs — ${port}\n📅 ${date}\n📊 Total: ${total} | Online: ${online} | Offline: ${offline}\n\n${rows}`;
    }

    function toggleShareMenu() {
        const menu = document.getElementById('shareMenu');
        menu.classList.toggle('hidden');
        setTimeout(() => {
            document.addEventListener('click', closeShareMenu, { once: true });
        }, 0);
    }

    function closeShareMenu(e) {
        const wrapper = document.getElementById('shareMenuWrapper');
        if (!wrapper.contains(e.target)) {
            document.getElementById('shareMenu').classList.add('hidden');
        }
    }

    function copyData() {
        document.getElementById('shareMenu').classList.add('hidden');
        const text = buildShareText();
        navigator.clipboard.writeText(text).then(() => {
            const btn = document.getElementById('shareBtn');
            const orig = btn.innerHTML;
            btn.innerHTML = '<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="M5 13l4 4L19 7"/></svg> Copiado!';
            btn.classList.add('text-accent-500');
            setTimeout(() => { btn.innerHTML = orig; btn.classList.remove('text-accent-500'); }, 2000);
        });
    }

    function shareWhatsApp() {
        document.getElementById('shareMenu').classList.add('hidden');
        const text = encodeURIComponent(buildShareText());
        window.open(`https://api.whatsapp.com/send?text=${text}`, '_blank');
    }

    // ---- Delete ONU (admin only) ----
    // ---- ONU Detail ----
    async function fetchOnuDetail(onuId) {
        const deviceId = document.getElementById('deviceSelect').value;
        const frame    = document.getElementById('frame').value || 1;
        const slot     = document.getElementById('slotSelect').value;
        const port     = selectedPort;

        if (!deviceId || !slot || !port) return;

        // Find SN from table data
        const onu = lastStatusData.find(o => o.onu_id === onuId);

        document.getElementById('detailOnuId').textContent = `#${onuId}`;
        document.getElementById('detailSN').textContent = onu?.sn || '—';
        document.getElementById('detailLoading').classList.remove('hidden');
        document.getElementById('detailContent').classList.add('hidden');
        document.getElementById('detailError').classList.add('hidden');
        document.getElementById('detailModal').classList.remove('hidden');

        try {
            const resp = await fetch(`${baseUrl}/onu-status/${deviceId}/onu-detail`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
                body: JSON.stringify({ frame: parseInt(frame), slot: parseInt(slot), port: parseInt(port), onu_number: onuId })
            });
            const data = await resp.json();

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

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

            document.getElementById('detailName').textContent = data.detail.name || '—';
            document.getElementById('detailDistance').textContent = data.detail.distance || '—';
            document.getElementById('detailDuration').textContent = data.detail.duration || '—';
            document.getElementById('detailContent').classList.remove('hidden');
        } catch(e) {
            document.getElementById('detailLoading').classList.add('hidden');
            document.getElementById('detailError').classList.remove('hidden');
            document.getElementById('detailErrorMsg').textContent = 'Error: ' + e.message;
        }
    }

    function closeDetailModal() {
        document.getElementById('detailModal').classList.add('hidden');
    }

    // ---- Delete ONU ----
    let deleteTarget = null;

    function openDeleteModal(onuId, sn) {
        deleteTarget = { onuId, sn };

        document.getElementById('delOnuId').textContent = onuId;
        document.getElementById('delOnuSn').textContent = sn;
        document.getElementById('delOnuPort').textContent = document.getElementById('portLabel').textContent;
        document.getElementById('delConfirmHint').textContent = onuId;
        document.getElementById('deleteConfirmInput').value = '';
        document.getElementById('deleteConfirmBtn').disabled = true;

        const modal = document.getElementById('deleteModal');
        const panel = document.getElementById('deletePanel');
        modal.classList.remove('hidden');
        requestAnimationFrame(() => { panel.style.transform = 'scale(1)'; panel.style.opacity = '1'; });

        // Focus the input
        setTimeout(() => document.getElementById('deleteConfirmInput').focus(), 200);
    }

    function closeDeleteModal() {
        const modal = document.getElementById('deleteModal');
        const panel = document.getElementById('deletePanel');
        panel.style.transform = 'scale(0.95)';
        panel.style.opacity = '0';
        setTimeout(() => modal.classList.add('hidden'), 180);
        deleteTarget = null;
    }

    function checkDeleteConfirm() {
        const input = document.getElementById('deleteConfirmInput').value.trim();
        const btn = document.getElementById('deleteConfirmBtn');
        btn.disabled = !deleteTarget || input !== String(deleteTarget.onuId);
    }

    function executeDelete() {
        if (!deleteTarget) return;

        const deviceId = document.getElementById('deviceSelect').value;
        const frame    = document.getElementById('frame').value || 1;
        const slot     = document.getElementById('slotSelect').value;
        const port     = selectedPort;
        const onuId    = deleteTarget.onuId;

        const btn = document.getElementById('deleteConfirmBtn');
        const origHtml = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<svg class="w-3.5 h-3.5 animate-spin" 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> Eliminando...';

        fetch(`${baseUrl}/onu-status/${deviceId}/delete-onu`, {
            method: 'DELETE',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
            body: JSON.stringify({
                frame: parseInt(frame),
                slot: parseInt(slot),
                port: parseInt(port),
                onu_number: onuId
            })
        })
        .then(r => r.json())
        .then(data => {
            closeDeleteModal();

            if (data.success) {
                showModal({
                    type: 'success',
                    title: 'ONU Eliminada',
                    message: data.message,
                });
                // Refresh the table
                fetchOnuStatus();
            } else {
                showModal({
                    type: 'error',
                    title: 'Error al eliminar',
                    message: data.message,
                    detail: data.detail || '',
                });
            }
        })
        .catch(err => {
            closeDeleteModal();
            showModal({
                type: 'error',
                title: 'Error de conexion',
                message: err.message || 'No se pudo conectar con el servidor.',
            });
        });
    }

    // Close delete modal with Escape
    document.addEventListener('keydown', e => {
        if (e.key === 'Escape' && deleteTarget) closeDeleteModal();
    });

    // ---- Main fetch ----
    function fetchOnuStatus() {
        const deviceId = document.getElementById('deviceSelect').value;
        const frame    = document.getElementById('frame').value || 1;
        const slot     = document.getElementById('slotSelect').value;
        const port     = selectedPort;

        if (!deviceId || !slot || !port) return;

        // UI states
        ['emptyState', 'statusError', 'statsRow', 'filterRow', 'tableCard'].forEach(id =>
            document.getElementById(id).classList.add('hidden'));
        document.getElementById('statusLoading').classList.remove('hidden');

        fetch(`${baseUrl}/onu-status/${deviceId}/status`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken, 'Accept': 'application/json' },
            body: JSON.stringify({ frame: parseInt(frame), slot: parseInt(slot), port: parseInt(port) })
        })
        .then(r => r.json())
        .then(data => {
            document.getElementById('statusLoading').classList.add('hidden');
            if (!data.success) {
                document.getElementById('statusError').classList.remove('hidden');
                document.getElementById('statusErrorMsg').textContent = data.message;
                return;
            }

            // Stats
            document.getElementById('statTotal').textContent  = data.stats.total;
            document.getElementById('statOnline').textContent = data.stats.online;
            document.getElementById('statOffline').textContent = data.stats.offline;
            document.getElementById('statsRow').classList.remove('hidden');

            // Port label & timestamp
            document.getElementById('portLabel').textContent = `gpon-olt_${frame}/${slot}/${port}`;
            const tsEl = document.getElementById('queryTimestamp');
            tsEl.textContent = new Date().toLocaleString('es-SV', { day: '2-digit', month: '2-digit', year: '2-digit', hour: 'numeric', minute: '2-digit', second: '2-digit', hour12: true });
            tsEl.classList.remove('hidden');

            // Filter row
            document.getElementById('filterRow').classList.remove('hidden');
            document.getElementById('searchInput').value = '';
            document.getElementById('stateFilter').value = '';

            // Table
            lastStatusData = data.onus;
            document.getElementById('tableCount').textContent = `${data.stats.total} ONUs`;
            buildTable(data.onus);
            document.getElementById('tableCard').classList.remove('hidden');
        })
        .catch(err => {
            document.getElementById('statusLoading').classList.add('hidden');
            document.getElementById('statusError').classList.remove('hidden');
            document.getElementById('statusErrorMsg').textContent = 'Error: ' + (err.message || '');
        });
    }
    </script>
 <?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $attributes = $__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__attributesOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54)): ?>
<?php $component = $__componentOriginal9ac128a9029c0e4701924bd2d73d7f54; ?>
<?php unset($__componentOriginal9ac128a9029c0e4701924bd2d73d7f54); ?>
<?php endif; ?>
<?php /**PATH C:\xampp\htdocs\adminolt\resources\views/onu-status/index.blade.php ENDPATH**/ ?>