<?php include 'files/guardiankey.php'; ?>
<?php
// =================================================================
//        DATA BLOCK FOR FORM PRE-FILLING (Best Practice)
// =================================================================

// 1. Include the central business information file.
//    This creates the $client_info variable with all the data.
include __DIR__ . '/client-information.php';

// 2. Assign info to easy-to-use variables for this form.
//    Using English names for consistency with the database and array keys.
$client_name       = $client_info['name'] ?? '';
$business_name     = $client_info['business_name'] ?? '';
$phone             = $client_info['phone'] ?? '';
$whatsapp          = $client_info['whatsapp'] ?? '';
$email             = $client_info['email'] ?? '';
$website           = $client_info['website'] ?? '';
$operating_cities  = $client_info['operating_cities'] ?? '';
$value_proposition = $client_info['value_proposition'] ?? '';
$logo_url          = $client_info['logo_url'] ?? '';

// Social links come as an array, hence the '?? []' fallback.
$social_links      = $client_info['social_links'] ?? [];

// =================================================================
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Analista De Resultados Publicitarios Con IAMarketing™ Powered By OrozCO</title>
    <meta name="description" content="Analiza Tus Anuncios Y Recibe Ideas Claras Para Mejorar Tus Resultados">
    <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="tools.css">
    <script src="files/header-manager.js"></script>

</head>
<body data-page-title="Analista De Resultados Publicitarios" 
      data-page-subtitle="Analiza Tus Anuncios Y Recibe Ideas Claras Para Mejorar Tus Resultados" 
      data-page-icon="brain">

    <div id="toast-container" class="toast-container"></div>

    <?php include 'files/gtm-body.php'; ?>

<div class="relative min-h-screen md:flex">

    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    <div id="task-panel-overlay" class="off-canvas-overlay"></div> 
    
    <?php include 'ia-menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

        <div id="content-area" class="p-4 md:p-8">
            <section id="analyzer" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
                    <div class="lg:col-span-3">
                        <form id="analyzer-form" class="space-y-8 bg-white p-8 rounded-xl shadow-md">
                            <div>
                                <div class="step-header">
                                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase justify-center md:justify-start">
                                        <i data-lucide="scan-search" class="mr-3 text-[var(--color-secondary)]"></i> 
                                        <span class="text-[var(--color-secondary)] mr-2">PASO 1:</span> Ingresa Tus Resultados
                                    </h2>
                                    <p class="step-subtitle text-center md:text-left uppercase">Ingresa los datos de tu campaña para analizar los resultados obtenidos.</p>
                                </div>
                                <div class="border-b border-[var(--color-primary)] pb-4 mb-6"></div>
                                
                                <div class="space-y-6">
                                    <div>
                                        <label for="campaign_objective" class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Cuál Fue El Objetivo De Tu Anuncio?</label>
                                        <select id="campaign_objective" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                            <option value="">Selecciona Un Objetivo</option>
                                            <option value="Recibir Mensajes">Conseguir Mensajes (Recomendado)</option>
                                            <option value="Tráfico a la Página Web">Llevar Tráfico A Tu Página Web</option>
                                            <option value="Generación de Clientes Potenciales">Obtener Datos De Clientes (Formulario)</option>
                                            <option value="Interacción con la Publicación">Conseguir "Me Gusta" y Comentarios</option>
                                        </select>
                                    </div>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 pt-4">
                                        <div>
                                            <label for="investment" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Inversión Total ($)</label>
                                            <input type="number" step="0.01" id="investment" placeholder="Ej: 150" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                        </div>
                                        <div>
                                            <label for="service_price" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Precio De Tu Producto/Servicio ($)</label>
                                            <input type="number" step="0.01" id="service_price" placeholder="Ej: 300" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                        </div>
                                        <div>
                                            <label for="messages" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Contactos Recibidos</label>
                                            <input type="number" id="messages" placeholder="Ej: 25" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                        </div>
                                        <div>
                                            <label for="closed_clients" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Clientes Cerrados</label>
                                            <input type="number" id="closed_clients" placeholder="Ej: 5" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                        </div>
                                        <div>
                                            <label for="impressions" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Impresiones (Opcional)</label>
                                            <input type="number" id="impressions" placeholder="Ej: 15000" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                        </div>
                                        <div>
                                            <label for="clicks" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Clics (Opcional)</label>
                                            <input type="number" id="clicks" placeholder="Ej: 300" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                        </div>
                                        <div>
                                            <label for="demographics" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Mejor Audiencia</label>
                                            <input type="text" id="demographics" placeholder="Ej: Mujeres de 35-44 Años" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                        </div>
                                        <div>
                                            <label for="platform" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Mejor Plataforma</label>
                                            <select id="platform" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                                <option value="">Selecciona Una Plataforma</option>
                                                <option value="Facebook">Facebook</option>
                                                <option value="Instagram">Instagram</option>
                                                <option value="Ambas por igual">Ambas Por Igual</option>
                                            </select>
                                        </div>
                                        <div class="md:col-span-2">
                                            <label for="locations" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Mejores Zonas O Ciudades</label>
                                            <textarea id="locations" placeholder="Ej: Miami, Orlando, Tampa" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" rows="3" required></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div id="form-error-message" class="hidden bg-red-100 text-center p-3 text-red-700 rounded-lg border border-red-300" role="alert">
                                Por Favor, Completa Todos Los Campos Requeridos.
                            </div>
                        </form>
                    </div>

                    <div class="lg:col-span-2 space-y-8">
                        <img src="img/VideoLeccion.png" alt="VideoLeccion - IAMarketing">
                        <div class="w-full">
                                <div class="bg-black/40 rounded-xl ring-1 ring-white/10 overflow-hidden">
                                    <div class="relative w-full" style="padding-bottom: 56.25%;">
                                        <video class="absolute top-0 left-0 w-full h-full object-cover" id="videoPlayer" controls controlslist="nodownload fullscreen" preload="metadata">
                                            <source src="https://samplelib.com/lib/preview/mp4/sample-5s.mp4" type="video/mp4">
                                            TU NAVEGADOR NO SOPORTA LA ETIQUETA DE VIDEO
                                        </video>
                                        <div id="playOverlay" class="absolute inset-0 flex justify-center items-center cursor-pointer group">
                                            <img src="img/VideoLeccion-IAMarketing.jpg" alt="VideoLeccion - IAMarketing" class="absolute inset-0 w-full h-full object-cover">
                                            <div class="absolute inset-0 w-full h-full bg-black/40 transition-colors group-hover:bg-black/60"></div>
                                            <i data-lucide="play" class="relative w-16 h-16 text-white opacity-80 group-hover:opacity-100 transition-opacity"></i>
                                        </div>
                                    </div>
                                    <div class="p-4 text-white/90 text-sm flex items-center justify-between">
                                        <span class="inline-flex items-center gap-2">
                                            <i data-lucide="play-circle" class="w-4 h-4"></i> Video De Introducción A La Plataforma SiteFlowCMS
                                        </span>
                                        <span class="inline-flex items-center gap-2">
                                            <i data-lucide="clock" class="w-4 h-4"></i> 2–3 min
                                        </span>
                                    </div>
                                </div>
                            </div>
                        <div class="bg-white text-brand-dark p-6 md:p-8 rounded-xl shadow-md">
                            <div class="step-header">
                                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase justify-center md:justify-start">
                                        <i data-lucide="book-open" class="mr-3 text-[var(--color-highlight)]"></i>
                                        <span class="step-title">INSTRUCCIONES IMPORTANTES</span>
                                    </h2>
                                     <p class="step-subtitle text-center md:text-left uppercase">REVISA ESTOS PUNTOS DETALLADAMENTE</p>
                                </div>
                            <div class="border-b border-gray-200 pb-4 mb-6"></div>
                            
                            <ul class="space-y-4 text-gray-700">
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="monitor-play"></i></span><div><strong class="text-brand-dark uppercase">MIRA EL VIDEO:</strong> El tutorial te explica cómo usar la herramienta y los datos que necesitas.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="pencil-ruler"></i></span><div><strong class="text-brand-dark uppercase">SÉ EXACTO CON TUS DATOS:</strong> La precisión de la IA depende de ti. Usa números reales de tus campañas para un diagnóstico útil.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="lightbulb"></i></i></span><div><strong class="text-brand-dark uppercase">CONFÍA EN LA GUÍA, NO EN LA MAGIA:</strong> La IA te da un plan, pero tu conocimiento de negocio es clave para tomar decisiones.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="trending-up"></i></span><div><strong class="text-brand-dark uppercase">APLICA Y MIDE EL CAMBIO:</strong> El valor no está en el análisis, sino en la acción. Implementa las recomendaciones y regresa a medir los nuevos resultados.</div></li>
                            </ul>
                        </div>
                    </div>
                    
                    <div class="lg:col-span-5 bg-white text-brand-dark p-6 md:p-8 rounded-xl shadow-md mt-6">
                        <div class="step-header">
                            <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase justify-center md:justify-start">
                                <i data-lucide="settings-2" class="mr-3 text-[var(--color-secondary)]"></i> 
                                <span class="text-[var(--color-secondary)] mr-2">PASO 2:</span> Crear Tu Plan De Mejora Y Optimización
                            </h2>
                            <p class="step-subtitle text-center md:text-left uppercase">Obtén un plan de acción personalizado y estratégico.</p>
                        </div>
                        <div class="border-b border-gray-200 pb-4 mb-6"></div>
                        
                        <div class="flex flex-col md:flex-row items-center md:justify-between gap-4 md:gap-8 mb-6">
                            <p class="text-lg text-center md:text-left text-gray-700 md:flex-1 md:pr-4 mb-0">Para mejorar tus resultados, <strong>es importante</strong> que tengas tus estadísticas de los resultados obtenidos. Basado en tu información, nuestra Inteligencia Artificial <strong>IA Marketing</strong> hará un <strong>Análisis De Resultados Publicitarios</strong>, para que obtengas ideas claras y concretas sobre cómo optimizar tus campañas publicitarias</p>
                            <div class="flex flex-col items-center">
                            <i data-lucide="brain" class="w-12 h-12 text-[var(--color-primary)] mb-2"></i>
                             <button id="generateBtn" type="submit" form="analyzer-form" class="w-full md:w-auto bg-[var(--color-highlight)] text-[var(--color-primary)] font-bold py-4 px-6 rounded-lg hover:scale-105 transition-transform shadow-lg text-lg flex items-center justify-center gap-2 uppercase">
                               <span id="btn-text">GENERAR CON IA MARKETING</span>
                               <i data-lucide="mouse-pointer-click" class="w-6 h-6 animate-bounce"></i>
                               <div id="loader-container" class="hidden ml-3"></div>
                             </button>
                        </div>
                        </div>
                    </div>

                    <div id="result-container" class="lg:col-span-5 mt-8"></div>
                </div>
            </section>
        </div>
    </main>
</div>

<script type="module">
// --- VARIABLES GENERALES Y LÓGICA DE CARGA ---
document.addEventListener('DOMContentLoaded', () => {
    lucide.createIcons();
    
    // Elementos del menú y la cabecera
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    const playOverlay = document.getElementById('playOverlay');
    const videoPlayer = document.getElementById('videoPlayer');
    const phoneInput = document.getElementById('contact_phone');
    const form = document.getElementById('analyzer-form');
    const resultContainer = document.getElementById('result-container');
    const generateBtn = document.getElementById('generateBtn');
    const btnText = document.getElementById('btn-text');
    const loaderContainer = document.getElementById('loader-container');
    const formErrorMessage = document.getElementById('form-error-message');
    
    const messages = ["Contactando Con OrozCO IA...", "Evaluando tus métricas...", "Analizando rendimiento...", "Generando insights...", "Casi Está Listo..."];
    let loadingInterval = null;

    // --- MANEJO DEL MENÚ MÓVIL ---
    mobileMenuButton.addEventListener('click', () => {
        sidebar.classList.toggle('-translate-x-full');
        sidebarOverlay.classList.toggle('hidden');
    });

    sidebarOverlay.addEventListener('click', () => {
        sidebar.classList.add('-translate-x-full');
        sidebarOverlay.classList.add('hidden');
    });
    
    // --- MANEJO DEL REPRODUCTOR DE VIDEO ---
    if (playOverlay && videoPlayer) {
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.play();
        });
    }
    
    // --- MÁSCARA DE INPUTS ---
    if (phoneInput) {
        IMask(phoneInput, { mask: '(000) 000-0000' });
    }
    
    // --- GESTIÓN DE NOTIFICACIONES TOAST ---
    const urlParams = new URLSearchParams(window.location.search);
    const notificationType = urlParams.get('notification_type');
    const notificationMessage = urlParams.get('notification_message');

    if (notificationType && notificationMessage && typeof showToast === 'function') {
        showToast(notificationMessage, notificationType);
    }

    // --- LÓGICA DEL ASISTENTE DE IA ---
    const validateForm = () => {
        const requiredInputs = form.querySelectorAll('[required]');
        let allValid = true;
        requiredInputs.forEach(input => {
            const isInvalid = !input.value.trim() || (input.type === 'number' && parseFloat(input.value) < 0);
            input.classList.toggle('border-red-500', isInvalid);
            if (isInvalid) allValid = false;
        });

        if (!allValid) {
            if (formErrorMessage) formErrorMessage.classList.remove('hidden');
            if (typeof showToast === 'function') showToast('Por favor, completa todos los campos requeridos con valores válidos.', 'warning');
        } else {
            if (formErrorMessage) formErrorMessage.classList.add('hidden');
        }
        return allValid;
    };

    const setProcessingState = (isProcessing) => {
        loaderContainer.classList.toggle('hidden', !isProcessing);
        generateBtn.disabled = isProcessing;
        generateBtn.classList.toggle('opacity-50', isProcessing);
        generateBtn.classList.toggle('cursor-not-allowed', isProcessing);

        if (isProcessing) {
            loaderContainer.innerHTML = '<div class="w-6 h-6 border-4 border-t-transparent border-[var(--color-primary)] rounded-full animate-spin"></div>';
            resultContainer.innerHTML = '';
            resultContainer.style.opacity = '0';
            resultContainer.style.transform = 'scale(0.95)';
            let messageIndex = 0;
            btnText.textContent = messages[messageIndex];
            loadingInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % messages.length;
                btnText.textContent = messages[messageIndex];
            }, 2500);
        } else {
            if (loadingInterval) clearInterval(loadingInterval);
            btnText.textContent = 'ANALIZAR TUS RESULTADOS';
        }
    };

    const displayResult = (data) => {
        const formatText = (text) => (text || '').replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');

        const planDeAccionHtml = data.plan_de_accion?.map(s => `
            <li class="flex items-start p-3 bg-gray-100 rounded-lg">
                <i data-lucide="check-circle" class="w-5 h-5 mr-3 text-green-500 flex-shrink-0 mt-1"></i>
                <span>${formatText(s)}</span>
            </li>
        `).join('') || '';

        resultContainer.innerHTML = `
            <div class="ai-response p-6 md:p-8 rounded-xl shadow-xl animate-slideInUp bg-white">
                <div class="mb-8 pb-6 border-b border-gray-200">
                    <h3 class="text-2xl font-bold text-gray-800 mb-4 flex items-center"><i data-lucide="clipboard-list" class="mr-3 text-[var(--color-secondary)]"></i>Diagnóstico General</h3>
                    <p class="text-lg text-gray-700 leading-relaxed">${formatText(data.diagnostico_general) || 'No se pudo generar un diagnóstico general.'}</p>
                </div>
                
                <div class="mb-8 pb-6 border-b border-gray-200">
                    <h3 class="text-2xl font-bold text-gray-800 mb-4 flex items-center"><i data-lucide="trending-up" class="mr-3 text-[var(--color-secondary)]"></i>Análisis Financiero y de Rendimiento</h3>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 text-center my-6">
                        <div class="bg-gray-50 p-6 rounded-lg border border-gray-200 shadow-sm">
                            <p class="text-sm text-gray-700 mb-2 font-semibold uppercase">Costo por Cliente Nuevo</p>
                            <span class="text-5xl font-black text-brand-dark">${data.metricas_clave?.cac || 'N/A'}</span>
                        </div>
                        <div class="bg-gray-50 p-6 rounded-lg border border-gray-200 shadow-sm">
                            <p class="text-sm text-gray-700 mb-2 font-semibold uppercase">Retorno de Inversión</p>
                            <span class="text-5xl font-black text-brand-dark">${data.metricas_clave?.roi || 'N/A'}</span>
                        </div>
                        <div class="bg-[var(--color-highlight)] p-6 rounded-lg border border-yellow-300 shadow-sm">
                            <p class="text-sm text-gray-800 mb-2 font-semibold uppercase">Tasa de Cierre</p>
                            <span class="text-5xl font-black text-brand-dark">${data.metricas_clave?.tasa_cierre || 'N/A'}</span>
                        </div>
                    </div>
                    <p class="text-lg text-gray-700 leading-relaxed mb-4">${formatText(data.analisis_financiero) || ''}</p>
                    <p class="text-lg text-gray-700 leading-relaxed">${formatText(data.diagnostico_anuncio) || ''}</p>
                </div>

                <div>
                    <h3 class="text-2xl font-bold text-gray-800 mb-4 flex items-center"><i data-lucide="rocket" class="mr-3 text-[var(--color-secondary)]"></i>Plan de Acción Sugerido</h3>
                    <ul class="space-y-4">
                        ${planDeAccionHtml}
                    </ul>
                </div>
            </div>
        `;
        
        lucide.createIcons();
        setTimeout(() => { 
            resultContainer.style.opacity = '1'; 
            resultContainer.style.transform = 'scale(1)'; 
            resultContainer.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }, 100);
    };

    form.addEventListener('submit', async (event) => {
        event.preventDefault();
        
        if (!validateForm()) {
            return;
        }

        setProcessingState(true);
        
        const formData = {
            campaign_objective: document.getElementById('campaign_objective').value,
            investment: parseFloat(document.getElementById('investment').value),
            messages: parseInt(document.getElementById('messages').value),
            closed_clients: parseInt(document.getElementById('closed_clients').value),
            service_price: parseFloat(document.getElementById('service_price').value),
            impressions: parseInt(document.getElementById('impressions').value) || 0,
            clicks: parseInt(document.getElementById('clicks').value) || 0,
            demographics: document.getElementById('demographics').value,
            locations: document.getElementById('locations').value,
            platform: document.getElementById('platform').value
        };

        try {
            const response = await fetch('api/api-analista-de-resultados-publicitarios.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || `El servidor respondió con un error ${response.status}.`);
            }

            const data = await response.json();
            if (data.error) {
                throw new Error(data.error);
            }
            
            displayResult(data);
            showToast('¡Análisis generado con éxito!', 'success');

        } catch (error) {
            console.error("Error:", error);
            let errorMessage = "No se pudo generar el análisis. Por favor, revisa los datos que ingresaste e inténtalo de nuevo.";

            try {
                const jsonStartIndex = error.message.indexOf('{');
                if (jsonStartIndex !== -1) {
                    const errorJsonString = error.message.substring(jsonStartIndex);
                    const errorDetails = JSON.parse(errorJsonString);
                    if (errorDetails.error?.code === 503) {
                        errorMessage = "LO SENTIMOS En Este Momento, Nuestra Inteligencia Artificial Está Saturada. Por favor, Inténtalo De Nuevo En Unos Minutos.";
                    } else {
                        errorMessage += ` Detalles: ${error.message}`;
                    }
                } else {
                    errorMessage += ` Detalles: ${error.message}`;
                }
            } catch (parseError) {
                errorMessage += ` Detalles: ${error.message}`;
            }

            resultContainer.innerHTML = `<div class="bg-red-100 text-center p-4 text-red-700 rounded-lg border border-red-300"><p><strong>Error:</strong> ${errorMessage}</p></div>`;
            resultContainer.style.opacity = '1';
            resultContainer.style.transform = 'scale(1)';
            if (typeof showToast === 'function') {
                showToast(errorMessage, 'error');
            }
        } finally {
            setProcessingState(false);
        }
    });
});
</script>
</body>
</html>