<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');
$paginaActual = pathinfo(basename($_SERVER['PHP_SELF']), PATHINFO_FILENAME);

echo '<link rel="stylesheet" href="files/menu-styles.css">';
echo '<script src="files/menu-scripts.js" defer></script>';
?>

<header class="md:hidden fixed top-0 inset-x-0 z-40 bg-[var(--color-primary)] border-b border-gray-900/20" style="padding-top: max(env(safe-area-inset-top), 10px);">
    <div class="h-14 flex items-center justify-between px-3 text-white">
        <button id="open-sidebar" type="button" aria-label="Abrir menú" class="p-3 -ml-2 rounded-md hover:bg-white/10"><i data-lucide="menu" class="w-5 h-5"></i></button>
        <div class="flex items-center gap-2"><img src="img/LogoIAMarketing.webp" alt="Logotipo FlowCRM By OrozCo" class="h-10 w-auto" onerror="this.style.display='none'"></div>
        <button id="open-help-top" type="button" aria-label="Abrir ayuda" class="p-3 -mr-2 rounded-md hover:bg-white/10"><i data-lucide="life-buoy" class="w-5 h-5"></i></button>
    </div>
</header>

<div id="nav-overlay" class="md:hidden inset-0 bg-black/50 opacity-0 pointer-events-none transition-opacity duration-300 z-40"></div>

<aside id="sidebar" class="bg-[var(--color-primary)] text-white w-full md:w-72 fixed md:relative inset-0 md:inset-y-0 md:left-0 transform -translate-x-full md:translate-x-0 transition-transform duration-300 ease-in-out z-50 md:z-40 flex flex-col shadow-2xl md:rounded-r-xl overflow-y-auto" role="navigation" aria-label="Menú Principal">
    
    <?php include 'profile.php'; ?>
    
    <div class="md:hidden flex items-center justify-between px-7 py-3 border-b border-white/10 bg-[var(--color-primary)]" style="padding-top: max(env(safe-area-inset-top), 0px);">
        <div class="flex items-center gap-2">
            <img src="img/LogoIAMarketing.webp" alt="Logotipo FlowCRM By OrozCo" class="h-12 w-auto">
        </div>
        <button id="close-sidebar" type="button" aria-label="Cerrar Menú" class="p-2 rounded-md hover:bg-white/10">
            <i data-lucide="x" class="w-5 h-5 text-white"></i>
        </button>
    </div>

    <nav id="main-nav">
        <div class="hidden md:block text-center pt-5 pb-5 px-4 border-b border-white/10 sticky top-0 z-10 bg-[var(--color-primary)]">
            <img src="img/LogoIAMarketing.webp" alt="Logotipo FlowCRM By OrozCo" class="h-12 w-auto mx-auto">
             <p class="font-thin text-sm text-white/70 flex items-center justify-center gap-1.5">
                Powered by <i data-lucide="shield-check" class="w-4 h-4 text-green-400"></i>
                <span class="font-black text-[var(--color-highlight)] tracking-wide">Flow<span class="font-black text-white tracking-wide">CRM</span>™</span>
             </p>
        </div>

        <div class="px-4 py-4 border-b border-white/10">
            <div class="relative">
                <button type="button" id="platform-switcher-button" class="w-full flex items-center justify-between px-3 py-2.5 bg-white/5 rounded-lg hover:bg-white/10 transition-colors duration-150 focus:outline-none focus:ring-2 focus:ring-white/20">
                    <span class="flex items-center gap-3"><i data-lucide="cpu" class="w-5 h-5 text-[var(--color-highlight)]"></i><span class="font-bold">IA Marketing Tools</span></span>
                    <i data-lucide="chevrons-up-down" class="w-4 h-4 text-white/70"></i>
                </button>
                <div id="platform-switcher-dropdown" class="platform-switcher-dropdown hidden absolute w-full bg-[var(--color-secondary)] rounded-lg shadow-xl overflow-hidden z-20 divide-y divide-white/10">
                         <a href="dashboard.php" class="flex items-start gap-3 p-3 text-white hover:bg-white/10 transition-colors duration-150"><i data-lucide="gem" class="w-5 h-5 text-[var(--color-highlight)] flex-shrink-0 mt-1"></i><div><p class="font-bold leading-tight">Suite FlowCRM</p><p class="text-xs text-white/70">Gestión Completa De Tu Negocio</p></div></a>
                         <a href="adn-dashboard.php" class="flex items-start gap-3 p-3 text-white hover:bg-white/10 transition-colors duration-150"><i data-lucide="graduation-cap" class="w-5 h-5 text-[var(--color-highlight)] flex-shrink-0 mt-1"></i><div><p class="font-bold leading-tight">Programa ADN</p><p class="text-xs text-white/70">Acelerador De Negocios</p></div></a>
                         <a href="stock-dashboard.php" class="flex items-start gap-3 p-3 text-white hover:bg-white/10 transition-colors duration-150"><i data-lucide="graduation-cap" class="w-5 h-5 text-[var(--color-highlight)] flex-shrink-0 mt-1"></i><div><p class="font-bold leading-tight">Recursos IAStock</p><p class="text-xs text-white/70">Recursos Creativos De Promoción</p></div></a>
                   </div>
            </div>
        </div>

        <?php
        // ========= CAMBIO PRINCIPAL: MENÚ PARA IA MARKETING =========
        // ==================================
        //      ENLACES CORREGIDOS
        // ==================================
        $menuCategories = [
            'HERRAMIENTAS IA'    => ['icon' => 'home', 'items' => [['ia-marketing', 'brain-circuit', 'Dasboard IA Marketing']], 'is_single' => true],
            'ESTRATEGIA'         => ['icon' => 'compass', 'items' => [
                ['ia-business-diagnostic-radar', 'radar', 'Radar De Diagnóstico'],
                ['ia-swot-analysis', 'scan', 'Análisis FODA'],
                ['ia-local-market-analsyis', 'search', 'Análisis de Mercado'],
                ['ia-ideal-client-generator', 'user-search', 'Perfil Cliente Ideal'],
                ['ia-value-propositions', 'shield-check', 'Propuesta De Valor'],
                ['ia-marketing-goal-planner', 'target', 'Plan de Objetivos'],
            ]],
            'MARKETING'          => ['icon' => 'megaphone', 'items' => [
                ['ia-services-descriptions', 'file-check-2', 'Descripciones Servicios'],
                ['ia-offers-promotions', 'ticket', 'Ofertas y Promociones'],
                ['ia-social-post-creator', 'share-2', 'Publicaciones Sociales'],
                ['ia-post-title-generator', 'text-initial', 'Títulos Para Imágenes'],
                ['ia-ads-generator', 'clapperboard', 'Textos Para Anuncios']
            ]],
            'SEGUIMIENTO'        => ['icon' => 'handshake', 'items' => [
                ['ia-first-contact-message', 'send-horizontal', 'Primer Contacto'],
                ['ia-project-proposals', 'file-text', 'Propuestas de Proyectos'],
                ['ia-leads-follow-up-assistant', 'user-plus', 'Seguimiento Prospectos'],
                ['ia-customer-follow-up-assistant', 'user-check', 'Seguimiento Clientes']
            ]],
            'PERFILES DIGITALES' => ['icon' => 'sparkles', 'items' => [
                ['ia-gmb-profile-optimizer', 'map-pin', 'Google Business'],
                ['ia-facebook-page-optimizer', 'facebook', 'Página de Facebook'],
                ['ia-whatsapp-business-optimizer', 'message-circle', 'WhatsApp Business'],
                ['ia-instagram-profile-optimizer', 'instagram', 'Instagram Perfil'] 
            ]],
            'UTILIDADES'         => ['icon' => 'wand-2', 'items' => [
                ['ia-sales-assistant', 'shopping-bag', 'Asistente De Ventas'],
                ['ia-english-translator', 'languages', 'Traductor Inteligente']
            ]],
        ];
        
        // Nueva función para verificar el slug activo
        function isActiveSlug($slug, $paginaActual) {
            return $paginaActual === $slug;
        }
        ?>

        <div class="p-2 space-y-1">
            <div class="px-4 pt-3 pb-2">
                <h3 class="text-xs font-bold uppercase text-[var(--color-highlight)] tracking-wider">Menu Principal</h3>
            </div>
            <?php foreach ($menuCategories as $category => $data):
                $items = $data['items'];
                $isSingle = $data['is_single'] ?? false;
                $catIcon = $data['icon'];
                // CAMBIO: Usando la nueva función para verificar hijos activos
                $hasActiveChild = array_reduce($items, fn($carry, $item) => $carry || isActiveSlug($item[0], $paginaActual), false);

                if ($isSingle):
                    $it = $items[0];
                    // CAMBIO: Usando la nueva función
                    $active = isActiveSlug($it[0], $paginaActual);
                    $classes = "flex items-center gap-3 px-4 py-2.5 rounded-lg text-[14px] transition-colors duration-150 hover:bg-[var(--color-secondary)] focus:outline-none focus:ring-2 focus:ring-white/20" . ($active ? " active-button" : "");
                ?>
                    <a href="<?php echo $it[0]; ?>.php" class="<?php echo $classes; ?>"><i data-lucide="<?php echo $it[1]; ?>" class="w-5 h-5"></i><span class="uppercase font-bold"><?php echo htmlspecialchars($it[2]); ?></span></a>
                <?php else: ?>
                    <div>
                        <button type="button" class="accordion-toggle w-full flex items-center justify-between px-4 py-2.5 rounded-lg hover:bg-[var(--color-secondary)] transition-colors duration-150">
                            <span class="flex items-center gap-3"><i data-lucide="<?php echo $catIcon; ?>" class="w-5 h-5"></i><span class="uppercase font-bold text-[14px] tracking-wide"><?php echo htmlspecialchars($category); ?></span></span>
                            <i data-lucide="chevron-down" class="accordion-icon w-5 h-5 transition-transform duration-300"></i>
                        </button>
                        <div class="accordion-content pl-4 pt-2 space-y-1" <?php if($hasActiveChild) echo 'data-active="true"'; ?>>
                            <?php foreach ($items as $it):
                                // CAMBIO: Usando la nueva función
                                $active = isActiveSlug($it[0], $paginaActual);
                                $classes = "flex w-full items-center gap-3 px-4 py-2.5 rounded-lg text-[14px] transition-colors duration-150 hover:bg-white/10" . ($active ? " active-button" : "");
                            ?>
                                <a href="<?php echo $it[0]; ?>.php" class="<?php echo $classes; ?>"><i data-lucide="<?php echo $it[1]; ?>" class="w-5 h-5"></i><span class="font-bold uppercase"><?php echo htmlspecialchars($it[2]); ?></span></a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endforeach; ?>

            <div class="my-4 py-4 bg-black/20 border-y border-white/10">
                <div class="px-4">
                    <div class="flex items-center gap-3 mb-3">
                        <i data-lucide="megaphone" class="w-5 h-5 text-[var(--color-highlight)]"></i>
                        <h4 class="font-bold uppercase text-sm tracking-wider text-[var(--color-highlight)]">Lo Más Reciente</h4>
                    </div>
                    <?php if (file_exists('ads.php')) { include 'ads.php'; } ?>
                </div>
            </div>
            
            <button id="open-help" class="w-full flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-[var(--color-secondary)]" type="button"><i data-lucide="life-buoy" class="w-5 h-5"></i><span class="uppercase font-bold text-[14px]">Soporte Técnico</span></button>
            <a href="login.php?logout=true" class="w-full flex items-center gap-3 px-4 py-3 rounded-lg bg-red-700 hover:bg-red-800 text-white"><i data-lucide="log-out" class="w-5 h-5"></i><span class="uppercase font-extrabold text-[14px]">Cerrar Sesión</span></a>
        </div>
        
        <div class="p-4 mt-auto border-t border-white/10">
            <?php if (file_exists('files/footer.php')) { include 'files/footer.php'; } ?>
        </div>
        </nav>
</aside>

<div id="help-overlay" class="fixed inset-0 bg-black/50 opacity-0 pointer-events-none transition-opacity duration-300 z-40"></div>
<aside id="help-panel" class="fixed inset-y-0 right-0 w-full md:w-[520px] bg-white shadow-2xl transform translate-x-full transition-transform duration-300 z-50" role="dialog" aria-modal="true" aria-labelledby="help-title" aria-hidden="true">
    <div class="h-full flex flex-col">
        <div class="px-5 py-4 border-b border-gray-200 bg-gradient-to-r from-[var(--color-primary)] to-[#0f2749] text-white" style="padding-top: max(env(safe-area-inset-top), 0px);">
            <div class="flex items-center justify-between">
                <h3 id="help-title" class="text-lg font-extrabold uppercase tracking-wide">Centro De Soporte</h3>
                <button type="button" class="p-2 rounded-md hover:bg-white/10" data-close-help aria-label="Cerrar panel"><i data-lucide="x" class="w-5 h-5"></i></button>
            </div>
            <p class="text-white/80 text-xs mt-1">¿Tienes Una Duda O Problema? Envíanos Un Mensaje</p>
        </div>
        <form action="support.php" method="POST" enctype="multipart/form-data" class="flex-1 overflow-y-auto p-5 space-y-4">
            <div><label class="block text-xs font-semibold text-gray-700 uppercase mb-1">Nombre</label><input type="text" name="name" value="<?php echo $userFullName ?? ''; ?>" class="w-full rounded-lg border border-gray-300 px-3 py-3 focus:ring-2 focus:ring-[var(--color-highlight)] focus:border-[var(--color-secondary)]" required></div>
            <div><label class="block text-xs font-semibold text-gray-700 uppercase mb-1">Email</label><input type="email" name="email" value="<?php echo $userEmail ?? ''; ?>" class="w-full rounded-lg border border-gray-300 px-3 py-3 focus:ring-2 focus:ring-[var(--color-highlight)] focus:border-[var(--color-secondary)]" required></div>
            <div>
                <label class="block text-xs font-semibold text-gray-700 uppercase mb-1">Asunto</label>
                <select name="subject" class="w-full rounded-lg border border-gray-300 px-3 py-3 focus:ring-2 focus:ring-[var(--color-highlight)] focus:border-[var(--color-secondary)]" required>
                    <option value="Soporte técnico">Soporte Técnico</option><option value="Facturación">Facturación</option><option value="Sugerencia">Sugerencia</option><option value="Otra consulta">Otra Consulta</option>
                </select>
            </div>
            <div><label class="block text-xs font-semibold text-gray-700 uppercase mb-1">Mensaje</label><textarea name="message" rows="5" class="w-full rounded-lg border border-gray-300 px-3 py-3 focus:ring-2 focus:ring-[var(--color-highlight)] focus:border-[var(--color-secondary)]" placeholder="Cuéntanos el detalle de tu consulta…" required></textarea></div>
            <div><label class="block text-xs font-semibold text-gray-700 uppercase mb-1">Adjuntar Captura (opcional)</label><input type="file" name="attachment" accept="image/*,.pdf" class="block w-full text-sm text-gray-600 file:mr-3 file:py-2 file:px-3 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-[var(--color-primary)] file:text-white hover:file:brightness-110"></div>
            <input type="hidden" name="current_page" value="<?php echo htmlspecialchars($paginaActual); ?>">
            <div class="pt-2 flex items-center justify-between gap-3"><button type="button" class="px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50" data-close-help>CANCELAR</button><button type="submit" class="px-4 py-2 rounded-lg bg-[var(--color-secondary)] text-white font-bold hover:brightness-110">ENVIAR FORMULARIO</button></div>
        </form>
    </div>
</aside>