<?php
// --- REGLA GLOBAL SPA ---
$is_spa = isset($_SERVER['HTTP_X_SPA_REQUEST']) && $_SERVER['HTTP_X_SPA_REQUEST'] === 'true';
if ($is_spa) return;
// ------------------------------

$current_path = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';

function active_link($path, $current_path) {
    return strpos($current_path, $path) === 0 ? 'is-active' : '';
}


if (!function_exists('safe_text')) {
    function safe_text($value) {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}
if (!function_exists('role_label')) {
    function role_label($role) {
        $labels = array(
            'admin' => 'Admin',
            'manager' => 'Manager',
            'user' => 'Usuario',
            'sales' => 'Ventas',
            'production' => 'Produccion',
            'quality' => 'Calidad'
        );
        return $labels[$role] ?? ucfirst((string)$role);
    }
}

// 1. Intentamos obtener el usuario
$currentUser = function_exists('current_user') ? current_user() : (isset($_SESSION['user']) ? $_SESSION['user'] : array());

// 2. Verificamos el rol
$isAdmin = false;
if (isset($currentUser['role']) && $currentUser['role'] === 'admin') {
    $isAdmin = true;
} elseif (isset($_SESSION['user']['role']) && $_SESSION['user']['role'] === 'admin') {
    $isAdmin = true;
}

// 3. Variables para la interfaz
$userName = $currentUser['name'] ?? $_SESSION['user']['name'] ?? 'Usuario';
$userEmail = $currentUser['email'] ?? $_SESSION['user']['email'] ?? '';
$userRole = role_label($currentUser['role'] ?? $_SESSION['user']['role'] ?? '');
$userInitial = 'U';
if (!empty($userName)) {
    $userInitial = strtoupper(substr($userName, 0, 1));
}


if (!function_exists('icylab_sidebar_fallback_modules')) {
    function icylab_sidebar_fallback_modules() {
        return array(
            'operations'  => array('title' => 'Produccion', 'icon' => 'flask-conical', 'section' => 'Operacion', 'order' => 10, 'is_active' => 1),
            'quality'     => array('title' => 'Calidad', 'icon' => 'shield-check', 'section' => 'Operacion', 'order' => 20, 'is_active' => 1),
            'stock'       => array('title' => 'Stock', 'icon' => 'boxes', 'section' => 'Operacion', 'order' => 30, 'is_active' => 1),
            'commercial'  => array('title' => 'Dashboard Com.', 'icon' => 'line-chart', 'section' => 'Comercial', 'order' => 50, 'is_active' => 1),
            'crm'         => array('title' => 'CRM', 'icon' => 'briefcase-business', 'section' => 'Comercial', 'order' => 60, 'is_active' => 1),
            'customers'   => array('title' => 'Clientes', 'icon' => 'users', 'section' => 'Comercial', 'order' => 70, 'is_active' => 1),
            'products'    => array('title' => 'Productos', 'icon' => 'package', 'section' => 'Comercial', 'order' => 80, 'is_active' => 1),
            'billing'     => array('title' => 'Facturacion', 'icon' => 'file-text', 'section' => 'Finanzas', 'order' => 90, 'is_active' => 1),
            'notifications' => array('title' => 'Notificaciones', 'icon' => 'bell', 'section' => 'Empresa', 'order' => 100, 'is_active' => 1)
        );
    }
}
?>

<style>
/* ==========================================================================
   Estilos Base del Sidebar Gemini-Style
   ========================================================================== */
.sidebar-gemini {
    background: var(--surface-0);
    border-right: 1px solid var(--border-subtle);
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: var(--space-3) var(--space-2);
    transition: width var(--motion-base), transform var(--motion-base) cubic-bezier(0.2, 0, 0, 1);
}

.sidebar-nav-container {
    flex: 1; 
    overflow-y: auto; 
    overflow-x: hidden;
    scrollbar-width: none; 
    -ms-overflow-style: none; 
}
.sidebar-nav-container::-webkit-scrollbar { display: none; }

.sidebar-gemini .sidebar-nav { gap: 4px; display: flex; flex-direction: column; }
.sidebar-gemini .sidebar-link {
    border-radius: 50px; padding: 10px 16px; color: var(--text-secondary);
    font-weight: 500; transition: all 0.2s ease; border: none; margin: 2px 0;
    white-space: nowrap; overflow: hidden; text-decoration: none;
}
.sidebar-gemini .sidebar-link:hover { background: var(--surface-2); color: var(--text-primary); }
.sidebar-gemini .sidebar-link.is-active { background: var(--surface-3); color: var(--color-primary); }
.sidebar-gemini .sidebar-title { font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; padding: 16px 16px 8px; color: var(--text-muted); white-space: nowrap; }

/* Perfil de usuario (Abajo) */
.sidebar-gemini-footer { margin-top: auto; padding-top: var(--space-4); border-top: 1px solid var(--border-subtle); position: relative; z-index: 50; }
.sidebar-user-pill { width: 100%; display: flex; align-items: center; gap: 12px; padding: 8px 12px; border-radius: 50px; cursor: pointer; transition: background 0.2s; text-decoration: none; color: inherit; background: transparent; border: none; text-align: left; }
.sidebar-user-pill:hover { background: var(--surface-2); }
.sidebar-user-avatar { width: 32px; height: 32px; border-radius: 50%; min-width: 32px; background: var(--surface-1); border: 1px solid var(--border-default); display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 0.85rem; color: var(--text-primary); }

.gemini-user-dropdown { position: absolute; bottom: calc(100% + 10px); left: 0; width: 100%; z-index: 9999; background: var(--surface-1); border: 1px solid var(--border-default); border-radius: 18px; box-shadow: var(--shadow-lg); padding: 8px; opacity: 0; visibility: hidden; transform: translateY(10px); transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); }
.gemini-user-dropdown.is-open { opacity: 1; visibility: visible; transform: translateY(0); }

/* Submenús */
.sidebar-submenu { display: none; flex-direction: column; padding-left: 24px; margin-top: 2px; gap: 2px; }
.sidebar-item-has-children.is-open .sidebar-submenu { display: flex; }
.sidebar-item-has-children .submenu-chevron { margin-left: auto; width: 16px; transition: transform 0.2s ease; }
.sidebar-item-has-children.is-open .submenu-chevron { transform: rotate(180deg); }
.sidebar-sublink { font-size: 0.85rem; padding: 8px 16px; }
body.is-sidebar-collapsed .sidebar-submenu { display: none !important; }

/* Lógica de logos */
.logo-collapsed { display: none; }
body.is-sidebar-collapsed .logo-expanded { display: none !important; }
body.is-sidebar-collapsed .logo-collapsed { display: block !important; margin: 0 auto; }

/* Modo comprimido Escritorio */
body.is-sidebar-collapsed { --sidebar-width: 84px !important; }
body.is-sidebar-collapsed .sidebar-title, body.is-sidebar-collapsed .sidebar-link span:not(.sidebar-icon), body.is-sidebar-collapsed .sidebar-user-info, body.is-sidebar-collapsed .user-menu-chevron, body.is-sidebar-collapsed .sidebar-brand-text, body.is-sidebar-collapsed .submenu-chevron { display: none !important; }
body.is-sidebar-collapsed .sidebar-link, body.is-sidebar-collapsed .sidebar-user-pill { justify-content: center; padding-left: 0; padding-right: 0; }
body.is-sidebar-collapsed .sidebar-gemini { padding: var(--space-3) 8px; }
body.is-sidebar-collapsed .sidebar-icon { margin: 0; }
body.is-sidebar-collapsed .gemini-user-dropdown { width: 240px; left: 100%; bottom: 0; margin-left: 10px; }

/* ==========================================================================
   LÓGICA DEL LOGO Y BOTÓN TOGGLE
   ========================================================================== */
.toggle-icon-collapsed { display: none !important; }

body.is-sidebar-collapsed .sidebar-brand { justify-content: center !important; padding-left: 0 !important; padding-right: 0 !important; }
body.is-sidebar-collapsed #sidebarLogoLink { display: none !important; }
body.is-sidebar-collapsed #desktopSidebarToggle { display: flex !important; width: 100% !important; justify-content: center !important; }
body.is-sidebar-collapsed .toggle-icon-expanded { display: none !important; }
body.is-sidebar-collapsed .toggle-icon-collapsed { display: block !important; margin: 0 auto; transition: transform 0.2s; }
body.is-sidebar-collapsed .toggle-icon-collapsed:hover { transform: scale(1.05); }

/* Backdrop móvil para gestures */
.mobile-close-btn { display: none; }
.sidebar-backdrop {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    height: 100dvh;
    background: rgba(0, 0, 0, 0.5);
    z-index: 998;
    opacity: 0;
    visibility: hidden;
    transition: opacity var(--motion-base);
}

/* Sincronizamos las clases is-open de app.js con el CSS */
body.is-mobile-sidebar-open .sidebar-backdrop,
.sidebar-backdrop.is-open {
    opacity: 1;
    visibility: visible;
}

@media (max-width: 760px) {
    .mobile-close-btn { display: flex; align-items: center; justify-content: center; width: 34px; height: 34px; border: none; background: var(--surface-2); border-radius: 50%; color: var(--text-primary); cursor: pointer; transition: background 0.2s; }
    .mobile-close-btn:active { background: var(--surface-3); }
    
    .sidebar-gemini {
        position: fixed;
        left: 0;
        top: 0;
        height: 100dvh;
        z-index: 999;
        transform: translateX(-100%);
        width: 280px;
    }
    
    body.is-mobile-sidebar-open .sidebar-gemini,
    .sidebar-gemini.is-open {
        transform: translateX(0);
        box-shadow: var(--shadow-lg);
    }
}
</style>

<aside class="sidebar sidebar-gemini" id="sidebar">
    <div class="sidebar-inner" style="display: flex; flex-direction: column; height: 100%; padding: 0;">
        
        <div class="sidebar-brand" style="padding: 16px 16px 24px; display: flex; align-items: center; justify-content: space-between;">
            <a href="/modules/dashboard/" id="sidebarLogoLink" aria-label="ICYLAB OS" style="display: flex; align-items: center; text-decoration: none;">
                <img src="/assets/img/icylab-os.svg" alt="ICYLAB OS" class="logo-expanded" style="height: 22px; filter: var(--logo-filter);">
            </a>
            
            <button id="desktopSidebarToggle" class="icon-btn mobile-hidden" style="width: 32px; height: 32px; border: none; background: transparent; box-shadow: none; cursor: pointer; display: flex; align-items: center; justify-content: center; padding: 0;" aria-label="Alternar menú">
                <i data-lucide="panel-left-close" class="toggle-icon-expanded" style="color: var(--text-muted); width: 20px; height: 20px;"></i>
                <img src="/assets/img/favicon.svg" alt="OS" class="toggle-icon-collapsed" style="height: 26px; filter: var(--logo-filter);">
            </button>
            
            <button id="mobileSidebarClose" class="mobile-close-btn mobile-only" aria-label="Cerrar menú"><i data-lucide="x" style="width: 18px; height: 18px;"></i></button>
        </div>

        <div class="sidebar-nav-container">
            <nav class="sidebar-nav">
                
                <div class="sidebar-title">Empresa</div>
                <a class="sidebar-link <?php echo active_link('/modules/dashboard', $current_path); ?>" href="/modules/dashboard/">
                    <span class="sidebar-icon"><i data-lucide="layout-dashboard"></i></span>
                    <span>Dashboard</span>
                </a>

                <?php 
                $all_modules = [];
                try {
                    $all_modules = function_exists('get_system_modules') ? get_system_modules(true) : [];
                } catch (Throwable $e) {
                    error_log('ICYLAB sidebar get_system_modules failed: ' . $e->getMessage());
                    $all_modules = [];
                }
                if (!is_array($all_modules)) {
                    $all_modules = [];
                }
                if (empty($all_modules)) {
                    $all_modules = icylab_sidebar_fallback_modules();
                }
                $grouped_modules = [];
                foreach ($all_modules as $key => $mod) {
                    if (!is_array($mod)) { continue; }
                    $section = isset($mod['section']) && $mod['section'] !== '' ? $mod['section'] : 'Otros Modulos';
                    $grouped_modules[$section][$key] = $mod;
                }

                foreach ($grouped_modules as $section_name => $mods): 
                    $has_section_access = $isAdmin;
                    if (!$isAdmin) {
                        foreach ($mods as $key => $mod) {
                            if (user_can('module.' . $key)) { $has_section_access = true; break; }
                        }
                    }

                    if ($has_section_access):
                ?>
                    <?php if ($section_name !== 'Empresa'): ?>
                        <div class="sidebar-title"><?php echo safe_text($section_name); ?></div>
                    <?php endif; ?>
                    
                    <?php foreach ($mods as $key => $mod): ?>
                        <?php if ($isAdmin || user_can('module.' . $key)): ?>
                            <?php if ($key === 'crm'): ?>
                                <?php
                                    $isCrmPath = strpos($current_path, '/modules/crm') === 0;
                                    $isCrmEmbudoPath = strpos($current_path, '/modules/crm/embudo.php') === 0;
                                    $isCrmQuotesPath = strpos($current_path, '/modules/crm/quotes.php') === 0;
                                    $isCrmMainPath = $isCrmPath && !$isCrmEmbudoPath && !$isCrmQuotesPath;
                                ?>
                                <div class="sidebar-item-has-children <?php echo $isCrmPath ? 'is-open' : ''; ?>" id="crm-menu-parent">
                                    <a class="sidebar-link <?php echo $isCrmPath ? 'is-active' : ''; ?>" href="/modules/crm/" id="crm-main-link" style="display: flex; align-items: center;" aria-expanded="<?php echo $isCrmPath ? 'true' : 'false'; ?>">
                                        <span class="sidebar-icon"><i data-lucide="<?php echo safe_text($mod['icon']); ?>"></i></span>
                                        <span><?php echo safe_text($mod['title']); ?></span>
                                        <i data-lucide="chevron-down" class="submenu-chevron"></i>
                                    </a>
                                    <div class="sidebar-submenu">
                                        <a class="sidebar-link sidebar-sublink <?php echo $isCrmMainPath ? 'is-active' : ''; ?>" href="/modules/crm/" style="display: flex; align-items: center; gap: 8px;">
                                            <i data-lucide="layout-list" style="width: 18px; height: 18px; color: var(--text-muted);"></i><span>CRM</span>
                                        </a>
                                        <a class="sidebar-link sidebar-sublink <?php echo $isCrmEmbudoPath ? 'is-active' : ''; ?>" href="/modules/crm/embudo.php" style="display: flex; align-items: center; gap: 8px;">
                                            <i data-lucide="kanban-square" style="width: 18px; height: 18px; color: var(--text-muted);"></i><span>Embudo</span>
                                        </a>
                                        <a class="sidebar-link sidebar-sublink <?php echo $isCrmQuotesPath ? 'is-active' : ''; ?>" href="/modules/crm/quotes.php" style="display: flex; align-items: center; gap: 8px;">
                                            <i data-lucide="file-text" style="width: 18px; height: 18px; color: var(--text-muted);"></i><span>Cotizaciones</span>
                                        </a>
                                    </div>
                                </div>
                            <?php elseif ($key === 'billing'): ?>
                                <?php
                                    $isBillingPath = strpos($current_path, '/modules/billing') === 0;
                                    $isBillingReceivePath = strpos($current_path, '/modules/billing/receive.php') === 0;
                                    $isBillingPayablesPath = strpos($current_path, '/modules/billing/payables.php') === 0;
                                    $isBillingMainPath = $isBillingPath && !$isBillingReceivePath && !$isBillingPayablesPath;
                                ?>
                                <div class="sidebar-item-has-children <?php echo $isBillingPath ? 'is-open' : ''; ?>" id="billing-menu-parent">
                                    <a class="sidebar-link <?php echo $isBillingPath ? 'is-active' : ''; ?>" href="/modules/billing/" id="billing-main-link" style="display: flex; align-items: center;" aria-expanded="<?php echo $isBillingPath ? 'true' : 'false'; ?>">
                                        <span class="sidebar-icon"><i data-lucide="<?php echo safe_text($mod['icon']); ?>"></i></span>
                                        <span><?php echo safe_text($mod['title']); ?></span>
                                        <i data-lucide="chevron-down" class="submenu-chevron"></i>
                                    </a>
                                    <div class="sidebar-submenu">
                                        <a class="sidebar-link sidebar-sublink <?php echo $isBillingMainPath ? 'is-active' : ''; ?>" href="/modules/billing/" style="display: flex; align-items: center; gap: 8px;">
                                            <i data-lucide="file-plus-2" style="width: 18px; height: 18px; color: var(--text-muted);"></i><span>Emitir</span>
                                        </a>
                                        <a class="sidebar-link sidebar-sublink <?php echo $isBillingReceivePath ? 'is-active' : ''; ?>" href="/modules/billing/receive.php" style="display: flex; align-items: center; gap: 8px;">
                                            <i data-lucide="inbox" style="width: 18px; height: 18px; color: var(--text-muted);"></i><span>Recibir DTE</span>
                                        </a>
                                        <a class="sidebar-link sidebar-sublink <?php echo $isBillingPayablesPath ? 'is-active' : ''; ?>" href="/modules/billing/payables.php" style="display: flex; align-items: center; gap: 8px;">
                                            <i data-lucide="receipt-text" style="width: 18px; height: 18px; color: var(--text-muted);"></i><span>Cuentas por pagar</span>
                                        </a>
                                    </div>
                                </div>
                            <?php elseif ($key === 'customers'): ?>
                                <?php
                                    $isCustomersPath = strpos($current_path, '/modules/customers') === 0;
                                    $isCustomersTerritoryPath = strpos($current_path, '/modules/customers/territory.php') === 0;
                                ?>
                                <div class="sidebar-item-has-children <?php echo $isCustomersPath ? 'is-open' : ''; ?>" id="customers-menu-parent">
                                    <a class="sidebar-link <?php echo $isCustomersPath ? 'is-active' : ''; ?>" href="/modules/customers/" id="customers-main-link" style="display: flex; align-items: center;" aria-expanded="<?php echo $isCustomersPath ? 'true' : 'false'; ?>">
                                        <span class="sidebar-icon"><i data-lucide="<?php echo safe_text($mod['icon']); ?>"></i></span>
                                        <span><?php echo safe_text($mod['title']); ?></span>
                                        <i data-lucide="chevron-down" class="submenu-chevron"></i>
                                    </a>
                                    <div class="sidebar-submenu">
                                        <a class="sidebar-link sidebar-sublink <?php echo ($isCustomersPath && !$isCustomersTerritoryPath) ? 'is-active' : ''; ?>" href="/modules/customers/" style="display: flex; align-items: center; gap: 8px;">
                                            <i data-lucide="users" style="width: 18px; height: 18px; color: var(--text-muted);"></i><span>Clientes</span>
                                        </a>
                                        <a class="sidebar-link sidebar-sublink <?php echo $isCustomersTerritoryPath ? 'is-active' : ''; ?>" href="/modules/customers/territory.php" style="display: flex; align-items: center; gap: 8px;">
                                            <i data-lucide="map" style="width: 18px; height: 18px; color: var(--text-muted);"></i><span>Territorio</span>
                                        </a>
                                    </div>
                                </div>
                            <?php else: ?>
                                <a class="sidebar-link <?php echo active_link('/modules/' . $key, $current_path); ?>" href="/modules/<?php echo $key; ?>/">
                                    <span class="sidebar-icon"><i data-lucide="<?php echo safe_text($mod['icon']); ?>"></i></span>
                                    <span><?php echo safe_text($mod['title']); ?></span>
                                </a>
                            <?php endif; ?>
                        <?php endif; ?>
                    <?php endforeach; ?>
                <?php endif; endforeach; ?>

                <?php if ($isAdmin): ?>
                    <div class="sidebar-title">Administración</div>
                    <a class="sidebar-link <?php echo active_link('/modules/admin/users.php', $current_path); ?>" href="/modules/admin/users.php">
                        <span class="sidebar-icon"><i data-lucide="user-cog"></i></span><span>Usuarios</span>
                    </a>
                    <a class="sidebar-link <?php echo active_link('/modules/admin/company_settings.php', $current_path); ?>" href="/modules/admin/company_settings.php">
                        <span class="sidebar-icon"><i data-lucide="settings"></i></span><span>Configuración</span>
                    </a>
                <?php endif; ?>

            </nav>
        </div>
        
        <div class="sidebar-gemini-footer">
            <div class="gemini-user-dropdown" id="geminiUserDropdown">
                <div class="user-dropdown-header">
                    <strong><?php echo safe_text($userName); ?></strong>
                    <span><?php echo safe_text($userEmail); ?></span>
                </div>
                <a href="/modules/admin/my_profile.php" class="user-dropdown-link"><i data-lucide="user"></i><span>Mi Perfil</span></a>
                <?php if ($isAdmin): ?>
                    <a href="/modules/admin/users.php" class="user-dropdown-link"><i data-lucide="user-cog"></i><span>Usuarios</span></a>
                <?php endif; ?>
                <button type="button" class="user-dropdown-link" id="themeToggleBtn" style="width: 100%; text-align: left; background: transparent; border: none; font-family: inherit; cursor: pointer; padding: 0 12px;">
                    <i data-lucide="moon" id="themeIcon"></i><span id="themeText">Modo Oscuro</span>
                </button>
                <div style="height: 1px; background: var(--border-subtle); margin: 4px 0;"></div>
                <a href="/logout.php" class="user-dropdown-link is-danger"><i data-lucide="log-out"></i><span>Cerrar sesión</span></a>
            </div>

            <button id="geminiUserToggle" type="button" class="sidebar-user-pill">
                <div class="sidebar-user-avatar"><?php echo $userInitial; ?></div>
                <div class="sidebar-user-info" style="display: flex; flex-direction: column; overflow: hidden; white-space: nowrap;">
                    <span style="font-weight: 500; font-size: 0.9rem; text-overflow: ellipsis; overflow: hidden; color: var(--text-primary);"><?php echo safe_text($userName); ?></span>
                    <span style="font-size: 0.75rem; color: var(--text-muted);"><?php echo $userRole; ?></span>
                </div>
                <i data-lucide="chevron-up" class="user-menu-chevron" style="margin-left: auto; width: 16px; color: var(--text-muted);"></i>
            </button>
        </div>

    </div>
</aside>

<div class="sidebar-backdrop" id="sidebarBackdrop"></div>

<script>
// =========================================================================
// INTERACCIONES DEL MENÚ Y GESTOS MÓVILES (SPA SAFE)
// =========================================================================

if (!window.__sidebarInteractionsInitialized) {

    document.addEventListener('DOMContentLoaded', () => {
        
        // 1. Submenús del sidebar
        const crmLink = document.getElementById('crm-main-link');
        const crmParent = document.getElementById('crm-menu-parent');
        const customersLink = document.getElementById('customers-main-link');
        const customersParent = document.getElementById('customers-menu-parent');
        const billingLink = document.getElementById('billing-main-link');
        const billingParent = document.getElementById('billing-menu-parent');

        // CRM actúa como contenedor: tocar la sección abre/cierra el submenú.
        // La navegación queda explícita en los sublinks CRM, Embudo y Cotizaciones.
        if (crmLink && crmParent) {
            crmLink.addEventListener('click', function(e) {
                if (document.body.classList.contains('is-sidebar-collapsed')) return;

                e.preventDefault();
                e.stopPropagation();

                const willOpen = !crmParent.classList.contains('is-open');
                crmParent.classList.toggle('is-open', willOpen);
                crmLink.setAttribute('aria-expanded', willOpen ? 'true' : 'false');
            });
        }

        // Facturación actúa como contenedor: tocar la sección abre/cierra el submenú.
        if (billingLink && billingParent) {
            billingLink.addEventListener('click', function(e) {
                if (document.body.classList.contains('is-sidebar-collapsed')) return;

                e.preventDefault();
                e.stopPropagation();

                const willOpen = !billingParent.classList.contains('is-open');
                billingParent.classList.toggle('is-open', willOpen);
                billingLink.setAttribute('aria-expanded', willOpen ? 'true' : 'false');
            });
        }

        // Clientes actúa como contenedor: tocar la sección abre/cierra el submenú.
        // La navegación queda explícita en los sublinks Clientes y Territorio.
        if (customersLink && customersParent) {
            customersLink.addEventListener('click', function(e) {
                if (document.body.classList.contains('is-sidebar-collapsed')) return;

                e.preventDefault();
                e.stopPropagation();

                const willOpen = !customersParent.classList.contains('is-open');
                customersParent.classList.toggle('is-open', willOpen);
                customersLink.setAttribute('aria-expanded', willOpen ? 'true' : 'false');
            });
        }

        // 2. Gestos Táctiles (Swipe)
        let touchStartX = 0;
        let touchStartY = 0;
        let ignoreSwipe = false; // 🔥 Bandera para detectar scroll horizontal

        document.addEventListener('touchstart', e => {
            touchStartX = e.touches[0].clientX;
            touchStartY = e.touches[0].clientY;
            
            // 🔥 PREVENCIÓN DE CONFLICTO: 
            // Evaluamos si el inicio del toque ocurre en un elemento diseñado para hacer scroll horizontal
            const scrollableEl = e.target.closest('.table-wrap, .crm-kanban-wrapper, .table-container-scroll, .crm-timeline-scroll, .territory-map-card, .territory-map-canvas, [data-map-canvas], .gm-style, [style*="overflow-x: auto"]');
            
            if (scrollableEl) {
                ignoreSwipe = true;
            } else {
                ignoreSwipe = false;
            }
        }, {passive: true});

        document.addEventListener('touchend', e => {
            if (window.innerWidth > 760) return; 

            let touchEndX = e.changedTouches[0].clientX;
            let touchEndY = e.changedTouches[0].clientY;
            
            let diffX = touchEndX - touchStartX;
            let diffY = touchEndY - touchStartY;

            if (Math.abs(diffY) > Math.abs(diffX)) return;

            const sidebar = document.getElementById("sidebar");
            const backdrop = document.getElementById("sidebarBackdrop");
            const isMenuOpen = document.body.classList.contains('is-mobile-sidebar-open') || (sidebar && sidebar.classList.contains('is-open'));

            // --- SWIPE DERECHO (ABRIR) ---
            // Solo abrimos si superó el umbral, el menú está cerrado, y NO estamos tocando una tabla
            if (diffX > 40 && !isMenuOpen && !ignoreSwipe) {
                if (touchStartX <= 28) {
                    document.body.classList.add('is-mobile-sidebar-open');
                    if (sidebar) sidebar.classList.add("is-open");
                    if (backdrop) backdrop.classList.add("is-open");
                }
            }
            
            // --- SWIPE IZQUIERDO (CERRAR) ---
            // El gesto de cerrar siempre se permite si el menú está abierto
            if (diffX < -40 && isMenuOpen) {
                document.body.classList.remove('is-mobile-sidebar-open');
                if (sidebar) sidebar.classList.remove("is-open");
                if (backdrop) backdrop.classList.remove("is-open");
            }
        }, {passive: true});

    });

    window.__sidebarInteractionsInitialized = true;
}
</script>