<?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>Asistente Inteligente De Ventas 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>

</head>
<body data-page-title="Asistente Inteligente De Ventas"
      data-page-subtitle="Tu Copiloto De IA Que Te Dice Qué Responder Para Cerrar Más Ventas"
      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="sales-copilot" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
                    <div class="lg:col-span-3">
                        <form id="copilot-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="book-open" class="mr-3 text-[var(--color-secondary)]"></i> PASO 1:
                                        </span>
                                        <span class="step-title"> Contexto de la Venta
                                        </span>
                                    </h2>
                                    <p class="step-subtitle uppercase">Define los detalles para que la IA entienda la situación.</p>
                                </div>
                                <div class="border-b border-[var(--color-primary)] pb-4 mb-6"></div>
                                <div id="context-section" class="space-y-6">
                                    <div>
                                        <label for="client_name" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Nombre Del Prospecto</label>
                                        <input type="text" id="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_info" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tu Servicio Principal</label>
                                        <textarea id="service_info" placeholder="Ej: Asesoría Financiera Para Pequeños Empresarios" 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="ad_copy" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Copy del Anuncio (Opcional)</label>
                                        <textarea id="ad_copy" placeholder="Pega Aquí El Texto Del Anuncio Que Vio Tu Cliente" 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"></textarea>
                                    </div>
                                    
                                    <div>
                                        <label for="profile_selector" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tu Cliente Ideal</label>
                                        <select id="profile_selector" 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)]">
                                            <option value="" data-resumen="">Selecciona Un Perfil De Cliente...</option>
                                            <?php foreach ($current_client_profiles as $profile): ?>
                                                <option 
                                                    value="<?php echo htmlspecialchars($profile['id'] ?? ''); ?>"
                                                    data-resumen="<?php echo htmlspecialchars($profile['resumen_copiar'] ?? ''); ?>">
                                                    <?php echo htmlspecialchars($profile['titulo_perfil'] ?? 'Perfil sin título'); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>

                                    <div>
                                        <label for="ideal_client_summary" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Resumen De Tu Cliente Ideal</label>
                                        <textarea id="ideal_client_summary" placeholder="Ej: Emprendedores Que Buscan Organizar Sus Finanzas Y Planificar Su Futuro" 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="5" required></textarea>
                                    </div>
                                </div>
                            </div>
                            <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="message-circle-question" class="mr-3 text-[var(--color-secondary)]"></i> PASO 2:
                                        </span>
                                        <span class="step-title"> Mensaje del Cliente
                                        </span>
                                    </h2>
                                    <p class="step-subtitle uppercase">Pega aquí la pregunta u objeción de tu prospecto.</p>
                                </div>
                                <div class="border-b border-[var(--color-primary)] pb-4 mb-6"></div>
                                <div id="conversation-section" class="space-y-6">
                                    <div>
                                        <label for="client_message" class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué te respondió tu cliente?</label>
                                        <textarea id="client_message" placeholder="Pega Aquí El Mensaje Que Recibiste" 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>
                            </div>
                            <input type="hidden" name="value_proposition" id="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; ?>
                        
                        <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="clipboard-list"></i></span><div><strong class="text-brand-dark uppercase">CONTEXTO INICIAL:</strong> Rellena todos los campos para que la IA entienda bien la situación de venta.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="message-square"></i></span><div><strong class="text-brand-dark uppercase">MENSAJE DEL CLIENTE:</strong> Pega la objeción o pregunta más reciente de tu prospecto.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="zap"></i></span><div><strong class="text-brand-dark uppercase">GENERA RESPUESTAS:</strong> La IA te dará 2 opciones estratégicas para contestar.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="copy"></i></span><div><strong class="text-brand-dark uppercase">ELIGE Y ADAPTA:</strong> Copia la respuesta que mejor se ajuste a tu estilo y situación.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="message-circle-reply"></i></span><div><strong class="text-brand-dark uppercase">CONTINÚA LA CONVERSACIÓN:</strong> Pega el nuevo mensaje del cliente para obtener más ayuda y cerrar la venta.</div></li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="bg-white text-brand-dark p-6 md:p-8 rounded-xl shadow-md mt-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="award" class="mr-3 text-[var(--color-secondary)]"></i> PASO 3:
                            </span>
                            <span class="step-title"> Genera tu Respuesta Estratégica
                            </span>
                        </h2>
                        <p class="step-subtitle uppercase">Crea respuestas estratégicas de seguimiento para cerrar la 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 cerrar más ventas, <b>es importante</b> que comprendas como hablar con tus prospectos. Con ese contexto, nuestra <b>inteligencia artificial</b> actuará como tu <b>Asistente Inteligente de Ventas</b>, para que sepas exactamente qué responder y cuándo, impulsando cada trato hasta el cierre.
        </p>
        
        <div class="flex justify-center md:justify-start">
            <button id="generateBtn" type="submit" form="copilot-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 RESPUESTAS CON IA</span>
                
                <div id="loader-container" class="hidden ml-3"></div>
            </button>
        </div>
    </div>
    
</div>
                    
                </div>
                <div id="result-container" class="mt-8 space-y-8"></div>
            </section>
        </div>
    </main>
</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');
    const playOverlay = document.getElementById('playOverlay');
    const videoPlayer = document.getElementById('videoPlayer');
    const form = document.getElementById('copilot-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 contextSection = document.getElementById('context-section');
    let conversationHistory = [];

    // --- DATOS DEL FORMULARIO Y AUTOLLENADO ---
    const profileSelector = document.getElementById('profile_selector');
    const idealClientSummaryInput = document.getElementById('ideal_client_summary');
    const valuePropositionInput = document.getElementById('value_proposition'); // Input hidden para PV
    // Asegurarse de que esta variable exista en PHP y esté inyectada
    const savedProfiles = <?php echo json_encode($current_client_profiles ?? []); ?>; 

    // Lógica de auto-llenado del perfil de cliente
    if (profileSelector) {
        profileSelector.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const resumen = selectedOption.getAttribute('data-resumen');

            if (resumen) {
                idealClientSummaryInput.value = resumen.trim();
                if (typeof showToast === 'function') showToast('Perfil de cliente ideal cargado.', 'success');
            } else {
                idealClientSummaryInput.value = '';
            }
        });
    }

    // --- LÓGICA DE UI Y VALIDACIÓN (omitted for brevity) ---
    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');
    });
    if (playOverlay && videoPlayer) {
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.play();
        });
    }
    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);
    }
    
    function setProcessingState(isProcessing) {
        const messages = ["Analizando la objeción...", "Buscando la mejor estrategia...", "Redactando respuestas...", "Afinando el mensaje...", "¡Casi listo para cerrar!"];
        let messageIndex = 0;
        
        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>';
            btnText.textContent = messages[messageIndex];
            window.loadingInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % messages.length;
                btnText.textContent = messages[messageIndex];
            }, 2500);
        } else {
            if (window.loadingInterval) clearInterval(window.loadingInterval);
            btnText.textContent = 'GENERAR CON IA MARKETING';
        }
    }

    async function handleFormSubmit(event) {
        event.preventDefault();
        const clientMessageInput = document.getElementById('client_message');
        const clientMessage = clientMessageInput.value.trim();
        
        let allValid = true;
        form.querySelectorAll('[required]').forEach(input => {
            if (!input.value.trim()) {
                allValid = false;
                input.classList.add('border-[var(--color-secondary)]');
            } else {
                input.classList.remove('border-[var(--color-secondary)]');
            }
        });

        if (!allValid) {
            showToast('Por favor, completa todos los campos obligatorios.', 'error');
            return;
        }

        setProcessingState(true);
        // Si no es el primer mensaje, añadirlo a la UI
        if (conversationHistory.length > 0) {
             addClientMessageToUI(clientMessage);
        }
        conversationHistory.push({ role: 'user', text: clientMessage });

        const context = {
            client_name: document.getElementById('client_name').value.trim(),
            service_info: document.getElementById('service_info').value.trim(),
            ad_copy: document.getElementById('ad_copy').value.trim(),
            ideal_client_summary: document.getElementById('ideal_client_summary').value.trim(),
            // PV AÑADIDA AL CONTEXTO DE LA API
            value_proposition: valuePropositionInput.value.trim() 
        };

        try {
            const payload = { context, history: conversationHistory };
            // RUTA DE LA API CORREGIDA
            const response = await fetch("api/api-sales-assistant.php", {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

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

            const suggestions = data.sugerencias || [];
            if (suggestions.length > 0) {
                // El primer mensaje del modelo se añade al historial para mantener el contexto
                conversationHistory.push({ role: 'model', text: suggestions[0].respuesta.es }); 
            }
            displayResult(suggestions);
            
            // Limpiar solo la caja del cliente y bloquear el contexto
            clientMessageInput.value = '';
            lockContext();
        } catch (error) {
            console.error("Error al generar respuesta:", error);
            showError(error.message);
            // Si falla, revertir el último mensaje del cliente del historial para reintentar
            conversationHistory.pop(); 
        } finally {
            setProcessingState(false);
        }
    }

    function addClientMessageToUI(message) {
        const messageCard = document.createElement('div');
        messageCard.className = 'client-message-card mb-6 p-6 bg-blue-50 border-l-4 border-blue-400 rounded-r-lg shadow-md animate-slideInUp';
        messageCard.innerHTML = `<h3 class="text-xl font-bold text-gray-800 mb-3 flex items-center"><i data-lucide="user-circle" class="mr-3 text-blue-500"></i>Mensaje del Cliente:</h3><p class="text-lg text-gray-700 whitespace-pre-wrap">${message.replace(/\n/g, '<br>')}</p>`;
        resultContainer.appendChild(messageCard);
        lucide.createIcons();
    }

    function displayResult(sugerencias) {
        // Limpiar solo las sugerencias anteriores (manteniendo el historial de conversación)
        // Buscamos y removemos todas las sugerencias anteriores si existen
        document.querySelectorAll('.ai-suggestion-card').forEach(card => card.remove());

        sugerencias.forEach((sug, index) => {
            const card = createSuggestionCard(sug, index);
            resultContainer.appendChild(card);
        });
        scrollToElement(resultContainer.lastChild);
    }

    function createSuggestionCard(sug, index) {
        // (La lógica de renderizado de la tarjeta se mantiene igual)
        const card = document.createElement('div');
        card.className = 'ai-suggestion-card p-6 md:p-8 rounded-xl shadow-md bg-white animate-slideInUp mb-6';
        card.style.animationDelay = `${index * 150}ms`;
        card.innerHTML = `
            <h3 class="text-2xl font-bold text-gray-800 mb-3 flex items-center"><i data-lucide="lightbulb" class="mr-3 text-[var(--color-secondary)]"></i> ${sug.titulo_estrategia}</h3>
            <p class="ai-explanation text-lg text-gray-700 mb-4 bg-yellow-50 border-l-4 border-yellow-400 p-4 rounded-r-lg"><strong class="text-[var(--color-primary)]">Por qué funciona:</strong> ${sug.explicacion}</p>
            <div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <h4 class="text-xl font-semibold text-gray-700 mb-2">🇪🇸 Respuesta Sugerida</h4>
                    <div class="message-box bg-gray-50 p-4 rounded-lg border border-gray-200 shadow-sm">${sug.respuesta.es.replace(/\n/g, '<br>')}</div>
                     <button class="btn-copy mt-3" data-copytarget-text="${encodeURIComponent(sug.respuesta.es)}">
                        <i data-lucide="copy"></i><span class="copy-text">Copiar Respuesta</span>
                    </button>
                </div>
                <div>
                    <h4 class="text-xl font-semibold text-gray-700 mb-2">🇺🇸 Suggested Response</h4>
                    <div class="message-box bg-gray-50 p-4 rounded-lg border border-gray-200 shadow-sm">${sug.respuesta.en.replace(/\n/g, '<br>')}</div>
                    <button class="btn-copy mt-3" data-copytarget-text="${encodeURIComponent(sug.respuesta.en)}">
                        <i data-lucide="copy"></i><span class="copy-text">Copy Response</span>
                    </button>
                </div>
            </div>`;
        
        lucide.createIcons({ nodes: [card] });
        return card;
    }

    function showError(message) {
        const errorCard = document.createElement('div');
        errorCard.className = 'bg-[var(--color-secondary)] text-center p-4 text-white rounded-lg border border-[var(--color-secondary)] mt-6';
        errorCard.innerHTML = `<p><strong>Error:</strong> ${message}</p>`;
        resultContainer.appendChild(errorCard);
        scrollToElement(errorCard);
    }

    function lockContext() {
        if (contextSection.classList.contains('context-locked')) return;
        contextSection.classList.add('context-locked');
        contextSection.querySelectorAll('input, textarea').forEach(el => {
            el.disabled = true;
            el.classList.add('bg-gray-200', 'cursor-not-allowed');
        });
        // Agregar botón de reiniciar
        if (!document.querySelector('.reset-button')) {
            const resetButton = document.createElement('button');
            resetButton.textContent = 'Reiniciar Conversación';
            resetButton.className = 'reset-button mt-4 w-full bg-[var(--color-secondary)] text-white font-bold py-2 px-4 rounded-lg hover:opacity-90 transition-opacity';
            resetButton.type = 'button';
            resetButton.onclick = function() {
                if (confirm('¿Seguro que quieres reiniciar? Se perderá el historial actual.')) {
                    // Desbloquear campos
                    contextSection.classList.remove('context-locked');
                    contextSection.querySelectorAll('input, textarea').forEach(el => {
                        el.disabled = false;
                        el.classList.remove('bg-gray-200', 'cursor-not-allowed');
                        // No limpiar la Propuesta de Valor, Servicio, Ad Copy, o Cliente Ideal, solo el nombre.
                        if (el.id === 'client_name' || el.id === 'client_message') {
                            el.value = '';
                        }
                    });
                    conversationHistory = [];
                    resultContainer.innerHTML = '';
                    document.getElementById('client_message').value = '';
                    this.remove();
                }
            };
            contextSection.appendChild(resetButton);
        }
    }

    function scrollToElement(element) {
        if (!element) return;
        setTimeout(() => {
            element.scrollIntoView({ behavior: 'smooth', block: 'end' });
        }, 200);
    }

    form.addEventListener('submit', handleFormSubmit);

    resultContainer.addEventListener('click', function(e) {
        const button = e.target.closest('.btn-copy');
        if (!button || button.classList.contains('reset-button')) return;

        const textToCopy = decodeURIComponent(button.dataset.copytargetText);
        // ... (Lógica de copiado) ...
        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('Respuesta copiada al portapapeles.', 'success');
            setTimeout(() => {
                buttonContent.innerHTML = originalHTML;
                buttonContent.classList.remove('copied');
                lucide.createIcons({ nodes: [buttonContent] });
            }, 2000);
        }).catch(err => {
            console.error('Error al copiar el texto: ', err);
            showToast('No se pudo copiar el texto.', 'error');
        });
    });
});
</script>
<script src="files/toast.js"></script>
</body>
</html>