<x-app-layout>
    <x-slot name="title">Backup Config</x-slot>
    <x-slot name="breadcrumb">
        <span class="text-gray-400">Backup Config</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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
            </svg>
            Backup de Configuraci&oacute;n de ONUs
        </h1>
        <p class="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
            Exporta la running-config de puertos GPON individuales o de un slot completo
        </p>
    </div>

    {{-- Selector --}}
    <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>
                        @foreach($devices as $device)
                            <option value="{{ $device->id }}">{{ $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 *</label>
                    <select id="slotSelect" class="input text-sm py-1.5 w-28 font-mono" onchange="onSlotChange()" disabled>
                        <option value="">—</option>
                    </select>
                </div>
                <div>
                    <label class="label text-xs">Puerto</label>
                    <select id="portSelect" class="input text-sm py-1.5 w-28 font-mono" disabled>
                        <option value="">— Todos —</option>
                    </select>
                </div>
                <button onclick="backupPort()" id="btnBackupPort" disabled
                        class="btn btn-sm bg-primary-600 hover:bg-primary-500 text-white focus:ring-primary-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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
                    </svg>
                    Backup Puerto
                </button>
                <button onclick="backupSlot()" id="btnBackupSlot" disabled
                        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 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"/>
                    </svg>
                    Backup Slot Completo
                </button>
            </div>

            {{-- Slot loading --}}
            <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>

    {{-- Stats --}}
    <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 12h6m-6 4h6m2 5H7a2 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>
            <div>
                <div class="text-2xl font-bold text-gray-900 dark:text-white font-mono" id="statLines">0</div>
                <div class="text-xs text-gray-400">L&iacute;neas</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">
                <svg class="w-5 h-5 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="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>
            </div>
            <div>
                <div class="text-2xl font-bold text-accent-600 dark:text-accent-400 font-mono" id="statPorts">0</div>
                <div class="text-xs text-gray-400">Puertos</div>
            </div>
        </div>
        <div class="card p-4 flex items-center gap-3">
            <div class="w-10 h-10 rounded-xl bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
                <svg class="w-5 h-5 text-green-600 dark:text-green-400" 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>
            </div>
            <div>
                <div class="text-sm font-bold text-green-600 dark:text-green-400" id="statTime">—</div>
                <div class="text-xs text-gray-400">Completado</div>
            </div>
        </div>
    </div>

    {{-- Action buttons --}}
    <div id="actionRow" class="hidden flex flex-wrap gap-3 mb-5">
        <button onclick="downloadConfig()" class="btn btn-sm bg-primary-600 hover:bg-primary-500 text-white focus:ring-primary-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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
            </svg>
            Descargar .txt
        </button>
        <button onclick="copyConfig()" id="btnCopy" class="btn btn-sm border border-gray-200 dark:border-white/10 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-white/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="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>
    </div>

    {{-- Config preview --}}
    <div id="configCard" class="hidden card mb-5">
        <div class="card-header">
            <h3 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="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"/>
                </svg>
                Running Config
            </h3>
            <span class="text-xs text-gray-400 font-mono" id="configLabel"></span>
        </div>
        <div class="card-body p-0">
            <pre id="configPre" class="bg-gray-900 text-green-400 font-mono text-xs leading-relaxed p-4 overflow-x-auto max-h-[600px] overflow-y-auto rounded-b-xl whitespace-pre-wrap"></pre>
        </div>
    </div>

    {{-- Loading --}}
    <div id="backupLoading" 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" id="loadingMsg">Obteniendo running-config...</p>
            <p class="text-xs text-gray-400" id="loadingHint">Esto puede tomar varios segundos</p>
        </div>
    </div>

    {{-- Error --}}
    <div id="backupError" 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="backupErrorMsg"></span>
    </div>

    {{-- 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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
                </svg>
            </div>
            <p class="text-sm">Selecciona un <strong>OLT</strong> y <strong>slot</strong> para obtener el backup de configuraci&oacute;n</p>
        </div>
    </div>

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

    let lastConfig = '';
    let lastSlotVal = '';
    let lastPortVal = '';

    function onDeviceChange() {
        const deviceId = document.getElementById('deviceSelect').value;
        const slotSel  = document.getElementById('slotSelect');
        const portSel  = document.getElementById('portSelect');

        slotSel.innerHTML = '<option value="">—</option>';
        slotSel.disabled = true;
        portSel.innerHTML = '<option value="">— Todos —</option>';
        portSel.disabled = true;
        document.getElementById('btnBackupPort').disabled = true;
        document.getElementById('btnBackupSlot').disabled = true;

        if (!deviceId) return;

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

        fetch(`${baseUrl}/backup-config/${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'));
    }

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

        portSel.innerHTML = '<option value="">— Todos —</option>';
        portSel.disabled = true;
        document.getElementById('btnBackupPort').disabled = true;
        document.getElementById('btnBackupSlot').disabled = !slot;

        if (!slot) return;

        for (let i = 1; i <= 16; i++) {
            const opt = document.createElement('option');
            opt.value = i;
            opt.textContent = `Puerto ${i}`;
            portSel.appendChild(opt);
        }
        portSel.disabled = false;
        portSel.onchange = () => {
            document.getElementById('btnBackupPort').disabled = !portSel.value;
        };
    }

    function showLoading(msg, hint) {
        ['emptyState', 'backupError', 'statsRow', 'actionRow', 'configCard'].forEach(id =>
            document.getElementById(id).classList.add('hidden'));
        document.getElementById('loadingMsg').textContent = msg || 'Obteniendo running-config...';
        document.getElementById('loadingHint').textContent = hint || 'Esto puede tomar varios segundos';
        document.getElementById('backupLoading').classList.remove('hidden');
    }

    function hideLoading() {
        document.getElementById('backupLoading').classList.add('hidden');
    }

    function showError(msg) {
        hideLoading();
        document.getElementById('backupError').classList.remove('hidden');
        document.getElementById('backupErrorMsg').textContent = msg;
    }

    function showResult(data, label) {
        hideLoading();

        lastConfig = data.config;

        // Stats
        document.getElementById('statLines').textContent = data.stats.lines;
        document.getElementById('statPorts').textContent = data.stats.ports;
        const now = new Date().toLocaleString('es-PE', {
            day: '2-digit', month: '2-digit', year: 'numeric',
            hour: 'numeric', minute: '2-digit', hour12: true
        });
        document.getElementById('statTime').textContent = now;
        document.getElementById('statsRow').classList.remove('hidden');

        // Actions
        document.getElementById('actionRow').classList.remove('hidden');

        // Config preview
        document.getElementById('configLabel').textContent = label;
        document.getElementById('configPre').textContent = data.config;
        document.getElementById('configCard').classList.remove('hidden');
    }

    function setButtons(disabled) {
        document.getElementById('btnBackupPort').disabled = disabled;
        document.getElementById('btnBackupSlot').disabled = disabled;
    }

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

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

        lastSlotVal = slot;
        lastPortVal = port;

        showLoading('Obteniendo running-config del puerto...', 'Esto puede tomar varios segundos');
        setButtons(true);

        fetch(`${baseUrl}/backup-config/${deviceId}/backup-port`, {
            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 => {
            setButtons(false);
            if (!data.success) {
                showError(data.message);
                return;
            }
            showResult(data, `gpon-olt_${frame}/${slot}/${port}`);
        })
        .catch(err => {
            setButtons(false);
            showError('Error: ' + (err.message || 'Error de red'));
        });
    }

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

        if (!deviceId || !slot) return;

        lastSlotVal = slot;
        lastPortVal = '';

        showLoading(
            'Obteniendo running-config de 16 puertos...',
            'Este proceso puede tomar hasta 5 minutos'
        );
        setButtons(true);

        fetch(`${baseUrl}/backup-config/${deviceId}/backup-slot`, {
            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 => {
            setButtons(false);
            if (!data.success) {
                showError(data.message);
                return;
            }
            showResult(data, `Slot ${frame}/${slot} (16 puertos)`);
        })
        .catch(err => {
            setButtons(false);
            showError('Error: ' + (err.message || 'Error de red'));
        });
    }

    function downloadConfig() {
        if (!lastConfig) return;

        const deviceId = document.getElementById('deviceSelect').value;
        if (!deviceId) return;

        // Create a hidden form to POST the config for download
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `${baseUrl}/backup-config/${deviceId}/download`;
        form.style.display = 'none';

        const tokenInput = document.createElement('input');
        tokenInput.name = '_token';
        tokenInput.value = csrfToken;
        form.appendChild(tokenInput);

        const configInput = document.createElement('input');
        configInput.name = 'config';
        configInput.value = lastConfig;
        form.appendChild(configInput);

        const slotInput = document.createElement('input');
        slotInput.name = 'slot';
        slotInput.value = lastSlotVal;
        form.appendChild(slotInput);

        if (lastPortVal) {
            const portInput = document.createElement('input');
            portInput.name = 'port';
            portInput.value = lastPortVal;
            form.appendChild(portInput);
        }

        document.body.appendChild(form);
        form.submit();
        document.body.removeChild(form);
    }

    function copyConfig() {
        if (!lastConfig) return;
        navigator.clipboard.writeText(lastConfig).then(() => {
            const btn = document.getElementById('btnCopy');
            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);
        });
    }
    </script>
</x-app-layout>
