<?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';

$db_error_message = null;

// =================================================================
//        BLOQUE DE DATOS SEGURO
// =================================================================

// Sanitización de salida (XSS Mitigation)
$company_name_from_db = $client_info['business_name'] ?? 'Nombre de la Empresa';
$contact_phone_from_db = $client_info['phone'] ?? '';
$website_url_from_db = $client_info['website'] ?? '';
$logo_url = $client_info['logo_url'] ?? '';

// LOGICA DE LIMPIEZA PROFUNDA AJUSTADA
$raw_db_value = $ia_results['value_proposition'] ?? '';
$allowed_tags = '<p><br><strong><b><em><i><u><ul><ol><li><h1><h2><h3><blockquote><span>';
$value_proposition_clean = trim(strip_tags(html_entity_decode($raw_db_value), $allowed_tags));

$social_links = $client_info['social_links'] ?? [];

// Obtener datos del video dinámicamente
$video_data = get_ia_video_by_id('ia-marketing');

// =================================================================

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, maximum-scale=1.0, user-scalable=no">
    <title>Dashboard Herramientas De <?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="Dashboard De IA Marketing ToolKit" 
      data-page-subtitle="Bienvenidos IA Marketing Center de herramienta potencializadas con IA" 
      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>
        
        <?php include 'ia-menu.php'; ?>
        
        <main class="flex-1 overflow-y-auto w-full">
            <header class="bg-white shadow-sm p-4 flex flex-wrap md:flex-nowrap justify-between items-center sticky top-0 z-20 gap-4">
              <div class="flex items-center gap-2">
                  <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800 p-2">
                    <i data-lucide="menu" class="w-8 h-8"></i>
                  </button>

                  <div class="page-header-container hidden md:block">
                    <h2 id="page-title"></h2>
                    <p id="page-subtitle"></p>
                  </div>
              </div>
              
              <div class="show-widget-container hidden w-full md:w-auto">
                <button class="show-widget-btn w-full md:w-auto inline-flex items-center justify-center gap-3 text-base font-bold text-white bg-[var(--color-primary)] rounded-lg shadow-lg shadow-[var(--color-primary)]/20 py-3 px-6 transform hover:-translate-y-1 hover:shadow-xl transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--color-secondary)] min-h-[44px]"
                    data-widget-id="ia-marketing-intro-video">
                    <i data-lucide="eye" class="w-5 h-5"></i>
                    <span>VER VIDEO PRESENTACIÓN</span>
                </button>
            </div>

            </header>

            <div id="content-area" class="md:p-8 space-y-6 md:space-y-8">
                                      
                <section id="ia-marketing-intro-video" class="video-widget">
                    <div class="relative overflow-hidden rounded-2xl md:rounded-3xl ">
                        <div class="absolute -top-24 -left-16 h-72 w-72 rounded-full blur-3xl opacity-30 bg-[var(--color-secondary)]"></div>
                        <div class="absolute -bottom-24 -right-16 h-72 w-72 rounded-full blur-3xl opacity-30 bg-[#ffc857]"></div>
                        <div class="relative p-4 md:p-10">
                            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 items-center">
                                <div class="text-white">
                                    <div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/10 ring-1 ring-white/15 mb-4">
                                        <i data-lucide="brain-circuit" class="w-4 h-4"></i>
                                        <span class="text-xs tracking-wide">Tu Centro De Herramientas Con IA</span>
                                    </div>
                                    <h1 class="text-3xl md:text-4xl lg:text-5xl font-black leading-tight flex items-center gap-3 flex-wrap">
                                        <i data-lucide="brain" class="w-9 h-9 text-[var(--color-highlight)]"></i>
                                        <span>IA <span class="text-[var(--color-highlight)]">Marketing</span> Center</span>
                                    </h1>
                                    <p class="mt-3 md:mt-4 text-sm md:text-lg text-white/90">
                                        <strong>Bienvenidos IA Marketing Center</strong>, el centro de herramienta potencializadas con IA.
                                        Aquí estarán varias herramientas y este es como el dashboard de herramientas.
                                    </p>
                                    <div class="mt-6 grid grid-cols-1 sm:grid-cols-2 gap-3">
                                        <div class="rounded-xl bg-white/10 ring-1 ring-white/15 p-4">
                                            <div class="flex items-center gap-2">
                                                <i data-lucide="circle-fading-plus" class="w-5 h-5 text-[var(--color-highlight)]"></i>
                                                <p class="text-sm font-black uppercase">Contenidos & Anuncios</p>
                                            </div>
                                            <p class="text-xs text-white/80 mt-1">Ideas, copies y creatividades asistidas.</p>
                                        </div>
                                        <div class="rounded-xl bg-white/10 ring-1 ring-white/15 p-4">
                                            <div class="flex items-center gap-2">
                                                <i data-lucide="handshake" class="w-5 h-5 text-[var(--color-highlight)]"></i>
                                                <p class="text-sm font-black uppercase">Ventas & Seguimiento</p>
                                            </div>
                                            <p class="text-xs text-white/80 mt-1">Mensajes y propuestas que convierten.</p>
                                        </div>
                                    </div>
                                </div>
<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" preload="none" poster="<?= htmlspecialchars($video_data['poster_url']) ?>">
                <source src="<?= htmlspecialchars($video_data['video_url']) ?>" 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="<?= htmlspecialchars($video_data['poster_url']) ?>" alt="VideoLeccion - FlowCRM" class="absolute inset-0 w-full h-full object-cover">
                <div class="absolute inset-0 w-full h-full bg-black/70 transition-colors group-hover:bg-black/30"></div>
                <i data-lucide="play" class="relative w-16 h-16 text-white opacity-90 group-hover:opacity-100 transition-opacity"></i>
            </div>
        </div>
<div class="p-4 text-white/90 text-sm flex flex-col md:flex-row md:items-center justify-between gap-3">
    <span class="inline-flex items-center gap-2 truncate w-full md:w-auto">
        <i data-lucide="play-circle" class="w-4 h-4 text-[var(--color-highlight)] flex-shrink-0"></i>
        <b class="truncate">VIDEO:</b> <span class="truncate"><?= htmlspecialchars($video_data['title'] ?? 'Presentación') ?></span>
    </span>

    <button class="hide-widget-btn inline-flex items-center gap-2 text-xs font-black text-[var(--color-highlight)] hover:text-[var(--color-highlight)] transition-colors py-2 md:py-1 px-2 rounded-md justify-center md:justify-end w-full md:w-auto bg-white/10 md:bg-transparent min-h-[44px] md:min-h-0"
        data-widget-id="ia-marketing-intro-video"
        title="Ocultar Video">
        OCULTAR VIDEO
        <i data-lucide="square-x" class="w-4 h-4"></i>
    </button>
</div>
    </div>
</div>

                            </div>
                        </div>
                    </div>
                </section>
                                    
                <div class="bg-slate-900 p-4 md:p-6 rounded-xl shadow-lg flex flex-col lg:flex-row justify-between items-center gap-6 mt-6">
                    <div class="text-center lg:text-left">
                        <h3 class="text-2xl md:text-4xl font-black text-white uppercase flex flex-col md:flex-row items-center gap-2 justify-center lg:justify-start">
                            <i data-lucide="brain-cog" class="w-8 h-8 md:w-6 md:h-6 text-[var(--color-highlight)] mb-1 md:mb-0"></i>
                            <span>Tu Propuesta De Valor (UVP)</span>
                        </h3>
                        <p class="text-white text-sm md:text-md mt-2 md:mt-1">
                            Porque Eres Mejor Opción Para Tu Cliente Y Qué Beneficio Único Obtiene Al Elegirte
                        </p>
                    </div>

                    <div class="flex flex-col sm:flex-row gap-3 w-full lg:w-auto flex-shrink-0">
                        <button id="open-business-panel-btn"
                                class="border-2 border-[#ffc857] text-[#ffc857] px-6 py-3 rounded-lg font-bold text-base hover:bg-[#ffc857] hover:text-[var(--color-primary)]  transition-all duration-300
                                       flex items-center justify-center gap-2 uppercase w-full sm:w-auto transform hover:-translate-y-1 min-h-[48px]">
                            <i data-lucide="briefcase" class="w-5 h-5"></i>
                            <span>Tu Propuesta De Valor</span>
                        </button>

                        <a href="ia-value-propositions.php"
                           class="bg-[var(--color-secondary)] text-white px-6 py-3 rounded-lg font-bold text-base shadow-lg shadow-red-900/40 hover:bg-red-800 transition-all duration-300
                                      flex items-center justify-center gap-2 uppercase w-full sm:w-auto transform hover:-translate-y-1 min-h-[48px]">
                            <i data-lucide="plus-circle" class="w-5 h-5"></i>
                            <span>Crear Tu Propuesta</span>
                        </a>
                    </div>
                </div>
                    
                <section id="categoria-estrategia" class="dashboard-section">
                    <div class="bg-white p-4 md:p-6 rounded-xl shadow-md">
                        <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                            <div>
                                <h3 class="text-2xl md:text-4xl font-black text-gray-800 flex items-center gap-2">
                                    <i data-lucide="compass" class="w-6 h-6 md:w-7 md:h-7 text-[var(--color-secondary)]"></i> ESTRATEGIA Y PLANIFICACIÓN
                                </h3>
                                <p class="text-gray-500 text-xs md:text-sm mt-1 uppercase">(Herramientas Para Definir La Dirección, Audiencia Y Planes)</p>
                            </div>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="radar" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Radar De Diagnóstico Empresarial</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Una Evaluación EstratégICA 360° Del Estado Actual De Tu Negocio.</p>
                                <a href="ia-business-diagnostic-radar.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="scan" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Asistente de Análisis de Negocio FODA</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Identifica Fortalezas, Oportunidades, Debilidades y Amenazas.</p>
                                <a href="ia-swot-analysis.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="search" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Asistente de Análisis de Mercado Local</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Investiga tu entorno para entender tus oportunidades de crecimiento.</p>
                                <a href="ia-local-market-analsyis.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="user-search" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Generador de Perfil de Cliente Ideal</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Define con claridad a quién le vendes y cómo comunicarte mejor.</p>
                                <a href="ia-ideal-client-generator.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="target" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Planificador de Objetivos de Marketing</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Crea un plan semanal, mensual o trimestral paso a paso.</p>
                                <a href="ia-marketing-goal-planner.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="languages" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Traductor De Inglés Inteligente</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Traduce Textos A Inglés Con Enfoque En Marketing Y Ventas.</p>
                                <a href="ia-english-translator.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                </section>

                <section id="categoria-marketing" class="dashboard-section">
                    <div class="bg-white p-4 md:p-6 rounded-xl shadow-md">
                        <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4 border-b border-gray-100 pb-4">
                            <div>
                                <h3 class="text-2xl md:text-4xl font-black text-gray-800 flex items-center gap-2">
                                    <i data-lucide="megaphone" class="w-6 h-6 md:w-7 md:h-7 text-[var(--color-secondary)]"></i> MARKETING Y CONTENIDOS
                                </h3>
                                <p class="text-gray-500 text-xs md:text-sm mt-1 uppercase font-bold tracking-wide">(Herramientas Para Crear Mensajes Y Materiales Que Atraen)</p>
                            </div>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                            
                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="text-initial" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white leading-tight">Generador de Títulos</h4>
                                <p class="text-slate-400 text-sm mb-4 flex-grow uppercase font-medium">Crea títulos atractivos para tus blogs o videos.</p>
                                <a href="ia-post-title-generator.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="ticket" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white leading-tight">Ofertas y Promociones</h4>
                                <p class="text-slate-400 text-sm mb-4 flex-grow uppercase font-medium">Diseña mensajes atractivos para descuentos.</p>
                                <a href="ia-offers-promotions.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="share-2" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white leading-tight">Posts para Redes Sociales</h4>
                                <p class="text-slate-400 text-sm mb-4 flex-grow uppercase font-medium">Crea posts de problema/solución.</p>
                                <a href="ia-social-post-creator.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)] font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="clapperboard" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white leading-tight">Anuncios Publicitarios</h4>
                                <p class="text-slate-400 text-sm mb-4 flex-grow uppercase font-medium">Textos persuasivos que venden servicios.</p>
                                <a href="ia-ads-generator.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                        </div>
                    </div>
                </section>

                <section id="categoria-ventas" class="dashboard-section">
                    <div class="bg-white p-4 md:p-6 rounded-xl shadow-md">
                        <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                            <div>
                                <h3 class="text-2xl md:text-4xl font-black  text-gray-800 flex items-center gap-2">
                                    <i data-lucide="handshake" class="w-6 h-6 md:w-7 md:h-7 text-[var(--color-secondary)]"></i> SEGUIMIENTO Y VENTAS
                                </h3>
                                <p class="text-gray-500 text-xs md:text-sm mt-1 uppercase">(Herramientas Para Convertir Prospectos En Clientes)</p>
                            </div>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                            
                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="file-check-2" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Generador de Descripciones Para Servicios</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Crea textos que explican el valor y los detalles de lo que ofreces.</p>
                                <a href="ia-services-descriptions.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="send-horizontal" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Generador de Mensaje Primer Contacto</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Crea mensajes iniciales potentes para posibles nuevos clientes.</p>
                                <a href="ia-first-contact-message.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="shopping-bag" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Asistente de Ventas</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Obtén respuestas rápidas para manejar objeciones y cerrar ventas.</p>
                                <a href="ia-sales-assistant.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="file-text" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Creador de Propuestas de Proyectos</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Genera propuestas profesionales para ganar nuevos clientes.</p>
                                <a href="ia-project-proposals.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="user-plus" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Asistente de Seguimiento Para Prospectos</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Crea mensajes para convertir de clientes potenciales en clientes.</p>
                                <a href="ia-leads-follow-up-assistant.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="user-check" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Asistente de Seguimiento Para Clientes</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Genera mensajes post-servicio para fidelizar a tus clientes.</p>
                                <a href="ia-customer-follow-up-assistant.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                </section>

                <section id="categoria-optimizacion" class="dashboard-section">
                    <div class="bg-white p-4 md:p-6 rounded-xl shadow-md">
                        <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                            <div>
                                <h3 class="text-2xl md:text-4xl font-black text-gray-800 flex items-center gap-2">
                                    <i data-lucide="book-heart" class="w-6 h-6 md:w-7 md:h-7 text-[var(--color-secondary)]"></i> OPTIMIZACIÓN DE PERFILES DIGITALES
                                </h3>
                                <p class="text-gray-500 text-xs md:text-sm mt-1 uppercase">(Herramientas Para Mejorar Tu Visibilidad Y Reputación Online)</p>
                            </div>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                            
                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="map-pin" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Optimizador de Perfil de Google Business</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Optimiza tu perfil para destacar en búsquedas y mapas locales.</p>
                                <a href="ia-gmb-profile-optimizer.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="facebook" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Optimizador de Página de Facebook</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Ajusta tu página de empresa para mejorar el alcance y la interacción.</p>
                                <a href="ia-facebook-page-optimizer.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="instagram" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Optimizador de Perfil de Instagram</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Mejora tu biografía y contenido para atraer más seguidores.</p>
                                <a href="ia-instagram-profile-optimizer.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>

                            <div class="tool-card bg-slate-900 rounded-xl p-6 flex flex-col group hover:shadow-2xl transition-all duration-300 border border-[var(--color-primary)] ">
                                <div class="tool-card-icon w-14 h-14 rounded-full flex items-center justify-center mb-4 bg-slate-800 group-hover:bg-[var(--color-highlight)] transition-colors">
                                    <i data-lucide="message-circle" class="w-8 h-8 text-[var(--color-highlight)] group-hover:text-[var(--color-primary)] "></i>
                                </div>
                                <h4 class="font-extrabold text-2xl mb-2 uppercase text-white">Optimizador de WhatsApp Business</h4>
                                <p class="text-slate-300 text-sm mb-4 flex-grow uppercase">Saca el máximo provecho a tu cuenta de WhatsApp profesional.</p>
                                <a href="ia-whatsapp-business-optimizer.php" class="tool-card-button w-full mt-auto py-3 px-4 uppercase bg-[var(--color-highlight)] text-[var(--color-primary)]  font-black rounded hover:opacity-90 transition-opacity flex justify-between items-center text-xs tracking-widest min-h-[44px]">
                                    USAR HERRAMIENTA <i data-lucide="arrow-right" class="w-4 h-4"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                </section>

                <?php include 'push.php'; ?>

            </div>
        </main>
    </div>

<div id="business-panel" class="fixed top-0 right-0 h-full w-full lg:w-1/3 bg-[var(--color-background)] z-50 transform translate-x-full transition-transform duration-300 ease-in-out shadow-2xl flex flex-col">
    
    <div class="flex-shrink-0 flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow z-20">
        <h3 class="text-3xl font-black text-[var(--color-highlight)] flex items-center uppercase">
            <i data-lucide="briefcase" class="w-8 h-8 mr-2 text-white"></i>
            PROPUESTA DE VALOR
        </h3>
        <button id="close-business-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 id="panel-body" class="flex-grow relative overflow-hidden bg-gray-50">
        
        <div id="proposal-display-container" class="flex flex-col h-full w-full">
            
            <div class="flex-grow overflow-y-auto p-4 md:p-6 relative">
                <div class="bg-white p-5 rounded-xl shadow-md border border-gray-100 h-full">
                    
                    <div class="border-b pb-3 mb-4">
                        <h4 class="text-2xl font-black text-[var(--color-secondary)] uppercase flex items-center">
                            <i data-lucide="eye" class="w-5 h-5 mr-2"></i>
                            VISTA PREVIA
                        </h4>
                    </div>

                    <div class="display-value-text text-gray-700 leading-relaxed text-lg" id="display-value-proposition">
                        <?php 
                            if (!empty($value_proposition_clean)) {
                                echo $value_proposition_clean; 
                            } else {
                                echo '<div class="flex flex-col items-center justify-center h-40 text-gray-400 text-center p-4 border-2 border-dashed border-gray-200 rounded-lg bg-gray-50">
                                            <i data-lucide="file-edit" class="w-8 h-8 mb-2 opacity-50"></i>
                                            <span class="italic text-sm">Aún no has definido tu propuesta de valor.<br>Haz clic en "Editar" para comenzar.</span>
                                          </div>';
                            }
                        ?>
                    </div>
                </div>
            </div>

            <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10">
                <div class="grid grid-cols-2 gap-3">
                    <button type="button" onclick="document.getElementById('close-business-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
                    </button>
                    <button type="button" id="panel-btn-editar" class="w-full btn btn-primary uppercase flex items-center justify-center gap-2">
                        <i data-lucide="edit-3" class="w-5 h-5"></i> EDITAR
                    </button>
                </div>
            </div>
        </div>

        <form id="business-info-form" class="hidden flex flex-col h-full w-full" novalidate>
            
            <div class="flex-grow overflow-y-auto p-4 md:p-6 relative">
                
                <div class="bg-blue-50 border-l-4 border-blue-500 p-4 mb-6 rounded-r-lg shadow-sm flex items-start gap-3">
                    <i data-lucide="info" class="h-5 w-5 text-blue-600 flex-shrink-0 mt-0.5"></i>
                    <div>
                        <p class="text-sm text-blue-800 font-bold uppercase mb-1">¿Qué escribir aquí?</p>
                        <p class="text-xs text-blue-700 leading-relaxed">
                            La propuesta de valor es la razón principal por la que un cliente te elige a ti en lugar de a la competencia. Sé claro y directo.
                        </p>
                    </div>
                </div>
                
                <div class="bg-white p-4 rounded-xl shadow-md border border-gray-100 flex flex-col h-[calc(100%-120px)]">
                    <div class="border-b pb-3 mb-4">
                        <h4 class="text-2xl font-black text-[var(--color-secondary)] uppercase flex items-center">
                            <i data-lucide="pen-tool" class="w-5 h-5 mr-2"></i>
                            EDITOR DE CONTENIDO
                        </h4>
                    </div>

                    <div class="flex flex-col flex-grow mb-5">
                        <div class="relative group flex-grow flex flex-col">
                            <div class="bg-white rounded-lg border border-gray-300 flex-grow flex flex-col overflow-hidden focus-within:ring-1 focus-within:ring-[var(--color-highlight)] focus-within:border-[var(--color-highlight)] transition-all">
                                <div id="editor-container" class="flex-grow overflow-y-auto p-2 min-h-[200px]">
                                    <?php echo $value_proposition_clean; ?>
                                </div>
                            </div>
                            
                            <textarea id="business-description" name="businessDescription" class="hidden" maxlength="1500" required><?php echo htmlspecialchars($value_proposition_clean); ?></textarea>
                            
                            <div class="flex justify-between items-center mt-2">
                                <div class="error-message text-red-500 text-xs min-h-[1rem]" id="description-error"></div>
                                <div class="text-xs text-gray-400 font-mono bg-gray-100 px-2 py-1 rounded border border-gray-200" id="description-char-count">0 / 1500</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10">
                <div class="grid grid-cols-2 gap-3">
                    <button type="button" id="panel-btn-cancelar" 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> CANCELAR
                    </button>
                    <button type="button" id="save-proposal-btn" class="w-full btn btn-primary uppercase flex items-center justify-center gap-2">
                        <i data-lucide="save" class="w-5 h-5"></i> GUARDAR
                    </button>
                </div>
            </div>
        </form>
        
    </div>
</div>

    <div id="business-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 hidden backdrop-blur-sm transition-opacity"></div>

    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            
            // ==========================================
            // CONFIGURACIÓN EDITOR QUILL
            // ==========================================
            var quill = new Quill('#editor-container', {
                theme: 'snow',
                placeholder: 'Escribe aquí tu propuesta de valor...',
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline'],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        [{ 'header': [2, 3, false] }],
                        ['clean']
                    ]
                }
            });

            const DOMElements = {
                mobileMenuButton: document.getElementById('mobile-menu-button'),
                sidebar: document.getElementById('sidebar'),
                sidebarOverlay: document.getElementById('sidebar-overlay'),
                phoneInput: document.getElementById('contact_phone'),
                
                openBusinessPanelBtn: document.getElementById('open-business-panel-btn'),
                businessPanel: document.getElementById('business-panel'),
                closeBusinessPanelBtn: document.getElementById('close-business-panel-btn'),
                businessPanelOverlay: document.getElementById('business-panel-overlay'),
                
                proposalDisplayContainer: document.getElementById('proposal-display-container'),
                displayValueProposition: document.getElementById('display-value-proposition'),
                businessInfoForm: document.getElementById('business-info-form'),
                businessDescriptionInput: document.getElementById('business-description'),
                descriptionCharCount: document.getElementById('description-char-count'),
                descriptionError: document.getElementById('description-error'),
                
                panelBtnEditar: document.getElementById('panel-btn-editar'),
                panelBtnCancelar: document.getElementById('panel-btn-cancelar'),
                saveProposalBtn: document.getElementById('save-proposal-btn'),
                
                phoneWhatsappInput: document.getElementById('phone-whatsapp')
            };

            // Variable JS con el valor LIMPIO desde PHP
            let originalProposalText = <?php echo json_encode($value_proposition_clean); ?>;

            // =================================================================
            // SINCRONIZACIÓN QUILL -> TEXTAREA OCULTO
            // =================================================================
            quill.on('text-change', function() {
                var html = quill.root.innerHTML;
                var text = quill.getText();
                DOMElements.businessDescriptionInput.value = html;
                
                // Actualizar contador de caracteres (basado en texto plano)
                if (DOMElements.descriptionCharCount) {
                    var length = text.trim().length;
                    var maxLength = DOMElements.businessDescriptionInput.maxLength;
                    DOMElements.descriptionCharCount.textContent = `${length} / ${maxLength}`;
                    if(length > 1400) DOMElements.descriptionCharCount.classList.add('text-red-500', 'font-bold');
                    else DOMElements.descriptionCharCount.classList.remove('text-red-500', 'font-bold');
                }
            });

            // =================================================================
            // FUNCIONES UTILIDAD
            // =================================================================
            const handleGlobalNotifications = () => {
                const urlParams = new URLSearchParams(window.location.search);
                const notificationType = urlParams.get('notification_type');
                const notificationMessage = urlParams.get('notification_message');
                if (notificationType && notificationMessage) {
                    if (typeof showToast === 'function') {
                        showToast(notificationMessage, notificationType);
                    }
                }
            };
            
            const formatPhoneNumber = (phoneStr) => {
                if (!phoneStr) return '';
                const cleaned = ('' + phoneStr).replace(/\D/g, '');
                const match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
                return match ? `(${match[1]}) ${match[2]}-${match[3]}` : phoneStr;
            };

            // =================================================================
            // LOGICA DEL PANEL LATERAL
            // =================================================================
            const openBusinessPanel = () => {
                DOMElements.businessPanel.classList.remove('translate-x-full');
                DOMElements.businessPanelOverlay.classList.remove('hidden');
                if (typeof lucide !== 'undefined') lucide.createIcons();
            };

            const closeBusinessPanel = () => {
                DOMElements.businessPanel.classList.add('translate-x-full');
                DOMElements.businessPanelOverlay.classList.add('hidden');
                setTimeout(() => toggleEditMode(false), 300);
            };
            
            const toggleEditMode = (isEditing) => {
                if(isEditing) {
                    DOMElements.proposalDisplayContainer.classList.add('hidden');
                    DOMElements.businessInfoForm.classList.remove('hidden');
                    DOMElements.businessInfoForm.classList.add('flex');
                    // Focus en el editor Quill
                    quill.focus();
                } else {
                    DOMElements.proposalDisplayContainer.classList.remove('hidden');
                    DOMElements.businessInfoForm.classList.add('hidden');
                    DOMElements.businessInfoForm.classList.remove('flex');
                }
            };

            const handleSaveProposal = async (event) => {
                event.preventDefault();
                // Obtener valor desde el input oculto (sincronizado con Quill)
                const newValue = DOMElements.businessDescriptionInput.value.trim();

                // Validación simple de contenido vacío
                if (quill.getText().trim().length === 0) {
                      if (typeof showToast === 'function') showToast('El campo no puede estar vacío.', 'error');
                      return;
                }

                // UI Loading
                const originalBtnText = DOMElements.saveProposalBtn.innerHTML;
                DOMElements.saveProposalBtn.disabled = true;
                DOMElements.saveProposalBtn.innerHTML = '<i data-lucide="loader-2" class="w-5 h-5 animate-spin"></i> GUARDANDO...';
                if (typeof lucide !== 'undefined') lucide.createIcons();

                try {
                    const response = await fetch('db/business-info-update.php', { 
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ 
                                value_proposition: newValue,
                                action: 'update_value_proposition'
                            }) 
                    });
                    
                    const result = await response.json();

                    if (result.success) {
                        if (typeof showToast === 'function') showToast(result.message, 'success');
                        
                        originalProposalText = newValue;
                        
                        // Actualizar la vista previa con el HTML directo (sanitizado en guardado/carga)
                        DOMElements.displayValueProposition.innerHTML = newValue;
                        
                        toggleEditMode(false);
                        
                        // Opcional: Cerrar panel despues de guardar
                        setTimeout(() => closeBusinessPanel(), 1500);
                        
                    } else {
                        if (typeof showToast === 'function') showToast(`Error: ${result.message}`, 'error');
                    }
                } catch (error) {
                    console.error('Error:', error);
                    if (typeof showToast === 'function') showToast('Error de conexión.', 'error');
                } finally {
                    DOMElements.saveProposalBtn.disabled = false;
                    DOMElements.saveProposalBtn.innerHTML = originalBtnText;
                    if (typeof lucide !== 'undefined') lucide.createIcons();
                }
            };

            // =================================================================
            // INICIALIZACION Y EVENTOS
            // =================================================================
            const init = () => {
                if (DOMElements.phoneInput) IMask(DOMElements.phoneInput, { mask: '(000) 000-0000' });
                if (DOMElements.phoneWhatsappInput) DOMElements.phoneWhatsappInput.value = formatPhoneNumber(DOMElements.phoneWhatsappInput.value);

                // Listeners Panel
                DOMElements.openBusinessPanelBtn?.addEventListener('click', openBusinessPanel);
                DOMElements.closeBusinessPanelBtn?.addEventListener('click', closeBusinessPanel);
                DOMElements.businessPanelOverlay?.addEventListener('click', closeBusinessPanel);
                
                DOMElements.panelBtnEditar?.addEventListener('click', () => toggleEditMode(true));
                DOMElements.panelBtnCancelar?.addEventListener('click', () => {
                    // Restaurar valor original en Quill
                    quill.clipboard.dangerouslyPasteHTML(originalProposalText);
                    toggleEditMode(false);
                });
                DOMElements.saveProposalBtn?.addEventListener('click', handleSaveProposal);
                
                // Mobile Menu
                DOMElements.mobileMenuButton?.addEventListener('click', () => {
                    DOMElements.sidebar.classList.toggle('-translate-x-full');
                    DOMElements.sidebarOverlay.classList.toggle('hidden');
                });
                DOMElements.sidebarOverlay?.addEventListener('click', () => {
                    DOMElements.sidebar.classList.add('-translate-x-full');
                    DOMElements.sidebarOverlay.classList.add('hidden');
                });

                if (typeof lucide !== 'undefined') lucide.createIcons();
                handleGlobalNotifications();
            };

            init();
        });
    </script>
    <script>
    document.addEventListener('DOMContentLoaded', () => {
        const toggleWidgetVisibility = (widgetId, isHidden) => {
            const widget = document.getElementById(widgetId);
            const showContainer = document.querySelector(`.show-widget-container [data-widget-id="${widgetId}"]`)?.closest('.show-widget-container');
            const videoPlayer = widget ? widget.querySelector('video') : null;

            if (!widget || !showContainer) return; 

            if (isHidden) {
                widget.classList.add('hidden');
                showContainer.classList.remove('hidden');
                if (videoPlayer) videoPlayer.pause(); 
            } else {
                widget.classList.remove('hidden');
                showContainer.classList.add('hidden');
            }
            localStorage.setItem(`hide_${widgetId}`, isHidden ? 'true' : 'false');
        };

        document.querySelectorAll('.hide-widget-btn').forEach(button => {
            button.addEventListener('click', (event) => {
                const widgetId = event.currentTarget.dataset.widgetId; 
                toggleWidgetVisibility(widgetId, true); 
            });
        });

        document.querySelectorAll('.show-widget-btn').forEach(button => {
            button.addEventListener('click', (event) => {
                const widgetId = event.currentTarget.dataset.widgetId; 
                toggleWidgetVisibility(widgetId, false); 
            });
        });

        document.querySelectorAll('.video-widget').forEach(widget => {
            const widgetId = widget.id;
            const isHidden = localStorage.getItem(`hide_${widgetId}`) === 'true';
            if (isHidden) toggleWidgetVisibility(widgetId, true);
        });
    });
    </script>
<script src="files/toast.js"></script>
</body>
</html>