<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');
require_once 'ia-marketing-results.php';
require_once 'media/videos-ia.php';

$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'] ?? '';
$logo_url = $client_info['logo_url'] ?? '';
$value_proposition = $ia_results['value_proposition'] ?? '';
$current_client_profiles = $ia_results['ideal_client_profiles'] ?? [];
$social_links = $client_info['social_links'] ?? [];

if (ob_get_level() > 0) { ob_end_clean(); }
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generador De Mensaje Primer Contacto Con <?php echo htmlspecialchars($branding['iamarketing_name']); ?> Powered_by <?php echo htmlspecialchars($branding['powered_by']); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>
    
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></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;
            justify-content: 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;
            text-align: left;
        }
        .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;
                text-align: left;
            }
            .step-header .step-number i {
                font-size: 1.8rem;
            }
            .step-header .step-title {
                font-size: 1.5rem;
                width: auto;
                text-align: left;
            }
        }
        .message-card {
            border: 1px solid #e5e7eb; border-radius: 0.75rem;
            margin-bottom: 1rem; overflow: hidden;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        }
        
        .tox-tinymce {
            border-radius: 0.5rem !important;
            border: 1px solid #d1d5db !important;
        }
    </style>
</head>
<body data-page-title="Generador De Mensaje Primer Contacto"
      data-page-subtitle="Crea Mensajes Iniciales Potentes Para Posibles Nuevos Clientes"
      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="first-contact-message-generator" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">

                    <div class="lg:col-span-3">
                        <form id="message-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">
                                        <span class="step-number"> <i data-lucide="edit" class="mr-3 text-[var(--color-secondary)]"></i>
                                            PASO 1:
                                        </span>
                                        <span class="step-title"> Contexto de Tu Negocio
                                        </span>
                                    </h2>
                                    <p class="step-subtitle uppercase">Ingresa tus datos para generar un mensaje personalizado</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                <div class="space-y-6">
                                    <div>
                                        <label for="business_name" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Nombre De Tu Negocio</label>
                                        <input type="text" id="business_name" name="business_name" placeholder="Ej: Soluciones Web Creativas" 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>
                                        <label for="website_url" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tu Página Web O Perfil Social (Opcional)</label>
                                        <input type="text" id="website_url" name="website_url" placeholder="Ej: SolucionesWeb.com" 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>
                                        <label for="phone_whatsapp" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tu Teléfono / WhatsApp</label>
                                        <input type="text" id="phone_whatsapp" name="phone_whatsapp" placeholder="Ej: (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="service_zone" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Zona Geográfica De Servicio (Opcional)</label>
                                        <input type="text" id="service_zone" name="service_zone" placeholder="Ej: Orlando, FL" 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($operating_cities); ?>">
                                    </div>
                                    <div>
                                        <label for="prospect_name" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Nombre Del Prospecto (Opcional)</label>
                                        <input type="text" id="prospect_name" name="prospect_name" placeholder="Ej: Sra. Díaz" 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>
                            </div>

                            <div class="pt-8">
                                <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="lightbulb" class="mr-3 text-[var(--color-secondary)]"></i>
                                            PASO 2:
                                        </span>
                                        <span class="step-title"> La Parte Importante de tu Mensaje
                                        </span>
                                    </h2>
                                    <p class="step-subtitle uppercase">Describe tu servicio y el objetivo de tu comunicación</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                <div class="space-y-6">
                                    <div>
                                        <label for="product_service_description" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Descripción De Tu Servicio Principal</label>
                                        <textarea id="product_service_description" name="product_service_description" placeholder="Ej: Creamos Páginas Web Modernas Para Negocios Que Quieren Vender Más" 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="4" required></textarea>
                                    </div>
                                    <div>
                                        <label for="desired_outcome_client" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Resultado Ideal Que Tu Cliente Busca</label>
                                        <textarea id="desired_outcome_client" name="desired_outcome_client" placeholder="Ej: Atraer Más Clientes Y Verse Profesionales En Internet" 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>
                                        <label for="contact_context" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Contexto Del Contacto (¿Por qué les escribes?)</label>
                                        <textarea id="contact_context" name="contact_context" placeholder="Ej: Los Encontré En Un Grupo De Facebook Y Creo Que Podrían Beneficiarse" 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="2" required></textarea>
                                    </div>
                                    <div>
                                        <label for="desired_outcome_message" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Objetivo Del Mensaje (¿Qué quieres que hagan?)</label>
                                        <select id="desired_outcome_message" name="desired_outcome_message" 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 Resultado</option>
                                            <option value="Agendar una llamada corta">Agendar Una Llamada Corta</option>
                                            <option value="Responder con una pregunta">Responder Con Una Pregunta</option>
                                            <option value="Visitar mi página web">Visitar Mi Página Web</option>
                                            <option value="Descargar un recurso gratuito">Descargar Un Recurso Gratuito</option>
                                            <option value="Solicitar más información">Solicitar Más Información</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label for="communication_tone" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tono De Comunicación</label>
                                        <select id="communication_tone" name="communication_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">Amigable</option>
                                            <option value="Profesional">Profesional</option>
                                            <option value="Entusiasta">Entusiasta</option>
                                            <option value="Directo">Directo</option>
                                            <option value="Empático">Empático</option>
                                            <option value="Innovador">Innovador</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div id="form-error-message" class="hidden bg-[var(--color-secondary)] text-center p-3 text-white rounded-lg border border-[var(--color-secondary)]" role="alert">
                                Por Favor, Completa Todos Los Campos Requeridos.
                            </div>
                             <input type="hidden" name="value_proposition" value="<?php echo htmlspecialchars($value_proposition); ?>">
                        </form>
                    </div>

                    <div class="lg:col-span-2 space-y-8">
                        
                        <?php if (!empty($logo_url)): ?>
                            <div class="bg-white p-4 rounded-xl shadow-md">
                                <img src="<?php echo htmlspecialchars($logo_url); ?>" 
                                     alt="Logotipo de <?php echo htmlspecialchars($business_name); ?>" 
                                     class="block mx-auto" 
                                     style="max-width: 250px;">
                            </div>
                        <?php endif; ?>
                        
                        <button id="open-messages-panel-btn" class="btn-copy bg-[var(--color-secondary)] text-white flex items-center justify-center w-full py-4 px-6 rounded-lg font-black text-lg uppercase gap-2 hover:scale-102 transition-transform">
                            <i data-lucide="save" class="w-5 h-5"></i> <span>Tus Mensajes Guardados</span>
                        </button>

                        <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 Tutorial
                                        </span>
                                        <span class="inline-flex items-center gap-2">
                                            <i data-lucide="clock" class="w-4 h-4"></i> 2:30 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="lightbulb"></i></span><div><strong class="text-brand-dark uppercase">SÉ PRECISO:</strong> Cuanta más información des sobre el prospecto y el contexto, más efectivo será el mensaje.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="bot"></i></span><div><strong class="text-brand-dark uppercase">GENERA OPCIONES:</strong> Nuestra IA te dará varias versiones de mensajes para que elijas.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="copy"></i></span><div><strong class="text-brand-dark uppercase">COPIA Y ADAPTA:</strong> Copia el mensaje que mejor se ajuste y adáptalo a tu estilo si es necesario.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="messages-square"></i></span><div><strong class="text-brand-dark uppercase">INICIA LA CONVERSACIÓN:</strong> Usa estos mensajes para romper el hielo y empezar a conectar con potenciales clientes.</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="send" class="mr-3 text-[var(--color-secondary)]"></i>
                                    PASO 3:
                                </span>
                                <span class="step-title">
                                    Genera Tus Mensajes de Primer Contacto
                                </span>
                            </h2>
                            <p class="step-subtitle text-center md:text-left uppercase">Crea mensajes persuasivos para iniciar conversaciones de venta</p>
                        </div>
                        <div class="border-b border-gray-200 pb-4 mb-6"></div>
                        
<div class="grid grid-cols-1 md:grid-cols-3 gap-6 md:gap-8 items-center">

    <div class="flex flex-col justify-center items-center bg-[var(--color-primary)] p-6 rounded-xl">
        <i data-lucide="brain" class="w-24 h-24 md:w-32 md:h-32 text-white animate-pulse"></i>
        <p class="mt-4 text-white font-black text-xl uppercase tracking-wide">
            IA<span class="text-[var(--color-highlight)]">Marketing</span>™
        </p>
    </div>

    <div class="md:col-span-2 text-center md:text-left">
        
        <h3 class="text-2xl font-black text-gray-800 flex items-center justify-center md:justify-start mb-2 uppercase">
            <i data-lucide="bell-electric" class="w-6 h-6 text-[var(--color-secondary)] mr-2 flex-shrink-0"></i>
            Información Importante
        </h3>
        
        <p class="text-lg text-gray-700 mb-6">
            Para abrir conversaciones que generen clientes potenciales, <b>es muy importante</b> que conozcas el interés de tu cliente potencial. Con esa información, nuestra <b>inteligencia artificial</b> generará tus <b>Mensajes de Primer Contacto</b>, para que inicies conversaciones de forma potente y transformes a tus posibles nuevos clientes en oportunidades de venta reales.
        </p>
        
        <div class="flex justify-center md:justify-start">
            <button id="generateBtn" type="submit" form="message-form" class="w-full sm:w-auto bg-[var(--color-highlight)] text-[var(--color-primary)] font-black py-4 px-6 rounded-lg hover:scale-105 transition-transform text-lg flex items-center justify-center uppercase">
                
                <i data-lucide="arrow-big-right-dash" class="w-6 h-6"></i>
                
                <span id="btn-text">GENERAR MENSAJES CON IA</span>
                
                <div id="loader-container" class="hidden ml-3"></div>
            </button>
        </div>
    </div>
    
</div>
                        
                    </div>

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

<div id="messages-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 hidden" aria-hidden="true"></div>

<div id="messages-panel" class="fixed top-0 right-0 h-full w-full lg:w-1/3 bg-[var(--color-background)] z-50 transform translate-x-full transition-transform duration-300 ease-in-out shadow-2xl flex flex-col">
    
    <div class="flex-shrink-0 flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow z-20">
        <h3 class="text-3xl font-black text-[var(--color-highlight)] flex items-center uppercase">
            <i data-lucide="save" class="w-8 h-8 mr-2 text-white"></i>
            MENSAJES GUARDADOS
        </h3>
        <button id="close-messages-panel-btn" class="bg-[var(--color-secondary)] text-white hover:text-[var(--color-highlight)] p-1 rounded-md transition-colors duration-200">
            <i data-lucide="x" class="w-8 h-8"></i>
        </button>
    </div>

    <div class="flex-grow overflow-y-auto p-6 relative">
        
        <div id="messages-panel-content" class="bg-white p-6 rounded-xl shadow-md transition duration-300 min-h-[200px]">
            <div class="flex flex-col items-center justify-center h-40 text-gray-400">
                <i data-lucide="loader-2" class="w-8 h-8 animate-spin mb-2"></i>
                <span class="text-sm font-bold uppercase">Cargando mensajes...</span>
            </div>
        </div>
        
    </div>

    <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10"> 
        <button type="button" onclick="document.getElementById('close-messages-panel-btn').click()" class="w-full btn-cancel uppercase flex items-center justify-center gap-2">
            <i data-lucide="x-circle" class="w-5 h-5"></i> CERRAR PANEL DE RESULTADOS
        </button>
    </div>

</div>

<div id="confirmation-modal" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center hidden z-[100]"> 
    <div class="bg-white p-8 rounded-xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center">
        <div class="flex justify-center mb-4">
            <i id="modal-icon" data-lucide="alert-triangle" class="w-16 h-16 text-[var(--color-secondary)]"></i>
        </div>
        <h3 id="modal-title" class="text-2xl font-bold text-[var(--color-primary)] mb-4 uppercase">CONFIRMAR ACCIÓN</h3>
        <p id="modal-message" class="text-gray-700 mb-6 uppercase">¿Estás seguro?</p>
        <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm:space-x-4">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase w-full sm:w-auto" id="modal-cancel-btn">CANCELAR</button>
            <button type="button" class="btn-secondary font-bold text-white py-2 px-4 rounded-lg uppercase w-full sm:w-auto" id="modal-confirm-btn">CONFIRMAR</button>
        </div>
    </div>
</div>


<div id="input-modal" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center hidden z-[100]">
    <div class="bg-white p-8 rounded-xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-left">
        <h3 id="input-modal-title" class="text-2xl font-bold text-[var(--color-primary)] mb-4 uppercase"></h3>
        <p id="input-modal-message" class="text-gray-700 mb-4"></p>
        <input type="text" id="input-modal-field" 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)]" placeholder="Escribe aquí...">
        <p id="input-modal-error" class="text-[var(--color-secondary)] text-sm mt-1 hidden">El nombre no puede estar vacío.</p>
        <div class="flex justify-end space-x-4 mt-6">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" id="input-modal-cancel-btn">CANCELAR</button>
            <button type="button" class="btn-secondary font-bold text-white py-2 px-4 rounded-lg uppercase" id="input-modal-confirm-btn">GUARDAR</button>
        </div>
    </div>
</div>


<script type="module">
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
    
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');

    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) {
        if (typeof showToast === 'function') {
            showToast(notificationMessage, notificationType);
        } else {
            console.error("showToast function is not defined.");
        }
    }
    
    const playOverlay = document.getElementById('playOverlay');
    const videoPlayer = document.getElementById('videoPlayer');
    
    if (playOverlay && videoPlayer) {
        videoPlayer.controls = false;
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.controls = true;
            videoPlayer.play().catch(e => {
                if (typeof showToast === 'function') {
                    showToast("Error al reproducir video: " + e.message, 'error');
                }
            });
        });
        videoPlayer.addEventListener('ended', () => {
            playOverlay.style.display = 'flex';
            videoPlayer.controls = false;
        });
    }
    
    const phoneInput = document.getElementById('phone_whatsapp');
    if (phoneInput) {
        IMask(phoneInput, { mask: '(000) 000-0000' });
    }

    const form = document.getElementById('message-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 confirmationModal = document.getElementById('confirmation-modal');
    const modalIcon = document.getElementById('modal-icon');
    const modalTitle = document.getElementById('modal-title');
    const modalMessage = document.getElementById('modal-message');
    const modalConfirmBtn = document.getElementById('modal-confirm-btn');
    const modalCancelBtn = document.getElementById('modal-cancel-btn');
    const modalContent = confirmationModal.querySelector('div:first-of-type');
    let onConfirmCallback = null;

    const inputModal = document.getElementById('input-modal');
    const inputModalBox = inputModal.querySelector('div:first-of-type');
    const inputModalTitle = document.getElementById('input-modal-title');
    const inputModalMessage = document.getElementById('input-modal-message');
    const inputModalField = document.getElementById('input-modal-field');
    const inputModalError = document.getElementById('input-modal-error');
    const inputModalCancelBtn = document.getElementById('input-modal-cancel-btn');
    const inputModalConfirmBtn = document.getElementById('input-modal-confirm-btn');
    let onInputConfirmCallback = null;

    function openModal({ title, message, icon, confirmText, confirmClass, onConfirm }) {
        modalTitle.textContent = title;
        modalMessage.innerHTML = message;
        modalIcon.setAttribute('data-lucide', icon);
        lucide.createIcons({ nodes: [modalIcon] });
        modalConfirmBtn.textContent = confirmText || 'CONFIRMAR';
        modalConfirmBtn.className = 'btn-secondary font-bold py-2 px-4 rounded-lg uppercase w-full sm:w-auto text-white'; 
        if (confirmClass === 'danger') {
            modalConfirmBtn.classList.add('bg-[var(--color-secondary)]', 'hover:bg-[var(--color-secondary)]');
            modalConfirmBtn.classList.remove('btn-secondary');
        } else if (confirmClass === 'primary') {
             modalConfirmBtn.classList.add('bg-[var(--color-primary)]');
             modalConfirmBtn.classList.remove('btn-secondary');
        }
        onConfirmCallback = onConfirm; 
        confirmationModal.classList.remove('hidden');
        setTimeout(() => modalContent.classList.remove('scale-95', 'opacity-0'), 50);
        document.body.style.overflow = 'hidden';
    }

    function closeModal() {
        modalContent.classList.add('scale-95', 'opacity-0');
        setTimeout(() => {
            confirmationModal.classList.add('hidden');
            document.body.style.overflow = '';
        }, 300);
        onConfirmCallback = null;
    }

    modalCancelBtn.addEventListener('click', closeModal);
    modalConfirmBtn.addEventListener('click', () => {
        if (typeof onConfirmCallback === 'function') {
            onConfirmCallback();
        }
        closeModal();
    });

    confirmationModal.addEventListener('click', (e) => {
        if (e.target === confirmationModal) {
            closeModal();
        }
    });

    function openInputModal({ title, message, placeholder, defaultValue, confirmText, onConfirm }) {
        inputModalTitle.textContent = title;
        inputModalMessage.textContent = message;
        inputModalField.placeholder = placeholder || "Escribe aquí...";
        inputModalField.value = defaultValue || "";
        inputModalConfirmBtn.textContent = confirmText || 'GUARDAR';
        onInputConfirmCallback = onConfirm;
        
        inputModalError.classList.add('hidden');
        inputModal.classList.remove('hidden');
        setTimeout(() => {
            inputModalBox.classList.remove('scale-95', 'opacity-0');
            inputModalField.focus();
        }, 50);
        document.body.style.overflow = 'hidden';
    }

    function closeInputModal() {
        inputModalBox.classList.add('scale-95', 'opacity-0');
        setTimeout(() => {
            inputModal.classList.add('hidden');
            document.body.style.overflow = '';
        }, 300);
        onInputConfirmCallback = null;
    }

    inputModalCancelBtn.addEventListener('click', closeInputModal);
    inputModalConfirmBtn.addEventListener('click', () => {
        const value = inputModalField.value.trim();
        if (value === "") {
            inputModalError.classList.remove('hidden');
        } else {
            inputModalError.classList.add('hidden');
            if (typeof onInputConfirmCallback === 'function') {
                onInputConfirmCallback(value);
            }
            closeInputModal();
        }
    });
    
    const MAX_MESSAGES = 10;
    let generatedMessages = null;
    let savedMessageButtons = {};
    let savedMessages = [];
    
    const messageEndpoints = {
        fetch: 'api-db/ia-first-contact-message-fetch.php',
        create: 'api-db/ia-first-contact-message-create.php',
        update: 'api-db/ia-first-contact-message-update.php',
        delete: 'api-db/ia-first-contact-message-delete.php'
    };
    
    const openMessagesPanelBtn = document.getElementById('open-messages-panel-btn');
    const closeMessagesPanelBtn = document.getElementById('close-messages-panel-btn');
    const messagesPanelOverlay = document.getElementById('messages-panel-overlay');
    const messagesPanel = document.getElementById('messages-panel');
    const messagesPanelContent = document.getElementById('messages-panel-content');

    openMessagesPanelBtn.addEventListener('click', openMessagesPanel);
    closeMessagesPanelBtn.addEventListener('click', closeMessagesPanel);
    messagesPanelOverlay.addEventListener('click', closeMessagesPanel);

    function openMessagesPanel() {
        messagesPanel.classList.remove('translate-x-full');
        messagesPanelOverlay.classList.remove('hidden');
        fetchAndDrawMessages();
    }
    function closeMessagesPanel() {
        messagesPanel.classList.add('translate-x-full');
        messagesPanelOverlay.classList.add('hidden');
    }

    async function fetchAndDrawMessages() {
        messagesPanelContent.innerHTML = '<div class="text-center p-4"><div class="w-8 h-8 border-4 border-t-transparent border-[var(--color-secondary)] rounded-full animate-spin mx-auto mb-3"></div><p class="text-gray-600">Cargando mensajes guardados...</p></div>';
        try {
            const response = await fetch(messageEndpoints.fetch, { method: 'POST' });
            const result = await response.json();

            if (response.ok && result.success) {
                savedMessages = result.messages;
                if (savedMessages.length === 0) {
                    messagesPanelContent.innerHTML = `<div class="text-center p-4 border border-dashed rounded-lg"><i data-lucide="info" class="w-12 h-12 text-gray-400 mx-auto mb-3"></i><p class="text-gray-500">Aún no tienes mensajes guardados.</p></div>`;
                } else {
                    let html = `<p class="text-gray-600 mb-4 uppercase font-black">Has guardado ${savedMessages.length} de ${MAX_MESSAGES} mensajes.</p>`;
                    html += '<div class="space-y-6">';
                    savedMessages.forEach((msg) => { html += createSavedMessageCard(msg); });
                    html += '</div>';
                    messagesPanelContent.innerHTML = html;
                }
            } else {
                throw new Error(result.message || 'Error al obtener mensajes.');
            }
        } catch (error) {
            messagesPanelContent.innerHTML = `<div class="bg-[var(--color-secondary)] text-center p-4 text-white rounded-lg border border-[var(--color-secondary)]"><p><strong>Error al cargar:</strong> ${error.message}</p></div>`;
        }
        lucide.createIcons();
    }
    
    function createSavedMessageCard(msg) {
        const full_es = msg.message_es;
        const full_en = msg.message_en;
        
        return `
            <div class="border border-gray-200 rounded-xl overflow-hidden" data-msg-id="${msg.id}">
                <div class="bg-gray-50 p-4 flex justify-between items-center">
                    <div id="display-name-${msg.id}" class="flex-1 overflow-hidden">
                        <h4 class="text-lg font-black uppercase text-[var(--color-primary)] truncate" title="${msg.context_input}">
                            ${msg.context_input}
                        </h4>
                    </div>
                    <div id="edit-name-area-${msg.id}" class="flex-1 hidden">
                        <textarea id="edit-context-input-${msg.id}" class="w-full p-2 border border-gray-300 rounded-lg text-sm bg-white" rows="2">${msg.context_input}</textarea>
                    </div>
                    <div class="flex space-x-2 ml-4">
                        <button class="btn-copy btn-xs bg-[var(--color-primary)] text-white btn-panel-edit" data-id="${msg.id}"><i data-lucide="edit"></i></button>
                        <button class="btn-copy btn-xs bg-[var(--color-secondary)] text-white btn-panel-delete" data-id="${msg.id}"><i data-lucide="trash-2"></i></button>
                        <button class="btn-copy btn-xs bg-green-600 text-white btn-panel-save hidden" data-id="${msg.id}"><i data-lucide="save"></i></button>
                        <button class="btn-copy btn-xs bg-gray-500 text-white btn-panel-cancel hidden" data-id="${msg.id}"><i data-lucide="x"></i></button>
                    </div>
                </div>
                <div class="p-4">
                    <div id="display-content-${msg.id}" class="space-y-4">
                        <div class="bg-gray-50 p-3 rounded-lg border">
                            <strong class="text-[var(--color-secondary)]">🇪🇸 Español:</strong>
                            <div class="text-gray-800 whitespace-pre-wrap">${msg.message_es.replace(/\n/g, '<br>')}</div>
                            <button class="btn-copy btn-xs bg-[var(--color-highlight)] text-[var(--color-primary)] mt-2" data-copy-text="${encodeURIComponent(full_es)}">
                                <i data-lucide="copy"></i> Copiar ES
                            </button>
                        </div>
                         <div class="bg-gray-50 p-3 rounded-lg border">
                            <strong class="text-[var(--color-primary)]">🇺🇸 English:</strong>
                            <div class="text-gray-800 whitespace-pre-wrap">${msg.message_en.replace(/\n/g, '<br>')}</div>
                            <button class="btn-copy btn-xs bg-blue-600 text-white mt-2" data-copy-text="${encodeURIComponent(full_en)}">
                                <i data-lucide="copy"></i> Copiar EN
                            </button>
                        </div>
                    </div>
                    <div id="edit-content-area-${msg.id}" class="hidden mt-4 space-y-3">
                        <label class="block font-bold text-gray-700">🇪🇸 Español:</label>
                        <textarea id="edit-es-${msg.id}" class="w-full p-2 border rounded-lg" rows="6">${msg.message_es}</textarea>
                        
                        <label class="block font-bold text-gray-700">🇺🇸 English:</label>
                        <textarea id="edit-en-${msg.id}" class="w-full p-2 border rounded-lg" rows="6">${msg.message_en}</textarea>
                    </div>
                </div>
            </div>
        `;
    }

    messagesPanelContent.addEventListener('click', function(e) {
        const editBtn = e.target.closest('.btn-panel-edit');
        const deleteBtn = e.target.closest('.btn-panel-delete');
        const saveBtn = e.target.closest('.btn-panel-save');
        const cancelBtn = e.target.closest('.btn-panel-cancel');
        const copyBtn = e.target.closest('[data-copy-text]');

        if (editBtn) {
            const id = editBtn.dataset.id;
            toggleEditMode(id, true);
            
            if (typeof tinymce !== 'undefined') {
                tinymce.init({
                    selector: `#edit-context-input-${id}, #edit-es-${id}, #edit-en-${id}`,
                    menubar: false,
                    statusbar: false,
                    height: 250,
                    plugins: 'lists link',
                    toolbar: 'bold italic underline | bullist numlist | removeformat',
                    language: 'es',
                    skin: 'oxide',
                    content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px; color:#333; }'
                });
            }
        }
        
        if (cancelBtn) {
            const id = cancelBtn.dataset.id;
            
            if (typeof tinymce !== 'undefined') {
                tinymce.remove(`#edit-context-input-${id}`);
                tinymce.remove(`#edit-es-${id}`);
                tinymce.remove(`#edit-en-${id}`);
            }
            toggleEditMode(id, false);
            
            const msg = savedMessages.find(m => m.id == id);
            if (msg) {
                document.getElementById(`edit-context-input-${id}`).value = msg.context_input;
            }
        }
        
        if (saveBtn) {
            const id = saveBtn.dataset.id;
            handleUpdateMessage(id);
        }
        
        if (deleteBtn) {
            const id = deleteBtn.dataset.id;
            handleDeleteMessage(id);
        }
        
        if (copyBtn) {
            const textToCopy = decodeURIComponent(copyBtn.dataset.copyText);
            navigator.clipboard.writeText(textToCopy).then(() => {
                const originalHTML = copyBtn.innerHTML;
                copyBtn.innerHTML = '<i data-lucide="check" class="w-4 h-4"></i> Copiado!';
                lucide.createIcons({ nodes: [copyBtn] });
                if (typeof showToast === 'function') showToast('Copiado al portapapeles.', 'success');
                setTimeout(() => { copyBtn.innerHTML = originalHTML; lucide.createIcons({ nodes: [copyBtn] }); }, 2000);
            }).catch(err => console.error('Error al copiar:', err));
        }
    });

    function toggleEditMode(id, isEditing) {
        const container = document.querySelector(`[data-msg-id="${id}"]`);
        if (!container) return;

        container.querySelector(`#display-name-${id}`).classList.toggle('hidden', isEditing);
        container.querySelector(`#edit-name-area-${id}`).classList.toggle('hidden', !isEditing);
        container.querySelector(`#display-content-${id}`).classList.toggle('hidden', isEditing);
        container.querySelector(`#edit-content-area-${id}`).classList.toggle('hidden', !isEditing);
        
        // CORRECCIÓN: Visibilidad de botones en el header
        container.querySelector(`.btn-panel-edit`).classList.toggle('hidden', isEditing);
        container.querySelector(`.btn-panel-delete`).classList.toggle('hidden', isEditing);
        container.querySelector(`.btn-panel-save`).classList.toggle('hidden', !isEditing);
        container.querySelector(`.btn-panel-cancel`).classList.toggle('hidden', !isEditing);
    }

    async function handleUpdateMessage(id) {
        let payload = { id: parseInt(id, 10) };
        const fields = ['context-input', 'es', 'en'];
        
        fields.forEach(field => {
            const editorId = `edit-${field}-${id}`;
            const key = (field === 'context-input') ? 'context_input' : `message_${field}`;
            
            if (typeof tinymce !== 'undefined' && tinymce.get(editorId)) {
                payload[key] = tinymce.get(editorId).getContent();
                tinymce.remove(editorId);
            } else {
                payload[key] = document.getElementById(editorId).value;
            }
        });

        openModal({
            title: 'CONFIRMAR ACTUALIZACIÓN',
            message: '¿Estás seguro de que quieres guardar estos cambios?',
            icon: 'save',
            confirmText: 'SÍ, GUARDAR',
            onConfirm: async () => {
                await updateMessageInDB(payload);
                await fetchAndDrawMessages();
            }
        });
    }
    
    async function updateMessageInDB(payload) {
         setProcessingState(true, 'Actualizando...');
         try {
            const response = await fetch(messageEndpoints.update, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast(result.message, 'success');
            } else {
                 if (typeof showToast === 'function') showToast(result.message, 'warning');
                 throw new Error(result.message || 'Error desconocido al actualizar.');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al actualizar: ${error.message}`, 'error');
        } finally {
            setProcessingState(false);
        }
    }
    
    async function saveIndividualMessage(messageData, button) {
        setProcessingState(true, `Guardando Mensaje...`); 
        try {
            if (savedMessages.length >= MAX_MESSAGES) {
                 if (typeof showToast === 'function') showToast(`Límite de ${MAX_MESSAGES} mensajes alcanzado. Elimina uno para guardar.`, 'warning');
                 setProcessingState(false);
                 return;
            }

            const response = await fetch(messageEndpoints.create, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(messageData)
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast(result.message, 'success');
                if (button) {
                    button.disabled = true;
                    button.classList.add('bg-green-600', 'opacity-50');
                    button.classList.remove('bg-[var(--color-primary)]');
                    button.innerHTML = '<i data-lucide="check"></i> <span>¡Guardado!</span>';
                    lucide.createIcons({ nodes: [button] });
                }
                openMessagesPanel();
            } else {
                 if (typeof showToast === 'function') showToast(result.message, 'warning');
                 throw new Error(result.message || 'Error desconocido al guardar el mensaje.');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al guardar: ${error.message}`, 'error');
        } finally {
            setProcessingState(false);
        }
    }
    
    function handleDeleteMessage(msgId) {
        openModal({
            title: 'ELIMINAR MENSAJE',
            message: '¿Estás seguro de que quieres eliminar este mensaje? Esta acción no se puede deshacer.',
            icon: 'alert-triangle',
            confirmText: 'SÍ, ELIMINAR',
            confirmClass: 'danger',
            onConfirm: async () => {
                await deleteMessageFromDB(msgId);
                await fetchAndDrawMessages();
            }
        });
    }

    async function deleteMessageFromDB(msgId) {
        setProcessingState(true, 'Eliminando...');
        try {
            const response = await fetch(messageEndpoints.delete, {
                method: 'POST', 
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ id: msgId })
            });
            const result = await response.json();
            if (response.ok && result.success) {
                if (typeof showToast === 'function') toast(result.message, 'success');
            } else {
                throw new Error(result.message || 'Error desconocido al eliminar.');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al eliminar: ${error.message}`, 'error');
        } finally {
            setProcessingState(false);
        }
    }
    
    function validateForm() {
        const requiredInputs = form.querySelectorAll('[required]');
        let allValid = true;
        requiredInputs.forEach(input => {
            if (!input.value.trim() || (input.tagName === 'SELECT' && input.value === '')) {
                input.classList.add('border-[var(--color-secondary)]');
                allValid = false;
            } else {
                input.classList.remove('border-[var(--color-secondary)]');
            }
        });

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

    function setProcessingState(isProcessing, customMessage = null) {
        if (isProcessing) {
            loaderContainer.innerHTML = '<div class="w-6 h-6 border-4 border-t-transparent border-[var(--color-primary)] rounded-full animate-spin"></div>';
            loaderContainer.classList.remove('hidden');
            generateBtn.disabled = true;
            generateBtn.classList.add('opacity-50', 'cursor-not-allowed');
            
            if (customMessage) {
                 btnText.textContent = customMessage;
                 if (window.loadingInterval) clearInterval(window.loadingInterval);
                 window.loadingInterval = null;
                 return;
            }

            resultContainer.innerHTML = ''; 
            resultContainer.style.opacity = '0'; 
            resultContainer.style.transform = 'scale(0.95)';

            const messages = ["Contactando Con OrozCO IA...", "Analizando datos...", "Creando mensajes...", "Optimizando tono...", "Casi Está Listo..."];
            let messageIndex = 0;
            btnText.textContent = messages[messageIndex];

            window.loadingInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % messages.length;
                btnText.textContent = messages[messageIndex];
            }, 2500);

        } else {
            if (window.loadingInterval) clearInterval(window.loadingInterval);
            loaderContainer.classList.add('hidden');
            generateBtn.disabled = false;
            generateBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            btnText.textContent = 'GENERAR CON IA MARKETING';
        }
    }


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

        if (!validateForm()) {
            return;
        }

        setProcessingState(true);

        const formData = {
            business_name: document.getElementById('business_name').value,
            website_url: document.getElementById('website_url').value,
            phone_whatsapp: document.getElementById('phone_whatsapp').value,
            service_zone: document.getElementById('service_zone').value,
            prospect_name: document.getElementById('prospect_name').value,
            product_service_description: document.getElementById('product_service_description').value,
            desired_outcome_client: document.getElementById('desired_outcome_client').value,
            contact_context: document.getElementById('contact_context').value,
            desired_outcome: document.getElementById('desired_outcome_message').value,
            communication_tone: document.getElementById('communication_tone').value,
            value_proposition: document.querySelector('input[name="value_proposition"]').value
        };

        const contextInput = `${formData.contact_context} | Objetivo: ${formData.desired_outcome} | Tono: ${formData.communication_tone}`;


        try {
            const response = await fetch('api/api-first-contact-message.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.messages, contextInput);
            showToast('¡Mensajes generados con éxito!', 'success');

        } catch (error) {
            let errorMessage = "No se pudieron generar los mensajes. Por favor, revisa los datos e inténtalo de nuevo.";

            resultContainer.innerHTML = `<div class="bg-[var(--color-secondary)] text-center p-4 text-white rounded-lg border border-[var(--color-secondary)]"><p><strong>Error:</strong> ${errorMessage}</p></div>`;
            resultContainer.style.opacity = '1';
            showToast(errorMessage, 'error');
        } finally {
            setProcessingState(false);
        }
    });

    function displayResult(messages, contextInput) {
        let allMessagesHtml = '';
        messages.forEach((message, index) => {
            const savePayload = {
                message_es: message.es,
                message_en: message.en,
                context_input: contextInput 
            };

            allMessagesHtml += `
                <div class="bg-white p-6 rounded-xl shadow-lg mb-8">
                    <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                        <i data-lucide="message-square" class="mr-3 text-[var(--color-primary)]"></i>Mensaje Sugerido ${index + 1}
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
                        <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <div class="flex justify-between items-center mb-3">
                                <h4 class="text-lg font-semibold text-gray-700">🇪🇸 Español</h4>
                                <button class="btn-copy" data-copy-text="${encodeURIComponent(message.es)}">
                                    <i data-lucide="copy"></i><span class="copy-text">Copiar</span>
                                </button>
                            </div>
                            <div>
                                <p class="text-gray-800 leading-relaxed whitespace-pre-wrap">${message.es.replace(/\n/g, '<br>')}</p>
                            </div>
                        </div>
                        <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <div class="flex justify-between items-center mb-3">
                                <h4 class="text-lg font-semibold text-gray-700">🇺🇸 English</h4>
                                <button class="btn-copy" data-copy-text="${encodeURIComponent(message.en)}">
                                    <i data-lucide="copy"></i><span class="copy-text">Copy</span>
                                </button>
                            </div>
                            <div>
                                <p class="text-gray-800 leading-relaxed whitespace-pre-wrap">${message.en.replace(/\n/g, '<br>')}</p>
                            </div>
                        </div>
                    </div>
                    <div class="mt-4 text-center">
                        <button class="btn-save-message btn-copy bg-[var(--color-primary)] text-white font-bold py-2 px-6 rounded-lg flex items-center justify-center mx-auto gap-2 hover:scale-105 transition-transform uppercase"
                                data-payload="${encodeURIComponent(JSON.stringify(savePayload))}">
                            <i data-lucide="save"></i> <span>Guardar Mensaje</span>
                        </button>
                    </div>
                </div>
            `;
        });

        resultContainer.innerHTML = `<div class="ai-response p-6 md:p-8 rounded-xl shadow-md">${allMessagesHtml}</div>`;
        lucide.createIcons();
        setTimeout(() => { resultContainer.style.opacity = '1'; resultContainer.style.transform = 'scale(1)'; resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' }); }, 100);

        resultContainer.querySelectorAll('.btn-copy').forEach(button => {
            button.addEventListener('click', function(e) {
                 if(this.classList.contains('btn-save-message')) return; 
                 const textToCopy = decodeURIComponent(this.dataset.copyText);
                 navigator.clipboard.writeText(textToCopy).then(() => {
                    const originalHtml = this.innerHTML;
                    this.innerHTML = '<i data-lucide="check"></i> Copiado';
                    lucide.createIcons({nodes: [this]});
                    setTimeout(() => { this.innerHTML = originalHtml; lucide.createIcons({nodes: [this]}); }, 2000);
                 });
            });
        });
        
        resultContainer.querySelectorAll('.btn-save-message').forEach(button => {
            button.addEventListener('click', function() {
                const payload = JSON.parse(decodeURIComponent(this.dataset.payload));
                saveIndividualMessage(payload, this);
            });
        });
    }
});
</script>
<script src="files/toast.js"></script>
</body>
</html>