<?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>Creador De Ofertas Y Promociones 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>
        .tox-tinymce {
            border-radius: 0.5rem !important;
            border: 1px solid #d1d5db !important;
        }
    </style>
</head>
<body data-page-title="Creador De Ofertas Y Promociones"
      data-page-subtitle="Diseña Mensajes Atractivos Y Estratégicos Para Promociones Y Descuentos "
      data-page-icon="tag">

    <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="offers-promotions-assistant" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">

                    <div class="lg:col-span-3">
                        <form id="offerForm" 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="megaphone" class="mr-3 text-[var(--color-secondary)]"></i>
                                        <span class="text-[var(--color-secondary)] mr-2">PASO 1:</span> Define La Promoción Que Quieres Lanzar
                                    </h2>
                                    <p class="step-subtitle uppercase">Ingresa los datos para convertir tu idea en una oferta irresistible.</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="businessName" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Nombre De Tu Negocio</label>
                                            <input type="text" id="businessName" name="businessName" 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="Ej: Tu Contador Confiable" value="<?php echo htmlspecialchars($business_name); ?>">
                                        </div>
                                        <div>
                                            <label for="businessContact" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Teléfono / WhatsApp</label>
                                            <input type="text" id="businessContact" name="businessContact" 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="Ej: (555) 123-4567" value="<?php echo htmlspecialchars($phone); ?>">
                                        </div>
                                    </div>
                                    <div>
                                        <label for="businessWeb" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Página Web / Red Social</label>
                                        <input type="text" id="businessWeb" name="businessWeb" 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="Ej: @TuContadorConfiable" value="<?php echo htmlspecialchars($website); ?>">
                                    </div>
                                    <div>
                                        <label for="offerObjective" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Objetivo De La Oferta</label>
                                        <select id="offerObjective" name="offerObjective" 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="" disabled selected>-- Elige Una Opción --</option>
                                            <option value="referrals">Promoción Por Referidos</option>
                                            <option value="neighborhood">Oferta En Un Vecindario</option>
                                            <option value="marketplace">Oferta Para Marketplace</option>
                                            <option value="service_bundle">Promocionar Un Servicio Específico</option>
                                            <option value="seasonal">Oferta De Temporada</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label for="mainService" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Servicio A Promocionar</label>
                                        <input type="text" id="mainService" name="mainService" 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="Ej: Declaración De Impuestos Anual" required>
                                    </div>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div>
                                            <label for="discountType" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tipo De Descuento</label>
                                            <select id="discountType" name="discountType" 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="percentage">Porcentaje (%)</option>
                                                <option value="amount">Monto Fijo ($)</option>
                                                <option value="free_service">Servicio/Producto Gratis</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label for="discountValue" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Valor Del Descuento / Detalle</label>
                                            <input type="text" id="discountValue" name="discountValue" 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="Ej: 20, 50, Asesoría Financiera Gratis" required>
                                        </div>
                                    </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-offers-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 Ofertas Guardadas</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="tag"></i></span>
                                    <div>
                                        <strong class="text-brand-dark uppercase">DETALLA LA OFERTA:</strong> Cuanto más específico seas con el tipo y valor del descuento, más atractiva será.
                                    </div>
                                </li>
                                <li class="instructions-list-item">
                                    <span class="icon-wrapper"><i data-lucide="lightbulb"></i></span>
                                    <div>
                                        <strong class="text-brand-dark uppercase">GENERA IDEAS:</strong> La IA te ofrecerá dos opciones de ofertas distintas con texto listo para tus redes.
                                    </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 PROMOCIONA:</strong> Elige la oferta que más te guste y úsala en tus campañas para atraer clientes.
                                    </div>
                                </li>
                                <li class="instructions-list-item">
                                    <span class="icon-wrapper"><i data-lucide="target"></i></span>
                                    <div>
                                        <strong class="text-brand-dark uppercase">LOGRA TUS OBJETIVOS:</strong> Estas ofertas están diseñadas para ayudarte a cumplir tus metas de atracción de 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">
                                <i data-lucide="zap" class="mr-3 text-[var(--color-secondary)]"></i>
                                <span class="text-[var(--color-secondary)] mr-2">PASO 2:</span> Recibe Ofertas Para Atraer Clientes
                            </h2>
                            <p class="step-subtitle uppercase">Obtén ofertas personalizadas listas para captar la atención y generar ventas.</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 que tus ofertas y promociones sean irresistibles, <b>es importante</b> que definas todos los detalles importantes de la misma. Con esos datos, nuestra <b>inteligencia artificial</b> creará tus <b>Ofertas y Promociones</b>, para que diseñes mensajes atractivos, impactantes y principalmente estratégicos que impulsen tus ventas.
        </p>
        
        <div class="flex justify-center md:justify-start">
            <button id="generateBtn" type="submit" form="offerForm" 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 OFERTAS 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="offers-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 hidden" aria-hidden="true"></div>

<div id="offers-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>
            TUS OFERTAS
        </h3>
        <button id="close-offers-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="offers-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 ofertas...</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-offers-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('businessContact');
    if (phoneInput) {
        IMask(phoneInput, { mask: '(000) 000-0000' });
    }

    const form = document.getElementById('offerForm');
    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');
    
    let generatedOffers = null; 
    let inputsGeneradosReciente = null; 
    const MAX_OFFERS = 5; 
    let savedOffers = [];

    const openOffersPanelBtn = document.getElementById('open-offers-panel-btn');
    const closeOffersPanelBtn = document.getElementById('close-offers-panel-btn');
    const offersPanelOverlay = document.getElementById('offers-panel-overlay');
    const offersPanel = document.getElementById('offers-panel');
    const offersPanelContent = document.getElementById('offers-panel-content');

    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;

    const offerEndpoints = {
        fetch: 'api-db/ia-offers-promotions-fetch.php', 
        create: 'api-db/ia-offers-promotions-create.php',
        update: 'api-db/ia-offers-promotions-update.php',
        delete: 'api-db/ia-offers-promotions-delete.php'
    };

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

    async function openOffersPanel() {
        offersPanel.classList.remove('translate-x-full');
        offersPanelOverlay.classList.remove('hidden');
        await fetchAndDrawOffers(); 
    }

    function closeOffersPanel() {
        offersPanel.classList.add('translate-x-full');
        offersPanelOverlay.classList.add('hidden');
    }

    openOffersPanelBtn.addEventListener('click', openOffersPanel);
    closeOffersPanelBtn.addEventListener('click', closeOffersPanel);
    offersPanelOverlay.addEventListener('click', closeOffersPanel);
    
    function decodeTextareaContent(htmlText) {
        if (typeof htmlText !== 'string') return '';
        let cleanText = htmlText.replace(/<br\s*\/?>/gi, '\n');
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = cleanText;
        return tempDiv.textContent || tempDiv.innerText || '';
    }

    async function fetchAndDrawOffers() {
        offersPanelContent.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 ofertas guardadas...</p></div>';

        try {
            const response = await fetch(offerEndpoints.fetch, { method: 'POST' }); 
            const result = await response.json();

            if (response.ok && result.success) {
                savedOffers = result.offers; 
                
                if (savedOffers.length === 0) {
                    offersPanelContent.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 ofertas guardadas. (Máx. ${MAX_OFFERS})
                            </p>
                        </div>
                    `;
                } else {
                    let html = `<p class="text-gray-600 mb-4 uppercase font-black">Has guardado ${savedOffers.length} de ${MAX_OFFERS} ofertas.</p>`;
                    html += '<div class="space-y-6">';
                    savedOffers.forEach(offerRecord => {
                        html += createOfferPanelCard(offerRecord);
                    });
                    html += '</div>';
                    offersPanelContent.innerHTML = html;
                }
            } else {
                throw new Error(result.message || 'Error al obtener las ofertas.');
            }
        } catch (error) {
            offersPanelContent.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>`;
            if (typeof showToast === 'function') showToast(`Error al cargar ofertas: ${error.message}`, 'error');
        }
        lucide.createIcons();
    }
    
    function createOfferPanelCard(offerRecord) {
        
        const promo_es_display = (offerRecord.promo_text_es || '').replace(/\n/g, '<br>');
        const promo_en_display = (offerRecord.promo_text_en || '').replace(/\n/g, '<br>');
        const offer_desc_display = (offerRecord.offer_description || '').replace(/\n/g, '<br>');
        
        const promo_es_textarea = offerRecord.promo_text_es;
        const promo_en_textarea = offerRecord.promo_text_en;
        const offer_description_textarea = offerRecord.offer_description;


        return `
        <div class="border border-gray-200 rounded-xl overflow-hidden" data-offer-id="${offerRecord.id}">
            <div class="bg-gray-50 p-4 flex justify-between items-center">
                <div id="display-name-${offerRecord.id}" class="flex-1">
                    <h4 class="text-xl font-black uppercase text-[var(--color-primary)]">${offerRecord.offer_name}</h4>
                </div>
                <div id="edit-name-area-${offerRecord.id}" class="flex-1 hidden">
                    <input type="text" id="edit-name-input-${offerRecord.id}" value="${offerRecord.offer_name}" 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="${offerRecord.id}"><i data-lucide="edit"></i></button>
                    <button class="btn-copy btn-xs bg-[var(--color-secondary)] text-white btn-panel-delete" data-id="${offerRecord.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="${offerRecord.id}"><i data-lucide="save"></i></button>
                    <button class="btn-copy btn-xs bg-gray-500 text-white btn-panel-cancel hidden" data-id="${offerRecord.id}"><i data-lucide="x"></i></button>
                </div>
            </div>
            
            <div class="p-4">
                <div id="display-content-${offerRecord.id}" class="space-y-4">
                    <p class="text-sm text-gray-500">Generado para: ${offerRecord.service_input} | Objetivo: ${offerRecord.objective_input}</p>
                    <div class="bg-gray-50 p-4 rounded-lg border-l-4 border-[var(--color-highlight)] shadow-inner">
                        ${offer_desc_display}
                    </div>
                    <div>
                        <h5 class="font-bold text-gray-700 mt-4 mb-2">🇪🇸 Texto Promocional:</h5>
                        <div class="bg-gray-50 p-4 rounded-lg border-l-4 border-[var(--color-highlight)] shadow-inner">
                            ${promo_es_display}
                        </div>
                    </div>
                    <div>
                        <h5 class="font-bold text-gray-700 mt-4 mb-2">🇺🇸 Promo Text:</h5>
                        <div class="bg-gray-50 p-4 rounded-lg border-l-4 border-[var(--color-highlight)] shadow-inner">
                            ${promo_en_display}
                        </div>
                    </div>
                </div>
                <div id="edit-content-area-${offerRecord.id}" class="hidden space-y-4">
                    <div>
                        <label class="font-bold text-gray-700">Descripción:</label>
                        <textarea id="edit-desc-input-${offerRecord.id}" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg h-32 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">${offer_description_textarea}</textarea>
                    </div>
                    <div>
                        <label class="font-bold text-gray-700">🇪🇸 Español:</label>
                        <textarea id="edit-es-input-${offerRecord.id}" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg h-48 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">${promo_es_textarea}</textarea>
                    </div>
                    <div>
                        <label class="font-bold text-gray-700">🇺🇸 English:</label>
                        <textarea id="edit-en-input-${offerRecord.id}" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg h-48 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">${promo_en_textarea}</textarea>
                    </div>
                </div>
            </div>
        </div>
        `;
    }
    
    offersPanelContent.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');

        if (editBtn) {
            const id = editBtn.dataset.id;
            toggleEditMode(id, true);
            
            if (typeof tinymce !== 'undefined') {
                tinymce.init({
                    selector: `#edit-desc-input-${id}, #edit-es-input-${id}, #edit-en-input-${id}`,
                    menubar: false,
                    statusbar: false,
                    height: 300,
                    plugins: 'lists link',
                    toolbar: 'bold italic underline | h3 h4 | 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-desc-input-${id}`);
                tinymce.remove(`#edit-es-input-${id}`);
                tinymce.remove(`#edit-en-input-${id}`);
            }
            
            toggleEditMode(id, false);
            const offer = savedOffers.find(p => p.id == id);
            document.getElementById(`edit-name-input-${id}`).value = offer.offer_name;
        }
        
        if (saveBtn) {
            const id = saveBtn.dataset.id;
            handleUpdateOffer(id);
        }
        
        if (deleteBtn) {
            const id = deleteBtn.dataset.id;
            handleDeleteOffer(id);
        }
    });

    function toggleEditMode(id, isEditing) {
        const container = document.querySelector(`[data-offer-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);

        if(isEditing) {
            const nameInput = container.querySelector(`#edit-name-input-${id}`);
            if(nameInput) nameInput.focus();
        }
    }
    
    async function createOfferInDB(offerData, inputData) {
        if (savedOffers.length >= MAX_OFFERS) {
            openModal({
                title: 'LÍMITE ALCANZADO',
                message: `Ya has guardado el máximo de ${MAX_OFFERS} ofertas. <br>Por favor, elimina una para guardar esta nueva.`,
                icon: 'alert-circle',
                confirmText: 'ENTENDIDO',
                confirmClass: 'primary',
                onConfirm: () => {}
            });
            return;
        }

        setProcessingState(true, 'Guardando Oferta...'); 
        
        const payload = {
            offer_name: offerData.offer_name,
            offer_description: offerData.offer_description,
            promo_text_es: offerData.promo_text_es,
            promo_text_en: offerData.promo_text_en,
            inputs: inputData 
        };
        
        try {
            const response = await fetch(offerEndpoints.create, {
                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');
                await fetchAndDrawOffers(); 
                openOffersPanel(); 
                return true; 
            } else {
                throw new Error(result.message || 'Error desconocido al guardar la oferta.');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al guardar: ${error.message}`, 'error');
            throw error;
        } finally {
            setProcessingState(false); 
        }
    }
    
    async function handleUpdateOffer(offerId) {
        
        let newOfferData;
        if (typeof tinymce !== 'undefined' && tinymce.get(`edit-desc-input-${offerId}`)) {
            newOfferData = {
                id: offerId,
                offer_name: document.getElementById(`edit-name-input-${offerId}`).value,
                offer_description: tinymce.get(`edit-desc-input-${offerId}`).getContent(),
                promo_text_es: tinymce.get(`edit-es-input-${offerId}`).getContent(),
                promo_text_en: tinymce.get(`edit-en-input-${offerId}`).getContent()
            };
        } else {
            newOfferData = {
                id: offerId,
                offer_name: document.getElementById(`edit-name-input-${offerId}`).value,
                offer_description: document.getElementById(`edit-desc-input-${offerId}`).value,
                promo_text_es: document.getElementById(`edit-es-input-${offerId}`).value,
                promo_text_en: document.getElementById(`edit-en-input-${offerId}`).value
            };
        }

        if (typeof tinymce !== 'undefined') {
            tinymce.remove(`#edit-desc-input-${offerId}`);
            tinymce.remove(`#edit-es-input-${offerId}`);
            tinymce.remove(`#edit-en-input-${offerId}`);
        }
        
        openModal({
            title: 'CONFIRMAR ACTUALIZACIÓN',
            message: '¿Estás seguro de que quieres guardar estos cambios en la oferta?',
            icon: 'save',
            confirmText: 'SÍ, GUARDAR',
            onConfirm: async () => {
                setProcessingState(true, 'Actualizando...');
                try {
                    const response = await fetch(offerEndpoints.update, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(newOfferData)
                    });
                    const result = await response.json();
                    if (response.ok && result.success) {
                        if (typeof showToast === 'function') showToast(result.message, 'success');
                        await fetchAndDrawOffers();
                    } 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 handleDeleteOffer(offerId) {
        openModal({
            title: 'CONFIRMAR ELIMINACIÓN',
            message: '¿Estás seguro de que quieres eliminar esta oferta? <br> Esta acción no se puede deshacer.',
            icon: 'alert-triangle',
            confirmText: 'SÍ, ELIMINAR',
            confirmClass: 'danger',
            onConfirm: async () => {
                setProcessingState(true, 'Eliminando...');
                try {
                    const response = await fetch(offerEndpoints.delete, {
                        method: 'POST', 
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ id: offerId })
                    });
                    const result = await response.json();
                    if (response.ok && result.success) {
                        if (typeof showToast === 'function') showToast(result.message, 'success');
                        await fetchAndDrawOffers();
                    } 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;
            }
            
            const messages = ["Contactando Con OrozCO IA...", "Analizando Datos...", "Creando Estrategias...", "Diseñando Ofertas...", "Casi Está Listo..."];
            let messageIndex = 0;
            btnText.textContent = messages[messageIndex];

            if (window.loadingInterval) clearInterval(window.loadingInterval);
            
            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);

        inputsGeneradosReciente = {
            mainService: document.getElementById('mainService').value,
            offerObjective: document.getElementById('offerObjective').value
        };
        
        const formData = {
            businessName: document.getElementById('businessName').value,
            businessContact: document.getElementById('businessContact').value,
            businessWeb: document.getElementById('businessWeb').value,
            offerObjective: document.getElementById('offerObjective').value,
            mainService: document.getElementById('mainService').value,
            discountType: document.getElementById('discountType').value,
            discountValue: document.getElementById('discountValue').value,
            value_proposition: document.querySelector('input[name="value_proposition"]').value
        };

        try {
            resultContainer.innerHTML = '';    
            resultContainer.style.opacity = '0';    
            resultContainer.style.transform = 'scale(0.95)';
            
            const response = await fetch('api/api-offers-promotions.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

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

            const data = await response.json();
            if(data.error) {
                throw new Error(data.error);
            }
            
            generatedOffers = data.offers;
            displayResult(generatedOffers);
            
            if (typeof showToast === 'function') {
                showToast('¡Ofertas generadas con éxito!', 'success');
            }

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

            try {
                if (error.message.includes('429') || error.message.includes('Rate Limit')) {
                    errorMessage = "LO SENTIMOS: El límite de peticiones a la IA ha sido excedido (429). Por favor, inténtalo de nuevo en unos minutos.";
                } else if (error.message.includes('cURL') || error.message.includes('503')) {
                    errorMessage = "LO SENTIMOS: Error de conexión o saturación. Nuestra Inteligencia Artificial está saturada. Por favor, inténtalo de nuevo en unos minutos.";
                } else {
                    errorMessage += ` Detalles: ${error.message}`;
                }
            } catch (parseError) {
                errorMessage += ` 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';
            resultContainer.style.transform = 'scale(1)';
            if (typeof showToast === 'function') {
                showToast(errorMessage, 'error');
            }
        } finally {
            setProcessingState(false);
        }
    });

    function displayResult(offers) {
        let allOffersHtml = '';

        offers.forEach((offer, index) => {
            const promo_text_es = offer.promo_text_es.replace(/\n/g, '<br>'); 
            const promo_text_en = offer.promo_text_en.replace(/\n/g, '<br>');

            const raw_promo_text_es = encodeURIComponent(offer.promo_text_es);
            const raw_promo_text_en = encodeURIComponent(offer.promo_text_en);
            const raw_offer_name = encodeURIComponent(offer.offer_name);
            const raw_offer_description = encodeURIComponent(offer.offer_description);

            allOffersHtml += `
                <div class="ai-response p-6 md:p-8 rounded-xl shadow-md mb-8 bg-white">
                    <h3 class="text-2xl font-black text-gray-800 mb-2 flex items-center">
                        <i data-lucide="tag" class="mr-3 text-[var(--color-primary)]"></i>Oferta ${index + 1}: ${offer.offer_name}
                    </h3>
                    <p class="text-gray-600 mb-6">${offer.offer_description}</p>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
                        <div>
                            <h4 class="text-xl font-bold text-[var(--color-secondary)] mb-2">🇪🇸 Español</h4>
                            <div class="message-box bg-gray-50 p-4 rounded-lg border border-gray-200 shadow-inner text-base text-gray-800 leading-relaxed whitespace-pre-wrap">${promo_text_es}</div>
                            <button class="btn-copy mt-3 w-full justify-center" data-copy-text="${raw_promo_text_es}">
                                <i data-lucide="copy"></i><span class="copy-text">Copiar Oferta</span>
                            </button>
                        </div>
                        <div>
                            <h4 class="text-xl font-bold text-[var(--color-secondary)] mb-2">🇺🇸 English</h4>
                            <div class="message-box bg-gray-50 p-4 rounded-lg border border-gray-200 shadow-inner text-base text-gray-800 leading-relaxed whitespace-pre-wrap">${promo_text_en}</div>
                            <button class="btn-copy mt-3 w-full justify-center" data-copy-text="${raw_promo_text_en}">
                                <i data-lucide="copy"></i><span class="copy-text">Copy Offer</span>
                            </button>
                        </div>
                    </div>
                    <div class="mt-8 text-center border-t border-gray-200 pt-4">
                        <button class="btn-save-offer btn-copy bg-[var(--color-secondary)] text-white font-bold py-3 px-8 rounded-lg flex items-center justify-center mx-auto gap-2 hover:scale-105 transition-transform uppercase shadow-lg"
                                data-offer-name="${raw_offer_name}"
                                data-offer-description="${raw_offer_description}"
                                data-promo-es="${raw_promo_text_es}"
                                data-promo-en="${raw_promo_text_en}">
                            <i data-lucide="save"></i> <span>Guardar Oferta</span>
                        </button>
                    </div>
                </div>
            `;
        });

        resultContainer.innerHTML = `<div class="space-y-8">${allOffersHtml}</div>`;
        lucide.createIcons();
        setTimeout(() => { 
            resultContainer.style.opacity = '1'; 
            resultContainer.style.transform = 'scale(1)'; 
            resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' }); 
        }, 100);
    }

    resultContainer.addEventListener('click', function(e) {
        const copyButton = e.target.closest('.btn-copy:not(.btn-save-offer)');
        const saveButton = e.target.closest('.btn-save-offer');

        if (copyButton) {
            const textToCopy = decodeURIComponent(copyButton.dataset.copyText);
            navigator.clipboard.writeText(textToCopy).then(() => {
                const buttonContent = copyButton;
                const originalHTML = buttonContent.innerHTML;
                
                const originalClasses = buttonContent.className;
                buttonContent.className = 'btn-copy mt-3 w-full justify-center bg-green-500 text-white';
                
                buttonContent.innerHTML = '<i data-lucide="check"></i><span class="copy-text">¡Copiado!</span>';
                lucide.createIcons({ nodes: [buttonContent] });
                if (typeof showToast === 'function') {
                     showToast('Oferta copiada al portapapeles.', 'success');
                }
                setTimeout(() => {
                    buttonContent.innerHTML = originalHTML;
                    buttonContent.className = originalClasses;
                    lucide.createIcons({ nodes: [buttonContent] });
                }, 2000);
            }).catch(err => {
                console.error('Error al copiar:', err);
                if (typeof showToast === 'function') {
                    showToast('No se pudo copiar el texto.', 'error');
                }
            });
        }
        
        if (saveButton) {
            const offerToSave = {
                offer_name: decodeURIComponent(saveButton.dataset.offerName),
                offer_description: decodeURIComponent(saveButton.dataset.offerDescription),
                promo_text_es: decodeURIComponent(saveButton.dataset.promoEs),
                promo_text_en: decodeURIComponent(saveButton.dataset.promoEn)
            };
            
            createOfferInDB(offerToSave, inputsGeneradosReciente)
                .then(success => {
                    if (success) {
                        saveButton.disabled = true;
                        saveButton.classList.remove('bg-[var(--color-secondary)]', 'hover:scale-105');
                        saveButton.classList.add('bg-green-600', 'opacity-90', 'cursor-not-allowed');
                        saveButton.innerHTML = '<i data-lucide="check"></i> <span>¡Guardado!</span>';
                        lucide.createIcons({ nodes: [saveButton] });
                    }
                })
                .catch(() => {
                });
        }
    });

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