<?php include 'files/guardiankey.php'; ?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LocalCRM ToolKit Con IA | Asistente De Ofertas Y Promociones | OrozDesign Multiemdia</title>
    <meta name="description" content="Crea y gestiona ofertas y promociones con el Toolkit de LocalCRM: automatiza campañas, optimiza precios y atrae más clientes de forma sencilla">
    <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="tools.css">
        <script src="files/header-manager.js"></script>
</head>
<body data-page-title="Asistente De Ofertas y Promociones"
      data-page-subtitle="Crea Ofertas Atractivas Para Conseguir Más Clientes"
      data-page-icon="tag">
    
    <?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>

    <?php include '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 class="fas fa-bullhorn mr-3 text-[var(--color-secondary)]"></i>
                                        <span class="text-[var(--color-secondary)] mr-2">PASO 1:</span> DEFINE TU OFERTA
                                    </h2>
                                    <p class="step-subtitle uppercase">Ingresa los detalles de tu negocio y la oferta.</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 text-gray-700 mb-2">Nombre de tu Negocio</label>
                                            <input type="text" id="businessName" name="businessName" class="w-full p-3 bg-white border border-gray-300 rounded-lg" placeholder="Ej: Limpieza Brillante" required>
                                        </div>
                                        <div>
                                            <label for="businessContact" class="block font-bold text-gray-700 mb-2">Teléfono / WhatsApp</label>
                                            <input type="text" id="businessContact" name="businessContact" class="w-full p-3 bg-white border border-gray-300 rounded-lg" placeholder="Ej: 555-123-4567" required>
                                        </div>
                                    </div>
                                    <div>
                                        <label for="businessWeb" class="block font-bold text-gray-700 mb-2">Página Web / Red Social</label>
                                        <input type="text" id="businessWeb" name="businessWeb" class="w-full p-3 bg-white border border-gray-300 rounded-lg" placeholder="Ej: @limpiezabrillante" required>
                                    </div>
                                    <div>
                                        <label for="offerObjective" class="block font-bold text-gray-700 mb-2">Objetivo de la Oferta</label>
                                        <select id="offerObjective" name="offerObjective" class="w-full p-3 bg-white border border-gray-300 rounded-lg" required>
                                            <option value="" disabled selected>-- Elige una opción --</option>
                                            <option value="referrals">Crear una promoción por referidos</option>
                                            <option value="neighborhood">Lanzar una oferta en un vecindario</option>
                                            <option value="marketplace">Diseñar una oferta para Marketplace</option>
                                            <option value="service_bundle">Crear un paquete de servicios</option>
                                            <option value="seasonal">Crear una oferta de temporada</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label for="mainService" class="block font-bold text-gray-700 mb-2">Servicio a Promocionar</label>
                                        <input type="text" id="mainService" name="mainService" class="w-full p-3 bg-white border border-gray-300 rounded-lg" placeholder="Ej: limpieza profunda, ventanales" required>
                                    </div>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div>
                                            <label for="discountType" class="block font-bold text-gray-700 mb-2">Tipo de Descuento</label>
                                            <select id="discountType" name="discountType" class="w-full p-3 bg-white border border-gray-300 rounded-lg" 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 text-gray-700 mb-2">Valor del Descuento / Detalle</label>
                                            <input type="text" id="discountValue" name="discountValue" class="w-full p-3 bg-white border border-gray-300 rounded-lg" placeholder="Ej: 20 (para %), 50 (para $), limpieza de horno" required>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                    <div class="lg:col-span-2 space-y-8">
                        <div class="bg-white rounded-xl shadow-md">
                            <div class="native-video-wrapper" id="videoWrapper">
                                <div class="play-overlay" id="playOverlay">
                                    <img src="https://placehold.co/600x337/07162d/ffc857?text=VIDEO" alt="Imagen de previsualización del video" class="absolute inset-0 w-full h-full object-cover rounded-xl">
                                    <i class="fas fa-play play-icon"></i>
                                </div>
                                <video class="w-full h-full object-cover" id="videoPlayer" controlslist="nodownload nofullscreen" 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>
                        </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 class="fas fa-book mr-3 text-[var(--color-highlight)]"></i> 
                                    INSTRUCCIONES
                                </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 class="fas fa-percent"></i></span><div><strong class="text-brand-dark">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 class="fas fa-lightbulb"></i></span><div><strong class="text-brand-dark">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 class="fas fa-copy"></i></span><div><strong class="text-brand-dark">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 class="fas fa-bullseye"></i></span><div><strong class="text-brand-dark">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 class="fas fa-gift mr-3 text-[var(--color-secondary)]"></i>
                                <span class="text-[var(--color-secondary)] mr-2">PASO 2:</span> GENERAR OFERTAS
                            </h2>
                            <p class="step-subtitle uppercase">Crea ofertas atractivas y promociones estratégicas.</p>
                        </div>
                        <div class="border-b border-gray-200 pb-4 mb-6"></div>
                        <div class="flex flex-col md:flex-row items-center md:justify-between gap-4">
                            <p class="text-lg text-center md:text-left text-gray-700 md:flex-1 md:pr-4 mb-0">Basado en los detalles de tu negocio y el objetivo de tu oferta, <strong class="font-black">CLIENT3 IA</strong>, generará <b>dos ideas de ofertas promocionales</b> creativas y efectivas, listas para captar la atención de nuevos clientes.</p>
                            <button id="generateBtn" type="submit" form="offerForm" class="w-full md:w-auto bg-[var(--color-highlight)] text-brand-dark font-bold py-4 px-6 rounded-lg hover:scale-105 transition-transform shadow-lg text-lg flex items-center justify-center uppercase">
                                <i class="fas fa-bolt mr-3"></i>
                                <span id="btn-text">Generar Ofertas</span>
                                <div id="loader-container" class="hidden ml-3"></div>
                            </button>
                        </div>
                    </div>

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

<script>
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();

    // --- Lógica del Video Player ---
    const videoPlayer = document.getElementById('videoPlayer');
    const playOverlay = document.getElementById('playOverlay');
    if (videoPlayer && playOverlay) {
        videoPlayer.controls = false;
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.controls = true;
            videoPlayer.play().catch(e => console.error("Error al reproducir video:", e));
        });
        videoPlayer.addEventListener('ended', () => {
            playOverlay.style.display = 'flex';
            videoPlayer.controls = false;
        });
    }

    // --- Lógica del Generador ---
    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');

    form.addEventListener('submit', async function(event) {
        event.preventDefault();
        btnText.textContent = 'Generando Ofertas...';
        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;
        resultContainer.innerHTML = '';
        resultContainer.style.opacity = '0'; // Reinicia la opacidad para la animación

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

        try {
            const response = await fetch('api/API-Asistente-De-Ofertas-Y-Promociones.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

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

            const data = await response.json();
            if(data.error) {
                throw new Error(data.error);
            }
            displayResult(data.offers);

        } 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 {
                const jsonStartIndex = error.message.indexOf('{');
                if (jsonStartIndex !== -1) {
                    const errorJsonString = error.message.substring(jsonStartIndex);
                    const errorDetails = JSON.parse(errorJsonString);
                    if (errorDetails.error && errorDetails.error.code === 503) {
                        errorMessage = "LO SENTIMOS En Este Momento, Nuestra Inteligencia Artificial Está Saturada. Por favor, Inténtalo De Nuevo En Unos Minutos.";
                    } else {
                        errorMessage += ` Detalles: ${error.message}`;
                    }
                } else {
                    errorMessage += ` Detalles: ${error.message}`;
                }
            } catch (parseError) {
                errorMessage += ` Detalles: ${error.message}`;
            }

            resultContainer.innerHTML = `<div class="bg-red-100 text-center p-4 text-red-700 rounded-lg border border-red-300"><p><strong>Error:</strong> ${errorMessage}</p></div>`;
            resultContainer.style.opacity = '1'; // Mostrar el error inmediatamente
        } finally {
            btnText.textContent = 'Generar Ofertas';
            loaderContainer.classList.add('hidden');
            generateBtn.disabled = false;
        }
    });

    function displayResult(offers) {
        let allOffersHtml = '';
        offers.forEach((offer, index) => {
            allOffersHtml += `
                <div class="ai-response p-6 md:p-8 rounded-xl shadow-md mb-8">
                    <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                        <i class="fas fa-gift mr-3 text-[var(--color-primary)]"></i>Oferta ${index + 1}: ${offer.offer_name}
                    </h3>
                    <p class="section-subtitle text-gray-600 mb-4">${offer.offer_description}</p>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
                        <div class="social-post-lang-card bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <div class="social-post-lang-header flex justify-between items-center mb-3">
                                <h4 class="text-lg font-semibold text-gray-700">🇪🇸 Español</h4>
                                <button class="copy-social-post-btn bg-[var(--color-primary)] text-white px-3 py-1 rounded-md text-sm hover:opacity-90 transition-opacity" data-copy-text="${encodeURIComponent(offer.promo_text_es)}"><i class="fas fa-copy mr-1"></i>COPIAR OFERTA</button>
                            </div>
                            <div class="social-post-body">
                                <p class="post-copy text-gray-800 leading-relaxed whitespace-pre-wrap">${offer.promo_text_es.replace(/\n/g, '<br>')}</p>
                            </div>
                        </div>
                        <div class="social-post-lang-card bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <div class="social-post-lang-header flex justify-between items-center mb-3">
                                <h4 class="text-lg font-semibold text-gray-700">🇺🇸 English</h4>
                                <button class="copy-social-post-btn bg-[var(--color-secondary)] text-white px-3 py-1 rounded-md text-sm hover:opacity-90 transition-opacity" data-copy-text="${encodeURIComponent(offer.promo_text_en)}"><i class="fas fa-copy mr-1"></i>COPY OFFER</button>
                            </div>
                            <div class="social-post-body">
                                <p class="post-copy text-gray-800 leading-relaxed whitespace-pre-wrap">${offer.promo_text_en.replace(/\n/g, '<br>')}</p>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });

        resultContainer.innerHTML = `<div class="ai-response p-6 md:p-8 rounded-xl shadow-md space-y-8">${allOffersHtml}</div>`;
        setTimeout(() => { resultContainer.style.opacity = '1'; resultContainer.style.transform = 'scale(1)'; }, 100);

        resultContainer.addEventListener('click', function(e) {
            const button = e.target.closest('.copy-social-post-btn');
            if (button) {
                const textToCopy = decodeURIComponent(button.dataset.copyText);
                navigator.clipboard.writeText(textToCopy).then(() => {
                    const originalContent = button.innerHTML;
                    button.innerHTML = '<i class="fas fa-check"></i> Copiado';
                    button.classList.add('copied');
                    setTimeout(() => {
                        button.innerHTML = originalContent;
                        button.classList.remove('copied');
                    }, 2000);
                }).catch(err => {
                    console.error('Error al copiar el texto: ', err);
                });
            }
        });
    }
});
</script>

</body>
</html>