document.addEventListener('DOMContentLoaded', function() {
    const apiConfigForm = document.getElementById('apiConfigForm');
    
    // Cargar configuración guardada
    loadSavedConfig();

    apiConfigForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const config = {
            openai_key: document.getElementById('openaiKey').value,
            huggingface_key: document.getElementById('huggingfaceKey').value,
            elevenlabs_key: document.getElementById('elevenLabsKey').value
        };

        try {
            const response = await fetch('/save_config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(config)
            });

            if (response.ok) {
                showAlert('success', 'Configuración guardada exitosamente');
            } else {
                showAlert('danger', 'Error al guardar la configuración');
            }
        } catch (error) {
            console.error('Error:', error);
            showAlert('danger', 'Error al guardar la configuración');
        }
    });

    async function loadSavedConfig() {
        try {
            const response = await fetch('/get_config');
            if (response.ok) {
                const config = await response.json();
                document.getElementById('openaiKey').value = config.openai_key || '';
                document.getElementById('huggingfaceKey').value = config.huggingface_key || '';
                document.getElementById('elevenLabsKey').value = config.elevenlabs_key || '';
            }
        } catch (error) {
            console.error('Error al cargar la configuración:', error);
        }
    }

    function showAlert(type, message) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
        alertDiv.role = 'alert';
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        `;
        
        const form = document.getElementById('apiConfigForm');
        form.insertAdjacentElement('beforebegin', alertDiv);

        // Auto-cerrar la alerta después de 3 segundos
        setTimeout(() => {
            alertDiv.remove();
        }, 3000);
    }
});