import { Component, OnInit, OnDestroy, Output, EventEmitter } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { RouterLink, RouterLinkActive, Router, NavigationEnd } from '@angular/router';
import { MobileMenuService } from '../../services/mobile/mobile-menu.service';
import { ThemeService } from '../../services/theme/theme.service';
import { Subscription } from 'rxjs';
import { filter } from 'rxjs/operators';

interface MenuItem {
  id: string;
  label: string;
  icon: string;
  notifications: number;
  children?: MenuItem[];
  expanded?: boolean;
  disabled?: boolean;
  disabledReason?: string;
}

@Component({
  selector: 'app-sidebar',
  standalone: true,
  imports: [CommonModule, FormsModule, RouterLink, RouterLinkActive],
  template: `
    <aside class="sidebar" 
           [class.collapsed]="isCollapsed && !isTemporarilyExpanded"
           [class.hidden-mobile]="isHiddenInMobile"
           [class.force-visible]="isForcedVisible"
           [class.temporarily-expanded]="isTemporarilyExpanded">
      
      <!-- ✅ Botão de Toggle sempre visível no desktop -->
      <div class="toggle-container" *ngIf="!isMobile">
        <button class="main-toggle-btn" 
                (click)="toggleSidebar()" 
                [title]="isCollapsed ? 'Expandir sidebar' : 'Recolher sidebar'">
          <i class="fas" 
             [class.fa-chevron-right]="isCollapsed" 
             [class.fa-chevron-left]="!isCollapsed"></i>
        </button>
      </div>
      
      <!-- Campo de Pesquisa -->
      <div class="search-container">
        <!-- <div style="background: lime; color: black; padding: 8px; font-size: 12px; margin-bottom: 8px; font-weight: bold;">
          ✅ SIDEBAR ATUALIZADA - FUNCIONANDO!
        </div> -->
        <input 
          type="text" 
          [(ngModel)]="searchTerm" 
          placeholder="Buscar..."
          (input)="filterMenuItems()"
          class="search-input"
        >
      </div>

      <!-- Menu de Navegação -->
      <nav class="menu">
        <ul>
          <ng-container *ngFor="let item of filteredMenuItems">
            <!-- Item principal -->
            <li [class.active]="selectedItem === item.id"
                [class.has-children]="item.children && item.children.length > 0"
                [class.expanded]="item.expanded"
                [class.disabled]="item.disabled">
              
              <div class="menu-item" 
                   (click)="!item.disabled && selectMenuItem(item)"
                   [routerLink]="!item.children && !item.disabled ? ['/app', item.id] : null"
                   routerLinkActive="active"
                   [routerLinkActiveOptions]="{exact: true}"
                   [title]="item.disabled ? item.disabledReason : ''">
                <i [class]="item.icon"></i>
                <span class="menu-text">{{ item.label }}</span>
                <span class="notification" *ngIf="item.notifications > 0">
                  {{ item.notifications }}
                </span>
                <i class="expand-icon fa fa-angle-down" 
                   *ngIf="item.children && item.children.length > 0 && !item.disabled"
                   [class.rotated]="item.expanded"></i>
                <!-- 🚫 Ícone de bloqueio -->
                <i class="fas fa-lock disabled-icon" 
                   *ngIf="item.disabled"
                   title="Funcionalidade bloqueada"></i>
              </div>

              <!-- Submenus -->
              <ul class="submenu" *ngIf="item.children && item.expanded && !item.disabled">
                <li *ngFor="let child of item.children"
                    [class.active]="selectedItem === child.id"
                    [class.disabled]="child.disabled"
                    routerLinkActive="active"
                    [routerLinkActiveOptions]="{exact: true}"
                    (click)="!child.disabled && selectMenuItem(child)"
                    [routerLink]="!child.disabled ? ['/app', child.id] : null">
                  <div class="submenu-item" [title]="child.disabled ? child.disabledReason : ''">
                    <i [class]="child.icon"></i>
                    <span class="menu-text">{{ child.label }}</span>
                    <span class="notification" *ngIf="child.notifications > 0">
                      {{ child.notifications }}
                    </span>
                    <!-- 🚫 Ícone de bloqueio para submenu -->
                    <i class="fas fa-lock disabled-icon" 
                       *ngIf="child.disabled"
                       title="Funcionalidade bloqueada"></i>
                  </div>
                </li>
              </ul>
            </li>
          </ng-container>
        </ul>
      </nav>

      <!-- Informações da Empresa e Licença -->
      <div class="license-info">
        <div class="license-content">
          <!-- Logo/Branding -->
          <div class="brand-section">
            <div class="brand-icon">
              <i class="fas fa-shield-alt"></i>
            </div>
            <div class="brand-text">
              <div class="company-name">Grupo PRA</div>
              <div class="software-name">PraFrota</div>
            </div>
          </div>
          
          <!-- Informações Legais -->
          <div class="legal-info">
            <div class="cnpj-info">
              <i class="fas fa-building"></i>
              <span>CNPJ: 31.882.636/0001-38</span>
            </div>
            <div class="license-info-text">
              <i class="fas fa-certificate"></i>
              <span>Software Licenciado</span>
            </div>
          </div>
        </div>
        
        <!-- Versão -->
        <div class="version-info">
          <i class="fas fa-code-branch"></i>
          <span>Versão 1.2.9</span>
        </div>
      </div>
    </aside>
  `,
  styles: [`
    /* ===== SIDEBAR BASE ===== */
    .sidebar {
      width: 240px;
      height: 90vh;
      background: var(--sidebar-bg);
      color: var(--text-primary);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      display: flex;
      flex-direction: column;
      position: fixed;
      top: 65;
      left: 10px; /* ✅ Margem esquerda */
      z-index: 1000;
      border-radius: 12px 12px 12px 12px; /* ✅ Cantos arredondados */
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      overflow: hidden;
    }

    .sidebar.collapsed {
      width: 80px;
    }

    /* ✅ Expansão temporária quando collapsed */
    .sidebar.temporarily-expanded {
      width: 240px !important;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2) !important;
      z-index: 1003 !important;
    }

    .sidebar.temporarily-expanded .menu-text,
    .sidebar.temporarily-expanded .notification,
    .sidebar.temporarily-expanded .expand-icon,
    .sidebar.temporarily-expanded .submenu {
      display: block !important;
    }

    .sidebar.temporarily-expanded .menu-item {
      justify-content: flex-start !important;
      padding: 0.75rem 1rem !important;
    }

    /* ===== BOTÃO DE TOGGLE ===== */
    .toggle-container {
      padding: 0.5rem 1rem;
      border-bottom: 1px solid var(--divider);
      display: flex;
      justify-content: flex-end;
      align-items: center;
      flex-shrink: 0;
      min-height: 48px; /* ✅ Altura mínima consistente */
    }

    .main-toggle-btn {
      width: 28px;
      height: 28px;
      border: 1px solid var(--divider);
      border-radius: 4px;
      background: var(--surface);
      color: var(--text-secondary);
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s ease;
      flex-shrink: 0;
      outline: none;
    }

    .main-toggle-btn:hover {
      background: var(--hover);
      color: var(--text-primary);
      border-color: var(--primary);
      transform: scale(1.05); /* ✅ Leve aumento de escala */
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12); /* ✅ Sombra no hover */
    }

    .main-toggle-btn:focus {
      box-shadow: 0 0 0 2px rgba(255, 200, 46, 0.2);
    }

    .main-toggle-btn i {
      font-size: 0.8rem;
      transition: transform 0.2s ease;
    }

    /* ✅ Quando colapsada, centralizar e reduzir padding */
    .collapsed .toggle-container {
      justify-content: center;
      padding: 0.5rem;
    }

    /* ===== CAMPO DE PESQUISA ===== */
    .search-container {
      padding: 1rem;
      border-bottom: 1px solid var(--divider);
      flex-shrink: 0;
    }

    .search-input {
      width: 100%;
      padding: 0.75rem 1rem;
      border: 1px solid var(--divider);
      border-radius: 8px;
      background: var(--surface);
      color: var(--text-primary);
      font-size: 14px;
      outline: none;
      transition: all 0.2s ease;
    }

    .search-input:hover {
      border-color: var(--text-secondary);
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08); /* ✅ Sombra suave no hover */
    }

    .search-input:focus {
      border-color: var(--primary);
      box-shadow: 0 0 0 2px rgba(255, 200, 46, 0.2);
    }

    .search-input::placeholder {
      color: var(--text-secondary);
    }

    /* ===== MENU NAVEGAÇÃO ===== */
    .menu {
      flex: 1;
      padding: 0.5rem 0;
      overflow-y: auto; /* ✅ Scroll vertical */
      overflow-x: hidden;
    }

    .menu::-webkit-scrollbar {
      width: 4px;
    }

    .menu::-webkit-scrollbar-track {
      background: transparent;
    }

    .menu::-webkit-scrollbar-thumb {
      background: var(--divider);
      border-radius: 2px;
    }

    .menu ul {
      list-style: none;
      padding: 0;
      margin: 0;
    }

    .menu > ul > li {
      margin: 0.25rem 0.75rem;
    }

    /* ===== ITEM MENU ===== */
    .menu-item {
      padding: 0.75rem 1rem;
      display: flex;
      align-items: center;
      gap: 0.75rem;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.2s ease;
      text-decoration: none;
      color: var(--text-primary);
    }

    .menu-item:hover {
      background: var(--hover);
      transform: translateX(2px); /* ✅ Leve movimento para a direita */
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* ✅ Sombra suave */
      border-left: 3px solid var(--primary); /* ✅ Borda destacada */
    }

    /* ✅ Efeito hover mais destacado - sem conflitar com active */
    .menu-item:hover:not(.active) {
      background: rgba(241, 194, 50, 0.1); /* ✅ Tom dourado transparente */
      color: var(--text-primary);
    }

    /* ✅ DESTAQUE ATIVO - Tom igual à imagem */
    .menu-item.active,
    li.active > .menu-item {
      background: #f1c232 !important; /* Tom dourado mais suave */
      color: #1a1a1a !important;
      font-weight: 500;
      border-radius: 8px;
    }

    .menu-item i {
      font-size: 1.1rem;
      width: 20px;
      text-align: center;
      flex-shrink: 0;
    }

    .menu-text {
      flex: 1;
      font-size: 0.95rem;
    }

    .notification {
      background: var(--error);
      color: white;
      font-size: 0.7rem;
      padding: 0.2rem 0.4rem;
      border-radius: 10px;
      min-width: 16px;
      text-align: center;
    }

    .expand-icon {
      font-size: 0.8rem;
      transition: transform 0.3s ease;
    }

    .expand-icon.rotated {
      transform: rotate(180deg);
    }

    /* ===== SUBMENU ===== */
    .submenu {
      margin-top: 0.5rem;
      margin-left: 0.5rem; /* ✅ Indentação esquerda para hierarquia */
      border-left: 2px solid var(--divider); /* ✅ Linha visual de hierarquia */
      padding-left: 1rem; /* ✅ Espaçamento interno maior */
    }

    .submenu li {
      margin: 0.25rem 0;
    }

    .submenu-item {
      padding: 0.6rem 0.75rem; /* ✅ Padding ligeiramente maior */
      padding-left: 1.25rem; /* ✅ Espaçamento esquerdo maior para destacar hierarquia */
      margin-left: 0.5rem; /* ✅ Margem adicional para hierarquia visual */
      display: flex;
      align-items: center;
      gap: 0.5rem;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.2s ease;
      font-size: 0.9rem;
      color: var(--text-secondary);
      position: relative; /* Para poder adicionar elementos visuais */
    }

    /* ✅ Linha conectora visual para mostrar hierarquia */
    .submenu-item::before {
      content: '';
      position: absolute;
      left: -1rem;
      top: 50%;
      width: 0.75rem;
      height: 1px;
      background: var(--divider);
      transform: translateY(-50%);
    }

    .submenu-item:hover {
      background: var(--hover);
      color: var(--text-primary);
      transform: translateX(2px); /* ✅ Leve movimento para a direita */
      box-shadow: 0 1px 6px rgba(0, 0, 0, 0.08); /* ✅ Sombra mais sutil para subitens */
      border-left: 2px solid var(--primary); /* ✅ Borda destacada menor para subitens */
      margin-left: 0.3rem; /* ✅ Ajuste na margem para acomodar a borda */
    }

    /* ✅ Efeito hover para subitens - sem conflitar com active */
    .submenu-item:hover:not(.active) {
      background: rgba(241, 194, 50, 0.08); /* ✅ Tom dourado mais sutil para subitens */
    }

    /* ✅ DESTAQUE SUBMENU ATIVO - Tom igual à imagem */
    .submenu li.active .submenu-item {
      background: #f1c232 !important; /* Mesmo tom dourado */
      color: #1a1a1a !important;
      font-weight: 500;
      border-radius: 6px;
    }

    /* ===== INFORMAÇÕES EMPRESA E LICENÇA ===== */
    .license-info {
      padding: 1.25rem 1rem;
      border-top: 1px solid var(--divider);
      background: linear-gradient(135deg, var(--surface) 0%, var(--hover) 100%);
      color: var(--text-secondary);
      flex-shrink: 0;
      transition: all 0.3s ease;
    }

    /* Brand Section */
    .brand-section {
      display: flex;
      align-items: center;
      gap: 0.75rem;
      margin-bottom: 1rem;
      padding-bottom: 0.75rem;
      border-bottom: 1px solid var(--divider);
    }

    .brand-icon {
      width: 32px;
      height: 32px;
      background: var(--primary);
      color: white;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 1rem;
      box-shadow: 0 2px 8px rgba(241, 194, 50, 0.3);
    }

    .brand-text {
      flex: 1;
    }

    .company-name {
      font-weight: 700;
      font-size: 0.9rem;
      color: var(--primary);
      margin-bottom: 0.25rem;
      letter-spacing: 0.5px;
    }

    .software-name {
      font-size: 0.75rem;
      color: var(--text-secondary);
      font-weight: 500;
      opacity: 0.8;
    }

    /* Legal Info */
    .legal-info {
      margin-bottom: 1rem;
    }

    .cnpj-info,
    .license-info-text {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      margin-bottom: 0.5rem;
      font-size: 0.7rem;
      color: var(--text-secondary);
      opacity: 0.9;
    }

    .cnpj-info i,
    .license-info-text i {
      width: 12px;
      text-align: center;
      color: var(--primary);
      opacity: 0.7;
    }

    /* Version Info */
    .version-info {
      padding: 0.5rem;
      font-size: 0.75rem;
      color: var(--text-secondary);
      display: flex;
      align-items: center;
      gap: 0.375rem;
      border-top: 1px solid var(--divider);
      margin-top: auto;
    }

    .version-info i {
      font-size: 0.7rem;
    }

    /* ===== COLLAPSED STATE ===== */
    .collapsed .menu-text,
    .collapsed .notification,
    .collapsed .expand-icon,
    .collapsed .submenu,
    .collapsed .search-container,
    .collapsed .license-content {
      display: none;
    }

    /* ✅ Ocultar ícone da versão quando colapsada */
    .collapsed .version-info i {
      display: none;
    }

    .collapsed .menu-item {
      justify-content: center;
      padding: 0.75rem 0.5rem;
    }

    /* ✅ Estado colapsado da seção de licença */
    .collapsed .license-info {
      padding: 0.75rem 0.5rem;
      text-align: center;
    }

    /* ===== MOBILE STYLES ===== */
    @media (max-width: 768px) {
      .sidebar {
        position: fixed !important;
        top: 60px !important; /* Abaixo do header */
        left: 0 !important;
        width: 240px !important;
        height: calc(100vh - 60px - 60px) !important; /* Header + espaço inferior */
        max-height: calc(100vh - 60px - 60px) !important;
        z-index: 1002 !important;
        border-radius: 0 16px 16px 0 !important;
        transform: translateX(-100%) !important;
        opacity: 0 !important;
        pointer-events: none !important;
        margin-left: 0 !important;
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3) !important;
      }

      .sidebar.force-visible {
        transform: translateX(0) !important;
        opacity: 1 !important;
        pointer-events: all !important;
        visibility: visible !important;
      }

      /* ✅ Ajustes específicos para mobile */
      .sidebar .menu {
        max-height: calc(100vh - 60px - 60px - 120px) !important; /* Desconta header + footer + seção licença */
        overflow-y: auto !important;
        flex: 1 !important;
      }

      .sidebar .license-info {
        flex-shrink: 0 !important;
        margin-top: auto !important;
      }

      /* Overlay para fechar ao clicar fora */
      .sidebar.force-visible::before {
        content: '';
        position: fixed;
        top: 0;
        left: 240px;
        width: calc(100vw - 240px);
        height: 100vh;
        background: rgba(0, 0, 0, 0.5);
        z-index: -1;
        pointer-events: all;
      }

      /* Estados collapsed não se aplicam em mobile */
      .sidebar.collapsed {
        width: 240px;
      }

      .collapsed .menu-text,
      .collapsed .notification,
      .collapsed .expand-icon,
      .collapsed .submenu,
      .collapsed .search-container,
      .collapsed .license-content {
        display: block;
      }

      .collapsed .menu-item {
        justify-content: flex-start;
        padding: 0.75rem 1rem;
      }
    }

    /* ===== TEMAS ===== */
    /* Tema claro já definido pelas variáveis CSS */

    /* Tema escuro */
    .dark-theme .sidebar {
      background: var(--sidebar-bg-dark, #1e1e1e);
      color: var(--text-primary-dark, #e0e0e0);
    }

    .dark-theme .search-input {
      background: var(--surface-dark, #2a2a2a);
      border-color: var(--divider-dark, #404040);
      color: var(--text-primary-dark, #e0e0e0);
    }

    .dark-theme .search-input::placeholder {
      color: var(--text-secondary-dark, #999);
    }

    /* ✅ Tema escuro - Efeitos de hover melhorados */
    .dark-theme .menu-item:hover:not(.active) {
      background: rgba(241, 194, 50, 0.12); /* ✅ Tom dourado para tema escuro */
      color: var(--text-primary-dark, #e0e0e0);
      border-left: 3px solid #f1c232;
    }

    .dark-theme .submenu-item:hover:not(.active) {
      background: rgba(241, 194, 50, 0.08); /* ✅ Tom dourado mais sutil para subitens */
      color: var(--text-primary-dark, #e0e0e0);
      border-left: 2px solid #f1c232;
    }

    .dark-theme .main-toggle-btn:hover {
      background: rgba(255, 255, 255, 0.1);
      border-color: #f1c232;
      color: #f1c232;
    }

    .dark-theme .search-input:hover {
      border-color: rgba(255, 255, 255, 0.3);
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
    }

    /* ✅ Tema escuro - Seção de licença */
    .dark-theme .license-info {
      background: linear-gradient(135deg, var(--surface-dark, #2a2a2a) 0%, rgba(255, 255, 255, 0.05) 100%);
      border-top-color: var(--divider-dark, #404040);
    }

    .dark-theme .brand-section {
      border-bottom-color: var(--divider-dark, #404040);
    }

    .dark-theme .brand-icon {
      background: #f1c232;
      color: #1a1a1a;
    }

    .dark-theme .company-name {
      color: #f1c232;
    }

    .dark-theme .software-name,
    .dark-theme .cnpj-info,
    .dark-theme .license-info-text {
      color: var(--text-secondary-dark, #999);
    }

    .dark-theme .cnpj-info i,
    .dark-theme .license-info-text i {
      color: #f1c232;
    }

    /* ===== RESPONSIVE ===== */
    @media (max-width: 768px) {
      .sidebar {
        left: 0 !important;
        border-radius: 0 !important;
        width: 100% !important;
        height: calc(100vh - 60px) !important;
        top: 60px !important;
        transform: translateX(-100%);
        transition: transform 0.3s ease;
      }

      .sidebar.force-visible {
        transform: translateX(0);
        box-shadow: none !important;
      }

      .sidebar.collapsed {
        width: 100% !important;
        transform: translateX(-100%);
      }

      .toggle-container {
        display: none !important;
      }

      .license-info {
        padding: 1rem 1.5rem !important;
      }

      .brand-section,
      .legal-info {
        padding: 0.5rem 0 !important;
      }
    }

    /* 🚫 ESTILOS PARA ITENS DESABILITADOS */
    .menu li.disabled,
    .submenu li.disabled {
      opacity: 0.5;
      pointer-events: none;
    }

    .menu li.disabled .menu-item,
    .submenu li.disabled .submenu-item {
      cursor: not-allowed;
      color: var(--text-disabled, #999) !important;
    }

    .menu li.disabled .menu-item:hover,
    .submenu li.disabled .submenu-item:hover {
      background: transparent !important;
      color: var(--text-disabled, #999) !important;
    }

    .disabled-icon {
      color: var(--warning, #f59e0b) !important;
      font-size: 0.75rem !important;
      margin-left: auto;
    }

    /* Tooltip para itens desabilitados */
    .menu-item[title]:hover::after,
    .submenu-item[title]:hover::after {
      content: attr(title);
      position: absolute;
      background: var(--surface-dark, #2d3748);
      color: var(--text-primary);
      padding: 0.5rem;
      border-radius: 4px;
      font-size: 0.75rem;
      white-space: nowrap;
      z-index: 1000;
      top: 100%;
      left: 0;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    }

    .collapsed .menu-item[title]:hover::after {
      left: 100%;
      top: 0;
      margin-left: 0.5rem;
    }
  `]
})
export class SidebarComponent implements OnInit, OnDestroy {
  @Output() collapsedChange = new EventEmitter<boolean>();
  isCollapsed = false;
  isHiddenInMobile = false;
  isForcedVisible = false;
  searchTerm = '';
  selectedItem: string | null = null;
  isTemporarilyExpanded = false; // ✅ Para expansão temporária quando collapsed
  private isDarkMode = false;
  private themeSubscription = new Subscription();
  private routerSubscription = new Subscription();
  
  // 🚫 CONFIGURAÇÃO DE BLOQUEIOS TEMPORÁRIOS
  // Para habilitar/desabilitar itens para deploy, modifique aqui:
  private temporaryBlocks: { [key: string]: boolean } = {
    'maintenance': true,        // ✅ BLOQUEAR Manutenção
    'reports': true,           // ✅ BLOQUEAR Relatórios  
    'settings': false,          // ✅ BLOQUEAR Configurações
    'finances': false,         // ✅ LIBERAR Finanças
    'routes/shopee': false,     // ✅ BLOQUEAR Shopee (submenu)
    'routes/mercado-live': false,     // ✅ BLOQUEAR Mercado Live (submenu)
    'integration': false,            // ✅ BLOQUEAR Integrações
    // Adicione mais IDs conforme necessário
  };

  menuItems: MenuItem[] = [
    { id: 'dashboard', label: 'Dashboard', icon: 'fa fa-home', notifications: 0 },
    { 
      id: 'vehicle-group', 
      label: 'Veículos', 
      icon: 'fa fa-car', 
      notifications: 0,
      expanded: false,
      children: [
        { id: 'vehicles', label: 'Veículos', icon: 'fa fa-car', notifications: 0 },
        { id: 'fuelcontroll', label: 'Controle de Combustível', icon: 'fas fa-folder', notifications: 0 },
        { id: 'devicetracker', label: 'Rastreadores', icon: 'fas fa-folder', notifications: 0 },
        { id: 'tollparking', label: 'Pedágio & Estacionamento', icon: 'fa fa-road', notifications: 0 },
        { id: 'fines', label: 'Multas', icon: 'fas fa-exclamation-triangle', notifications: 0 },                
      ]
    },
    { 
      id: 'drivers', 
      label: 'Motoristas', 
      icon: 'fa fa-user', 
      notifications: 0,
      expanded: false,
      children: [
        { id: 'drivers', label: 'Motoristas', icon: 'fa fa-user', notifications: 0 },
        { id: 'driverperformance', label: 'Performance', icon: 'fas fa-folder', notifications: 0 },

      ]
    },
    // { id: 'drivers', label: 'Motoristas', icon: 'fa fa-user', notifications: 0 },
    { id: 'maintenance', label: 'Manutenção', icon: 'fa fa-wrench', notifications: 0 },
    { 
      id: 'finances', 
      label: 'Finanças', 
      icon: 'fa fa-line-chart', 
      notifications: 0,
      expanded: false,
      children: [
        { id: 'finances/accountpayable', label: 'Contas a Pagar', icon: 'fa fa-file-text', notifications: 0 },
        { id: 'finances/categories', label: 'Categorias Financeiras', icon: 'fa fa-tags', notifications: 0 },
        { id: 'finances/supplier', label: 'Fornecedores', icon: 'fa fa-truck', notifications: 0 },
        { id: 'customer', label: 'Clientes', icon: 'fas fa-folder', notifications: 0 },    
        { id: 'contract', label: 'Contratos', icon: 'fas fa-folder', notifications: 0 },    
      ]
    },
    { 
      id: 'routes', 
      label: 'Rotas', 
      icon: 'fa fa-map', 
      notifications: 0,
      expanded: false,
      children: [
        { id: 'routes', label: 'Todas as Rotas', icon: 'fa fa-map', notifications: 0 },
        // { id: 'routes/mercado-live', label: 'Mercado Live', icon: 'fa fa-shopping-cart', notifications: 0 },
        // { id: 'routes/shopee', label: 'Shopee', icon: 'fa fa-store', notifications: 0 }
      ]
    },
    { id: 'reports', label: 'Relatórios', icon: 'fa fa-bar-chart', notifications: 0 },
    { id: 'integration', label: 'Integrações', icon: 'fa fa-link', notifications: 0 },
    { 
      id: 'settings', 
      label: 'Configurações', 
      icon: 'fa fa-cog', 
      notifications: 0,
      expanded: false,
      children: [
        { id: 'company', label: 'Empresas', icon: 'fa fa-building', notifications: 0 },
        { id: 'person', label: 'Pessoas', icon: 'fas fa-folder', notifications: 0 },
        { id: 'product', label: 'Produtos', icon: 'fas fa-folder', notifications: 0 },
        { id: 'user', label: 'Usuários', icon: 'fa fa-users', notifications: 0 },
        { id: 'preferences', label: 'Preferências', icon: 'fa fa-sliders', notifications: 0 }
      ]
    },
  ];
  
  filteredMenuItems: MenuItem[] = [...this.menuItems];
  private mediaQuery: MediaQueryList;
  private mediaQueryListener: ((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null = null;

  constructor(
    private router: Router, 
    private mobileMenuService: MobileMenuService, 
    private themeService: ThemeService
  ) {
    this.mediaQuery = window.matchMedia('(max-width: 768px)');
    this.isHiddenInMobile = this.mediaQuery.matches;
    // ✅ Iniciar sempre colapsada (tanto mobile quanto desktop)
    this.isCollapsed = true;
  }

  ngOnInit() {
    // 🚫 Aplicar bloqueios temporários
    this.applyTemporaryBlocks();

    this.themeSubscription = this.themeService.isDarkMode$.subscribe(isDark => {
      this.isDarkMode = isDark;
    });

    // ✅ Escutar mudanças de rota para sincronizar seleção
    this.routerSubscription = this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe((event) => {
        this.updateSelectedItemFromRoute((event as NavigationEnd).url);
      });

    this.mediaQueryListener = (e: MediaQueryListEvent) => {
      const isMobile = e.matches;
      this.isHiddenInMobile = isMobile;
      this.isCollapsed = isMobile;
      
      if (isMobile) {
        this.isForcedVisible = false;
        this.updateSidebarClasses();
        this.mobileMenuService.setSidebarVisible(false);
      }
      
      this.collapsedChange.emit(this.isCollapsed);
    };

    this.mediaQuery.addEventListener('change', this.mediaQueryListener);
    
    // ✅ Inicializar seleção baseada na URL atual
    this.updateSelectedItemFromRoute(this.router.url);
    this.updateSidebarClasses();

    // ✅ Emitir estado inicial da sidebar
    this.collapsedChange.emit(this.isCollapsed);

    // ✅ Fechar ao clicar fora
    document.addEventListener('click', this.handleOutsideClick.bind(this));
  }

  ngOnDestroy() {
    this.themeSubscription.unsubscribe();
    this.routerSubscription.unsubscribe();
    
    if (this.mediaQueryListener) {
      this.mediaQuery.removeEventListener('change', this.mediaQueryListener);
    }
    
    document.removeEventListener('click', this.handleOutsideClick.bind(this));
  }

  private handleOutsideClick(event: Event) {
    const isMobile = this.mediaQuery.matches;
    const target = event.target as HTMLElement;
    const sidebar = document.querySelector('.sidebar') as HTMLElement;
    
    // ✅ Fechar expansão temporária quando clicar fora (desktop)
    if (!isMobile && this.isTemporarilyExpanded && sidebar && !sidebar.contains(target)) {
      this.closeTemporaryExpansion();
    }
    
    // Comportamento existente para mobile
    if (isMobile && this.isForcedVisible) {
      const mobileFooterMenu = document.querySelector('.mobile-footer-menu') as HTMLElement;
      
      if (sidebar && !sidebar.contains(target) && 
          mobileFooterMenu && !mobileFooterMenu.contains(target)) {
        this.hideMobileSidebar();
      }
    }
  }

  toggleSidebar() {
    const isMobile = this.mediaQuery.matches;
    
    if (isMobile) {
      this.isForcedVisible = !this.isForcedVisible;
      this.updateSidebarClasses();
      this.mobileMenuService.setSidebarVisible(this.isForcedVisible);
    } else {
      this.isCollapsed = !this.isCollapsed;
      this.collapsedChange.emit(this.isCollapsed);
    }
  }

  private updateSidebarClasses() {
    const sidebar = document.querySelector('.sidebar') as HTMLElement;
    if (sidebar) {
      const isMobile = this.mediaQuery.matches;
      
      if (isMobile) {
        sidebar.classList.remove('force-visible');
        if (this.isForcedVisible) {
          sidebar.classList.add('force-visible');
        }
      } else {
        sidebar.classList.remove('force-visible');
      }
    }
  }

  public showMobileSidebar() {
    if (this.mediaQuery.matches) {
      this.isForcedVisible = true;
      this.updateSidebarClasses();
      this.mobileMenuService.setSidebarVisible(true);
    }
  }

  public hideMobileSidebar() {
    if (this.mediaQuery.matches) {
      this.isForcedVisible = false;
      this.updateSidebarClasses();
      this.mobileMenuService.setSidebarVisible(false);
    }
  }

  public get isMobile(): boolean {
    return this.mediaQuery.matches;
  }

  public get isVisible(): boolean {
    const isMobile = this.mediaQuery.matches;
    return isMobile ? this.isForcedVisible : true;
  }

  selectMenuItem(item: MenuItem) {
    // 🚫 Não processar itens desabilitados
    if (item.disabled) {
      return;
    }

    const isMobile = this.mediaQuery.matches;
    
    if (item.children && item.children.length > 0) {
      // ✅ Se está collapsed no desktop, expandir temporariamente
      if (this.isCollapsed && !isMobile) {
        this.isTemporarilyExpanded = true;
        item.expanded = true;
        
        // ✅ Auto-fechar após 10 segundos se nenhum subitem for clicado
        setTimeout(() => {
          if (this.isTemporarilyExpanded && this.isCollapsed) {
            this.closeTemporaryExpansion();
          }
        }, 10000);
      } else {
        // Comportamento normal quando não está collapsed
        item.expanded = !item.expanded;
      }
    } else {
      this.selectedItem = item.id;
      
      // ✅ Se era uma seleção de subitem e estava temporariamente expandida
      if (this.isTemporarilyExpanded && this.isCollapsed && !isMobile) {
        this.closeTemporaryExpansion();
      }
      
      // Fechar sidebar no mobile após seleção
      if (isMobile) {
        this.hideMobileSidebar();
      }
      
      const routePath = `/app/${item.id}`;
      this.router.navigate([routePath]);
    }
  }

  filterMenuItems() {
    if (!this.searchTerm.trim()) {
      this.filteredMenuItems = [...this.menuItems];
      return;
    }

    const searchLower = this.searchTerm.toLowerCase();
    this.filteredMenuItems = this.menuItems.filter(item => {
      const matchesParent = item.label.toLowerCase().includes(searchLower);
      const matchesChildren = item.children?.some(child => 
        child.label.toLowerCase().includes(searchLower)
      );
      return matchesParent || matchesChildren;
    });
  }

  // ✅ Atualizar item selecionado baseado na URL atual
  private updateSelectedItemFromRoute(url: string) {
    // Remover /app/ do início da URL
    const routePath = url.replace(/^\/app\//, '');
    
    // Primeiro, limpar qualquer seleção anterior
    this.selectedItem = null;
    
    // Procurar nos itens principais
    for (const item of this.menuItems) {
      // Verificar item principal
      if (item.id === routePath) {
        this.selectedItem = item.id;
        return;
      }
      
      // Verificar subitens
      if (item.children) {
        for (const child of item.children) {
          if (child.id === routePath) {
            this.selectedItem = child.id;
            // Expandir o item pai automaticamente
            item.expanded = true;
            return;
          }
        }
      }
    }
    
    // Se não encontrou correspondência exata, definir como dashboard por padrão
    if (!this.selectedItem) {
      this.selectedItem = 'dashboard';
    }
  }

  /**
   * ✅ Fecha a expansão temporária e recolhe todos os menus
   */
  private closeTemporaryExpansion() {
    this.isTemporarilyExpanded = false;
    
    // Recolher todos os itens expandidos
    this.menuItems.forEach(item => {
      if (item.children) {
        item.expanded = false;
      }
    });
  }

  /**
   * 🚫 Aplica bloqueios temporários aos menu items
   * Chamado no ngOnInit para configurar os bloqueios
   */
  private applyTemporaryBlocks(): void {
    this.menuItems = this.menuItems.map(item => {
      // Verificar se o item principal está bloqueado
      if (this.temporaryBlocks[item.id]) {
        item.disabled = true;
        item.disabledReason = 'Funcionalidade temporariamente indisponível para manutenção';
      }

      // Verificar se tem filhos e aplicar bloqueios nos submenus
      if (item.children) {
        item.children = item.children.map(child => {
          if (this.temporaryBlocks[child.id]) {
            child.disabled = true;
            child.disabledReason = 'Funcionalidade temporariamente indisponível para manutenção';
          }
          return child;
        });
      }

      return item;
    });

    // Atualizar itens filtrados
    this.filteredMenuItems = [...this.menuItems];
  }
} 