<?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 Anuncios Publicitarios 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>
        .ad-card-container {
            border: 1px solid #e2e8f0;
            border-radius: 0.75rem;
            margin-bottom: 1.5rem;
            overflow: hidden;
        }
        .ad-card-header {
            background-color: #f9fafb;
            padding: 1rem 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .tox-tinymce {
            border-radius: 0.5rem !important;
            border: 1px solid #d1d5db !important;
        }
    </style>
    
</head>
<body data-page-title="Generador De Anuncios Publicitarios"
      data-page-subtitle="Crea Textos De Anuncios Para Tus Servicios Que Realmente Venden"
      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="ad-generator" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">

                    <div class="lg:col-span-3">
                        <form id="ad-generator-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">
                                        <i data-lucide="briefcase" class="mr-3 text-[var(--color-secondary)]"></i>
                                        <span class="text-[var(--color-secondary)] mr-2">PASO 1:</span> DEFINE EL ADN DE TU ANUNCIO
                                    </h2>
                                    <p class="step-subtitle uppercase">Ingresa los datos de tu servicio y el dolor/deseo de tu cliente.</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="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: Limpieza Brillante" 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="phone" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Teléfono / WhatsApp</label>
                                            <input type="text" id="phone" name="phone" 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>
                                    <div>
                                        <label for="website" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Página Web o Facebook (Opcional)</label>
                                        <input type="text" id="website" name="website" placeholder="Ej: LimpiezaBrillante.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 class="grid grid-cols-1 md:grid-cols-2 gap-6 pt-4">
                                        <div>
                                            <label for="service" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Servicio A Promocionar</label>
                                            <input type="text" id="service" name="service" placeholder="Ej: Limpieza Profunda" 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="zone" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Zona De Servicio</label>
                                            <input type="text" id="zone" name="zone" placeholder="Ej: Seattle, WA" 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>
                                    
                                    <div>
                                        <label for="client_profile_select" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tu Cliente Ideal:</label>
                                        <select id="client_profile_select" 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>
                                            <option value="manual" data-resumen="manual">-- Escribir Manualmente (Recomendado) --</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="client_summary" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Resumen Del Problema y Deseo Del Cliente</label>
                                        <textarea id="client_summary" name="client_summary" placeholder="Ej: Padres ocupados que no tienen tiempo de limpiar (Problema) y desean llegar a casa y encontrarla impecable (Deseo)." 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="6" required></textarea>
                                    </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-ads-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 Anuncios Publicitarios</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é Específico:</strong> Carga un perfil de cliente para darle a la IA la base del problema y el deseo.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="settings-2"></i></span><div><strong class="text-brand-dark uppercase">Genera Las Opciones:</strong> Haz clic en 'Generar Anuncios' para que la IA cree 3 versiones distintas para tu campaña.</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 Pega:</strong> Elige el anuncio que más te guste, cópialo con un solo clic y úsalo en tus campañas.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="repeat"></i></span><div><strong class="text-brand-dark uppercase">Prueba y Optimiza:</strong> No dudes en generar varias veces con pequeñas variaciones para encontrar el texto perfecto.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="save"></i></span><div><strong class="text-brand-dark uppercase">Guarda Tus Favoritos:</strong> Podrás guardar tus 5 anuncios favoritos en el panel lateral.</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">
                                <i data-lucide="zap" class="mr-3 text-[var(--color-secondary)]"></i>
                                <span class="text-[var(--color-secondary)] mr-2">PASO 2:</span> RECIBE TUS ANUNCIOS PERSUASIVOS
                            </h2>
                            <p class="step-subtitle uppercase">OBTÉN 3 VERSIONES DEL ANUNCIO LISTAS PARA CAPTAR LA ATENCIÓN Y VENDER</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 crear textos para tus anuncios que motiven a adquirir tus productos y servicios, <b>es importante</b> que conozcas a tu cliente ideal. Usando esos datos, nuestra <b>inteligencia artificial</b> creará <b>Textos Para Anuncios Publicitarios</b> que realmente capten la atención de tus clientes y aumentes tus ventas.
        </p>
        
        <div class="flex justify-center md:justify-start">
            <button id="generateBtn" type="submit" form="ad-generator-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 TEXTOS PARA ANUNCIOS 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="ads-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 hidden" aria-hidden="true"></div>

<div id="ads-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>
            ANUNCIOS GUARDADOS
        </h3>
        <button id="close-ads-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="ads-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 anuncios...</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-ads-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 && typeof showToast === 'function') { showToast(notificationMessage, notificationType); }

    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');
    if (phoneInput) { IMask(phoneInput, { mask: '(000) 000-0000' }); }

    const form = document.getElementById('ad-generator-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 openAdsPanelBtn = document.getElementById('open-ads-panel-btn');
    const closeAdsPanelBtn = document.getElementById('close-ads-panel-btn');
    const adsPanelOverlay = document.getElementById('ads-panel-overlay');
    const adsPanel = document.getElementById('ads-panel');
    const adsPanelContent = document.getElementById('ads-panel-content');
    
    const MAX_ADS = 5;
    let generatedAds = null;
    let inputsGeneradosReciente = null;
    let savedAdButtons = {};
    const savedProfiles = <?php echo json_encode($current_client_profiles ?? []); ?>;
    let savedAds = [];

    const modal = document.getElementById('confirmation-modal');
    const modalBox = modal.querySelector('div:first-of-type');
    const modalIcon = document.getElementById('modal-icon');
    const modalTitle = document.getElementById('modal-title');
    const modalMessage = document.getElementById('modal-message');
    const modalCancelBtn = document.getElementById('modal-cancel-btn');
    const modalConfirmBtn = document.getElementById('modal-confirm-btn');
    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; 
        modal.classList.remove('hidden');
        setTimeout(() => modalBox.classList.remove('scale-95', 'opacity-0'), 50);
        document.body.style.overflow = 'hidden';
    }

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

    modalCancelBtn.addEventListener('click', closeModal);
    modalConfirmBtn.addEventListener('click', () => {
        if (typeof onConfirmCallback === 'function') { onConfirmCallback(); }
        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 clientProfileSelect = document.getElementById('client_profile_select');
    const clientSummaryTextarea = document.getElementById('client_summary');

    if (clientProfileSelect) {
        clientProfileSelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const resumen = selectedOption.getAttribute('data-resumen');

            if (resumen && resumen !== 'manual') {
                clientSummaryTextarea.value = resumen.trim();
                clientSummaryTextarea.dispatchEvent(new Event('input'));
            } else if (resumen === 'manual') {
                clientSummaryTextarea.value = '';
                clientSummaryTextarea.focus();
            } else {
                clientSummaryTextarea.value = '';
                clientSummaryTextarea.dispatchEvent(new Event('input'));
            }
        });
    }

    function openAdsPanel() {
        adsPanel.classList.remove('translate-x-full');
        adsPanelOverlay.classList.remove('hidden');
        fetchAndDrawAds();
    }
    function closeAdsPanel() {
        adsPanel.classList.add('translate-x-full');
        adsPanelOverlay.classList.add('hidden');
    }
    openAdsPanelBtn.addEventListener('click', openAdsPanel);
    closeAdsPanelBtn.addEventListener('click', closeAdsPanel);
    adsPanelOverlay.addEventListener('click', closeAdsPanel);

    const adEndpoints = {
        fetch: 'api-db/ia-ads-generator-fetch.php',
        create: 'api-db/ia-ads-generator-create.php',
        update: 'api-db/ia-ads-generator-update.php',
        delete: 'api-db/ia-ads-generator-delete.php'
    };
    
    async function fetchAndDrawAds() {
        adsPanelContent.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 anuncios guardados...</p></div>';
        try {
            const response = await fetch(adEndpoints.fetch, { method: 'POST' });
            const result = await response.json();

            if (response.ok && result.success) {
                savedAds = result.ads;
                if (savedAds.length === 0) {
                    adsPanelContent.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 anuncios guardados.</p></div>`;
                } else {
                    let html = `<p class="text-gray-600 mb-4 uppercase font-black">Has guardado ${savedAds.length} de ${MAX_ADS} anuncios.</p>`;
                    html += '<div class="space-y-6">';
                    savedAds.forEach((ad, index) => { html += createAdPanelCard(ad, index); });
                    html += '</div>';
                    adsPanelContent.innerHTML = html;
                }
            } else {
                throw new Error(result.message || 'Error al obtener anuncios.');
            }
        } catch (error) {
            adsPanelContent.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 createAdPanelCard(ad) {
        const full_es = `${ad.gancho_es}\n\n${ad.solucion_es}\n\n${ad.cta_es}`;
        const full_en = `${ad.gancho_en}\n\n${ad.solucion_en}\n\n${ad.cta_en}`;
        
        const adTypeMap = {
            'problema': 'Enfoque en el Problema',
            'deseo': 'Enfoque en el Deseo',
            'servicio': 'Enfoque en el Servicio'
        };
        const adTypeDisplay = adTypeMap[ad.ad_type] || ad.ad_type || 'General';
        const adTitle = ad.title_ad || adTypeDisplay;

        return `
        <div class="border border-gray-200 rounded-xl overflow-hidden" data-ad-id="${ad.id}">
            <div class="bg-gray-50 p-4 flex justify-between items-center">
                <div id="display-name-${ad.id}" class="flex-1">
                    <h4 class="text-xl font-black uppercase text-[var(--color-primary)]">${adTitle}</h4>
                </div>
                <div id="edit-name-area-${ad.id}" class="flex-1 hidden">
                    <input type="text" id="edit-title-input-${ad.id}" value="${adTitle}" class="w-full p-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-highlight)]">
                </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="${ad.id}"><i data-lucide="edit"></i></button>
                    <button class="btn-copy btn-xs bg-[var(--color-secondary)] text-white btn-panel-delete" data-id="${ad.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="${ad.id}"><i data-lucide="save"></i></button>
                    <button class="btn-copy btn-xs bg-gray-500 text-white btn-panel-cancel hidden" data-id="${ad.id}"><i data-lucide="x"></i></button>
                </div>
            </div>

            <div class="p-4">
                <div id="display-content-${ad.id}" class="space-y-4">
                    <p class="text-xs text-gray-500">Servicio: ${ad.service_input}</p>
                    <div class="p-3 border rounded-lg bg-gray-50">
                        <strong class="block font-bold text-lg text-[var(--color-secondary)]">🇪🇸 ESPAÑOL</strong>
                        <p class="pt-2"><strong class="font-semibold text-gray-700">Gancho:</strong> ${ad.gancho_es}</p>
                        <p><strong class="font-semibold text-gray-700">Solución:</strong> ${ad.solucion_es.replace(/\n/g, '<br>')}</p>
                        <p><strong class="font-semibold text-gray-700">CTA:</strong> ${ad.cta_es}</p>
                        <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="p-3 border rounded-lg bg-gray-50">
                        <strong class="block font-bold text-lg text-[var(--color-primary)]">🇺🇸 ENGLISH</strong>
                        <p class="pt-2"><strong class="font-semibold text-gray-700">Hook:</strong> ${ad.gancho_en}</p>
                        <p><strong class="font-semibold text-gray-700">Solution:</strong> ${ad.solucion_en.replace(/\n/g, '<br>')}</p>
                        <p><strong class="font-semibold text-gray-700">CTA:</strong> ${ad.cta_en}</p>
                        <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-${ad.id}" class="hidden space-y-4">
                    <p class="text-xs text-gray-500">Servicio: ${ad.service_input}</p>
                    <div>
                        <label class="font-bold text-gray-700">🇪🇸 Gancho:</label>
                        <textarea id="edit-gancho-es-${ad.id}" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg h-24">${ad.gancho_es}</textarea>
                    </div>
                    <div>
                        <label class="font-bold text-gray-700">🇪🇸 Solución:</label>
                        <textarea id="edit-solucion-es-${ad.id}" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg h-32">${ad.solucion_es}</textarea>
                    </div>
                    <div>
                        <label class="font-bold text-gray-700">🇪🇸 CTA:</label>
                        <textarea id="edit-cta-es-${ad.id}" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg h-24">${ad.cta_es}</textarea>
                    </div>
                     <div>
                        <label class="font-bold text-gray-700">🇺🇸 Hook:</label>
                        <textarea id="edit-gancho-en-${ad.id}" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg h-24">${ad.gancho_en}</textarea>
                    </div>
                    <div>
                        <label class="font-bold text-gray-700">🇺🇸 Solution:</label>
                        <textarea id="edit-solucion-en-${ad.id}" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg h-32">${ad.solucion_en}</textarea>
                    </div>
                    <div>
                        <label class="font-bold text-gray-700">🇺🇸 CTA:</label>
                        <textarea id="edit-cta-en-${ad.id}" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg h-24">${ad.cta_en}</textarea>
                    </div>
                </div>
            </div>
        </div>
        `;
    }
    
    adsPanelContent.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-gancho-es-${id}, #edit-solucion-es-${id}, #edit-cta-es-${id}, #edit-gancho-en-${id}, #edit-solucion-en-${id}, #edit-cta-en-${id}`,
                    menubar: false,
                    statusbar: false,
                    height: 200,
                    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-gancho-es-${id}`);
                tinymce.remove(`#edit-solucion-es-${id}`);
                tinymce.remove(`#edit-cta-es-${id}`);
                tinymce.remove(`#edit-gancho-en-${id}`);
                tinymce.remove(`#edit-solucion-en-${id}`);
                tinymce.remove(`#edit-cta-en-${id}`);
            }
            toggleEditMode(id, false);
            const ad = savedAds.find(a => a.id == id);
            const adTypeMap = {'problema': 'Enfoque en el Problema', 'deseo': 'Enfoque en el Deseo', 'servicio': 'Enfoque en el Servicio'};
            const adTypeDisplay = adTypeMap[ad.ad_type] || ad.ad_type || 'General';
            document.getElementById(`edit-title-input-${id}`).value = ad.title_ad || adTypeDisplay;
        }
        
        if (saveBtn) {
            const id = saveBtn.dataset.id;
            
            let payload = { id: parseInt(id, 10) };
            payload.title_ad = document.getElementById(`edit-title-input-${id}`).value;

            const fields = ['gancho-es', 'solucion-es', 'cta-es', 'gancho-en', 'solucion-en', 'cta-en'];
            
            fields.forEach(field => {
                const editorId = `edit-${field}-${id}`;
                if (typeof tinymce !== 'undefined' && tinymce.get(editorId)) {
                    payload[field.replace('-', '_')] = tinymce.get(editorId).getContent();
                    tinymce.remove(editorId);
                } else {
                    payload[field.replace('-', '_')] = 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 handleUpdateAd(payload);
                    await fetchAndDrawAds();
                }
            });
        }
        
        if (deleteBtn) {
            const id = deleteBtn.dataset.id;
            handleDeleteAd(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-ad-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);
        
        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 saveIndividualAd(adData, button) {
        setProcessingState(true, 'Guardando Anuncio...'); 
        try {
            const checkResponse = await fetch(adEndpoints.fetch, { method: 'POST' });
            const checkResult = await checkResponse.json();
            if (checkResult.success && checkResult.ads.length >= MAX_ADS) {
                if (typeof showToast === 'function') showToast(`Límite de ${MAX_ADS} anuncios alcanzado. Elimina uno antes de guardar.`, 'warning');
                setProcessingState(false);
                return;
            }

            const response = await fetch(adEndpoints.create, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(adData)
            });
            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] });
                }
                openAdsPanel();
            } else if (response.status === 409) {
                if (typeof showToast === 'function') showToast(result.message, 'warning');
            } else {
                throw new Error(result.message || 'Error desconocido al guardar el anuncio.');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al guardar: ${error.message}`, 'error');
        } finally {
            setProcessingState(false);
        }
    }

    async function handleUpdateAd(payload) {
        setProcessingState(true, 'Actualizando...');
        try {
            const response = await fetch(adEndpoints.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 {
                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 handleDeleteAd(adId) {
        openModal({
            title: 'CONFIRMAR ELIMINACIÓN',
            message: '¿Estás seguro de que quieres eliminar este anuncio?',
            icon: 'alert-triangle',
            confirmText: 'SÍ, ELIMINAR',
            confirmClass: 'danger',
            onConfirm: async () => {
                setProcessingState(true, 'Eliminando...');
                try {
                    const response = await fetch(adEndpoints.delete, {
                        method: 'POST', 
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ id: adId })
                    });
                    const result = await response.json();
                    if (response.ok && result.success) {
                        if (typeof showToast === 'function') showToast(result.message, 'success');
                        fetchAndDrawAds();
                    } 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.classList.add('border-[var(--color-secondary)]');
                allValid = false;
            } else {
                input.classList.remove('border-[var(--color-secondary)]');
            }
        });
        if (!allValid) {
            formErrorMessage.classList.remove('hidden');
            formErrorMessage.focus();
            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) {
        
        generateBtn.disabled = isProcessing;
        generateBtn.classList.toggle('opacity-50', isProcessing);
        generateBtn.classList.toggle('cursor-not-allowed', isProcessing);
        loaderContainer.classList.toggle('hidden', !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>';
            
            if (customMessage) {
                btnText.textContent = customMessage;
                if(window.loadingInterval) clearInterval(window.loadingInterval);
                window.loadingInterval = null;
                return;
            }
            const messages = ["Contactando Con OrozCO IA...", "Analizando tu negocio...", "Definiendo estrategia...", "Generando anuncios...", "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);
            btnText.textContent = 'GENERAR CON IA MARKETING';
        }
    }


    form.addEventListener('submit', async function(event) {
        event.preventDefault();
        if (!validateForm()) { return; }
        setProcessingState(true);

        const clientSummaryValue = document.getElementById('client_summary').value;
        
        const formData = {
            business_name: document.getElementById('business_name').value,
            phone: document.getElementById('phone').value,
            website: document.getElementById('website').value,
            service: document.getElementById('service').value,
            zone: document.getElementById('zone').value,
            client_summary: clientSummaryValue, 
            value_proposition: document.querySelector('input[name="value_proposition"]').value
        };
        inputsGeneradosReciente = {
             service: formData.service,
             problem_input: clientSummaryValue, 
             desire_input: clientSummaryValue   
        };

        try {
            const response = await fetch('api/api-ads-generator.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); }
            if(!data.anuncios || !Array.isArray(data.anuncios) || data.anuncios.length !== 3) { throw new Error("La IA no devolvió el set de 3 anuncios esperados."); }
            
            generatedAds = data.anuncios;
            displayResults(data.anuncios);
            if (typeof showToast === 'function') { showToast('¡Anuncios generados con éxito!', 'success'); }

        } catch (error) {
            console.error("Error:", error);
            const errorMessage = "No se pudieron generar los anuncios. Detalles: " + error.message;
            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';
            if (typeof showToast === 'function') { showToast(errorMessage, 'error'); }
        } finally {
            setProcessingState(false);
        }
    });
    
    function displayResults(anuncios) {
        let allAdCardsHtml = '';
        savedAdButtons = {};

        anuncios.forEach((anuncio, index) => {
            const full_es_text = `${anuncio.es.gancho}\n\n${anuncio.es.solucion}\n\n${anuncio.es.cta}`;
            const full_en_text = `${anuncio.en.gancho}\n\n${anuncio.en.solucion}\n\n${anuncio.en.cta}`;
            
            let adType = 'problema'; 
            if (anuncio.titulo.includes('DESEO')) adType = 'deseo';
            else if (anuncio.titulo.includes('SERVICIO')) adType = 'servicio';

            allAdCardsHtml += `
                <div class="bg-white p-6 rounded-xl shadow-lg mb-8">
                    <h3 class="text-2xl font-black text-brand-dark mb-4">${anuncio.titulo}</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-xl font-bold text-gray-700">🇪🇸 Español</h4>
                                <button class="btn-copy" data-copytext="${encodeURIComponent(full_es_text)}">
                                    <i data-lucide="copy"></i><span class="copy-text">Copiar</span>
                                </button>
                            </div>
                            <div class="space-y-4">
                                <div><strong class="block font-bold text-[var(--color-secondary)]">Gancho:</strong><p class="text-gray-800 leading-relaxed">${anuncio.es.gancho}</p></div>
                                <div><strong class="block font-bold text-[var(--color-secondary)]">Solución:</strong><p class="text-gray-800 leading-relaxed">${anuncio.es.solucion.replace(/\n/g, '<br>')}</p></div>
                                <div><strong classs="block font-bold text-[var(--color-secondary)]">Llamada a la Acción:</strong><p class="text-gray-800 leading-relaxed">${anuncio.es.cta}</p></div>
                            </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-xl font-bold text-gray-700">🇺🇸 English</h4>
                                <button class="btn-copy" data-copytext="${encodeURIComponent(full_en_text)}">
                                    <i data-lucide="copy"></i><span class="copy-text">Copy</span>
                                </button>
                            </div>
                            <div class="space-y-4">
                                <div><strong class="block font-bold text-[var(--color-secondary)]">Hook:</strong><p class="text-gray-800 leading-relaxed">${anuncio.en.gancho}</p></div>
                                <div><strong class="block font-bold text-[var(--color-secondary)]">Solution:</strong><p class="text-gray-800 leading-relaxed">${anuncio.en.solucion.replace(/\n/g, '<br>')}</p></div>
                                <div><strong class="block font-bold text-[var(--color-secondary)]">Call to Action:</strong><p class="text-gray-800 leading-relaxed">${anuncio.en.cta}</p></div>
                            </div>
                        </div>
                    </div>
                    <div class="mt-4 text-center">
                        <button class="btn-save-ad 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-ad-type="${adType}" data-ad-index="${index}">
                            <i data-lucide="save"></i> <span>Guardar Este Anuncio</span>
                        </button>
                    </div>
                </div>
            `;
        });
        resultContainer.innerHTML = `<div class="ai-response p-6 md:p-8 rounded-xl shadow-md">${allAdCardsHtml}</div>`;
        lucide.createIcons();
        setTimeout(() => { resultContainer.style.opacity = '1'; resultContainer.style.transform = 'scale(1)'; resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' }); }, 100);

        resultContainer.querySelectorAll('[data-copytext]').forEach(button => {
            button.addEventListener('click', function() {
                const textToCopy = decodeURIComponent(this.dataset.copytext);
                navigator.clipboard.writeText(textToCopy).then(() => {
                    const originalHTML = this.innerHTML;
                    this.innerHTML = '<i data-lucide="check"></i><span class="copy-text">Copiado!</span>';
                    lucide.createIcons({ nodes: [this] });
                    if (typeof showToast === 'function') { showToast('Anuncio copiado al portapapeles.', 'success'); }
                    setTimeout(() => { this.innerHTML = originalHTML; lucide.createIcons({ nodes: [this] }); }, 2000);
                }).catch(err => console.error('Error al copiar:', err));
            });
        });

        resultContainer.querySelectorAll('.btn-save-ad').forEach(button => {
            const adType = button.dataset.adType;
            const index = button.dataset.adIndex;
            savedAdButtons[adType] = button;
            
            button.addEventListener('click', function() {
                const adToSave = generatedAds[index];
                
                const payload = {
                    ad_type: adType,
                    title_ad: adToSave.titulo,
                    gancho_es: adToSave.es.gancho,
                    solucion_es: adToSave.es.solucion,
                    cta_es: adToSave.es.cta,
                    gancho_en: adToSave.en.gancho,
                    solucion_en: adToSave.en.solucion,
                    cta_en: adToSave.en.cta,
                    service_input: inputsGeneradosReciente.service,
                    problem_input: inputsGeneradosReciente.client_summary,
                    desire_input: inputsGeneradosReciente.client_summary   
                };
                saveIndividualAd(payload, this);
            });
        });
    }

});
</script>
<script src="files/toast.js"></script>
</body>
</html>