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

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

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="tools.css">
    <script src="files/header-manager.js"></script>
    
    <style>
        .plan-step-item {
            background-color: #f9fafb; padding: 1.25rem; border-radius: 0.5rem; 
            shadow-sm; border-left-width: 4px; display: flex; align-items: flex-start;
        }
        .plan-step-item h4 {
            font-size: 1.25rem; font-weight: 800; color: #1f2937;
            margin-bottom: 0.5rem; display: flex; align-items: center;
        }
        .plan-step-item h4 i { margin-right: 0.75rem; }
        .plan-step-item p {
            font-size: 1.125rem; color: #374151; line-height: 1.6;
        }
    </style>
</head>
<body data-page-title="Planificador De Objetivos Publicitarios"
      data-page-subtitle="Crea Un Plan Semanal, Mensual O Trimestral Paso A Paso"
      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="objectives-planner" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">

                    <div class="lg:col-span-3">
                        <form id="objectives-form" class="space-y-8 bg-white p-8 rounded-xl shadow-md">
                            <div>
                                <div class="step-header">
                                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                        <i data-lucide="crosshair" class="mr-3 text-[var(--color-secondary)]"></i>
                                        <span class="text-[var(--color-secondary)] mr-2">PASO 1:</span> Define Tus Metas Publicitarias
                                    </h2>
                                    <p class="step-subtitle uppercase">Ingresa tus objetivos de negocio y promoción De Tus Servicios</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                <div class="space-y-6">
                                    <div>
                                        <label for="main-goal" class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué Te Gustaría Lograr Al Promocionar Tu Negocio?</label>
                                        <input id="main-goal" name="main_goal" type="text" placeholder="Ej: Conseguir 5 Clientes Nuevos Cada Mes" 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="short-term-goal" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Objetivo A Corto Plazo (Esta Semana)</label>
                                        <input id="short-term-goal" name="short_term_goal" type="text" placeholder="Ej: Dejar Lista Mi Página Y Lanzar Mi Primer Anuncio" 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="medium-term-goal" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Objetivo A Mediano Plazo (Este Mes)</label>
                                        <input id="medium-term-goal" name="medium_term_goal" type="text" placeholder="Ej: Recibir Mis Primeros Mensajes De Prospectos" 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="long-term-goal" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Objetivo A Largo Plazo (En 3 Meses)</label>
                                        <input id="long-term-goal" name="long_term_goal" type="text" placeholder="Ej: Tener Un Sistema Que Atrae Clientes Constantemente" 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">
                                        <i data-lucide="lightbulb" class="mr-3 text-[var(--color-secondary)]"></i>
                                        <span class="text-[var(--color-secondary)] mr-2">PASO 2:</span> Define Tu Experiencia y Estrategia
                                    </h2>
                                    <p class="step-subtitle uppercase">Selecciona tu experiencia previa y cómo planeas alcanzar tus objetivos.</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="prior_experience" class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Has Invertido En Publicidad Antes?</label>
                                            <select id="prior_experience" name="prior_experience" 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="No, nunca he invertido">No, Nunca He Invertido</option>
                                                <option value="Sí, pero sin resultados claros">Sí, Pero Sin Buenos Resultados</option>
                                                <option value="Sí, con buenos resultados">Sí, Con Buenos Resultados</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label for="campaign_objective" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Objetivo Para Tu Negocio</label>
                                            <select id="campaign_objective" name="campaign_objective" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg recommended-select focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" required>
                                                <option value="Generar Más Clientes">Generar Más Clientes</option>
                                                <option value="Darte A Conocer">Darte A Conocer</option>
                                                <option value="Impulsar Nuevo Servicio">Impulsar Nuevo Servicio</option>
                                                <option value="Recibir Mensajes">Recibir Mensajes</option>
                                                <option value="Tráfico a la Página Web">Tráfico A La Página Web</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div>
                                        <label for="has_website" class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Tienes Página Web Que Venda Por Ti 24/7?</label>
                                        <select id="has_website" name="has_website" 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="No, todavía no">No, Todavía No La 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>
                                        <label for="other_strategies" class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué Otras Estrategias Has Utilizado?</label>
                                        <textarea id="other_strategies" name="other_strategies" placeholder="Ej: Repartir Tarjetas, Pedir Recomendaciones" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" rows="3" required></textarea>
                                    </div>
                                </div>
                            </div>

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

                                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    <div>
                                        <label for="monthly_budget" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Presupuesto Mensual</label>
                                        <input id="monthly_budget" name="budget" type="number" step="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>
                                        <label for="service-price" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Precio Promedio De Tu Servicio</label>
                                        <input id="service-price" name="service_price" type="number" step="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>
                            </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-plan-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>Tu Plan De Marketing</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="info"></i></span><div><strong class="text-brand-dark uppercase">PROPORCIONA DETALLES CLAROS:</strong> Cuanta más información des, más preciso y útil será tu plan táctico.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="coins"></i></span><div><strong class="text-brand-dark uppercase">SÉ REALISTA CON TU PRESUPUESTO:</strong> La IA te guiará para alcanzar tus metas de forma viable.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="clipboard-check"></i></span><div><strong class="text-brand-dark uppercase">GENERA TU PLAN ESTRATÉGICO:</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="trending-up"></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">
                                <i data-lucide="rocket" class="mr-3 text-[var(--color-secondary)]"></i>
                                <span class="text-[var(--color-secondary)] mr-2">PASO 4:</span> Genera Tu Plan De Objetivos
                            </h2>
                            <p class="step-subtitle uppercase">Obtén un análisis detallado de tu situación y un plan de acción estratégico.</p>
                        </div>
                        <div class="border-b border-gray-200 pb-4 mb-6"></div>
                        
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 md:gap-8 items-center">

    <div class="flex flex-col justify-center items-center bg-[var(--color-primary)] p-6 rounded-xl">
        <i data-lucide="brain" class="w-24 h-24 md:w-32 md:h-32 text-white animate-pulse"></i>
        <p class="mt-4 text-white font-black text-xl uppercase tracking-wide">
            IA<span class="text-[var(--color-highlight)]">Marketing</span>™
        </p>
    </div>

    <div class="md:col-span-2 text-center md:text-left">
        
        <h3 class="text-2xl font-black text-gray-800 flex items-center justify-center md:justify-start mb-2 uppercase">
            <i data-lucide="bell-electric" class="w-6 h-6 text-[var(--color-secondary)] mr-2 flex-shrink-0"></i>
            Información Importante
        </h3>
        
        <p class="text-lg text-gray-700 mb-6">
            Para crear un plan de marketing que sea realista, <b>es muy importante</b> que definas tus metas de forma clara. Con base en tus objetivos, nuestra <b>inteligencia artificial</b> creará un <b>Plan De Objetivos de Marketing</b>, para que tengas una estratégia de acción semanal, mensual o trimestral para alcanzar tus metas.
        </p>
        
        <div class="flex justify-center md:justify-start">
            <button id="generateBtn" type="submit" form="objectives-form" class="w-full sm:w-auto bg-[var(--color-highlight)] text-[var(--color-primary)] font-black py-4 px-6 rounded-lg hover:scale-105 transition-transform text-lg flex items-center justify-center uppercase">
                
                <i data-lucide="arrow-big-right-dash" class="w-6 h-6"></i>
                
                <span id="btn-text">GENERAR PLAN DE OBJETIVOS 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="plan-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 hidden" aria-hidden="true"></div>

<div id="plan-panel" class="fixed top-0 right-0 h-full w-full lg:w-1/2 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>
            TU PLAN DE MARKETING
        </h3>
        <button id="close-plan-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="plan-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 plan...</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-plan-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>

<script type="module">
// --- CARGA DOMCONTENT ---
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
    
    // --- UI BÁSICA (MENÚ, VIDEO, TOASTS) ---
    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' });
    }

    // --- ELEMENTOS DE LA HERRAMIENTA ---
    const form = document.getElementById('objectives-form');
    const resultContainer = document.getElementById('result-container');
    const generateBtn = document.getElementById('generateBtn');
    const btnText = document.getElementById('btn-text');
    const loaderContainer = document.getElementById('loader-container');
    
    // --- DATOS GLOBALES ---
    // Usamos el JSON codificado desde PHP
    let planGuardadoActual = <?php echo $plan_json_for_js; ?>;
    let planGeneradoReciente = null; // Almacena el último resultado de la IA

    // --- PANEL LATERAL ---
    const openPlanPanelBtn = document.getElementById('open-plan-panel-btn');
    const closePlanPanelBtn = document.getElementById('close-plan-panel-btn');
    const planPanelOverlay = document.getElementById('plan-panel-overlay');
    const planPanel = document.getElementById('plan-panel');
    const planPanelContent = document.getElementById('plan-panel-content');

    // --- MODAL DE CONFIRMACIÓN ---
    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;

    // --- LÓGICA DEL MODAL ---
    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';
        // Reiniciar clases y aplicar las correctas según el estándar unificado
        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();
    });

    // --- LÓGICA DEL PANEL LATERAL ---
    function openPlanPanel() {
        planPanel.classList.remove('translate-x-full');
        planPanelOverlay.classList.remove('hidden');
        drawPlanPanelContent(planGuardadoActual); 
    }

    function closePlanPanel() {
        planPanel.classList.add('translate-x-full');
        planPanelOverlay.classList.add('hidden');
    }

    openPlanPanelBtn.addEventListener('click', openPlanPanel);
    closePlanPanelBtn.addEventListener('click', closePlanPanel);
    planPanelOverlay.addEventListener('click', closePlanPanel);

    // Renderiza el contenido del plan dentro del panel (Modo Ver/Eliminar)
    function drawPlanPanelContent(planData) {
        if (planData && planData.analisis_objetivos) {
            const formattedHtml = formatPlanResult(planData); // Reutiliza la función de formateo
            planPanelContent.innerHTML = `
                <div class="space-y-3">
                    <div class="flex justify-between items-center bg-gray-50 p-4 rounded-xl shadow-sm border border-gray-200">
                        <h4 class="text-xl font-black uppercase text-[var(--color-primary)]">Plan Guardado</h4>
                        <button id="panel-plan-btn-eliminar" class="btn-copy btn-xs bg-[var(--color-secondary)] text-white">
                            <i data-lucide="trash-2"></i>
                        </button>
                    </div>
                    <div id="plan-display-container" class="p-4 border rounded-lg overflow-y-auto max-h-[80vh]">
                        ${formattedHtml}
                    </div>
                </div>
            `;
            lucide.createIcons();
            assignPlanPanelButtonEvents();
        } else {
            planPanelContent.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 un Plan de Marketing guardado. ¡Genera uno para empezar!
                    </p>
                </div>
            `;
            lucide.createIcons();
        }
    }

    // Maneja el evento del botón Eliminar en el panel
    function assignPlanPanelButtonEvents() {
        const btnEliminar = document.getElementById('panel-plan-btn-eliminar');
        if (btnEliminar) {
            btnEliminar.addEventListener('click', () => {
                openModal({
                    title: 'CONFIRMAR ELIMINACIÓN',
                    message: '¿Estás seguro de que quieres eliminar tu Plan de Marketing? <br> Esta acción no se puede deshacer.',
                    icon: 'alert-triangle',
                    confirmText: 'SÍ, ELIMINAR',
                    confirmClass: 'danger',
                    onConfirm: async () => {
                        await deletePlanFromDB();
                        drawPlanPanelContent(planGuardadoActual); 
                    }
                });
            });
        }
    }
    
    // --- LÓGICA CRUD ---
    const planEndpoints = {
        create: 'api-db/ia-marketing-goal-planner-create.php',
        update: 'api-db/ia-marketing-goal-planner-update.php',
        delete: 'api-db/ia-marketing-goal-planner-delete.php'
    };
    
    async function createPlanInDB(planData) {
        setProcessingState(true, 'Guardando...');
        try {
            const response = await fetch(planEndpoints.create, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(planData)
            });
            const result = await response.json();
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast('Plan de Marketing guardado con éxito.', 'success');
                planGuardadoActual = planData; // Actualiza la variable global
                openPlanPanel();
            } else {
                // Maneja el caso de conflicto (ya existe) para la lógica de sobrescribir
                if (response.status === 409) {
                    throw new Error('A marketing plan already exists'); 
                }
                throw new Error(result.message || 'Error desconocido al crear el Plan');
            }
        } catch (error) {
            throw error; // Propagar para manejo de sobrescritura
        } finally {
            setProcessingState(false);
        }
    }

    async function updatePlanInDB(planData) {
        setProcessingState(true, 'Actualizando...');
        try {
            const response = await fetch(planEndpoints.update, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(planData)
            });
            const result = await response.json();
            if (response.ok && result.success) {
                // Mensaje de éxito corto y en español.
                if (typeof showToast === 'function') showToast('Plan de Marketing actualizado con éxito.', 'success');
                planGuardadoActual = planData;
            } else {
                throw new Error(result.message || 'Error desconocido al actualizar el Plan');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al actualizar el Plan: ${error.message}`, 'error');
        } finally {
            setProcessingState(false);
        }
    }

    async function deletePlanFromDB() {
        setProcessingState(true, 'Eliminando...');
        try {
            const response = await fetch(planEndpoints.delete, {
                method: 'POST', 
                headers: { 'Content-Type': 'application/json' }
            });
            const result = await response.json();
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast('Plan de Marketing eliminado con éxito.', 'success');
                planGuardadoActual = null; // Limpia la variable global
            } else {
                throw new Error(result.message || 'Error desconocido al eliminar el Plan');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al eliminar el Plan: ${error.message}`, 'error');
        } finally {
            setProcessingState(false);
        }
    }

    // --- Lógica del Generador y Botón Guardar ---
    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');
            resultContainer.innerHTML = '';
            resultContainer.classList.remove('show');
            
            if (customMessage) {
                btnText.textContent = customMessage;
                if (window.loadingInterval) clearInterval(window.loadingInterval);
                window.loadingInterval = null;
                return;
            }

            const messages = ["Contactando Con OrozCO IA...", "Analizando tus objetivos...", "Calculando viabilidad...", "Generando plan estratégico...", "Casi Está Listo..."];
            let messageIndex = 0;
            btnText.textContent = messages[messageIndex];

            if (window.loadingInterval) clearInterval(window.loadingInterval); // Limpiar cualquier intervalo anterior
            window.loadingInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % messages.length;
                btnText.textContent = messages[messageIndex];
            }, 2500);

        } else {
            if (window.loadingInterval) clearInterval(window.loadingInterval);
            window.loadingInterval = null;
            loaderContainer.classList.add('hidden');
            generateBtn.disabled = false;
            generateBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            btnText.textContent = 'GENERAR CON IA MARKETING';
        }
    }

    // La función de formateo se mantiene para renderizar el JSON de la IA
    function formatPlanResult(data) {
        const formatText = (text) => (text || '').replace(/\*\*(.*?)\*\*/g, '<strong class="text-[var(--color-primary)]">$1</strong>');
        const plan = data.plan_de_accion || {};

        return `
            <div class="ai-response p-6 md:p-8 rounded-xl shadow-md space-y-8">
                <div class="text-center">
                    <h2 class="text-3xl font-black uppercase text-brand-dark mb-2">Tu Reporte Estratégico Publicitario</h2>
                </div>

                <div class="bg-gray-50 p-6 rounded-xl shadow-sm border border-gray-200">
                    <h3 class="text-2xl font-bold text-gray-800 mb-3 flex items-center"><i data-lucide="crosshair" class="mr-3 text-[var(--color-secondary)]"></i>Análisis De Tu Situación y Metas</h3>
                    <p class="text-lg text-gray-700 leading-relaxed">${formatText(data.analisis_objetivos)}</p>
                </div>

                <div class="bg-gray-50 p-6 rounded-xl shadow-sm border border-gray-200">
                    <h3 class="text-2xl font-bold text-gray-800 mb-3 flex items-center"><i data-lucide="calculator" class="mr-3 text-[var(--color-secondary)]"></i>Análisis De Viabilidad Financiera</h3>
                    <p class="text-lg text-gray-700 leading-relaxed">${formatText(data.analisis_viabilidad)}</p>
                </div>
                
                <div class="bg-white p-6 rounded-xl shadow-md border border-[var(--color-primary)]">
                    <h3 class="text-2xl font-extrabold text-[var(--color-primary)] mb-6 text-center"><i data-lucide="rocket" class="inline-block mr-3 text-[var(--color-secondary)]"></i>Tu Plan De Acción Personalizado</h3>
                    <div class="space-y-6">
                        <div class="plan-step-item border-[var(--color-secondary)]">
                            <div class="ml-4 flex-1">
                                <h4 class="text-xl font-bold text-gray-800 mb-2 flex items-center"><i data-lucide="flag-checkered" class="mr-2"></i>Primer Paso Inmediato</h4>
                                <p class="text-lg text-gray-700 leading-relaxed">${formatText(plan.primer_paso)}</p>
                            </div>
                        </div>
                        <div class="plan-step-item border-blue-500">
                            <div class="ml-4 flex-1">
                                <h4 class="text-xl font-bold text-gray-800 mb-2 flex items-center"><i data-lucide="calendar-check" class="mr-2"></i>Enfoque a Corto Plazo (Esta Semana)</h4>
                                <p class="text-lg text-gray-700 leading-relaxed">${formatText(plan.corto_plazo)}</p>
                            </div>
                        </div>
                        <div class="plan-step-item border-green-500">
                             <div class="ml-4 flex-1">
                                <h4 class="text-xl font-bold text-gray-800 mb-2 flex items-center"><i data-lucide="calendar" class="mr-2"></i>Enfoque a Mediano Plazo (Este Mes)</h4>
                                <p class="text-lg text-gray-700 leading-relaxed">${formatText(plan.mediano_plazo)}</p>
                            </div>
                        </div>
                        <div class="plan-step-item border-purple-500">
                            <div class="ml-4 flex-1">
                                <h4 class="text-xl font-bold text-gray-800 mb-2 flex items-center"><i data-lucide="calendar-clock" class="mr-2"></i>Enfoque a Largo Plazo (3 Meses)</h4>
                                <p class="text-lg text-gray-700 leading-relaxed">${formatText(plan.largo_plazo)}</p>
                            </div>
                        </div>
                    </div>
                </div>

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

                <div class="pt-6 border-t border-gray-200">
                    <h3 class="text-2xl font-bold text-gray-800 mb-3 flex items-center"><i data-lucide="wrench" class="mr-3 text-[var(--color-secondary)]"></i>Recomendaciones para Optimización</h3>
                    <p class="text-lg text-gray-700 leading-relaxed">${formatText(data.recomendaciones_optimizacion)}</p>
                </div>
            </div>
        `;
    }

    // --- FUNCIÓN DE VISUALIZACIÓN ---
    function displayResult(data, showSaveButton = false) {
        let html = formatPlanResult(data);
        
        if (showSaveButton) {
            html += `
            <div id="action-buttons-container" class="mt-4 text-center">
                <button id="save-plan-btn" class="btn-copy bg-[var(--color-primary)] text-white font-bold py-3 px-6 rounded-lg flex items-center justify-center mx-auto mt-4 gap-2 hover:scale-105 transition-transform uppercase">
                    <i data-lucide="save"></i> <span>Guardar Plan de Marketing</span>
                </button>
            </div>`;
        }
        
        resultContainer.innerHTML = html;
        lucide.createIcons();
        setTimeout(() => { 
            resultContainer.classList.add('show');
            resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 100);

        // Asignar evento al botón de "Guardar Plan" (si existe)
        if (showSaveButton) {
            document.getElementById('save-plan-btn').addEventListener('click', handleSavePlan);
        }
    }
    
    // --- LÓGICA DE GUARDADO ---
    function handleSavePlan() {
        if (!planGeneradoReciente) {
            if (typeof showToast === 'function') showToast("No hay un plan reciente para guardar.", "error");
            return;
        }

        const saveAction = async () => {
            try {
                await createPlanInDB(planGeneradoReciente);
            } catch (error) {
                if (error.message.includes('A marketing plan already exists')) {
                    // Si ya existe (409), pedir confirmación para sobrescribir
                    openModal({
                        title: 'CONFIRMAR SOBRESCRIBIR',
                        message: 'Ya tienes un Plan de Marketing guardado. ¿Deseas reemplazarlo con la versión actual?',
                        icon: 'refresh-cw',
                        confirmText: 'SÍ, REEMPLAZAR',
                        confirmClass: 'danger',
                        onConfirm: async () => {
                            await updatePlanInDB(planGeneradoReciente);
                            openPlanPanel();
                        }
                    });
                } else {
                    if (typeof showToast === 'function') showToast(`Error al guardar: ${error.message}`, "error");
                }
            }
        };
        saveAction();
    }
});
</script>
<script src="files/toast.js"></script>
</body>
</html>