<?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>Asistente De Análisis De Mercado Local 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>
</head>
<body data-page-title="Asistente Analista De Mercado Local"
      data-page-subtitle="Investiga Tu Entorno Para Entender Tus Oportunidades De Crecimiento"
      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="local-market-analyzer" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
                    <div class="lg:col-span-3">
                        <form id="market-analyzer-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">
                                        <span class="step-number text-[var(--color-primary)] flex items-center"> 
                                            <i data-lucide="map-pin" class="mr-3 w-6 h-6 text-[var(--color-secondary)]"></i> PASO 1:
                                        </span>
                                        <span class="step-title ml-2">Describe Tu Negocio y Mercado</span>
                                    </h2>
                                    <p class="step-subtitle uppercase text-gray-500 font-bold mt-2 ml-1">Ingresa la información para un análisis personalizado</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 class="form-question flex flex-col">
                                            <label for="company_name" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Nombre De Tu Negocio:</label>
                                            <input type="text" id="company_name" name="company_name" placeholder="Ej: Jardines Verdes" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]" value="<?php echo htmlspecialchars($business_name); ?>" required>
                                        </div>
                                        <div class="form-question flex flex-col">
                                            <label for="service_type" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tipo De Servicio:</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-1 focus:ring-[var(--color-highlight)]" required>
                                        </div>
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label for="location" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Ubicación Principal (Ciudad y Estado):</label>
                                        <input type="text" id="location" name="location" placeholder="Ej: San Francisco, CA" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]" <?php if (!empty($operating_cities)) { echo 'value="' . htmlspecialchars($operating_cities) . '"'; } ?> required>
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label for="target_audience" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Público Objetivo Principal:</label>
                                        <input type="text" id="target_audience" name="target_audience" placeholder="Ej: Dueños De Casas Con Jardín" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label for="price_range" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Rango De Precios (Opcional):</label>
                                        <select id="price_range" name="price_range" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                            <option value="">Selecciona Una Opción</option>
                                            <option value="bajo">Bajo (Económico)</option>
                                            <option value="medio">Medio (Competitivo)</option>
                                            <option value="alto">Alto (Premium)</option>
                                        </select>
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label for="additional_details" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Detalles Adicionales (Opcional):</label>
                                        <textarea id="additional_details" name="additional_details" rows="3" placeholder="Ej: Nos Especializamos En Diseño De Jardines Sostenibles" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]"></textarea>
                                    </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 object-contain h-24 max-w-[250px]">
                            </div>
                        <?php endif; ?>
                        
                        <button id="open-analysis-panel-btn" class="btn btn-primary w-full py-4 px-6 rounded-lg font-black text-lg uppercase gap-2 hover:scale-102 transition-transform shadow-lg">
                            <i data-lucide="save" class="w-5 h-5"></i> <span>Tu Análisis De Mercado</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 pb-[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 w-6 h-6 text-[var(--color-highlight)]"></i>
                                    <span class="step-title">INSTRUCCIONES IMPORTANTES</span>
                                </h2>
                                <p class="step-subtitle text-center md:text-left uppercase text-gray-500 font-bold mt-2 ml-1">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="flex items-start gap-3"><span class="bg-[var(--color-highlight)] p-1 rounded text-[var(--color-primary)]"><i data-lucide="map-pin" class="w-4 h-4"></i></span><div><strong class="text-[var(--color-primary)] font-black uppercase">TU ANÁLISIS ES LOCAL:</strong> La herramienta de IA Marketing funciona mejor con información precisa. Asegúrate de incluir la ciudad y estado de tu negocio.</div></li>
                                <li class="flex items-start gap-3"><span class="bg-[var(--color-highlight)] p-1 rounded text-[var(--color-primary)]"><i data-lucide="building" class="w-4 h-4"></i></span><div><strong class="text-[var(--color-primary)] font-black uppercase">IDENTIFICA TU NEGOCIO:</strong> Describe tu tipo de servicio o producto de forma clara. Así, el análisis de mercado y competencia será más preciso.</div></li>
                                <li class="flex items-start gap-3"><span class="bg-[var(--color-highlight)] p-1 rounded text-[var(--color-primary)]"><i data-lucide="users-round" class="w-4 h-4"></i></span><div><strong class="text-[var(--color-primary)] font-black uppercase">CONOCE A TU CLIENTE:</strong> Indicar tu público objetivo ayuda a la IA a sugerir estrategias que realmente conecten con las personas que quieres atraer.</div></li>
                                <li class="flex items-start gap-3"><span class="bg-[var(--color-highlight)] p-1 rounded text-[var(--color-primary)]"><i data-lucide="lightbulb" class="w-4 h-4"></i></span><div><strong class="text-[var(--color-primary)] font-black uppercase">DESCRIBE TU VALOR ÚNICO:</strong> En "Detalles adicionales", menciona lo que te diferencia. Esto permitirá a la IA destacar tus ventajas competitivas.</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">
                                <span class="step-number text-[var(--color-primary)] flex items-center"> 
                                    <i data-lucide="brain" class="mr-3 w-6 h-6 text-[var(--color-secondary)]"></i> PASO 2:
                                </span>
                                <span class="step-title ml-2"> OBTÉN TU REPORTE De Tu MERCADO Local</span>
                            </h2>
                            <p class="step-subtitle uppercase text-gray-500 font-bold mt-2 ml-1">Recibe un análisis de tu mercado y un plan de acción listo para implementar</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 shadow-lg">
                                <i data-lucide="brain" class="w-24 h-24 md:w-32 md:h-32 text-white animate-pulse"></i>
                                <p class="mt-4 text-white font-black text-xl uppercase tracking-wide">
                                    IA<span class="text-[var(--color-highlight)]">Marketing</span>™
                                </p>
                            </div>

                            <div class="md:col-span-2 text-center md:text-left">
                                <h3 class="text-2xl font-black text-gray-800 flex items-center justify-center md:justify-start mb-2 uppercase">
                                    <i data-lucide="bell-electric" class="w-6 h-6 text-[var(--color-secondary)] mr-2 flex-shrink-0"></i>
                                    Información Importante
                                </h3>
                                
                                <p class="text-lg text-gray-700 mb-6">
                                    Para que la investigación del mercado local sea útil, <b>es importante</b> que especifiques la ubicación donde opera tu negocio y el tipo de servicio que ofreces. Usando los datos que brindes, nuestra <b>inteligencia artificial</b> generará un <b>Análisis De Mercado Local</b>, para que comprendas tu mercado y entiendas tus oportunidades de crecimiento.
                                </p>
                                
                                <div class="flex justify-center md:justify-start">
                                    <button id="generateBtn" type="submit" form="market-analyzer-form" class="btn btn-primary w-full sm:w-auto py-4 px-6 rounded-lg text-lg flex items-center justify-center uppercase shadow-xl hover:scale-105 transition-transform">
                                        <i data-lucide="arrow-big-right-dash" class="w-6 h-6"></i>
                                        <span id="btn-text">GENERAR ANÁLISIS DE MERCADO 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 opacity-0 transition-opacity duration-500"></div>
                </div>
            </section>
        </div>
    </main>
</div>

<div id="analysis-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 hidden" aria-hidden="true"></div>

<div id="analysis-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>
            ANÁLISIS DE MERCADO
        </h3>
        <button id="close-analysis-panel-btn" class="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="analysis-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 análisis...</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-analysis-panel-btn').click()" class="w-full btn btn-secondary 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-90 flex items-center justify-center hidden z-[100]"
     onclick="if(event.target === this) closeModal()">
    
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center">
        
        <div class="modal-header-container rounded-t-xl pt-6">
            <h3 id="modal-title" class="text-4xl font-black uppercase text-[var(--color-highlight)] leading-none">CONFIRMAR</h3>
        </div>

        <div class="p-8">
            <div class="flex justify-center mb-6">
                <i id="modal-icon" data-lucide="alert-triangle" class="w-16 h-16 text-[var(--color-secondary)]"></i>
            </div>
            
            <p id="modal-message" class="text-[var(--color-primary)] mb-6 uppercase text-lg font-bold leading-tight">
                ¿ESTÁS SEGURO DE ESTA ACCIÓN?
            </p>

            <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm:space-x-4 mt-8">
                <button type="button" class="btn btn-secondary font-black py-2.5 px-4 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2" id="modal-cancel-btn">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                </button>
                
                <button type="button" class="btn btn-primary font-black py-2.5 px-4 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-md transition-all duration-200" id="modal-confirm-btn">
                    CONFIRMAR
                </button>
            </div>
        </div>
    </div>
</div>

<script type="module">
// --- VARIABLES GENERALES Y LÓGICA DE CARGA ---
document.addEventListener('DOMContentLoaded', () => {
    lucide.createIcons();
    
    // Elementos del menú y la cabecera
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');

    // Elementos del reproductor de video
    const playOverlay = document.getElementById('playOverlay');
    const videoPlayer = document.getElementById('videoPlayer');

    // Elemento del formulario y el asistente
    const phoneInput = document.getElementById('contact_phone');
    const form = document.getElementById('market-analyzer-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 ---
    let analysisGuardadoActual = <?php echo json_encode($current_market_analysis ?? null); ?>;
    let analysisGeneradoReciente = null;

    // --- PANEL LATERAL ---
    const openAnalysisPanelBtn = document.getElementById('open-analysis-panel-btn');
    const closeAnalysisPanelBtn = document.getElementById('close-analysis-panel-btn');
    const analysisPanelOverlay = document.getElementById('analysis-panel-overlay');
    const analysisPanel = document.getElementById('analysis-panel');
    const analysisPanelContent = document.getElementById('analysis-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;
    
    // Mensajes de carga de la IA
    const messages = ["Analizando tu ubicación...", "Evaluando competidores...", "Identificando oportunidades...", "Creando tu plan estratégico...", "¡Casi listo!"];
    let loadingInterval = null;

    // --- MANEJO DEL MENÚ MÓVIL ---
    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');
    });
    
    // --- MANEJO DEL REPRODUCTOR DE VIDEO ---
    if (playOverlay && videoPlayer) {
        videoPlayer.controls = false;
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.controls = true;
            videoPlayer.play().catch(e => {
                if (typeof showToast === 'function') {
                    showToast("Error al reproducir video: " + e.message, 'error');
                }
            });
        });
        videoPlayer.addEventListener('ended', () => {
            playOverlay.style.display = 'flex';
            videoPlayer.controls = false;
        });
    }
    
    // --- MÁSCARA DE INPUTS ---
    if (phoneInput) {
        IMask(phoneInput, { mask: '(000) 000-0000' });
    }
    
    // --- GESTIÓN DE NOTIFICACIONES TOAST (CÓDIGO PROPIO) ---
    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);
    }
    
    // --- 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';
        
        modalConfirmBtn.className = 'btn font-black py-2.5 px-4 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-md transition-all duration-200';
        
        if (confirmClass === 'danger') {
            modalConfirmBtn.classList.add('btn-primary'); 
        } else if (confirmClass === 'primary') {
             modalConfirmBtn.classList.add('btn-secondary');
        } else {
             modalConfirmBtn.classList.add('btn-primary');
        }
        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 openAnalysisPanel() {
        analysisPanel.classList.remove('translate-x-full');
        analysisPanelOverlay.classList.remove('hidden');
        drawAnalysisPanelContent(analysisGuardadoActual); 
    }

    function closeAnalysisPanel() {
        analysisPanel.classList.add('translate-x-full');
        analysisPanelOverlay.classList.add('hidden');
    }

    if(openAnalysisPanelBtn) openAnalysisPanelBtn.addEventListener('click', openAnalysisPanel);
    if(closeAnalysisPanelBtn) closeAnalysisPanelBtn.addEventListener('click', closeAnalysisPanel);
    if(analysisPanelOverlay) analysisPanelOverlay.addEventListener('click', closeAnalysisPanel);

    function drawAnalysisPanelContent(analysisData) {
        if (analysisData && analysisData.analisis_mercado) {
            const formattedHtml = formatAnalysisResult(analysisData); 
            analysisPanelContent.innerHTML = `
                <div class="space-y-3">
                    <div class="flex justify-end space-x-2 mb-4 pr-6">
                        <button id="panel-analysis-btn-eliminar" class="btn btn-primary text-white text-xs py-2 px-3">
                            <i data-lucide="trash-2" class="w-4 h-4"></i> ELIMINAR
                        </button>
                    </div>
                    <div id="analysis-display-container" class="space-y-8">
                        ${formattedHtml}
                    </div>
                </div>
            `;
            lucide.createIcons();
            assignAnalysisPanelButtonEvents();
        } else {
            analysisPanelContent.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 Análisis de Mercado guardado. ¡Genera uno para empezar!
                    </p>
                </div>
            `;
            lucide.createIcons();
        }
    }

    function assignAnalysisPanelButtonEvents() {
        const btnEliminar = document.getElementById('panel-analysis-btn-eliminar');
        if (btnEliminar) {
            btnEliminar.addEventListener('click', () => {
                openModal({
                    title: 'CONFIRMAR ELIMINACIÓN',
                    message: '¿Estás seguro de que quieres eliminar tu Análisis de Mercado? <br> Esta acción no se puede deshacer.',
                    icon: 'alert-triangle',
                    confirmText: 'SÍ, ELIMINAR',
                    confirmClass: 'danger',
                    onConfirm: async () => {
                        await deleteAnalysisFromDB();
                        drawAnalysisPanelContent(analysisGuardadoActual);
                    }
                });
            });
        }
    }
    
    // --- LÓGICA CRUD (NUEVA) ---
    const analysisEndpoints = {
        create: 'api-db/ia-local-market-analsyis-create.php',
        update: 'api-db/ia-local-market-analsyis-update.php',
        delete: 'api-db/ia-local-market-analsyis-delete.php'
    };
    
    async function createAnalysisInDB(analysisData) {
        setProcessingState(true, 'Guardando...');
        try {
            const response = await fetch(analysisEndpoints.create, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(analysisData)
            });
            const result = await response.json();
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast(result.message, 'success');
                analysisGuardadoActual = analysisData;
                openAnalysisPanel();
            } else {
                if (response.status === 409) {
                    throw new Error('An analysis already exists'); 
                }
                throw new Error(result.message || 'Error desconocido al crear Análisis');
            }
        } catch (error) {
            throw error;
        } finally {
            setProcessingState(false);
        }
    }

    async function updateAnalysisInDB(analysisData) {
        setProcessingState(true, 'Actualizando...');
        try {
            const response = await fetch(analysisEndpoints.update, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(analysisData)
            });
            const result = await response.json();
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast(result.message, 'success');
                analysisGuardadoActual = analysisData;
            } else {
                throw new Error(result.message || 'Error desconocido al actualizar Análisis');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al actualizar Análisis: ${error.message}`, 'error');
        } finally {
            setProcessingState(false);
        }
    }

    async function deleteAnalysisFromDB() {
        setProcessingState(true, 'Eliminando...');
        try {
            const response = await fetch(analysisEndpoints.delete, {
                method: 'POST', 
                headers: { 'Content-Type': 'application/json' }
            });
            const result = await response.json();
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast(result.message, 'success');
                analysisGuardadoActual = null;
            } else {
                throw new Error(result.message || 'Error desconocido al eliminar Análisis');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al eliminar Análisis: ${error.message}`, 'error');
        } finally {
            setProcessingState(false);
        }
    }

    // Función para formatear los resultados (JS con Clases Tailwind)
    const formatAnalysisResult = (data) => {
        const formatText = (text) => (text || '').replace(/\*\*(.*?)\*\*/g, '<strong class="text-gray-900">$1</strong>');

        return `
            <div class="space-y-8">
                <div class="bg-slate-50 p-6 rounded-xl shadow-sm border border-gray-200 hover:shadow-md transition-all duration-300">
                    <h3 class="text-2xl font-black uppercase flex items-center mb-3 text-gray-800"><i data-lucide="bar-chart-2" class="w-6 h-6 mr-3 text-[var(--color-secondary)]"></i>Análisis del Mercado Local</h3>
                    <p class="text-base leading-relaxed text-gray-600">${formatText(data.analisis_mercado)}</p>
                </div>
                <div class="bg-slate-50 p-6 rounded-xl shadow-sm border border-gray-200 hover:shadow-md transition-all duration-300">
                    <h3 class="text-2xl font-black uppercase flex items-center mb-3 text-gray-800"><i data-lucide="users-round" class="w-6 h-6 mr-3 text-[var(--color-secondary)]"></i>Análisis de la Competencia</h3>
                    <p class="text-base leading-relaxed text-gray-600">${formatText(data.analisis_competencia)}</p>
                </div>
                <div class="bg-white p-6 rounded-xl shadow-md border-2 border-[var(--color-primary)]">
                    <h3 class="text-3xl font-black uppercase text-center mb-6 flex items-center justify-center text-gray-800"><i data-lucide="rocket" class="w-8 h-8 mr-3 text-[var(--color-secondary)]"></i>Plan Estratégico Sugerido</h3>
                    <ul class="space-y-4">
                        ${data.plan_estrategico.map((step, index) => `
                            <li class="flex items-start gap-4">
                                <span class="w-8 h-8 flex items-center justify-center rounded-full bg-[var(--color-secondary)] text-white font-bold shrink-0 mt-1">${index + 1}</span>
                                <p class="text-base leading-relaxed text-gray-700 flex-1">${formatText(step)}</p>
                            </li>
                        `).join('')}
                    </ul>
                </div>
            </div>
        `;
    };

    // Función para mostrar los resultados de la IA en el DOM
    const displayResult = (data, showSaveButton = false) => {
        let html = formatAnalysisResult(data);
        
        if (showSaveButton) {
            html += `
            <div id="action-buttons-container" class="mt-4 text-center">
                <button id="save-analysis-btn" class="btn btn-primary 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 Análisis</span>
                </button>
            </div>`;
        }
        
        resultContainer.innerHTML = html;
        lucide.createIcons();
        setTimeout(() => { 
            resultContainer.style.opacity = '1'; 
            resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 100);
        
        if (showSaveButton) {
            document.getElementById('save-analysis-btn').addEventListener('click', handleSaveAnalysis);
        }
    };
    
    // --- LÓGICA DE GUARDADO ---
    function handleSaveAnalysis() {
        if (!analysisGeneradoReciente) {
            if (typeof showToast === 'function') showToast("No hay un análisis reciente para guardar.", "error");
            return;
        }

        const saveAction = async () => {
            try {
                await createAnalysisInDB(analysisGeneradoReciente);
            } catch (error) {
                if (error.message.includes('An analysis already exists')) {
                    openModal({
                        title: 'CONFIRMAR SOBRESCRIBIR',
                        message: 'Ya tienes un Análisis de Mercado guardado. ¿Deseas reemplazarlo con la versión actual?',
                        icon: 'refresh-cw',
                        confirmText: 'SÍ, REEMPLAZAR',
                        confirmClass: 'danger',
                        onConfirm: () => {
                            updateAnalysisInDB(analysisGeneradoReciente);
                            openAnalysisPanel();
                        }
                    });
                } else {
                    if (typeof showToast === 'function') showToast(`Error al guardar: ${error.message}`, "error");
                }
            }
        };
        saveAction();
    }

    // --- LÓGICA DEL ASISTENTE DE IA ---
    const setProcessingState = (isProcessing, customMessage = null) => {
        loaderContainer.classList.toggle('hidden', !isProcessing);
        generateBtn.disabled = isProcessing;
        generateBtn.classList.toggle('opacity-50', isProcessing);
        generateBtn.classList.toggle('cursor-not-allowed', 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>';
            resultContainer.innerHTML = '';
            resultContainer.style.opacity = '0';
            
            if (customMessage) {
                btnText.textContent = customMessage;
                if(loadingInterval) clearInterval(loadingInterval);
                loadingInterval = null;
                return;
            }
            
            let messageIndex = 0;
            btnText.textContent = messages[messageIndex];
            
            loadingInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % messages.length;
                btnText.textContent = messages[messageIndex];
            }, 2500);
        } else {
            if (loadingInterval) clearInterval(loadingInterval);
            loadingInterval = null;
            btnText.textContent = 'GENERAR CON IA MARKETING';
        }
    };

    // Manejador del evento 'submit' del formulario
    form.addEventListener('submit', async (event) => {
        event.preventDefault();
        
        const requiredFields = ['company_name', 'service_type', 'location'];
        let allFieldsValid = true;
        requiredFields.forEach(id => {
            const input = document.getElementById(id);
            if (!input) return;
            const isValid = input.value.trim() !== '';
            input.classList.toggle('border-[var(--color-secondary)]', !isValid);
            if (!isValid) allFieldsValid = false;
        });

        if (!allFieldsValid) {
            if (typeof showToast === 'function') showToast('Por favor, completa todos los campos obligatorios.', 'warning');
            return;
        }

        setProcessingState(true);

        const formData = {
            company_name: document.getElementById('company_name').value,
            service_type: document.getElementById('service_type').value,
            location: document.getElementById('location').value,
            target_audience: document.getElementById('target_audience').value,
            price_range: document.getElementById('price_range').value,
            additional_details: document.getElementById('additional_details').value,
            value_proposition: form.querySelector('input[name="value_proposition"]').value
        };

        try {
            const response = await fetch('api/api-local-market-analsyis.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });
            
            const data = await response.json(); 

            if (!response.ok) {
                let errorMsg = data.error || `Error del servidor: ${response.status}.`;
                if(data.api_response_body && data.api_response_body.error) {
                    errorMsg = `Error de Google API: ${data.api_response_body.error.message}`;
                } else if (data.curl_error) {
                    errorMsg = `Error de cURL: ${data.curl_error}`;
                }
                throw new Error(errorMsg);
            }

            analysisGeneradoReciente = data; 
            displayResult(data, true);
            if (typeof showToast === 'function') showToast('¡Análisis de mercado generado con éxito!', 'success');

        } catch (error) {
            let errorMessage = error.message || 'Hubo un problema al generar tu análisis. Por favor, intenta de nuevo.';
            
            resultContainer.innerHTML = `<div class="bg-[var(--color-secondary)] text-center p-4 text-white rounded-lg border border-[var(--color-secondary)]"><p><strong>Error:</strong> ${errorMessage}</p></div>`;
            resultContainer.style.opacity = '1';
            if (typeof showToast === 'function') showToast(errorMessage, 'error');
        } finally {
            setProcessingState(false);
        }
    });
});
</script>
<script src="files/toast.js"></script>
</body>
</html>