<?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 Plan Táctico Publicitario Con <?php echo htmlspecialchars($branding['iamarketing_name']); ?> Powered_by <?php echo htmlspecialchars($branding['powered_by']); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>
    
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="tools.css">
    <script src="files/header-manager.js"></script>
        
    <style>
        .step-header h2 {
            flex-direction: column;
            align-items: flex-start;
            justify-content: flex-start;
            text-align: left;
        }

        .step-header .step-number {
            font-size: 1.25rem;
            font-weight: 900;
            margin-right: 0;
            margin-bottom: 0.25rem;
            display: flex;
            align-items: center;
            color: var(--color-secondary);
            flex-shrink: 0;
            text-align: left;
        }
        .step-header .step-number i {
            margin-right: 0.5rem;
            font-size: 1.5rem;
        }

        .step-header .step-title {
            font-size: 1.4rem;
            font-weight: 900;
            color: #1e293b;
            line-height: 1.2;
            text-transform: uppercase;
            text-align: left;
            width: 100%;
        }

        @media (min-width: 768px) {
            .step-header h2 {
                flex-direction: row;
                align-items: center;
                justify-content: flex-start;
                text-align: left;
            }
            .step-header .step-number {
                font-size: 1.5rem;
                margin-right: 0.5rem;
                margin-bottom: 0;
                text-align: left;
            }
            .step-header .step-number i {
                font-size: 1.8rem;
            }
            .step-header .step-title {
                font-size: 1.5rem;
                width: auto;
                text-align: left;
            }
        }
    </style>
</head>
<body data-page-title="Generador De Plan Táctico Publicitario"
      data-page-subtitle="Obtén Un Plan Publicitario Estratégico Adaptado A Tu Presupuesto"
      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="tactical-plan-generator" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">

                    <div class="lg:col-span-3">
                        <form id="tactical-plan-form" class="space-y-8 bg-white p-8 rounded-xl shadow-md">
                            <input type="hidden" name="value_proposition" value="<?php echo htmlspecialchars($value_proposition); ?>">
                            <div>
                                <div class="step-header">
                                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase md:justify-start"> <span class="step-number"> <i data-lucide="store" class="mr-3 text-[var(--color-secondary)]"></i>
                                            PASO 1:
                                        </span>
                                        <span class="step-title"> Describe Tu Negocio
                                        </span>
                                    </h2>
                                    <p class="step-subtitle uppercase">Ingresa los datos para un plan preciso</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                <div class="space-y-6">
                                    <div>
                                        <label for="business_name" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Nombre De Tu Negocio</label>
                                        <input type="text" id="business_name" name="business_name" placeholder="Ej: Jardines Verdes" 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="service_type" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tipo De Servicio Principal</label>
                                        <input type="text" id="service_type" name="service_type" placeholder="Ej: Mantenimiento De Jardines" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                    </div>
                                    <div>
                                        <label for="service_zone" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Zona Geográfica De Servicio</label>
                                        <input type="text" id="service_zone" name="service_zone" placeholder="Ej: Austin, TX" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" value="<?php echo htmlspecialchars($operating_cities); ?>">
                                    </div>
                                    <div>
                                        <label for="service_price" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Precio Promedio ($)</label>
                                        <input type="number" id="service_price" name="service_price" step="1" min="1" placeholder="Ej: 150" 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>
                            </div>

                            <div class="pt-8">
                                <div class="step-header">
                                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase md:justify-start"> <span class="step-number"> <i data-lucide="clipboard-check" class="mr-3 text-[var(--color-secondary)]"></i>
                                            PASO 2:
                                        </span>
                                        <span class="step-title"> Define Tus Metas
                                        </span>
                                    </h2>
                                    <p class="step-subtitle uppercase">Establece lo que esperas lograr</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                <div class="space-y-6">
                                    <div>
                                        <label for="main_objective" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Objetivo Principal De Publicidad</label>
                                        <select id="main_objective" name="main_objective" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                            <option value="">Selecciona Un Objetivo</option>
                                            <option value="Conseguir más clientes">Conseguir Más Clientes</option>
                                            <option value="Dar a conocer mi negocio">Dar A Conocer Mi Negocio</option>
                                            <option value="Vender un producto/servicio específico">Vender Un Servicio Específico</option>
                                            <option value="Llenar mi agenda de citas">Llenar Mi Agenda De Citas</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label for="desired_new_clients" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Clientes Nuevos Deseados Al Mes</label>
                                        <input type="number" id="desired_new_clients" name="desired_new_clients" step="1" min="1" placeholder="Ej: 10" 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="commitment_level" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tu Nivel De Compromiso</label>
                                        <select id="commitment_level" name="commitment_level" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                            <option value="">Selecciona Tu Nivel De Compromiso</option>
                                            <option value="Bajo (Prefiero lo más simple y automatizado)">Bajo (Prefiero Lo Más Simple)</option>
                                            <option value="Medio (Dispuesto a aprender lo básico y dedicar algo de tiempo)">Medio (Dispuesto A Aprender)</option>
                                            <option value="Alto (Quiero dominar la publicidad y optimizar al máximo)">Alto (Quiero Dominar La Publicidad)</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label for="business_stage" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Etapa Actual De Tu Negocio</label>
                                        <select id="business_stage" name="business_stage" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                            <option value="">Selecciona La Etapa De Tu Negocio</option>
                                            <option value="Apenas voy a comenzar (negocio nuevo)">Apenas Voy A Comenzar</option>
                                            <option value="Ya tengo negocio, pero no consigo clientes">Tengo Negocio, Pero No Consigo Clientes</option>
                                            <option value="Tengo clientes, pero quiero más">Tengo Clientes, Pero Quiero Más</option>
                                            <option value="Quiero escalar mi negocio actual">Quiero Escalar Mi Negocio</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label for="has_website_optimized" class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Tienes Una Página Web Profesional?</label>
                                        <select id="has_website_optimized" name="has_website_optimized" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                            <option value="">Selecciona Una Opción</option>
                                            <option value="No, todavía no">No, Todavía No Tengo</option>
                                            <option value="Sí, pero es solo informativa">Sí, Pero Es Solo Informativa</option>
                                            <option value="Sí, y está optimizada para vender">Sí, Y Está Optimizada Para Vender</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="pt-8">
                                <div class="step-header">
                                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase md:justify-start"> <span class="step-number"> <i data-lucide="wallet" class="mr-3 text-[var(--color-secondary)]"></i>
                                            PASO 3:
                                        </span>
                                        <span class="step-title"> Define Tu Presupuesto
                                        </span>
                                    </h2>
                                    <p class="step-subtitle uppercase">Detalla tu inversión disponible para anuncios</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                <div class="space-y-6">
                                    <div>
                                        <label for="monthly_budget" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Presupuesto Mensual Para Anuncios ($)</label>
                                        <input type="number" id="monthly_budget" name="monthly_budget" step="1" min="1" placeholder="Ej: 300" 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="prior_ad_investment" class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Has Invertido En Publicidad Antes?</label>
                                        <select id="prior_ad_investment" name="prior_ad_investment" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                            <option value="">Selecciona Una Opción</option>
                                            <option value="No">No, Nunca</option>
                                            <option value="Sí">Sí, Un Poco</option>
                                            <option value="No estoy seguro">No Estoy Seguro</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label for="facebook_page_optimized" class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Tienes Una Página De Facebook Optimizada?</label>
                                        <select id="facebook_page_optimized" name="facebook_page_optimized" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                            <option value="">Selecciona Una Opción</option>
                                            <option value="No">No, Todavía No</option>
                                            <option value="Sí">Sí, Está Preparada</option>
                                            <option value="No estoy seguro">No Estoy Seguro(a)</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div id="form-error-message" class="hidden bg-red-100 text-center p-3 text-red-700 rounded-lg border border-red-300" role="alert">
                                Por Favor, Completa Todos Los Campos Requeridos.
                            </div>
                        </form>
                    </div>

                    <div class="lg:col-span-2 space-y-8">
                        <img src="img/VideoLeccion.png" alt="VideoLeccion - IAMarketing">
                        <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 De Introducción A La Plataforma SiteFlowCMS
                                        </span>
                                        <span class="inline-flex items-center gap-2">
                                            <i data-lucide="clock" class="w-4 h-4"></i> 2–3 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">PROPORCIONA DATOS DETALLADOS:</strong> Cuanta más información brindes, más preciso y útil será tu plan.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="wallet"></i></span><div><strong class="text-brand-dark uppercase">SÉ REALISTA CON TU PRESUPUESTO:</strong> Nuestra IA te guiará para alcanzar tus metas de forma viable.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="list-checks"></i></span><div><strong class="text-brand-dark uppercase">GENERA TU PLAN:</strong> Recibe un diagnóstico, estimaciones y un plan de acción paso a paso.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="bar-chart-2"></i></span><div><strong class="text-brand-dark uppercase">IMPLEMENTA Y OPTIMIZA:</strong> Sigue el plan y usa las métricas clave para mejorar continuamente tus campañas.</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 md:justify-start">
                                <span class="step-number"> <i data-lucide="trending-up" class="mr-3 text-[var(--color-secondary)]"></i>
                                    PASO 4:
                                </span>
                                <span class="step-title">
                                    Obtén Tu Estrategia Publicitaria
                                </span>
                            </h2>
                            <p class="step-subtitle text-center md:text-left uppercase">Tu plan de acción para conseguir clientes de forma efectiva</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">Para crear el mejor plan publicitario, <strong>es importante</strong> que los detalles sobre tu negocio y tu presupuesto sean precisos. Con los datos que proporciones, nuestra Inteligencia Artificial <strong>IA Marketing</strong> generará un <strong>Plan Táctico Publicitario</strong> y estratégico, para que obtengas una guía de anuncios adaptado a tus posibilidades económicas</p>
                        <div class="flex flex-col items-center">
                            <i data-lucide="brain" class="w-12 h-12 text-[var(--color-primary)] mb-2"></i>
                             <button id="generateBtn" type="submit" form="tactical-plan-form" class="w-full md:w-auto bg-[var(--color-highlight)] text-[var(--color-primary)] font-bold py-4 px-6 rounded-lg hover:scale-105 transition-transform shadow-lg text-lg flex items-center justify-center gap-2 uppercase">
                               <span id="btn-text">GENERAR CON IA MARKETING</span>
                               <i data-lucide="mouse-pointer-click" class="w-6 h-6 animate-bounce"></i>
                               <div id="loader-container" class="hidden ml-3"></div>
                             </button>
                        </div>
                        </div>
                    </div>

                    <div id="result-container" class="lg:col-span-5 mt-8 opacity-0 transition-opacity duration-500 transform scale-95"></div>
                </div>
            </section>
        </div>
    </main>
</div>

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

    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) {
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.play();
        });
    }
    
    const phoneInput = document.getElementById('contact_phone');
    if (phoneInput) {
        IMask(phoneInput, { mask: '(000) 000-0000' });
    }

    function setupPlanGenerator() {
        const form = document.getElementById('tactical-plan-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');

        function validateForm() {
            const requiredInputs = form.querySelectorAll('[required]');
            let allValid = true;
            requiredInputs.forEach(input => {
                if (!input.value || (input.type === 'number' && parseFloat(input.value) <= 0)) {
                    input.classList.add('border-red-500'); 
                    allValid = false;
                } else {
                    input.classList.remove('border-red-500');
                }
            });
            if (!allValid) {
                formErrorMessage.classList.remove('hidden');
                formErrorMessage.focus(); 
                showToast('Por favor, completa todos los campos requeridos.', 'warning');
            } else {
                formErrorMessage.classList.add('hidden');
            }
            return allValid;
        }

        function setProcessingState(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>';
                loaderContainer.classList.remove('hidden');
                generateBtn.disabled = true;
                generateBtn.classList.add('opacity-50', 'cursor-not-allowed');
                resultContainer.innerHTML = ''; 
                resultContainer.style.opacity = '0'; 
                resultContainer.style.transform = 'scale(0.95)';

                const messages = ["Contactando Con OrozCO IA...", "Analizando tu negocio...", "Definiendo estrategia...", "Generando tu plan...", "Casi Está Listo..."];
                let messageIndex = 0;
                btnText.textContent = messages[messageIndex];

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

            } else {
                if (window.loadingInterval) clearInterval(window.loadingInterval);
                loaderContainer.classList.add('hidden');
                generateBtn.disabled = false;
                generateBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                btnText.textContent = 'GENERAR TU PLAN TÁCTICO';
            }
        }


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

            if (!validateForm()) {
                return;
            }

            setProcessingState(true);

            const formData = {
                business_name: document.getElementById('business_name').value,
                service_type: document.getElementById('service_type').value,
                service_zone: document.getElementById('service_zone').value,
                service_price: parseFloat(document.getElementById('service_price').value),
                main_objective: document.getElementById('main_objective').value,
                desired_new_clients: parseInt(document.getElementById('desired_new_clients').value),
                commitment_level: document.getElementById('commitment_level').value,
                business_stage: document.getElementById('business_stage').value,
                has_website_optimized: document.getElementById('has_website_optimized').value,
                monthly_budget: parseFloat(document.getElementById('monthly_budget').value),
                prior_ad_investment: document.getElementById('prior_ad_investment').value,
                facebook_page_optimized: document.getElementById('facebook_page_optimized').value
            };

            try {
                const response = await fetch('api/api-generador-de-plan-tactico-publicitario.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 || `Error del servidor: ${response.status}. Por favor, inténtalo de nuevo.`);
                }

                const data = await response.json();
                if(data.error) {
                    throw new Error(data.error);
                }
                displayResult(data);
                showToast('¡Plan táctico generado con éxito!', 'success');

            } catch (error) {
                showToast("Error al generar el plan: " + error.message, 'error');
                resultContainer.innerHTML = `<div class="bg-red-100 text-center p-4 text-red-700 rounded-lg border border-red-300" role="alert"><p><strong>Error:</strong> No se pudo generar el plan táctico.</p><p class="mt-2 text-sm">${error.message}</p></div>`;
                resultContainer.style.opacity = '1'; 
                resultContainer.style.transform = 'scale(1)';
            } finally {
                setProcessingState(false);
            }
        });

        function displayResult(data) {
            const formatText = (text) => (text || '').replace(/\*\*(.*?)\*\*/g, '<strong class="text-[var(--color-primary)]">$1</strong>');
            
            resultContainer.innerHTML = `
                <div class="ai-response p-6 md:p-8 rounded-xl shadow-md space-y-8 bg-white">
                    <div class="text-center">
                        <h2 class="ai-report-main-title text-3xl font-black text-[var(--color-primary)] mb-4">Tu Plan Táctico Publicitario</h2>
                        <p class="text-lg text-gray-700">${formatText(data.summary)}</p>
                    </div>

                    <div class="ai-report-section border-t border-gray-200 pt-6">
                        <h3 class="text-2xl font-bold flex items-center text-[var(--color-dark)] mb-4"><i data-lucide="lightbulb" class="mr-3 text-[var(--color-primary)]"></i>Diagnóstico Rápido</h3>
                        <p class="section-content-text text-gray-700 leading-relaxed">${formatText(data.diagnostico_rapido)}</p>
                    </div>

                    <div class="ai-report-section border-t border-gray-200 pt-6">
                        <h3 class="text-2xl font-bold flex items-center text-[var(--color-dark)] mb-4"><i data-lucide="bar-chart-2" class="mr-3 text-[var(--color-primary)]"></i>Estimación de Clientes Potenciales</h3>
                        <p class="section-content-text text-gray-700 leading-relaxed">${formatText(data.estimacion_clientes)}</p>
                    </div>
                    
                    <div class="ai-report-action-plan-container border-t border-gray-200 pt-6">
                        <h3 class="ai-action-plan-title text-2xl font-bold flex items-center text-[var(--color-dark)] mb-4"><i data-lucide="clipboard-list" class="mr-3 text-[var(--color-secondary)]"></i>Tu Plan Táctico Detallado</h3>
                        <div class="mt-6 space-y-6">
                            ${data.plan_tactico.map((step, index) => `
                                <div class="tactical-step-item flex items-start p-4 bg-gray-50 rounded-lg shadow-sm">
                                    <div class="tactical-step-number-circle bg-[var(--color-secondary)] text-white text-lg font-black flex-shrink-0 flex items-center justify-center w-8 h-8 rounded-full">
                                        ${index + 1}
                                    </div>
                                    <div class="ml-4 flex-grow">
                                        <p class="tactical-step-text text-gray-800 leading-relaxed">
                                            ${formatText(step)}
                                        </p>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>

                    <div class="ai-report-section border-t border-gray-200 pt-6">
                        <h3 class="text-2xl font-bold flex items-center text-[var(--color-dark)] mb-4"><i data-lucide="gauge" class="mr-3 text-[var(--color-primary)]"></i>Métricas Clave a Monitorear</h3>
                        <p class="section-content-text text-gray-700 leading-relaxed">${formatText(data.metricas_clave)}</p>
                    </div>

                    <div class="ai-report-section border-t border-gray-200 pt-6">
                        <h3 class="text-2xl font-bold flex items-center text-[var(--color-dark)] mb-4"><i data-lucide="wrench" class="mr-3 text-[var(--color-primary)]"></i>Recomendaciones para Optimización</h3>
                        <p class="section-content-text text-gray-700 leading-relaxed">${formatText(data.recomendaciones_optimizacion)}</p>
                    </div>
                </div>
            `;
            lucide.createIcons();
            setTimeout(() => { 
                resultContainer.style.opacity = '1'; 
                resultContainer.style.transform = 'scale(1)'; 
                resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' }); 
            }, 100);
        }
    }
    
    // Asumiendo que initVideoPlayer() es una función global o no necesaria en este contexto, la eliminamos
    setupPlanGenerator();
});
</script>
<script src="files/toast.js"></script>
</body>
</html>