import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { Subscription } from 'rxjs';

import { TitleService } from '../../services/theme/title.service';
import { ThemeService } from '../../services/theme/theme.service';
import { HeaderActionsService, HeaderConfig } from '../../services/header-actions.service';
import { NotificationsComponent } from '../notifications/notifications.component';
import { AuthService, AuthUser } from '../../services/auth/auth.service';

interface Notification {
  id: number;
  message: string;
  type: 'info' | 'warning' | 'error';
  time: string;
}

@Component({
  selector: 'app-header',
  standalone: true,
  imports: [
    CommonModule, 
    RouterLink, 
    MatButtonModule, 
    MatIconModule, 
    MatTooltipModule,
    NotificationsComponent
  ],
  template: `
    <header class="header" [class.header-expanded]="sidebarExpanded">
      <div class="header-content">
        <div class="header-left">
          <div class="logo-container">
            <img [src]="getCurrentLogo()" alt="PraFrota" class="logo">
          </div>
          <div class="header-title">
            <h1>{{ pageTitle$ | async }}</h1>
          
            <!-- Contador discreto de registros -->
            <div class="record-count" *ngIf="headerConfig && headerConfig.recordCount !== undefined">
              <span class="count-badge">
                {{ headerConfig.recordCount }}
                <span class="domain-label">{{ getDomainLabel(headerConfig.domain) }}</span>
              </span>
            </div>
          </div>
        </div>
        
        <div class="header-actions">
          
          <!-- Ações dinâmicas do domínio -->
          <div class="domain-actions" *ngIf="headerConfig && headerConfig.actions.length > 0">
            <ng-container *ngFor="let action of headerConfig.actions">
              <button 
                *ngIf="action.visible"
                mat-raised-button
                [disabled]="action.disabled"
                [matTooltip]="action.tooltip || ''"
                (click)="executeAction(action.id)"
                class="domain-action"
                [class.primary-action]="action.type === 'primary'"
                [class.secondary-action]="action.type === 'secondary'">
                <mat-icon class="desktop-only">{{ action.icon }}</mat-icon>
                <span class="action-text desktop-text">{{ action.label }}</span>
                <span class="action-text mobile-text">Novo</span>
              </button>
            </ng-container>
          </div>
          
          <!-- Divisor se houver ações do domínio -->
          <div class="actions-divider" *ngIf="headerConfig && headerConfig.actions.length > 0"></div>
          
          <!-- Switch do tema removido - agora apenas no menu do usuário -->
          
          <!-- Notificações - TEMPORARIAMENTE OCULTAS EM MOBILE -->
          <!-- TODO: Reposicionar notificações em local adequado para mobile -->
          <!-- <app-notifications></app-notifications> -->
          <app-notifications class="desktop-only"></app-notifications>

          <!-- Menu do usuário -->
          <div class="user-menu" (click)="toggleUserMenu()" [class.active]="showUserMenu">
            <div class="avatar">
              <img [src]="getUserAvatar()" alt="Avatar do usuário">
            </div>
            <span class="user-name desktop-text">{{ currentUser?.name || 'Usuário' }}</span>
            <span class="user-name mobile-text">{{ getDisplayUserName() }}</span>
            <i class="fas fa-chevron-down"></i>

            <!-- Dropdown do Menu do Usuário -->
            <div class="user-dropdown" *ngIf="showUserMenu">
              <a routerLink="/app/profile" (click)="closeUserMenu()">
                <i class="fas fa-user"></i>
                Perfil
              </a>
              <a routerLink="/app/settings" (click)="closeUserMenu()">
                <i class="fas fa-cog"></i>
                Configurações
              </a>
              
              <!-- Opção de tema (sempre visível) -->
              <a class="theme-toggle" (click)="toggleTheme()">
                <i class="fas" [class.fa-moon]="!(themeService.isDarkMode$ | async)" [class.fa-sun]="themeService.isDarkMode$ | async"></i>
                {{ (themeService.isDarkMode$ | async) ? 'Modo Claro' : 'Modo Escuro' }}
              </a>
              
              <div class="dropdown-divider"></div>
              <a (click)="logout()">
                <i class="fas fa-sign-out-alt"></i>
                Sair
              </a>
            </div>
          </div>
        </div>
      </div>
    </header>
  `,
  styles: [`
    .header {
      padding: 0.4rem 1rem;
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      height: 60px;
      z-index: 1001;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      width: 100%;
      background: #fff;
      /* Gradiente moderno com cores da aplicação */
      // background: linear-gradient(
      //   135deg,
      //   rgba(255, 255, 255, 0.95) 0%,
      //   rgba(255, 200, 46, 0.1) 30%,
      //   rgba(255, 200, 46, 0.15) 70%,
      //   rgba(255, 200, 46, 0.2) 100%
      // );
      
      /* Efeito glassmorphism */
      backdrop-filter: blur(20px) saturate(180%);
      -webkit-backdrop-filter: blur(20px) saturate(180%);
      
      /* Borda com cor primary */
      border-bottom: 1px solid rgba(255, 200, 46, 0.2);
      
      /* Sombra inicial com toque primary */
      box-shadow: 
        0 1px 3px rgba(255, 200, 46, 0.1),
        0 1px 2px rgba(0, 0, 0, 0.05),
        inset 0 1px 0 rgba(255, 255, 255, 0.6);
      
      color: var(--text-primary);
      
      /* Animação de entrada */
      animation: headerSlideIn 0.6s ease-out;
    }

    /* Tema escuro - gradiente com cores da aplicação */
    :host-context(.dark-theme) .header {
      background: linear-gradient(
        135deg,
        rgba(0, 0, 0, 0.95) 0%,
        rgba(255, 200, 46, 0.1) 50%,
        rgba(255, 200, 46, 0.05) 100%
      );
      border-bottom: 1px solid rgba(255, 200, 46, 0.3);
      box-shadow: 
        0 1px 3px rgba(0, 0, 0, 0.3),
        0 1px 2px rgba(0, 0, 0, 0.2),
        inset 0 1px 0 rgba(255, 200, 46, 0.1);
    }

    @keyframes headerSlideIn {
      from {
        transform: translateY(-60px);
        opacity: 0;
      }
      to {
        transform: translateY(0);
        opacity: 1;
      }
    }

    /* Header agora sempre ocupa largura total */

    /* Sombra dinâmica quando houver scroll */
    .header.scrolled {
      box-shadow: 
        0 8px 32px rgba(255, 200, 46, 0.2),
        0 4px 16px rgba(0, 0, 0, 0.1),
        inset 0 1px 0 rgba(255, 255, 255, 0.6);
      
      /* Intensifica o blur quando há scroll */
      backdrop-filter: blur(25px) saturate(200%);
      -webkit-backdrop-filter: blur(25px) saturate(200%);
    }

    :host-context(.dark-theme) .header.scrolled {
      box-shadow: 
        0 8px 32px rgba(255, 200, 46, 0.3),
        0 4px 16px rgba(0, 0, 0, 0.4),
        inset 0 1px 0 rgba(255, 200, 46, 0.1);
    }

    .header-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 100%;
    }

    .header-left {
      display: flex;
      align-items: center;
      gap: 1.5rem;
    }

    .logo-container {
      display: flex;
      align-items: center;
    }

    .logo {
      height: 32px;
      width: auto;
      object-fit: contain;
    }

    .header-title {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      flex: 1;
      
      h1 {
        margin: 0;
        font-size: 1rem;
        font-weight: 600;
        
        /* Cores aplicadas baseadas no tema */
        color: #000000;
        
        /* Efeito de gradiente dourado para texto no tema claro */
        background: linear-gradient(135deg, #000000 0%, #000000 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        
        /* Sombra sutil para legibilidade */
        filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.1));
        
        /* Animação de entrada */
        animation: titleSlideIn 0.8s ease-out 0.2s both;
        
        /* Quebra de linha responsiva */
        word-break: break-word;
        line-height: 1.2;
      }
    }

    /* === LAYOUT RESPONSIVO PADRÃO === */
    /* Desktop: mostrar layout desktop por padrão */
    .desktop-layout {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      flex: 1;
    }
    
    /* Mobile: esconder layout mobile por padrão */
    .mobile-layout {
      display: none;
    }

    /* Esconder layout móvel específico por padrão */
    .header-title-mobile {
      display: none;
    }

    /* Contador de registros */
    .record-count {
      margin-left: 0.5rem;
      
      .count-badge {
        display: inline-flex;
        align-items: center;
        padding: 0.25rem 0.75rem;
        font-size: 0.8rem;
        font-weight: 500;
        border-radius: 12px;
        
        /* Estilo discreto com cores da aplicação */
        background: linear-gradient(135deg, 
          rgba(255, 200, 46, 0.15) 0%, 
          rgba(255, 200, 46, 0.25) 100%
        );
        color: #000000;
        border: 1px solid rgba(255, 200, 46, 0.3);
        
        /* Efeito glassmorphism */
        backdrop-filter: blur(10px);
        -webkit-backdrop-filter: blur(10px);
        
        /* Transição suave */
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        
        /* Sombra sutil */
        box-shadow: 0 2px 4px rgba(255, 200, 46, 0.1);
        
        /* ✅ Texto do domínio com espaçamento */
        .domain-label {
          margin-left: 0.25rem;
        }
      }
    }

    /* Tema escuro - contador */
    :host-context(.dark-theme) .record-count .count-badge {
      background: linear-gradient(135deg, 
        rgba(255, 200, 46, 0.2) 0%, 
        rgba(255, 200, 46, 0.1) 100%
      );
      color: #FFC82E;
      border-color: rgba(255, 200, 46, 0.4);
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    }

    /* Tema escuro - título */
    :host-context(.dark-theme) .header-title h1 {
      /* Gradiente dourado no tema escuro */
      background: linear-gradient(135deg, #FFC82E 0%, #FFD700 50%, #FFA500 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      filter: drop-shadow(0 1px 3px rgba(0, 0, 0, 0.3));
    }

    /* Navegação principal */
    .header-nav {
      display: flex;
      align-items: center;
      gap: 1rem;
    }

    .nav-link {
      text-decoration: none;
      padding: 0.5rem 1rem;
      border-radius: 4px;
      transition: all 0.2s ease;
      color: var(--text-secondary);
      font-size: 0.875rem;
      font-weight: 500;

      &:hover {
        background: var(--hover-bg);
        color: var(--text-primary);
      }

      &.active {
        background: var(--primary);
        color: white;
      }
    }

    .header-actions {
      display: flex;
      align-items: center;
      gap: 1rem;
      position: relative;
    }

    /* Estilos para ações do domínio */
    .domain-actions {
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }

    .domain-action {
      display: flex;
      align-items: center;
      gap: 0.375rem;
      padding: 0.375rem 0.75rem;
      border-radius: 8px;
      font-size: 0.875rem;
      font-weight: 500;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      cursor: pointer;
      border: 1px solid transparent;
      position: relative;
      overflow: hidden;
    }

    .primary-action {
      background: linear-gradient(135deg, #FFC82E 0%, #FFB300 100%);
      color: #000000;
      border-color: transparent;
      box-shadow: 0 2px 8px rgba(255, 200, 46, 0.3);

      &:hover:not(:disabled) {
        background: linear-gradient(135deg, #FFD700 0%, #FFC82E 100%);
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(255, 200, 46, 0.4);
      }

      &:active {
        transform: translateY(-1px);
      }
    }

    .secondary-action {
      background: rgba(255, 255, 255, 0.7);
      color: #000000;
      border-color: rgba(255, 200, 46, 0.3);
      backdrop-filter: blur(10px);

      &:hover:not(:disabled) {
        background: rgba(255, 200, 46, 0.1);
        color: #000000;
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(255, 200, 46, 0.2);
      }
    }

    :host-context(.dark-theme) .secondary-action {
      background: rgba(0, 0, 0, 0.5);
      border-color: rgba(255, 200, 46, 0.4);
      color: #FFC82E;

      &:hover:not(:disabled) {
        background: rgba(255, 200, 46, 0.1);
        color: #FFD700;
      }
    }

    .domain-action:disabled {
      opacity: 0.6;
      cursor: not-allowed;
      transform: none !important;
    }

    .domain-action mat-icon {
      font-size: 1.1rem;
      width: 1.1rem;
      height: 1.1rem;
    }

    .actions-divider {
      width: 1px;
      height: 24px;
      background: var(--divider);
      margin: 0 0.5rem;
    }

    /* Estilos das Notificações */
    .notifications-menu {
      position: relative;
    }

    .notifications-dropdown {
      position: absolute;
      top: calc(100% + 10px); /* Espaço entre o ícone e o dropdown */
      right: 0;
      width: 300px;
      background: var(--header-bg);
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      z-index: 1000;
    }

    .notifications-header {
      padding: 0.5rem;
      background: var(--surface);
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .notifications-list {
      background: var(--header-bg);
      color: var(--text-primary);
      max-height: 300px;
      overflow-y: auto;
    }

    .mark-all-read {
      background: none;
      border: none;
      color: var(--primary);
      cursor: pointer;
      font-size: 0.875rem;
    }


    /* Estilos do Menu do Usuário */
    .user-menu {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      cursor: pointer;
      position: relative;
      color: #000000;
      padding: 0.5rem 0.75rem;
      border-radius: 12px;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      background: rgba(255, 255, 255, 0.6);
      backdrop-filter: blur(10px);
      border: 1px solid rgba(255, 200, 46, 0.2);

      &:hover {
        background: rgba(255, 200, 46, 0.1);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(255, 200, 46, 0.2);
        border-color: rgba(255, 200, 46, 0.4);
      }

      &.active {
        background: rgba(255, 200, 46, 0.15);
        border-color: rgba(255, 200, 46, 0.5);
      }
    }

    :host-context(.dark-theme) .user-menu {
      background: rgba(0, 0, 0, 0.5);
      border-color: rgba(255, 200, 46, 0.3);
      color: #FFC82E;

      &:hover {
        background: rgba(255, 200, 46, 0.1);
        border-color: rgba(255, 200, 46, 0.6);
      }

      &.active {
        background: rgba(255, 200, 46, 0.2);
        border-color: rgba(255, 200, 46, 0.7);
      }
    }

    .avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      overflow: hidden;
      border: 2px solid rgba(255, 200, 46, 0.4);
      transition: all 0.3s ease;
    }

    .user-menu:hover .avatar {
      border-color: #FFC82E;
      transform: scale(1.05);
    }

    .avatar img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .user-name {
      font-weight: 500;
      color: #000000;
    }

    :host-context(.dark-theme) .user-name {
      color: #FFC82E;
    }

    .user-role {
      color: var(--text-secondary);
    }

    .user-dropdown {
      position: absolute;
      top: calc(100% + 8px);
      right: 0;
      width: 220px;
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(20px);
      border-radius: 12px;
      box-shadow: 
        0 20px 25px -5px rgba(0, 0, 0, 0.1),
        0 10px 10px -5px rgba(0, 0, 0, 0.04);
      margin-top: 0.5rem;
      padding: 0.5rem 0;
      border: 1px solid rgba(255, 255, 255, 0.3);
      
      /* Animação de entrada */
      animation: dropdownSlideIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      transform-origin: top right;
    }

    :host-context(.dark-theme) .user-dropdown {
      background: rgba(51, 65, 85, 0.95);
      border-color: rgba(148, 163, 184, 0.3);
      box-shadow: 
        0 20px 25px -5px rgba(0, 0, 0, 0.4),
        0 10px 10px -5px rgba(0, 0, 0, 0.2);
    }

    @keyframes dropdownSlideIn {
      from {
        opacity: 0;
        transform: scale(0.95) translateY(-5px);
      }
      to {
        opacity: 1;
        transform: scale(1) translateY(0);
      }
    }

    .user-dropdown a {
      display: flex;
      align-items: center;
      gap: 0.75rem;
      padding: 0.75rem 1rem;
      color: #000000;
      text-decoration: none;
      transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
      margin: 0 0.25rem;
      border-radius: 8px;
      position: relative;

      &:hover {
        background: rgba(255, 200, 46, 0.1);
        color: #000000;
        transform: translateX(4px);
      }

      i {
        font-size: 0.875rem;
        width: 16px;
        text-align: center;
        color: #FFC82E;
      }
    }

    :host-context(.dark-theme) .user-dropdown a {
      color: #FFC82E;

      i {
        color: #FFC82E;
      }

      &:hover {
        background: rgba(255, 200, 46, 0.2);
        color: #FFD700;
      }
    }

    .dropdown-divider {
      height: 1px;
      background: linear-gradient(
        90deg,
        transparent 0%,
        rgba(255, 200, 46, 0.4) 50%,
        transparent 100%
      );
      margin: 0.5rem 1rem;
    }

    /* Estilo específico para o toggle de tema no menu */
    .user-dropdown .theme-toggle {
      border-left: 3px solid transparent;
      transition: all 0.2s ease;
      
      &:hover {
        border-left-color: #FFC82E;
        background: rgba(255, 200, 46, 0.1);
      }
    }

    :host-context(.dark-theme) .user-dropdown .theme-toggle:hover {
      border-left-color: #FFD700;
      background: rgba(255, 200, 46, 0.15);
    }

    .notification-item.unread {
      background-color: rgba(255, 200, 46, 0.1);
    }

    .switch {
      position: relative;
      display: inline-block;
      width: 52px;
      height: 28px;
      background: transparent;
    }

    .switch input {
      opacity: 0;
      width: 0;
      height: 0;
    }

    .slider {
      position: absolute;
      cursor: pointer;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(135deg, rgba(255, 200, 46, 0.1) 0%, rgba(255, 200, 46, 0.2) 100%);
      transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
      border-radius: 34px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      padding: 3px;
      border: 1px solid rgba(255, 200, 46, 0.3);
      box-shadow: 
        inset 0 2px 4px rgba(255, 200, 46, 0.1),
        0 2px 8px rgba(255, 200, 46, 0.1);
    }

    .icon {
      font-style: normal;
      font-size: 1.1rem;
      transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
      width: 22px;
      height: 22px;
      background: white;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      transform: translateX(0);
      box-shadow: 0 2px 6px rgba(255, 200, 46, 0.2);
      
      /* ✅ Estilos simples para ícones Font Awesome */
      .theme-icon {
        font-size: 10px; /* ✅ Menor em mobile */
        color: var(--text-primary); /* ✅ Cor padrão */
      }
    }

    /* ✅ Cores simples baseadas no tema */
    input:not(:checked) + .slider .icon .theme-icon {
      /* Sol no modo claro - dourado */
      color: #FFC82E;
    }

    input:checked + .slider .icon .theme-icon {
      /* Lua no modo escuro - azul */
      color: #4A90E2;
    }

    input:checked + .slider {
      background: linear-gradient(135deg, #000000 0%, #333333 100%);
      border-color: #FFC82E;
    }

    input:checked + .slider .icon {
      transform: translateX(24px);
      box-shadow: 0 2px 8px rgba(255, 200, 46, 0.4);
      background: white;
    }

    @media (max-width: 768px) {
      .header {
        width: 100% !important;
        padding: 0.5rem 0.75rem; /* Padding otimizado */
        height: 60px; /* Altura fixa novamente */
        background:#ffffff;
        /* Manter gradiente da aplicação em mobile */
        // background: linear-gradient(
        //   135deg,
        //   rgba(255, 255, 255, 0.98) 0%,
        //   rgba(255, 200, 46, 0.15) 50%,
        //   rgba(255, 200, 46, 0.2) 100%
        // );
      }

      :host-context(.dark-theme) .header {
        background: linear-gradient(
          135deg,
          rgba(0, 0, 0, 0.98) 0%,
          rgba(255, 200, 46, 0.1) 50%,
          rgba(255, 200, 46, 0.05) 100%
        );
      }

      /* === HEADER CONTENT MOBILE === */
      .header-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 100%;
        gap: 0.5rem;
      }

      /* === HEADER TITLE MOBILE === */
      .header-title {
        display: flex;
        align-items: center;
        gap: 0.4rem;
        flex: 1;
        min-width: 0; /* Permitir encolhimento */
      }

      .header-title h1 {
        font-size: 0.9rem;
        margin: 0;
        white-space: nowrap;
        overflow: hidden;
        text-ellipsis: ellipsis;
        max-width: 120px; /* Limitar largura do título */
        font-weight: 600;
      }

      /* === CONTADOR MOBILE === */
      .record-count {
        margin-left: 0.25rem;
        flex-shrink: 0;
      }

      .record-count .count-badge {
        font-size: 0.7rem;
        padding: 0.15rem 0.4rem;
        border-radius: 8px;
        min-width: 18px;
        height: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        
        /* Esconder label do domain em mobile */
        .domain-label {
          display: none;
        }
      }

      /* === ACTIONS MOBILE === */
      .header-actions {
        display: flex;
        align-items: center;
        gap: 0.3rem;
        flex-shrink: 0;
      }

      /* === DOMAIN ACTIONS MOBILE === */
      .domain-actions {
        display: flex;
        gap: 0.25rem;
      }

      .domain-action {
        padding: 0.25rem 0.5rem;
        font-size: 0.75rem;
        border-radius: 6px;
        min-height: 32px;
        gap: 0.2rem;

        mat-icon {
          font-size: 1rem;
          width: 1rem;
          height: 1rem;
        }
        
        .action-text {
          font-weight: 500;
          white-space: nowrap;
        }
      }

      /* === ACTIONS DIVIDER MOBILE === */
      .actions-divider {
        width: 1px;
        height: 20px;
        margin: 0 0.25rem;
      }

      /* === USER MENU MOBILE === */
      .user-menu {
        padding: 0.3rem 0.5rem;
        gap: 0.3rem;
        border-radius: 8px;
        
        .user-name {
          font-size: 0.75rem;
          font-weight: 500;
        }
      }

      .user-dropdown {
        width: 200px;
        right: 0;
        top: calc(100% + 5px);
      }

      /* === THEME SWITCH MOBILE === */
      .switch {
        width: 36px;
        height: 20px;
      }

      .icon {
        width: 14px;
        height: 14px;
        font-size: 0.7rem;
        
        .theme-icon {
          font-size: 8px;
        }
      }

      input:checked + .slider .icon {
        transform: translateX(16px);
      }

      /* === AVATAR MOBILE === */
      .avatar {
        width: 24px;
        height: 24px;
      }

      /* === CONTROLE DE VISIBILIDADE MOBILE === */
      .desktop-text {
        display: none !important; /* Esconder texto desktop em mobile */
      }
      
      .mobile-text {
        display: inline !important; /* Mostrar texto mobile */
      }
      
      .desktop-only {
        display: none !important; /* Esconder elementos desktop-only em mobile */
      }

      .mobile-only {
        display: flex !important; /* Mostrar elementos mobile-only */
      }
    }

    /* === MOBILE PEQUENO === */
    @media (max-width: 480px) {
      .header {
        padding: 0.4rem 0.5rem;
      }
      
      .header-title h1 {
        font-size: 0.85rem;
        max-width: 100px;
      }
      
      .domain-action .action-text {
        display: none; /* Esconder texto, mostrar só ícone */
      }
      
      .user-menu .user-name {
        display: none; /* Esconder nome do usuário */
      }
      
      .header-actions {
        gap: 0.2rem;
      }
    }

    /* === REMOVER LAYOUTS ANTERIORES === */
    @media (min-width: 769px) {
      /* Manter tudo normal no desktop */
    }

    /* === CONTROLE DE VISIBILIDADE DESKTOP/MOBILE === */
    .desktop-text {
      display: inline; /* Mostrar no desktop por padrão */
    }
    
    .mobile-text {
      display: none; /* Esconder no mobile por padrão */
    }
    
    .desktop-only {
      display: inline-block; /* Mostrar elementos desktop-only por padrão */
    }

    .mobile-only {
      display: none; /* Esconder elementos mobile-only no desktop */
    }

    /* Contador de registros */
  `]
})
export class HeaderComponent implements OnInit, OnDestroy {
  @Input() sidebarExpanded = true;
  
  isDarkMode$ = this.themeService.isDarkMode$;
  pageTitle$ = this.titleService.pageTitle$;
  
  // 🎯 DADOS DO USUÁRIO REATIVO
  currentUser: AuthUser | null = null;
  currentUser$ = this.authService.currentUser$;
  
  private scrolled = false;
  private subscription = new Subscription();
  private isDarkMode = false;

  headerConfig: HeaderConfig | null = null;

  constructor(
    private router: Router,
    private titleService: TitleService,
    public themeService: ThemeService,
    private headerActionsService: HeaderActionsService,
    private authService: AuthService
  ) {}

  // 🎯 ESTADO DO HEADER
  unreadNotifications = 3;
  showNotifications = false;
  showUserMenu = false;

  notifications = [
    {
      id: 1,
      message: 'Nova manutenção agendada',
      type: 'info',
      time: '5 min atrás',
      read: false
    },
    {
      id: 2,
      message: 'Alerta de combustível baixo',
      type: 'warning',
      time: '1 hora atrás',
      read: false
    },
    {
      id: 3,
      message: 'Revisão vencida',
      type: 'error',
      time: '2 horas atrás',
      read: false
    }
  ];

  ngOnInit() {
    // Subscrever às configurações do header
    this.subscription.add(
      this.headerActionsService.config$.subscribe(config => {
        this.headerConfig = config;
      })
    );

    // Subscrever ao estado do tema
    this.subscription.add(
      this.themeService.isDarkMode$.subscribe(isDark => {
        this.isDarkMode = isDark;
      })
    );

    // 🎯 SUBSCREVER aos dados do usuário autenticado
    this.subscription.add(
      this.authService.currentUser$.subscribe(user => {
        this.currentUser = user;
        console.log('👤 Dados do usuário atualizados no header:', user);
      })
    );

    // Adiciona listener para o scroll
    window.addEventListener('scroll', () => {
      this.scrolled = window.scrollY > 0;
      const header = document.querySelector('.header');
      if (header) {
        if (this.scrolled) {
          header.classList.add('scrolled');
        } else {
          header.classList.remove('scrolled');
        }
      }
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
    // Remove o listener quando o componente for destruído
    window.removeEventListener('scroll', () => {});
  }

  /**
   * Executa uma ação do domínio
   */
  executeAction(actionId: string): void {
    this.headerActionsService.executeAction(actionId);
  }

  toggleNotifications() {
    this.showNotifications = !this.showNotifications;
    if (this.showUserMenu) this.showUserMenu = false;
  }

  toggleUserMenu() {
    this.showUserMenu = !this.showUserMenu;
    if (this.showNotifications) this.showNotifications = false;
  }

  markAllAsRead() {
    this.notifications.forEach(notification => notification.read = true);
    this.unreadNotifications = 0;
  }

  getNotificationIcon(type: string): string {
    switch (type) {
      case 'info': return 'fas fa-info-circle text-blue-500';
      case 'warning': return 'fas fa-exclamation-triangle text-yellow-500';
      case 'error': return 'fas fa-exclamation-circle text-red-500';
      default: return 'fas fa-bell';
    }
  }

  /**
   * Retorna o label plural do domain para exibição no contador
   */
  getDomainLabel(domain: string): string {
    const domainLabels: { [key: string]: string } = {
      'drivers': 'motoristas',
      'vehicles': 'veículos',
      'old-vehicles': 'veículos antigos',
      'routes': 'rotas',
      'maintenance': 'manutenções',
      'customers': 'clientes',
      'orders': 'pedidos',
      'reports': 'relatórios',
      'integrations': 'conectadas'
    };
    
    return domainLabels[domain] || 'registros';
  }

  getDisplayUserName(): string {
    if (!this.currentUser?.name) return 'Usuário';
    const nameParts = this.currentUser.name.split(' ');
    return nameParts[0]; // Retorna apenas o primeiro nome
  }

  /**
   * 🖼️ Obter avatar do usuário (com fallback)
   */
  getUserAvatar(): string {
    // 🎯 Usar avatar do AuthService se disponível
    if (this.currentUser?.avatar) {
      return this.currentUser.avatar;
    }
    
    // Avatar padrão para usuários sem foto
    return 'assets/imagens/user.placeholder.svg';
  }

  logout() {
    // Fecha o menu do usuário
    this.showUserMenu = false;
    
    // 🎯 USAR AuthService para logout (mais seguro e centralizado)
    this.authService.logout();
  }

  getCurrentLogo() {
    return this.isDarkMode ? 'assets/imagens/logo_for_dark.png' : 'assets/logo.png';
  }

  /**
   * Alterna o tema (usado no menu do usuário)
   */
  toggleTheme() {
    console.log('Toggle theme clicked'); // Debug
    this.themeService.toggleTheme();
    // Fecha o menu do usuário após selecionar o tema
    this.showUserMenu = false;
  }

  /**
   * Fecha o menu do usuário
   */
  closeUserMenu() {
    this.showUserMenu = false;
  }
}
