<?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>Generador de Emails de Seguimiento con IAMarketing™ Powered By OrozCO</title>
    <meta name="description" content="Crea emails de seguimiento post-servicio para fidelizar a tus clientes y fomentar la recompra.">
    <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>
    <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>

    <style>
        .step-header h2 {
            flex-direction: column;
            align-items: flex-start;
            text-align: left;
        }
        .step-header .step-number {
            font-size: 1.25rem;
            font-weight: 900;
            margin-right: 0;
            margin-bottom: 0.25rem;
            display: flex;
            align-items: center;
            color: var(--color-secondary);
            flex-shrink: 0;
        }
        .step-header .step-number i {
            margin-right: 0.5rem;
            font-size: 1.5rem;
        }
        .step-header .step-title {
            font-size: 1.4rem;
            font-weight: 900;
            color: #1e293b;
            line-height: 1.2;
            text-transform: uppercase;
            text-align: left;
            width: 100%;
        }
        @media (min-width: 768px) {
            .step-header h2 {
                flex-direction: row;
                align-items: center;
                justify-content: flex-start;
                text-align: left;
            }
            .step-header .step-number {
                font-size: 1.5rem;
                margin-right: 0.5rem;
                margin-bottom: 0;
            }
            .step-header .step-number i {
                font-size: 1.8rem;
            }
            .step-header .step-title {
                font-size: 1.5rem;
                width: auto;
            }
        }
    </style>
</head>
<body data-page-title="Generador de Emails de Seguimiento"
      data-page-subtitle="Crea emails post-servicio para fidelizar a tus clientes"
      data-page-icon="mail-check">

    <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="follow-up-email-generator" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
                    <div class="lg:col-span-3">
                        <form id="follow-up-form" class="space-y-8 bg-white p-8 rounded-xl shadow-md">
                            <input type="hidden" name="value_proposition" value="<?php echo htmlspecialchars($value_proposition); ?>">
                            <div>
                                <div class="step-header">
                                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                        <span class="step-number"> <i data-lucide="users-round" class="mr-3 text-[var(--color-secondary)]"></i> PASO 1:
                                        </span>
                                        <span class="step-title"> Contexto del Cliente y Servicio
                                        </span>
                                    </h2>
                                    <p class="step-subtitle uppercase">Ingresa la información fundamental para personalizar tu email.</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>
                                <div class="space-y-6">
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div>
                                            <label for="user_name" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tu Nombre:</label>
                                            <input type="text" id="user_name" name="user_name" placeholder="Ej: Miguel" 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)]" value="<?php echo htmlspecialchars($client_name); ?>">
                                        </div>
                                        <div>
                                            <label for="company_name" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Nombre De Tu Negocio:</label>
                                            <input type="text" id="company_name" name="company_name" placeholder="Ej: Super Car Wash" 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)]" value="<?php echo htmlspecialchars($business_name); ?>">
                                        </div>
                                    </div>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div>
                                            <label for="client_name" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Nombre De Tu Cliente:</label>
                                            <input type="text" id="client_name" name="client_name" placeholder="Ej: Ricardo" 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_type" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Servicio Realizado:</label>
                                            <input type="text" id="service_type" name="service_type" placeholder="Ej: Lavado Premium Con Cera" 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>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div>
                                            <label for="contact_phone" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tu Teléfono / WhatsApp:</label>
                                            <input type="text" id="contact_phone" name="contact_phone" placeholder="(555) 123-4567" 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)]" value="<?php echo htmlspecialchars($phone); ?>">
                                        </div>
                                        <div>
                                            <label for="contact_web" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Página Web / Red Social (Opcional):</label>
                                            <input type="text" id="contact_web" name="contact_web" placeholder="Ej: @SuperCarWash" 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)]" value="<?php echo htmlspecialchars($website); ?>">
                                        </div>
                                    </div>
                                    <div>
                                        <label for="scenario" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Selecciona Un Motivo:</label>
                                        <select id="scenario" name="scenario" 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="satisfaction">Agradecimiento y Satisfacción (0 - 1 Día)</option>
                                            <option value="recurrent">Recordatorio De Recompra (3-5 Días)</option>
                                            <option value="review">Solicitud De Reseña (1 - 2 Días)</option>
                                            <option value="referral">Oferta Por Referidos</option>
                                            <option value="reengage">Campaña De Volver A Conectar (1 Mes)</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label for="message_tone" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Selecciona El Tono:</label>
                                        <select id="message_tone" name="message_tone" 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="amigable_relajado">Amigable y Relajado</option>
                                            <option value="profesional_directo">Profesional y Directo</option>
                                            <option value="formal_conciso">Formal y Conciso</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label for="additional_details" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Detalles Adicionales (Opcional):</label>
                                        <textarea id="additional_details" name="additional_details" rows="3" placeholder="Ej: El Cliente Mencionó Que Su Auto No Había Brillado Así En 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)]"></textarea>
                                    </div>
                                </div>
                            </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="smile"></i></span>
                                    <div>
                                        <strong class="text-brand-dark uppercase">ELIGE EL MOTIVO:</strong> Selecciona el objetivo del email según el momento en que se encuentra tu cliente.
                                    </div>
                                </li>
                                <li class="instructions-list-item">
                                    <span class="icon-wrapper"><i data-lucide="mail"></i></span>
                                    <div>
                                        <strong class="text-brand-dark uppercase">TONO PROFESIONAL:</strong> La IA te dará borradores de email con un tono adecuado para la comunicación con clientes.
                                    </div>
                                </li>
                                <li class="instructions-list-item">
                                    <span class="icon-wrapper"><i data-lucide="repeat"></i></span>
                                    <div>
                                        <strong class="text-brand-dark uppercase">CONVIERTE EN RECURRENTE:</strong> Un buen seguimiento por email aumenta la satisfacción y las recompras.
                                    </div>
                                </li>
                                <li class="instructions-list-item">
                                    <span class="icon-wrapper"><i data-lucide="copy"></i></span>
                                    <div>
                                        <strong class="text-brand-dark uppercase">GENERA Y COPIA:</strong> Obtendrás tres ideas de emails listos para usar y un consejo estratégico.
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div>

                    <div class="lg:col-span-5 bg-white 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">
                                <span class="step-number"> <i data-lucide="zap" class="mr-3 text-[var(--color-secondary)]"></i> PASO 2:
                                </span>
                                <span class="step-title"> Genera Emails de Seguimiento Estratégico
                                </span>
                            </h2>
                            <p class="step-subtitle uppercase">Crea emails para construir relaciones duraderas con tus clientes</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">
                            <p class="text-lg text-center md:text-left text-gray-700 md:flex-1 md:pr-4 mb-0">Para retener a tus clientes y generar lealtad, <strong>es importante</strong> que definas el momento ideal para el contacto. Basándose en ese objetivo, nuestra Inteligencia Artificial <strong>IA Marketing</strong> creará tus <strong>Emails De Seguimiento</strong>, para que generes correos post-servicio que los hagan sentir valorados y vuelvan a comprar.</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="follow-up-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ú móvil y la interfaz
    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('follow-up-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 loadingMessages = ["Contactando con OrozCO IA...", "Analizando tu contexto...", "Redactando los emails...", "Afinando el borrador...", "¡Casi listo para enviar!"];
    let loadingInterval = null;

    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');
    });

    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);
    }

    if (playOverlay && videoPlayer) {
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.play();
        });
    }

    if (phoneInput) {
        IMask(phoneInput, { mask: '(000) 000-0000' });
    }

    const validateForm = () => {
        const requiredInputs = form.querySelectorAll('[required]');
        let allValid = true;
        requiredInputs.forEach(input => {
            const isInvalid = !input.value.trim();
            input.classList.toggle('border-red-500', isInvalid);
            if (isInvalid) allValid = false;
        });

        if (!allValid) {
            if (typeof showToast === 'function') {
                showToast('Por favor, completa todos los campos requeridos.', 'warning');
            }
        }
        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';
            let messageIndex = 0;
            btnText.textContent = loadingMessages[messageIndex];
            loadingInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % loadingMessages.length;
                btnText.textContent = loadingMessages[messageIndex];
            }, 2500);
        } else {
            if (loadingInterval) clearInterval(loadingInterval);
            btnText.textContent = 'GENERAR OTROS EMAILS';
        }
    };

    const displayResult = (suggestions) => {
        resultContainer.innerHTML = '';
        suggestions.forEach((data, index) => {
            const messageCard = document.createElement('div');
            messageCard.className = 'ai-response p-6 md:p-8 rounded-xl shadow-md space-y-6 animate-slideInUp';
            messageCard.style.animationDelay = `${index * 150}ms`;
            
            const spanish_message = data.spanish_message || "No disponible.";
            const english_message = data.english_message || "Not available.";
            const tip = data.tip || "No hay consejos adicionales.";

            messageCard.innerHTML = `
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <h3 class="text-xl font-bold text-gray-800 mb-3 flex items-center"><i data-lucide="mail" class="mr-2 text-[var(--color-primary)]"></i>Email Sugerido #${index + 1} (Español)</h3>
                        <div class="message-box bg-gray-50 p-4 rounded-lg border border-gray-200 shadow-sm whitespace-pre-wrap">${spanish_message.replace(/\n/g, '<br>')}</div>
                        <div class="copy-btn-wrapper mt-3">
                            <button class="btn-copy" data-copytarget-text="${encodeURIComponent(spanish_message)}">
                                <i data-lucide="copy"></i><span class="copy-text">Copiar Email</span>
                            </button>
                        </div>
                    </div>
                    <div>
                        <h3 class="text-xl font-bold text-gray-800 mb-3 flex items-center"><i data-lucide="mail" class="mr-2 text-[var(--color-primary)]"></i>Suggested Email #${index + 1} (English)</h3>
                        <div class="message-box bg-gray-50 p-4 rounded-lg border border-gray-200 shadow-sm whitespace-pre-wrap">${english_message.replace(/\n/g, '<br>')}</div>
                        <div class="copy-btn-wrapper mt-3">
                            <button class="btn-copy" data-copytarget-text="${encodeURIComponent(english_message)}">
                                <i data-lucide="copy"></i><span class="copy-text">Copy Email</span>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="pt-4 border-t border-gray-200">
                    <h3 class="text-xl font-bold text-gray-800 mb-3 flex items-center"><i data-lucide="lightbulb" class="mr-2 text-[var(--color-highlight)]"></i>Consejo Estratégico</h3>
                    <div class="tip-box bg-yellow-50 p-4 rounded-lg border-l-4 border-yellow-400 flex items-start">
                        <i data-lucide="info" class="text-yellow-500 mr-3 mt-1 flex-shrink-0"></i>
                        <div class="text-gray-700">${tip}</div>
                    </div>
                </div>
            `;
            resultContainer.appendChild(messageCard);
        });

        lucide.createIcons();
        resultContainer.style.opacity = '1';
        resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
    };

    resultContainer.addEventListener('click', (event) => {
        const button = event.target.closest('.btn-copy');
        if (!button) return;

        const textToCopy = decodeURIComponent(button.dataset.copytargetText);
        navigator.clipboard.writeText(textToCopy).then(() => {
            const buttonContent = button;
            const originalHTML = buttonContent.innerHTML;
            buttonContent.innerHTML = '<i data-lucide="check"></i><span class="copy-text">Copiado!</span>';
            lucide.createIcons();
            buttonContent.classList.add('copied');
            showToast('Email copiado al portapapeles.', 'success');
            setTimeout(() => {
                buttonContent.innerHTML = originalHTML;
                buttonContent.classList.remove('copied');
                lucide.createIcons({ nodes: [buttonContent] });
            }, 2000);
        }).catch(err => {
            console.error('Error al copiar:', err);
            showToast('No se pudo copiar el texto.', 'error');
        });
    });

    form.addEventListener('submit', async (event) => {
        event.preventDefault();

        if (!validateForm()) {
            return;
        }

        setProcessingState(true);

        const formData = {
            user_name: document.getElementById('user_name').value,
            company_name: document.getElementById('company_name').value,
            client_name: document.getElementById('client_name').value,
            service_type: document.getElementById('service_type').value,
            contact_phone: document.getElementById('contact_phone').value,
            contact_web: document.getElementById('contact_web').value,
            scenario: document.getElementById('scenario').value,
            message_tone: document.getElementById('message_tone').value,
            additional_details: document.getElementById('additional_details').value
        };

        try {
            const response = await fetch('api/api-asistente-de-seguimiento-clientes.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 || `Error del servidor: ${response.status}.`);
            }
            const data = await response.json();
            if (data.error) throw new Error(data.error);

            displayResult(data.suggestions);
            showToast('¡Emails generados con éxito!', 'success');

        } catch (error) {
            console.error("Error:", error);
            const errorMessage = `No se pudo generar el análisis. Detalles: ${error.message || 'Error desconocido.'}`;
            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>`;
            showToast(errorMessage, 'error');
        } finally {
            setProcessingState(false);
            resultContainer.style.opacity = '1';
        }
    });
});
</script>
</body>
</html>