<?php
// pages/importar_combinaciones.php

$error_message = null;
$success_message = null;
$current_role = $_SESSION['user_role'];

// Recuperar mensajes de sesión
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}

if (isset($_SESSION['import_error'])) {
    $error_message = $_SESSION['import_error'];
    unset($_SESSION['import_error']);
}

// Mostrar reporte de importación si existe
if (isset($_GET['report']) && isset($_SESSION['import_report'])) {
    $report = $_SESSION['import_report'];
    $success_message = "Importación completada: {$report['imported_count']} nuevos KITS importados";
    unset($_SESSION['import_report']);
}

// Obtener las excepciones activas
$excepciones_query = $pdo->prepare("
    SELECT codigo_articulo, etiqueta_como, precio_individual 
    FROM kit_component_exceptions 
    WHERE activo = 1
");
$excepciones_query->execute();
$excepciones_activas = [];
while ($exc = $excepciones_query->fetch()) {
    $excepciones_activas[$exc['codigo_articulo']] = $exc;
}

// LÓGICA DE PAGINACIÓN Y BÚSQUEDA
$items_per_page = 50;
$current_page = isset($_GET['page_num']) ? (int)$_GET['page_num'] : 1;
if ($current_page < 1) $current_page = 1;
$search_term = isset($_GET['search']) ? trim($_GET['search']) : '';
$sort_by = isset($_GET['sort']) ? $_GET['sort'] : 'alpha_asc';

$relations_grouped = [];
$total_kits_filtered = 0;
$total_pages = 0;

try {
    $where_clauses = [];
    $params = [];
    
    if ($search_term) {
        $where_clauses[] = "(lr.lmat LIKE :search OR lr.parte LIKE :search2)";
        $params[':search'] = '%' . $search_term . '%';
        $params[':search2'] = '%' . $search_term . '%';
    }
    
    $base_where_sql = !empty($where_clauses) ? 'WHERE ' . implode(' AND ', $where_clauses) : '';
    
    // Contar total de KITS únicos que coinciden con la búsqueda
    $count_sql = "SELECT COUNT(DISTINCT lr.lmat) as total FROM lmat_relations lr $base_where_sql";
    $count_stmt = $pdo->prepare($count_sql);
    $count_stmt->execute($params);
    $total_kits_filtered = $count_stmt->fetchColumn();
    $total_pages = ceil($total_kits_filtered / $items_per_page);
    
    // Obtener los KITS únicos para la página actual
    $offset = ($current_page - 1) * $items_per_page;
    
    // Definir el orden según el parámetro sort_by
    $order_clause = match($sort_by) {
        'alpha_desc' => 'ORDER BY lr.lmat DESC',
        'parts_asc' => 'ORDER BY total_parts ASC, lr.lmat ASC',
        'parts_desc' => 'ORDER BY total_parts DESC, lr.lmat ASC',
        default => 'ORDER BY lr.lmat ASC'
    };
    
    $kits_sql = "
        SELECT lr.lmat, COUNT(DISTINCT lr.parte) as total_parts
        FROM lmat_relations lr
        $base_where_sql
        GROUP BY lr.lmat
        $order_clause
        LIMIT :limit OFFSET :offset
    ";
    
    $kits_stmt = $pdo->prepare($kits_sql);
    foreach ($params as $key => $value) {
        $kits_stmt->bindValue($key, $value);
    }
    $kits_stmt->bindValue(':limit', $items_per_page, PDO::PARAM_INT);
    $kits_stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $kits_stmt->execute();
    
    $kit_codes = [];
    while ($row = $kits_stmt->fetch()) {
        $kit_codes[] = $row['lmat'];
    }
    
    // Obtener las relaciones para los KITS de la página actual
    if (!empty($kit_codes)) {
        $placeholders = implode(',', array_map(fn($i) => ":kit$i", array_keys($kit_codes)));
        $relations_sql = "
            SELECT lr.*, 
                   rd.nombre as parte_nombre,
                   sd.cantidad as stock_disponible,
                   sd.bodega as bodega,
                   sd.almacen as almacen
            FROM lmat_relations lr
            LEFT JOIN references_data rd ON lr.parte = rd.referencia
            LEFT JOIN stock_data sd ON lr.parte = sd.referencia
            WHERE lr.lmat IN ($placeholders)
            ORDER BY lr.lmat, lr.parte
        ";
        
        $rel_stmt = $pdo->prepare($relations_sql);
        foreach ($kit_codes as $i => $code) {
            $rel_stmt->bindValue(":kit$i", $code);
        }
        $rel_stmt->execute();
        
        while ($row = $rel_stmt->fetch()) {
            $lmat = $row['lmat'];
            if (!isset($relations_grouped[$lmat])) {
                $relations_grouped[$lmat] = [
                    'partes' => [],
                    'stock_completo' => true,
                    'total_stock' => PHP_INT_MAX
                ];
            }
            
            $stock_disponible = $row['stock_disponible'] ?? 0;
            $qty_required = $row['qty_required'] ?? 1;
            
            // Verificar si es una excepción
            $es_excepcion = isset($excepciones_activas[$row['parte']]);
            
            $relations_grouped[$lmat]['partes'][] = [
                'parte' => $row['parte'],
                'nombre' => $row['parte_nombre'] ?? 'Sin nombre',
                'qty_required' => $qty_required,
                'stock_disponible' => $stock_disponible,
                'bodega' => $row['bodega'] ?? '',
                'almacen' => $row['almacen'] ?? '',
                'es_excepcion' => $es_excepcion,
                'etiqueta_como' => $es_excepcion ? $excepciones_activas[$row['parte']]['etiqueta_como'] : null
            ];
            
            // Solo contar si NO es excepción
            if (!$es_excepcion) {
                $unidades_posibles = $qty_required > 0 ? floor($stock_disponible / $qty_required) : 0;
                
                if ($unidades_posibles == 0) {
                    $relations_grouped[$lmat]['stock_completo'] = false;
                }
                
                $relations_grouped[$lmat]['total_stock'] = min(
                    $relations_grouped[$lmat]['total_stock'], 
                    $unidades_posibles
                );
            }
        }
    }
    
} catch (Exception $e) {
    $error_message = "Error al obtener las relaciones: " . $e->getMessage();
}
?>

<div class="p-6 max-w-7xl mx-auto">
    <?php if ($error_message): ?>
        <div class="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded">
            <i class="fas fa-exclamation-circle mr-2"></i><?php echo htmlspecialchars($error_message); ?>
        </div>
    <?php endif; ?>
    
    <?php if ($success_message): ?>
        <div class="mb-4 p-4 bg-green-100 border border-green-400 text-green-700 rounded">
            <i class="fas fa-check-circle mr-2"></i><?php echo htmlspecialchars($success_message); ?>
        </div>
    <?php endif; ?>

    <div class="bg-white rounded-lg shadow-lg mb-6">
        <div class="p-6 border-b">
            <h1 class="text-3xl font-bold text-gray-800">
                <i class="fas fa-layer-group mr-3 text-blue-600"></i>Gestión de KITS (Combinaciones)
            </h1>
            <p class="text-gray-600 mt-2">Administra las relaciones entre productos principales y sus componentes</p>
        </div>
        
        <!-- SECCIÓN DE IMPORTACIÓN/EXPORTACIÓN -->
        <div class="grid md:grid-cols-2 gap-6 p-6 bg-gray-50">
            <div>
                <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4">
                    <h3 class="font-semibold text-lg text-blue-800">
                        <i class="fas fa-file-alt mr-2"></i>Importar desde TXT
                    </h3>
                    <p class="text-sm text-blue-700 mb-4">Formato directo del sistema</p>
                    
                    <div class="bg-white rounded p-3 mb-4">
                        <p class="text-xs font-semibold text-gray-700 mb-2">Formato esperado (línea por línea):</p>
                        <code class="text-xs bg-gray-100 p-2 rounded block">LMAT|PARTE|CANTIDAD</code>
                    </div>
                    
                    <form class="import-form" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="relaciones_import_ajax">
                        <input type="hidden" name="import_type" value="txt">
                        <label class="flex items-center justify-center w-full p-3 transition bg-white border-2 border-blue-300 border-dashed rounded-md cursor-pointer hover:border-blue-400">
                            <i class="fas fa-cloud-upload-alt mr-2 text-blue-600"></i>
                            <span class="text-sm text-blue-600 font-semibold">Seleccionar archivo .txt</span>
                            <input type="file" name="relations_file" class="hidden" accept=".txt" required>
                        </label>
                        <button type="submit" class="mt-3 w-full bg-blue-600 text-white px-4 py-3 rounded-lg hover:bg-blue-700 font-semibold flex items-center justify-center">
                            <i class="fas fa-upload mr-2"></i>Importar TXT
                        </button>
                    </form>
                </div>
                
                <div class="bg-cyan-50 border border-cyan-200 rounded-lg p-4">
                    <h3 class="font-semibold text-lg text-cyan-800">
                        <i class="fas fa-file-csv mr-2"></i>Importar desde CSV
                    </h3>
                    <p class="text-sm text-cyan-700 mb-4">Formato tabular simple</p>
                    
                    <div class="bg-white rounded p-3 mb-4">
                        <p class="text-xs font-semibold text-gray-700 mb-2">Columnas requeridas:</p>
                        <code class="text-xs bg-gray-100 p-2 rounded block">kit,parte,cantidad</code>
                    </div>
                    
                    <form class="import-form" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="relaciones_import_ajax">
                        <input type="hidden" name="import_type" value="csv">
                        <label class="flex items-center justify-center w-full p-3 transition bg-white border-2 border-cyan-300 border-dashed rounded-md cursor-pointer hover:border-cyan-400">
                            <i class="fas fa-cloud-upload-alt mr-2 text-cyan-600"></i>
                            <span class="text-sm text-cyan-600 font-semibold">Seleccionar archivo .csv</span>
                            <input type="file" name="relations_file" class="hidden" accept=".csv" required>
                        </label>
                        <button type="submit" class="mt-3 w-full bg-cyan-600 text-white px-4 py-3 rounded-lg hover:bg-cyan-700 font-semibold flex items-center justify-center">
                            <i class="fas fa-file-csv mr-2"></i>Importar CSV
                        </button>
                    </form>
                </div>
            </div>
            
            <div>
                <div class="bg-green-50 border border-green-200 rounded-lg p-4 mb-4">
                    <h3 class="font-semibold text-lg text-green-800">
                        <i class="fas fa-download mr-2"></i>Exportar a CSV
                    </h3>
                    <p class="text-sm text-green-700 mb-4">Descarga todos los KITS con información completa</p>
                    <a href="index.php?page=importar_combinaciones&action=relaciones_export" 
                       class="block text-center w-full bg-green-600 text-white px-4 py-3 rounded-lg hover:bg-green-700 font-semibold">
                        <i class="fas fa-download mr-2"></i>Exportar Todos los KITS
                    </a>
                </div>

                <div id="terminal-container" class="hidden">
                    <h4 class="font-semibold text-gray-700 mb-2">
                        <i class="fas fa-terminal mr-2"></i>Progreso de la Importación:
                    </h4>
                    <pre id="terminal-output" class="bg-gray-900 text-green-400 text-xs p-4 rounded-lg h-64 overflow-y-auto font-mono"></pre>
                    <button id="terminal-close-btn" class="mt-3 w-full bg-gray-600 text-white py-2 rounded-lg hover:bg-gray-700 hidden">
                        <i class="fas fa-check mr-2"></i>Cerrar y Recargar
                    </button>
                </div>
                
                <div class="bg-amber-50 border border-amber-200 rounded-lg p-4 mt-4">
                    <h4 class="font-semibold text-amber-800 mb-2">
                        <i class="fas fa-info-circle mr-2"></i>Notas Importantes
                    </h4>
                    <ul class="text-sm text-amber-700 space-y-1 list-disc list-inside">
                        <li>La importación <strong>reemplazará</strong> todos los KITS existentes</li>
                        <li>Asegúrate de que los códigos coincidan con los productos existentes</li>
                        <li>Las excepciones configuradas se mantendrán después de la importación</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- BÚSQUEDA Y FILTROS -->
    <div class="bg-white rounded-lg shadow-lg mb-6 p-6">
        <form method="GET" class="flex flex-wrap gap-4 items-end">
            <input type="hidden" name="page" value="importar_combinaciones">
            
            <div class="flex-1 min-w-[300px]">
                <label class="block text-sm font-medium text-gray-700 mb-1">
                    <i class="fas fa-search mr-1"></i>Buscar KIT o Componente
                </label>
                <input type="text" 
                       name="search" 
                       value="<?php echo htmlspecialchars($search_term); ?>"
                       placeholder="Código de KIT o parte..."
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
            </div>
            
            <div class="min-w-[200px]">
                <label class="block text-sm font-medium text-gray-700 mb-1">
                    <i class="fas fa-sort mr-1"></i>Ordenar por
                </label>
                <select name="sort" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    <option value="alpha_asc" <?php echo $sort_by === 'alpha_asc' ? 'selected' : ''; ?>>Alfabético A-Z</option>
                    <option value="alpha_desc" <?php echo $sort_by === 'alpha_desc' ? 'selected' : ''; ?>>Alfabético Z-A</option>
                    <option value="parts_asc" <?php echo $sort_by === 'parts_asc' ? 'selected' : ''; ?>>Menos componentes</option>
                    <option value="parts_desc" <?php echo $sort_by === 'parts_desc' ? 'selected' : ''; ?>>Más componentes</option>
                </select>
            </div>
            
            <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 font-semibold">
                <i class="fas fa-filter mr-2"></i>Aplicar Filtros
            </button>
            
            <?php if ($search_term): ?>
                <a href="index.php?page=importar_combinaciones" 
                   class="px-4 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400 font-semibold">
                    <i class="fas fa-times mr-2"></i>Limpiar
                </a>
            <?php endif; ?>
        </form>
        
        <?php if ($search_term): ?>
            <div class="mt-4 text-sm text-gray-600">
                <i class="fas fa-info-circle mr-1"></i>
                Mostrando <?php echo count($relations_grouped); ?> de <?php echo $total_kits_filtered; ?> KITS encontrados
            </div>
        <?php endif; ?>
    </div>

    <!-- LISTADO DE KITS -->
    <?php if (!empty($relations_grouped)): ?>
        <div class="space-y-4">
            <?php foreach ($relations_grouped as $lmat => $data): ?>
                <details class="bg-white rounded-lg shadow-lg overflow-hidden">
                    <summary class="p-4 cursor-pointer hover:bg-gray-50 transition-colors">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center space-x-4">
                                <span class="details-arrow text-gray-400 transition-transform">
                                    <i class="fas fa-chevron-right"></i>
                                </span>
                                <div>
                                    <h3 class="text-lg font-bold text-gray-800">
                                        KIT: <?php echo htmlspecialchars($lmat); ?>
                                    </h3>
                                    <p class="text-sm text-gray-600">
                                        <?php echo count($data['partes']); ?> componente(s)
                                    </p>
                                </div>
                            </div>
                            
                            <div class="flex items-center space-x-4">
                                <?php if ($data['stock_completo']): ?>
                                    <span class="px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm font-semibold">
                                        <i class="fas fa-check-circle mr-1"></i>
                                        <?php echo $data['total_stock']; ?> unidades disponibles
                                    </span>
                                <?php else: ?>
                                    <span class="px-3 py-1 bg-red-100 text-red-800 rounded-full text-sm font-semibold">
                                        <i class="fas fa-times-circle mr-1"></i>
                                        Sin stock completo
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </summary>
                    
                    <div class="border-t">
                        <div class="p-4 bg-gray-50">
                            <h4 class="font-semibold text-gray-700 mb-3">
                                <i class="fas fa-list mr-2"></i>Componentes del KIT
                            </h4>
                            
                            <div class="overflow-x-auto">
                                <table class="w-full text-sm">
                                    <thead>
                                        <tr class="bg-gray-200">
                                            <th class="px-4 py-2 text-left">Código</th>
                                            <th class="px-4 py-2 text-left">Nombre</th>
                                            <th class="px-4 py-2 text-center">Cantidad Requerida</th>
                                            <th class="px-4 py-2 text-center">Stock Disponible</th>
                                            <th class="px-4 py-2 text-left">Ubicación</th>
                                            <th class="px-4 py-2 text-center">Estado</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($data['partes'] as $parte): ?>
                                            <tr class="border-b hover:bg-gray-100">
                                                <td class="px-4 py-2 font-mono">
                                                    <?php echo htmlspecialchars($parte['parte']); ?>
                                                    <?php if ($parte['es_excepcion']): ?>
                                                        <span class="ml-2 px-2 py-1 bg-yellow-100 text-yellow-800 text-xs rounded">
                                                            Excepción: <?php echo htmlspecialchars($parte['etiqueta_como']); ?>
                                                        </span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="px-4 py-2"><?php echo htmlspecialchars($parte['nombre']); ?></td>
                                                <td class="px-4 py-2 text-center font-semibold">
                                                    <?php echo $parte['qty_required']; ?>
                                                </td>
                                                <td class="px-4 py-2 text-center">
                                                    <span class="<?php echo $parte['stock_disponible'] > 0 ? 'text-green-600' : 'text-red-600'; ?> font-semibold">
                                                        <?php echo $parte['stock_disponible']; ?>
                                                    </span>
                                                </td>
                                                <td class="px-4 py-2 text-sm">
                                                    <?php if ($parte['bodega']): ?>
                                                        <?php echo htmlspecialchars($parte['bodega']); ?>
                                                        <?php if ($parte['almacen']): ?>
                                                            / <?php echo htmlspecialchars($parte['almacen']); ?>
                                                        <?php endif; ?>
                                                    <?php else: ?>
                                                        <span class="text-gray-400">-</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="px-4 py-2 text-center">
                                                    <?php if ($parte['es_excepcion']): ?>
                                                        <span class="text-yellow-600">
                                                            <i class="fas fa-exclamation-triangle" title="Excepción activa"></i>
                                                        </span>
                                                    <?php elseif ($parte['stock_disponible'] >= $parte['qty_required']): ?>
                                                        <span class="text-green-600">
                                                            <i class="fas fa-check-circle"></i>
                                                        </span>
                                                    <?php else: ?>
                                                        <span class="text-red-600">
                                                            <i class="fas fa-times-circle"></i>
                                                        </span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </details>
            <?php endforeach; ?>
        </div>
        
        <!-- PAGINACIÓN -->
        <?php if ($total_pages > 1): ?>
            <div class="mt-6 flex justify-center">
                <nav class="flex space-x-2">
                    <?php if ($current_page > 1): ?>
                        <a href="?page=importar_combinaciones&page_num=<?php echo $current_page - 1; ?>&search=<?php echo urlencode($search_term); ?>&sort=<?php echo $sort_by; ?>" 
                           class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300">
                            <i class="fas fa-chevron-left"></i> Anterior
                        </a>
                    <?php endif; ?>
                    
                    <?php
                    $start_page = max(1, $current_page - 2);
                    $end_page = min($total_pages, $current_page + 2);
                    
                    if ($start_page > 1): ?>
                        <a href="?page=importar_combinaciones&page_num=1&search=<?php echo urlencode($search_term); ?>&sort=<?php echo $sort_by; ?>" 
                           class="px-4 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50">1</a>
                        <?php if ($start_page > 2): ?>
                            <span class="px-2 py-2">...</span>
                        <?php endif; ?>
                    <?php endif; ?>
                    
                    <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                        <a href="?page=importar_combinaciones&page_num=<?php echo $i; ?>&search=<?php echo urlencode($search_term); ?>&sort=<?php echo $sort_by; ?>" 
                           class="px-4 py-2 <?php echo $i === $current_page ? 'bg-blue-600 text-white' : 'bg-white border border-gray-300 text-gray-700 hover:bg-gray-50'; ?> rounded-lg">
                            <?php echo $i; ?>
                        </a>
                    <?php endfor; ?>
                    
                    <?php if ($end_page < $total_pages): ?>
                        <?php if ($end_page < $total_pages - 1): ?>
                            <span class="px-2 py-2">...</span>
                        <?php endif; ?>
                        <a href="?page=importar_combinaciones&page_num=<?php echo $total_pages; ?>&search=<?php echo urlencode($search_term); ?>&sort=<?php echo $sort_by; ?>" 
                           class="px-4 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50"><?php echo $total_pages; ?></a>
                    <?php endif; ?>
                    
                    <?php if ($current_page < $total_pages): ?>
                        <a href="?page=importar_combinaciones&page_num=<?php echo $current_page + 1; ?>&search=<?php echo urlencode($search_term); ?>&sort=<?php echo $sort_by; ?>" 
                           class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300">
                            Siguiente <i class="fas fa-chevron-right"></i>
                        </a>
                    <?php endif; ?>
                </nav>
            </div>
        <?php endif; ?>
        
    <?php else: ?>
        <div class="bg-white rounded-lg shadow-lg p-8 text-center">
            <i class="fas fa-inbox text-6xl text-gray-300 mb-4"></i>
            <p class="text-xl text-gray-600">No se encontraron KITS</p>
            <?php if ($search_term): ?>
                <p class="text-gray-500 mt-2">Intenta con otros términos de búsqueda</p>
            <?php else: ?>
                <p class="text-gray-500 mt-2">Importa un archivo para comenzar</p>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<style>
details > summary { list-style: none; }
details > summary::-webkit-details-marker { display: none; }
details[open] .details-arrow { transform: rotate(90deg); }
details summary:hover .details-arrow { transform: translateX(3px); }
details[open] summary:hover .details-arrow { transform: rotate(90deg) translateX(0); }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Manejo de formularios de importación con AJAX
    const importForms = document.querySelectorAll('.import-form');
    const terminalContainer = document.getElementById('terminal-container');
    const terminalOutput = document.getElementById('terminal-output');
    const terminalCloseBtn = document.getElementById('terminal-close-btn');
    
    importForms.forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.innerHTML;
            
            // Mostrar terminal
            terminalContainer.classList.remove('hidden');
            terminalOutput.textContent = '';
            terminalCloseBtn.classList.add('hidden');
            
            // Deshabilitar botón
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Procesando...';
            
            // Realizar petición AJAX
            fetch('index.php?page=importar_combinaciones', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                // Mostrar resultado en terminal
                terminalOutput.textContent = data;
                terminalCloseBtn.classList.remove('hidden');
                
                // Restaurar botón
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
                
                // Auto-scroll al final
                terminalOutput.scrollTop = terminalOutput.scrollHeight;
            })
            .catch(error => {
                terminalOutput.textContent = '❌ Error: ' + error.message;
                terminalCloseBtn.classList.remove('hidden');
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnText;
            });
        });
    });
    
    // Botón cerrar terminal
    if (terminalCloseBtn) {
        terminalCloseBtn.addEventListener('click', function() {
            window.location.reload();
        });
    }
    
    // Cambio de archivo
    const fileInputs = document.querySelectorAll('input[type="file"]');
    fileInputs.forEach(input => {
        input.addEventListener('change', function() {
            const label = this.closest('label');
            const span = label.querySelector('span');
            if (this.files.length > 0) {
                span.textContent = this.files[0].name;
                label.classList.add('border-green-400', 'bg-green-50');
            }
        });
    });
});
</script>