<!-- 
Archivo: FormPEul.html (CORREGIDO)
Ruta: src/templates/Ventas/Cotiz/CotizEspSolicitud/FormPEul.html
Descripción: Formulario de Plantas Eléctricas UL con IDs únicos
-->

<!-- CAMPOS DEL FORMULARIO CON IDs ÚNICOS -->
<div class="row-3col">
    <div class="field-group">
        <label for="peul_potencia" class="required">Potencia Requerida (kW):</label>
        <input type="number" id="peul_potencia" class="form-control" required
               placeholder="Ej: 500" min="1">
    </div>
    
    <div class="field-group">
        <label for="peul_voltaje" class="required">Voltaje (V):</label>
        <select id="peul_voltaje" class="form-control" required>
            <option value="" selected disabled>Selecciona voltaje</option>
            <option value="127">127V</option>
            <option value="220">220V</option>
            <option value="440">440V</option>
            <option value="480">480V</option>
            <option value="otro">Otro</option>
        </select>
    </div>
    
    <div class="field-group">
        <label for="peul_fases" class="required">Número de Fases:</label>
        <select id="peul_fases" class="form-control" required>
            <option value="" selected disabled>Selecciona fases</option>
            <option value="1">Monofásico (1φ)</option>
            <option value="3">Trifásico (3φ)</option>
        </select>
    </div>
</div>

<div class="row-3col">
    <div class="field-group">
        <label for="peul_combustible" class="required">Tipo de Combustible:</label>
        <select id="peul_combustible" class="form-control" required>
            <option value="" selected disabled>Selecciona combustible</option>
            <option value="diesel">Diésel</option>
            <option value="gas_natural">Gas Natural</option>
            <option value="gas_lp">Gas LP</option>
            <option value="gasolina">Gasolina</option>
        </select>
    </div>
    
    <div class="field-group">
        <label for="peul_uso" class="required">Tipo de Uso:</label>
        <select id="peul_uso" class="form-control" required>
            <option value="" selected disabled>Selecciona uso</option>
            <option value="emergencia">Emergencia</option>
            <option value="continuo">Uso Continuo</option>
            <option value="standby">Standby</option>
        </select>
    </div>
    
    <div class="field-group">
        <label for="peul_arranque" class="required">Tipo de Arranque:</label>
        <select id="peul_arranque" class="form-control" required>
            <option value="" selected disabled>Selecciona arranque</option>
            <option value="manual">Manual</option>
            <option value="automatico">Automático</option>
            <option value="remoto">Remoto</option>
        </select>
    </div>
</div>

<!-- CAMPO ESPECÍFICO PARA UL -->
<div class="row-2col">
    <div class="field-group">
        <label for="peul_certificacion" class="required">Certificación UL Requerida:</label>
        <select id="peul_certificacion" class="form-control" required>
            <option value="" selected disabled>Selecciona certificación</option>
            <option value="ul2200">UL 2200 - Stationary Engine Generator Assemblies</option>
            <option value="ul142">UL 142 - Steel Aboveground Tanks</option>
            <option value="ul508a">UL 508A - Industrial Control Panels</option>
            <option value="otra">Otra certificación UL</option>
        </select>
    </div>
    
    <div class="field-group">
        <label for="peul_mercado_destino" class="required">Mercado de Destino:</label>
        <select id="peul_mercado_destino" class="form-control" required>
            <option value="" selected disabled>Selecciona mercado</option>
            <option value="usa">Estados Unidos</option>
            <option value="canada">Canadá</option>
            <option value="mexico_exportacion">México (para exportación)</option>
        </select>
    </div>
</div>

<div class="row-1col">
    <div class="field-group">
        <label for="peul_observaciones">Observaciones Técnicas UL:</label>
        <textarea id="peul_observaciones" rows="3" class="form-control"
                  placeholder="Especifique requerimientos UL adicionales, normativas específicas, documentación requerida..."></textarea>
    </div>
</div>

<!-- SECCIÓN DE ARCHIVOS CORREGIDA -->
<div class="file-upload-section">
    <h5 class="file-section-title">📎 Documentos Técnicos UL</h5>
    <p class="file-section-description">
        Adjunte planos, especificaciones UL, certificaciones requeridas, fotos del sitio, etc. 
        <strong>Formatos permitidos:</strong> PDF, DOC, DOCX, JPG, PNG, XLSX, XLS (máx. 2MB por archivo)
    </p>
    
    <!-- Input de archivos -->
    <div class="file-input-container">
        <input type="file" 
               id="files_GensetUL" 
               name="files_GensetUL[]" 
               multiple 
               accept=".pdf,.doc,.docx,.jpg,.jpeg,.png,.xlsx,.xls"
               class="file-input"
               style="display: none;">
        <button type="button" class="file-input-label" onclick="FormPEul.openFileSelector()">
            <i class="fas fa-cloud-upload-alt"></i>
            <span>Seleccionar Archivos</span>
        </button>
    </div>
    
    <!-- Vista previa CORREGIDA -->
    <div id="preview_GensetUL" class="file-preview-container" style="display: none;">
        <div class="preview-header">
            <h6 class="preview-title">Archivos Seleccionados:</h6>
            <div class="file-counter">
                <span id="file-count-GensetUL">0</span> archivo(s) | 
                <span id="file-size-GensetUL">0</span> KB total
            </div>
        </div>
        <div class="file-preview-list"></div>
        <div class="preview-actions">
            <button type="button" class="btn-add-more" onclick="FormPEul.openFileSelector()">
                <i class="fas fa-plus"></i> Agregar Más
            </button>
            <button type="button" class="btn-remove-all" onclick="FormPEul.clearAllFiles()">
                <i class="fas fa-trash"></i> Quitar Todos
            </button>
        </div>
    </div>
    
    <!-- Información adicional -->
    <div class="file-info">
        <small class="text-muted">
            <i class="fas fa-info-circle"></i>
            Los archivos se subirán cuando envíe la solicitud completa.
        </small>
    </div>
</div>

<!-- JavaScript CORREGIDO -->
<script>
window.FormPEul = (function() {
    'use strict';
    
    // Variables de archivos
    const selectedFiles = new Map();
    let fileCounter = 0;
    const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
    const ALLOWED_EXTENSIONS = ['.pdf', '.doc', '.docx', '.jpg', '.jpeg', '.png', '.xlsx', '.xls'];
    
    // Elementos DOM cacheados
    let elements = {};
    
    function init() {
        console.log('FormPEul: Módulo inicializado');
        cacheElements();
        setupFileSystem();
        updateUI();
    }
    
    function cacheElements() {
        elements = {
            fileInput: document.getElementById('files_GensetUL'),
            previewContainer: document.getElementById('preview_GensetUL'),
            previewList: document.querySelector('#preview_GensetUL .file-preview-list'),
            fileCounter: document.getElementById('file-count-GensetUL'),
            fileSizeCounter: document.getElementById('file-size-GensetUL'),
            btnSelectFiles: document.querySelector('.file-input-label'),
            btnAddMore: document.querySelector('.btn-add-more')
        };
    }
    
    function setupFileSystem() {
        if (!elements.fileInput) {
            console.warn('FormPEul: Input de archivos no encontrado');
            return;
        }
        elements.fileInput.addEventListener('change', handleFileSelection);
    }
    
    function openFileSelector() {
        if (elements.fileInput) {
            console.log('FormPEul: Abriendo selector de archivos');
            elements.fileInput.click();
        }
    }
    
    function handleFileSelection(event) {
        const files = Array.from(event.target.files);
        console.log(`FormPEul: Procesando ${files.length} archivo(s)`);
        
        if (files.length === 0) {
            console.log('FormPEul: No se seleccionaron archivos - manteniendo existentes');
            return;
        }
        
        const validFiles = [];
        const errors = [];
        
        files.forEach(file => {
            const validation = validateFile(file);
            if (validation.valid) {
                // Verificar duplicados
                const isDuplicate = Array.from(selectedFiles.values()).some(existingFile =>
                    existingFile.file.name === file.name && existingFile.file.size === file.size
                );
                
                if (!isDuplicate) {
                    validFiles.push(file);
                } else {
                    errors.push(`${file.name}: Archivo ya seleccionado`);
                }
            } else {
                errors.push(`${file.name}: ${validation.error}`);
            }
        });
        
        if (errors.length > 0) {
            showFileErrors(errors);
        }
        
        if (validFiles.length > 0) {
            validFiles.forEach(file => {
                fileCounter++;
                selectedFiles.set(fileCounter, { id: fileCounter, file: file });
            });
            updateFilePreview();
            showSuccessMessage(`${validFiles.length} archivo(s) agregado(s)`);
        }
        
        // Limpiar input sin afectar archivos seleccionados
        event.target.value = '';
    }
    
    function validateFile(file) {
        if (file.size > MAX_FILE_SIZE) {
            return {
                valid: false,
                error: `Archivo muy grande (${(file.size / 1024 / 1024).toFixed(1)}MB). Máximo 2MB.`
            };
        }
        
        const extension = '.' + file.name.split('.').pop().toLowerCase();
        if (!ALLOWED_EXTENSIONS.includes(extension)) {
            return {
                valid: false,
                error: `Tipo de archivo no permitido (${extension})`
            };
        }
        
        return { valid: true };
    }
    
    function updateFilePreview() {
        if (selectedFiles.size === 0) {
            elements.previewContainer.style.display = 'none';
            updateUI();
            return;
        }
        
        elements.previewContainer.style.display = 'block';
        
        // Renderizar lista de archivos
        elements.previewList.innerHTML = '';
        let totalSize = 0;
        
        Array.from(selectedFiles.values()).forEach(fileData => {
            totalSize += fileData.file.size;
            const fileItem = createFilePreviewItem(fileData.file, fileData.id);
            elements.previewList.appendChild(fileItem);
        });
        
        // Actualizar contadores
        elements.fileCounter.textContent = selectedFiles.size;
        elements.fileSizeCounter.textContent = (totalSize / 1024).toFixed(1);
        
        updateUI();
    }
    
    function createFilePreviewItem(file, fileId) {
        const item = document.createElement('div');
        item.className = 'file-preview-item';
        item.setAttribute('data-file-id', fileId);
        
        const fileSize = (file.size / 1024).toFixed(1);
        const fileIcon = getFileIcon(file.name);
        
        item.innerHTML = `
            <div class="file-info">
                <i class="${fileIcon}"></i>
                <div class="file-details">
                    <span class="file-name" title="${file.name}">${file.name}</span>
                    <span class="file-size">${fileSize} KB</span>
                </div>
            </div>
            <button type="button" class="btn-remove-file" onclick="FormPEul.removeFile(${fileId})" title="Quitar archivo">
                <i class="fas fa-times"></i>
            </button>
        `;
        
        return item;
    }
    
    function getFileIcon(filename) {
        const extension = filename.split('.').pop().toLowerCase();
        
        const iconMap = {
            'pdf': 'fas fa-file-pdf text-danger',
            'doc': 'fas fa-file-word text-primary',
            'docx': 'fas fa-file-word text-primary',
            'xlsx': 'fas fa-file-excel text-success',
            'xls': 'fas fa-file-excel text-success',
            'jpg': 'fas fa-file-image text-warning',
            'jpeg': 'fas fa-file-image text-warning',
            'png': 'fas fa-file-image text-warning'
        };
        
        return iconMap[extension] || 'fas fa-file text-secondary';
    }
    
    function updateUI() {
        const hasFiles = selectedFiles.size > 0;
        elements.btnSelectFiles.style.display = hasFiles ? 'none' : 'inline-flex';
    }
    
    function removeFile(fileId) {
        if (selectedFiles.has(fileId)) {
            const fileData = selectedFiles.get(fileId);
            selectedFiles.delete(fileId);
            updateFilePreview();
            showSuccessMessage(`Archivo "${fileData.file.name}" removido`);
        }
    }
    
    function clearAllFiles() {
        const fileCount = selectedFiles.size;
        selectedFiles.clear();
        fileCounter = 0;
        updateFilePreview();
        showSuccessMessage(`${fileCount} archivo(s) removido(s)`);
    }
    
    function getFiles() {
        const filesArray = Array.from(selectedFiles.values()).map(fileData => fileData.file);
        console.log(`FormPEul: Retornando ${filesArray.length} archivo(s)`);
        return filesArray;
    }
    
    function getFileStats() {
        const files = Array.from(selectedFiles.values());
        const totalSize = files.reduce((sum, fileData) => sum + fileData.file.size, 0);
        
        return {
            count: selectedFiles.size,
            totalSize: totalSize,
            totalSizeMB: (totalSize / 1024 / 1024).toFixed(2),
            files: files.map(fileData => ({
                name: fileData.file.name,
                size: fileData.file.size,
                type: fileData.file.type
            }))
        };
    }
    
    function showSuccessMessage(message) {
        if (window.mostrarNotificacionToast) {
            window.mostrarNotificacionToast(message, 'success');
        } else {
            console.log('FormPEul:', message);
        }
    }
    
    function showFileErrors(errors) {
        const errorMessage = `Algunos archivos no pudieron agregarse:\n${errors.join('\n')}`;
        if (window.mostrarAlerta) {
            window.mostrarAlerta(errorMessage, 'warning');
        } else {
            alert(errorMessage);
        }
    }
    
    function onBecomeVisible() {
        console.log('FormPEul: Formulario visible, inicializando...');
        init();
    }
    
    // API pública - mantiene compatibilidad exacta
    return {
        init: init,
        openFileSelector: openFileSelector,
        removeFile: removeFile,
        clearAllFiles: clearAllFiles,
        getFiles: getFiles,
        getFileStats: getFileStats,
        onBecomeVisible: onBecomeVisible
    };
    
})();

// Auto-inicializar si el formulario ya está visible
document.addEventListener('DOMContentLoaded', function() {
    const formSection = document.querySelector('.section-FormPEul');
    if (formSection && formSection.style.display !== 'none') {
        FormPEul.init();
    }
});
</script>

<!-- CSS optimizado -->
<style>
.file-upload-section {
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 20px;
    margin-top: 20px;
}

.file-section-title {
    color: #495057;
    margin-bottom: 8px;
    font-weight: 600;
}

.file-section-description {
    color: #6c757d;
    font-size: 0.9em;
    margin-bottom: 15px;
    line-height: 1.4;
}

.file-input-container {
    display: flex;
    gap: 10px;
    margin-bottom: 15px;
    flex-wrap: wrap;
}

.file-input-label,
.btn-add-more {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 12px 20px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    transition: background-color 0.2s;
    font-weight: 500;
    text-decoration: none;
}

.file-input-label:hover,
.btn-add-more:hover {
    background: #0056b3;
}

.btn-add-more {
    background: #28a745;
}

.btn-add-more:hover {
    background: #218838;
}

.file-preview-container {
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 6px;
    padding: 15px;
    margin-top: 15px;
}

.preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e9ecef;
}

.preview-title {
    color: #495057;
    margin: 0;
    font-weight: 600;
}

.file-counter {
    color: #6c757d;
    font-size: 0.9em;
    font-weight: 500;
}

.file-preview-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    border: 1px solid #e9ecef;
    border-radius: 4px;
    margin-bottom: 8px;
    background: #f8f9fa;
    transition: background-color 0.2s;
}

.file-preview-item:hover {
    background: #e9ecef;
}

.file-info {
    display: flex;
    align-items: center;
    gap: 12px;
    flex: 1;
    min-width: 0;
}

.file-details {
    display: flex;
    flex-direction: column;
    min-width: 0;
    flex: 1;
}

.file-name {
    font-weight: 500;
    color: #495057;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.file-size {
    font-size: 0.85em;
    color: #6c757d;
}

.btn-remove-file {
    background: #dc3545;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 8px 10px;
    cursor: pointer;
    transition: background-color 0.2s;
    font-size: 0.9em;
    flex-shrink: 0;
}

.btn-remove-file:hover {
    background: #c82333;
}

.preview-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-start;
    margin-top: 15px;
    padding-top: 10px;
    border-top: 1px solid #e9ecef;
}

.btn-remove-all {
    background: #dc3545;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 8px 16px;
    cursor: pointer;
    transition: background-color 0.2s;
    font-size: 0.9em;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.btn-remove-all:hover {
    background: #c82333;
}

.file-info small {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-top: 10px;
}

/* Responsive */
@media (max-width: 768px) {
    .file-input-container {
        flex-direction: column;
    }
    
    .preview-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 5px;
    }
    
    .preview-actions {
        flex-direction: column;
    }
    
    .file-preview-item {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
}
</style>