<!-- Menu da Tabela -->
<div class="table-menu" [attr.data-table-id]="tableId">
  <!-- ✅ NOVA ESTRUTURA MOBILE: Linha 1 - Pesquisa + Filtros -->
  <div class="menu-top-row">
    <div class="global-filter-container">
      <input
        #searchInput
        type="text"
        [(ngModel)]="globalFilter"
        (ngModelChange)="onSearchChange($event)"
        placeholder=" Pesquisar..."
      />
      <i class="fas fa-search"></i>
    </div>

    <!-- ✨ NOVO: Botão Filtros Avançados -->
    <button
      class="control-button advanced-filter-button priority-1"
      [class.active]="showAdvancedFilters"
      (click)="toggleAdvancedFilters()"
      *ngIf="domainConfig"
    >
      <i class="fas fa-sliders-h"></i>
      <span class="desktop-text">Filtros Avançados</span>
      <span class="mobile-text">Avançados</span>
      <span *ngIf="activeAdvancedFiltersCount > 0" class="filter-count-badge">
        {{ activeAdvancedFiltersCount }}
      </span>
    </button>

    <!-- ✨ BOTÃO DE AÇÕES EM LOTE (SEMPRE HABILITADO) ✨ -->
    <div class="bulk-actions-container" *ngIf="bulkActions.length > 0">
      <button 
        class="control-button advanced-filter-button priority-1" 
        (click)="toggleBulkActionsModal()">
        <i class="fas fa-play"></i>
        <span class="desktop-text">Ações</span>
        <span class="mobile-text">Ações</span>
        <span *ngIf="selectedRows.size > 0" class="selection-count">
          {{ selectedRows.size }}
        </span>
        <!-- ✨ NOVO: Indicador de ações sempre disponíveis -->
        <span *ngIf="selectedRows.size === 0 && hasActionsWithoutSelection()" class="available-indicator" title="Ações disponíveis">
          <i class="fas fa-unlock"></i>
        </span>
      </button>
    </div>

    <!-- ❌ DESABILITADO: Filtros tradicionais removidos para evitar confusão com filtros diretos das colunas
    <button
      class="control-button filter-toggle priority-2"
      [class.active]="showFilters"
      (click)="toggleFilters()"
    >
      <i
        class="fas"
        [class.fa-filter]="!showFilters"
        [class.fa-filter-circle-xmark]="showFilters"
      ></i>
      <span class="desktop-text">{{ showFilters ? "Ocultar Filtros" : "Mostrar Filtros" }}</span>
      <span class="mobile-text">Filtros</span>
    </button>
    -->
  </div>

  <!-- ✅ NOVA ESTRUTURA MOBILE: Linha 2 - Controles -->
  <div class="menu-bottom-row">
    <div class="menu-left">
      <button
        class="control-button filter-toggle priority-3"
        [class.active]="showRequestFilters"
        (click)="toggleRequestFilters()"
        *ngIf="requestFilters.length > 0"
      >
        <i class="fas fa-filter"></i>
        <span class="desktop-text">Filtros Requisição</span>
        <span class="mobile-text">Req</span>
      </button>

      <button class="control-button normal-size priority-1" (click)="showColumnsMenu = !showColumnsMenu">
        <i class="fas fa-columns"></i>
        <span>Colunas</span>
      </button>

      <button
        class="control-button normal-size priority-2"
        [class.active]="hasActiveGrouping()"
        (click)="showGroupingMenu = !showGroupingMenu"
      >
        <i class="fas fa-layer-group"></i>
        <span>Agrupar</span>
      </button>
    </div>

    <div class="menu-right">
      <!-- Seletor de itens por página -->
      <div class="page-size-selector priority-2" *ngIf="false">
        <label class="desktop-text">{{ config.pageSize || pageSize }} itens</label>
        <select [value]="config.pageSize || pageSize" (change)="onPageSizeChange($event)">
          <option *ngFor="let size of config.pageSizeOptions || [10, 25, 50, 100]" [value]="size">
            {{ size }}
          </option>
        </select>
      </div>

      <button class="control-button priority-1" (click)="exportToCsv()">
        <i class="fas fa-download"></i>
        <span class="desktop-text">Exportar</span>
      </button>


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

<!-- ✨ NOVO: Domain Filter Component -->
<app-domain-filter
  *ngIf="domainConfig"
  [domainConfig]="domainConfig"
  [visible]="showAdvancedFilters"
  [activeFilters]="activeAdvancedFilters"
  (filtersChanged)="onAdvancedFiltersChanged($event)"
  (visibilityChanged)="showAdvancedFilters = $event">
</app-domain-filter>

<!-- Container da Tabela -->
<div class="data-table-container" [class.loading-state]="loading">
  <!-- Área de Filtros -->
  <div
    class="request-filters-container"
    *ngIf="showRequestFilters && requestFilters.length > 0"
  >
    <div class="filter-field" *ngFor="let filter of requestFilters">
      <div class="custom-field">
        <input
          [id]="'req-filter-' + filter.field"
          [type]="filter.type || 'text'"
          (input)="updateFilter(filter.field, $any($event.target).value)"
          [value]="activeFilters[filter.field] || ''"
          placeholder=" "
        />
        <label [for]="'req-filter-' + filter.field">{{ filter.label }}</label>
      </div>
    </div>
  </div>

  <!-- ❌ DESABILITADO: Filtros tradicionais removidos - agora usamos apenas filtros diretos das colunas + domain-filter
  <div class="filters-container" *ngIf="showFilters">
    <div class="filter-field" *ngFor="let column of visibleColumns">
      <ng-container *ngIf="column.filterable">
        <div class="custom-field">
          <input
            [id]="'filter-' + column.field"
            type="text"
            [value]="filters[column.field] || ''"
            (input)="handleFilterInput($event, column.field)"
            placeholder=" "
          />
          <label [for]="'filter-' + column.field"
            >Filtrar por {{ column.header.toLowerCase() }}</label
          >
        </div>
      </ng-container>
    </div>
  </div>
  -->

  <!-- ✅ VOLTA AO PADRÃO: Scroll Container Simples -->
  <div class="table-scroll-container" [class.has-active-column-filter]="activeColumnFilter">
    <table cdkDropListGroup>
    <!-- ✅ THEAD SIMPLES COM STICKY -->
    <thead>
      <tr
        cdkDropList
        cdkDropListOrientation="horizontal"
        (cdkDropListDropped)="dropColumn($event)"
      >
        <!-- ✅ COLUNA AÇÕES FIXA: Fica sempre visível à esquerda durante scroll horizontal -->
        <th *ngIf="config.actions?.length" class="actions-column">
          <div class="actions-header">
            <input
              type="checkbox"
              class="select-all-checkbox"
              [checked]="selectAllChecked"
              [indeterminate]="selectAllIndeterminate"
              (change)="toggleSelectAll()"
              title="Selecionar todas as linhas visíveis"
            />
            <span>Ações</span>
          </div>
        </th>
        <th
          *ngFor="let column of visibleColumns"
          [class.sortable]="column.sortable"
          [class.sorting]="sortField === column.field"
          [class.has-active-filter]="hasActiveColumnFilter(column.field)"
          [style.width]="column.width"
          [attr.data-field]="column.field"
          cdkDrag
          [cdkDragDisabled]="column.sortable && isDragging"
          (cdkDragStarted)="isDragging = true"
          (cdkDragEnded)="isDragging = false"
        >
          <div class="th-content" (click)="handleSort(column)">
            <i class="fas fa-grip-vertical drag-handle" cdkDragHandle></i>
            <span class="header-text">{{ column.header }}</span>
            <div class="column-actions">
              <!-- ✨ CORRIGIDO: Ícone de ordenação à ESQUERDA -->
              <i
                *ngIf="column.sortable"
                class="fas sort-icon"
                [class.fa-sort]="column.field !== sortField"
                [class.fa-sort-up]="
                  column.field === sortField && sortDirection === 'asc'
                "
                [class.fa-sort-down]="
                  column.field === sortField && sortDirection === 'desc'
                "
              >
              </i>
              <!-- ✨ NOVO: Botão de filtro à DIREITA -->
              <button
                *ngIf="column.filterable"
                class="column-filter-btn"
                [class.active]="hasActiveColumnFilter(column.field)"
                [class.open]="activeColumnFilter === column.field"
                (click)="toggleColumnFilter(column, $event)"
                title="Filtrar {{ column.header }}"
              >
                <i class="fas fa-filter"></i>
              </button>
            </div>
          </div>


          <div
            class="resize-handle"
            (mousedown)="
              $event.stopPropagation(); startResize($event, column)
            "
            (touchstart)="
              $event.stopPropagation(); startResize($event, column)
            "
          ></div>
        </th>
      </tr>
    </thead>
    <tbody>
      <ng-container *ngFor="let row of pagedData; trackBy: trackByFn">
        <tr
          *ngIf="row.isGroup"
          class="group-row"
          [class.group-level-1]="row.level === 1"
        >
          <td *ngIf="config.actions?.length" class="actions-column"></td>
          <td [attr.colspan]="visibleColumns.length">
            <div
              class="group-content"
              [style.padding-left.px]="row.level * 24"
            >
              <button class="group-toggle" (click)="toggleGroup(row)">
                <i
                  class="fas"
                  [class.fa-chevron-right]="!row.expanded"
                  [class.fa-chevron-down]="row.expanded"
                ></i>
              </button>
              <span class="group-title">
                {{ getColumnHeader(row.field) }}: {{ row.value }}
                <span class="group-aggregates" *ngIf="row.aggregates">
                  <ng-container *ngFor="let agg of getAggregates(row)">
                    {{ getColumnHeader(agg.key) }}:
                    {{ formatAggregateValue(agg.value, agg.type) }}
                  </ng-container>
                </span>
              </span>
            </div>
          </td>
        </tr>
        <tr
          *ngIf="!row.isGroup"
          class="data-row"
          [class.child-of-group]="row.level > 0"
          [class.row-selected]="isRowSelected(row)"
        >
          <td *ngIf="config.actions?.length" class="actions-column">
            <div class="actions-cell">
              <input
                type="checkbox"
                class="row-checkbox"
                [checked]="isRowSelected(row)"
                (change)="toggleRowSelection(row)"
                (click)="$event.stopPropagation()"
                title="Selecionar linha"
              />
              <div class="action-buttons">
                <ng-container *ngFor="let action of config.actions">
                  <button
                    *ngIf="!action.show || action.show(row)"
                    mat-icon-button
                    [color]="action.color || 'primary'"
                    [matTooltip]="action.label"
                    (click)="onActionClick(action.action, row)"
                  >
                    <i [class]="action.icon"></i>
                  </button>
                </ng-container>
              </div>
            </div>
          </td>
          <td *ngFor="let column of visibleColumns">
            <!-- ✅ SUPORTE A HTML: Se allowHtml=true, usa innerHTML sanitizado -->
            <span 
              *ngIf="shouldRenderHtml(column); else normalContent"
              [innerHTML]="getSafeHtml(column.label!(row[column.field], row))"
            ></span>
            
            <!-- ✅ CONTEÚDO NORMAL: Texto escapado (seguro) -->
            <ng-template #normalContent>
              {{
                column.date
                  ? formatDate(row[column.field])
                  : column.label
                  ? column.label(row[column.field], row)
                  : row[column.field]
              }}
            </ng-template>
          </td>
        </tr>
      </ng-container>
      
      <!-- ✨ NOVO: Mensagem quando não há registros -->
      <tr *ngIf="shouldShowEmptyMessage" class="empty-table-row">
        <td [attr.colspan]="getTotalColumnsCount()" class="empty-table-cell">
          <div class="empty-table-content">
            <div class="empty-icon">
              <i class="fas fa-inbox"></i>
            </div>
            <h3 class="empty-title">Nenhum registro encontrado</h3>
            <p class="empty-message" *ngIf="!hasAnyActiveFilter()">
              Não há dados para exibir nesta tabela.
            </p>
            <p class="empty-message" *ngIf="hasAnyActiveFilter()">
              Nenhum registro corresponde aos filtros aplicados.
            </p>
            <div class="empty-actions" *ngIf="hasAnyActiveFilter()">
              <button class="empty-action-btn" (click)="clearAllFilters()">
                <i class="fas fa-times"></i>
                Limpar Filtros
              </button>
            </div>
          </div>
        </td>
      </tr>
    </tbody>
    
    <!-- ✨ NOVO: Footer com valores calculados -->
    <tfoot *ngIf="shouldShowFooter" class="table-footer">
      <tr class="footer-row">
        <!-- ✅ COLUNA AÇÕES: Vazia no footer -->
        <td *ngIf="config.actions?.length" class="actions-column footer-cell">
          <div class="footer-actions">
            <span class="footer-label">Resumo:</span>
          </div>
        </td>
        
        <!-- ✅ COLUNAS DE DADOS: Com valores calculados -->
        <td *ngFor="let column of visibleColumns" 
            class="footer-cell"
            [class.has-footer-value]="column.footer && footerValues[column.field] !== null && footerValues[column.field] !== undefined">
          
          <div class="footer-content" *ngIf="column.footer && footerValues[column.field] !== null && footerValues[column.field] !== undefined">
            <span class="footer-label">{{ getFooterLabel(column) }}</span>
            <span class="footer-value" [class.footer-currency]="column.footer.format === 'currency'"
                                      [class.footer-number]="column.footer.format === 'number'"
                                      [class.footer-percentage]="column.footer.format === 'percentage'"
                                      [class.footer-count]="column.footer.type === 'count'">
              {{ formatFooterValue(column, footerValues[column.field]) }}
            </span>
          </div>
          
          <!-- ✅ COLUNA SEM FOOTER: Vazia -->
          <div class="footer-content empty" *ngIf="!column.footer">
            <span class="footer-placeholder">-</span>
          </div>
        </td>
      </tr>
    </tfoot>
  </table>
  </div>

  <!-- Paginação Moderna -->
  <div class="pagination">
    <div class="pagination-info">
      <!-- ✅ DESKTOP: Texto completo -->
      <span *ngIf="serverSidePagination" class="desktop-text">
        Exibindo <strong>{{ startIndex + 1 }}</strong> a <strong>{{ endIndex }}</strong> 
        de <strong>{{ totalItems }}</strong> registros
      </span>
      <span *ngIf="!serverSidePagination" class="desktop-text">
        Exibindo <strong>{{ startIndex + 1 }}</strong> a 
        <strong>{{ getMin(endIndex, filteredData.length) }}</strong> 
        de <strong>{{ filteredData.length }}</strong> registros
      </span>
      
      <!-- ✅ MOBILE: Texto simplificado -->
      <span *ngIf="serverSidePagination" class="mobile-text">
        <strong>{{ startIndex + 1 }}-{{ endIndex }}</strong> de <strong>{{ totalItems }}</strong>
      </span>
      <span *ngIf="!serverSidePagination" class="mobile-text">
        <strong>{{ startIndex + 1 }}-{{ getMin(endIndex, filteredData.length) }}</strong> de <strong>{{ filteredData.length }}</strong>
      </span>
    </div>

    <div class="pagination-controls">
      <!-- Controles de navegação -->
      <div class="navigation-controls">
        <!-- Primeira página -->
        <button
          class="pagination-button first-last"
          [disabled]="currentPage === 1"
          (click)="onPageChange(1)"
          title="Primeira página"
        >
          <i class="fas fa-angle-double-left"></i>
        </button>

        <!-- Página anterior -->
        <button
          class="pagination-button prev-next"
          [disabled]="currentPage === 1"
          (click)="onPageChange(currentPage - 1)"
          title="Página anterior"
        >
          <i class="fas fa-chevron-left"></i>
        </button>

        <!-- Páginas numeradas -->
        <div class="page-numbers">
          <ng-container *ngFor="let page of getPageNumbers()">
            <button
              *ngIf="page !== '...'"
              class="pagination-button page-number"
              [class.active]="page === currentPage"
              (click)="onPageChange(+page)"
            >
              {{ page }}
            </button>
            <span *ngIf="page === '...'" class="page-ellipsis">...</span>
          </ng-container>
        </div>

        <!-- Próxima página -->
        <button
          class="pagination-button prev-next"
          [disabled]="currentPage >= getTotalPages()"
          (click)="onPageChange(currentPage + 1)"
          title="Próxima página"
        >
          <i class="fas fa-chevron-right"></i>
        </button>

        <!-- Última página -->
        <button
          class="pagination-button first-last"
          [disabled]="currentPage >= getTotalPages()"
          (click)="onPageChange(getTotalPages())"
          title="Última página"
        >
          <i class="fas fa-angle-double-right"></i>
        </button>
      </div>
    </div>
  </div>

  <!-- ✨ LOADING OVERLAY: Geral -->
  <div *ngIf="loading" class="loading-overlay">
    <div class="loading-content">
      <div class="spinner"></div>
      <p>Carregando dados...</p>
    </div>
  </div>

  <!-- ✨ LOADING OVERLAY: Busca no Backend -->
  <div *ngIf="isSearchingBackend" class="loading-overlay backend-search">
    <div class="loading-content">
      <div class="spinner-backend"></div>
      <p class="backend-message">{{ backendSearchMessage }}</p>
      <small class="backend-hint">Nenhum resultado encontrado na lista atual</small>
    </div>
  </div>



  <!-- ✨ NOVO: Mensagem de "Nenhum Resultado Encontrado" -->
  <div *ngIf="showNoResultsMessage && !loading && !isSearchingBackend" class="no-results-overlay">
    <div class="no-results-content">
      <div class="no-results-icon">
        <i class="fas fa-search"></i>
      </div>
      <h3 class="no-results-title">Nenhum resultado encontrado</h3>
      <p class="no-results-message">
        Sua pesquisa não retornou resultados no servidor.
      </p>
      <div class="search-terms-display" *ngIf="lastSearchTerms">
        <span class="search-label">Termos pesquisados:</span>
        <span class="search-terms">{{ lastSearchTerms }}</span>
      </div>
      <div class="no-results-actions">
        <button class="action-btn secondary" (click)="clearAllFilters()">
          <i class="fas fa-times"></i>
          Limpar Filtros
        </button>
        <button class="action-btn primary" (click)="applyFilter()">
          <i class="fas fa-redo"></i>
          Tentar Novamente
        </button>
      </div>
    </div>
  </div>
</div>

<!-- ✨ NOVO: Painel de filtro direto da coluna (fora do container) -->
<div *ngIf="activeColumnFilter" class="column-filter-overlay">
  <div 
    class="column-filter-panel"
    [style.left.px]="getColumnFilterPosition().left"
    [style.top.px]="getColumnFilterPosition().top"
    (click)="$event.stopPropagation()">
    
    <div class="filter-panel-header">
      <div class="filter-title">
        <i class="fas fa-filter"></i>
        <span>Filtrar {{ getActiveColumnHeader() }}</span>
      </div>
      <button 
        class="close-filter-btn"
        (click)="activeColumnFilter = null"
        title="Fechar">
        <i class="fas fa-times"></i>
      </button>
    </div>

    <div class="filter-panel-content">
      <!-- ✨ NOVO: Área scrollável do conteúdo -->
      <div class="filter-panel-body">
        <!-- ✨ NOVO: Aviso de filtros cumulativos -->
        <div 
          *ngIf="hasReducedOptions(activeColumnFilter)" 
          class="cumulative-filter-notice">
          <i class="fas fa-info-circle"></i>
          <span>Mostrando apenas valores da lista filtrada atual</span>
        </div>

        <!-- Input de pesquisa -->
        <div class="filter-search">
          <input
            type="text"
            placeholder="Pesquisar valores..."
            [(ngModel)]="columnFilterSearch[activeColumnFilter]"
            class="filter-search-input"
          />
          <i class="fas fa-search search-icon"></i>
        </div>

        <!-- Controles de seleção -->
        <div class="filter-controls">
          <button 
            class="filter-control-btn"
            (click)="toggleSelectAllColumnValues(activeColumnFilter)">
            <i class="fas" 
               [class.fa-check-square]="areAllColumnValuesSelected(activeColumnFilter)"
               [class.fa-square]="!areAllColumnValuesSelected(activeColumnFilter)"></i>
            <span>{{ areAllColumnValuesSelected(activeColumnFilter) ? 'Desmarcar' : 'Selecionar' }} Todos</span>
          </button>
          <span class="selection-count">
            {{ getSelectedColumnValuesCount(activeColumnFilter) }} de {{ getTotalColumnValuesCount(activeColumnFilter) }}
            <!-- ✨ NOVO: Indicador de filtros cumulativos -->
            <span 
              *ngIf="hasReducedOptions(activeColumnFilter)" 
              class="filtered-indicator"
              title="Valores filtrados por outros filtros ativos">
              ({{ getOriginalColumnValuesCount(activeColumnFilter) }} total)
            </span>
          </span>
        </div>

        <!-- Lista de valores -->
        <div class="filter-values-list">
          <div 
            *ngFor="let item of getFilteredColumnValues(activeColumnFilter); trackBy: trackValueItem"
            class="filter-value-item">
            
            <label class="filter-value-label">
              <input
                type="checkbox"
                [checked]="isColumnValueSelected(activeColumnFilter, item.value)"
                (change)="toggleColumnValue(activeColumnFilter, item.value)"
                class="filter-value-checkbox"
              />
              <div class="checkbox-custom">
                <i class="fas fa-check"></i>
              </div>
              <span class="value-text">{{ item.display }}</span>
              <!-- ✨ NOVO: Preview visual para campos HTML -->
              <span 
                *ngIf="hasVisualPreview(activeColumnFilter, item)" 
                class="value-preview"
                [innerHTML]="getValuePreview(activeColumnFilter, item)">
              </span>
            </label>
          </div>
        </div>
      </div>

      <!-- ✨ NOVO: Footer fixo com ações -->
      <div class="filter-panel-actions">
        <button 
          class="filter-action-btn secondary"
          (click)="clearColumnFilter(activeColumnFilter)">
          <i class="fas fa-times"></i>
          Limpar
        </button>
        <button 
          class="filter-action-btn primary"
          (click)="applyColumnFilter(activeColumnFilter)">
          <i class="fas fa-check"></i>
          Aplicar
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Menus flutuantes movidos para fora do container -->
<div class="modal-overlay" *ngIf="showColumnsMenu || showGroupingMenu" (click)="closeModals()">
  <!-- ✅ NOVA TELA DE COLUNAS VISÍVEIS MELHORADA -->
  <div class="floating-panel columns-panel" *ngIf="showColumnsMenu" (click)="$event.stopPropagation()">
    <div class="panel-header">
      <div class="header-content">
        <div class="header-icon">
          <i class="fas fa-columns"></i>
        </div>
        <div class="header-text">
          <h4>Personalizar Colunas</h4>
          <span class="header-subtitle">{{getVisibleColumnsCount()}} de {{allColumns.length}} colunas visíveis</span>
        </div>
      </div>
      <button class="close-button" (click)="showColumnsMenu = false">
        <i class="fas fa-times"></i>
      </button>
    </div>
    
    <!-- ✅ CONTROLES RÁPIDOS -->
    <div class="panel-quick-actions">
      <button class="quick-action-btn" (click)="selectAllColumns()" [disabled]="areAllColumnsVisible()">
        <i class="fas fa-check-double"></i>
        Selecionar Todas
      </button>
      <button class="quick-action-btn" (click)="deselectAllColumns()" [disabled]="!hasVisibleColumns()">
        <i class="fas fa-times-circle"></i>
        Desmarcar Todas
      </button>
      <button class="quick-action-btn" (click)="resetToDefault()">
        <i class="fas fa-undo"></i>
        Restaurar Padrão
      </button>
    </div>

    <div class="panel-content">
      <!-- ✅ LISTA DE COLUNAS MELHORADA -->
      <div class="columns-list-enhanced">
        <div 
          class="column-item" 
          *ngFor="let column of allColumns; trackBy: trackColumnByField"
          [class.column-visible]="isColumnVisible(column.field)"
          [class.column-hidden]="!isColumnVisible(column.field)"
        >
          <div class="column-checkbox-wrapper">
            <input
              type="checkbox"
              [id]="'col-' + column.field"
              [checked]="isColumnVisible(column.field)"
              (change)="toggleColumnVisibility(column.field)"
              class="column-checkbox"
            />
            <div class="checkbox-custom">
              <i class="fas fa-check"></i>
            </div>
          </div>
          
          <div class="column-info">
            <label [for]="'col-' + column.field" class="column-label">
              {{ column.header }}
            </label>
            <div class="column-details">
              <span class="column-field">{{ column.field }}</span>
              <span class="column-type" *ngIf="getColumnType(column)">
                <i [class]="getColumnTypeIcon(column)"></i>
                {{ getColumnType(column) }}
              </span>
            </div>
          </div>

          <div class="column-actions">
            <button 
              class="column-action-btn"
              [disabled]="!isColumnVisible(column.field)"
              title="Mover para cima"
              (click)="moveColumnUp(column.field)"
            >
              <i class="fas fa-chevron-up"></i>
            </button>
            <button 
              class="column-action-btn"
              [disabled]="!isColumnVisible(column.field)"
              title="Mover para baixo"
              (click)="moveColumnDown(column.field)"
            >
              <i class="fas fa-chevron-down"></i>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- ✅ FOOTER COM ESTATÍSTICAS -->
    <div class="panel-footer">
      <div class="column-stats">
        <div class="stat-item">
          <i class="fas fa-eye text-success"></i>
          <span>{{getVisibleColumnsCount()}} visíveis</span>
        </div>
        <div class="stat-item">
          <i class="fas fa-eye-slash text-muted"></i>
          <span>{{getHiddenColumnsCount()}} ocultas</span>
        </div>
      </div>
      <div class="panel-actions">
        <button class="panel-btn secondary" (click)="showColumnsMenu = false">
          Cancelar
        </button>
        <button class="panel-btn primary" (click)="applyColumnChanges()">
          <i class="fas fa-check"></i>
          Aplicar
        </button>
      </div>
    </div>
  </div>

  <!-- ✅ NOVA TELA DE AGRUPAMENTO MELHORADA -->
  <div class="floating-panel grouping-panel" *ngIf="showGroupingMenu" (click)="$event.stopPropagation()">
    <div class="panel-header">
      <div class="header-content">
        <div class="header-icon">
          <i class="fas fa-layer-group"></i>
        </div>
        <div class="header-text">
          <h4>Configurar Agrupamento</h4>
          <span class="header-subtitle">{{getActiveGroupingLevels()}} de 2 níveis configurados</span>
        </div>
      </div>
      <button class="close-button" (click)="showGroupingMenu = false">
        <i class="fas fa-times"></i>
      </button>
    </div>
    
    <!-- ✅ CONTROLES RÁPIDOS -->
    <div class="panel-quick-actions">
      <button class="quick-action-btn" (click)="clearAllGrouping()" [disabled]="!hasActiveGrouping()">
        <i class="fas fa-times-circle"></i>
        Remover Agrupamento
      </button>
      <button class="quick-action-btn" (click)="resetGroupingToDefault()">
        <i class="fas fa-undo"></i>
        Restaurar Padrão
      </button>
    </div>

    <div class="panel-content">
      <!-- ✅ NÍVEIS DE AGRUPAMENTO MELHORADOS -->
      <div class="grouping-levels">
        
        <!-- NÍVEL 1 -->
        <div class="grouping-level-card" [class.level-active]="getGroupByField(0)">
          <div class="level-header">
            <div class="level-info">
              <i class="fas fa-layer-group"></i>
              <span class="level-title">Agrupamento Principal</span>
              <span class="level-subtitle">Nível 1</span>
            </div>
            <div class="level-status">
              <span class="status-badge" [class.active]="getGroupByField(0)">
                {{getGroupByField(0) ? 'Ativo' : 'Inativo'}}
              </span>
            </div>
          </div>
          
          <div class="level-content">
            <div class="form-group">
              <label for="group-level-0">Campo de Agrupamento</label>
              <select
                id="group-level-0"
                class="form-select"
                [ngModel]="getGroupByField(0)"
                (ngModelChange)="updateGrouping(0, $event)"
              >
                <option value="">Nenhum agrupamento</option>
                <option
                  *ngFor="let column of getAvailableColumns(0)"
                  [value]="column.field"
                >
                  {{ column.header }}
                </option>
              </select>
            </div>

            <!-- AGREGAÇÕES NÍVEL 1 -->
            <div class="aggregates-section" *ngIf="getGroupByField(0)">
              <div class="section-header collapsible-header" (click)="toggleAggregatesExpansion(0)">
                <div class="header-left">
                  <i class="fas fa-calculator"></i>
                  <span>Cálculos Agregados</span>
                </div>
                <div class="header-right">
                  <span class="aggregate-count" *ngIf="!aggregatesExpanded[0] && getAggregatesCountForLevel(0) > 0">
                    {{getAggregatesCountForLevel(0)}} configurados
                  </span>
                  <i class="fas toggle-icon" 
                     [class.fa-chevron-down]="!aggregatesExpanded[0]"
                     [class.fa-chevron-up]="aggregatesExpanded[0]"></i>
                </div>
              </div>
              
              <div class="aggregates-content" [class.expanded]="aggregatesExpanded[0]">
                <div class="aggregates-grid">
                  <div 
                    class="aggregate-item" 
                    *ngFor="let column of getNumericColumns(); trackBy: trackColumnByField"
                  >
                    <div class="column-name">
                      <i [class]="getColumnTypeIcon(column)"></i>
                      <span>{{ column.header }}</span>
                    </div>
                    <select
                      class="aggregate-select"
                      [(ngModel)]="groupingAggregates[0][column.field]"
                      (ngModelChange)="updateAggregates(0)"
                    >
                      <option [ngValue]="null">Nenhum</option>
                      <option value="sum">Soma</option>
                      <option value="avg">Média</option>
                      <option value="count">Contagem</option>
                      <option value="min">Mínimo</option>
                      <option value="max">Máximo</option>
                    </select>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- NÍVEL 2 - ✅ SÓ EXIBE QUANDO NÍVEL 1 ESTIVER ATIVO -->
        <div class="grouping-level-card" 
             *ngIf="getGroupByField(0)"
             [class.level-active]="getGroupByField(1)" 
             [class.level-disabled]="!getGroupByField(0)">
          <div class="level-header">
            <div class="level-info">
              <i class="fas fa-layer-group"></i>
              <span class="level-title">Agrupamento Secundário</span>
              <span class="level-subtitle">Nível 2</span>
            </div>
            <div class="level-status">
              <span class="status-badge" [class.active]="getGroupByField(1)" [class.disabled]="!getGroupByField(0)">
                {{getGroupByField(1) ? 'Ativo' : (!getGroupByField(0) ? 'Bloqueado' : 'Inativo')}}
              </span>
            </div>
          </div>
          
          <div class="level-content">
            <div class="form-group">
              <label for="group-level-1">Campo de Agrupamento</label>
              <select
                id="group-level-1"
                class="form-select"
                [ngModel]="getGroupByField(1)"
                [disabled]="!getGroupByField(0)"
                (ngModelChange)="updateGrouping(1, $event)"
              >
                <option value="">Nenhum agrupamento</option>
                <option
                  *ngFor="let column of getAvailableColumns(1)"
                  [value]="column.field"
                >
                  {{ column.header }}
                </option>
              </select>
            </div>

            <!-- AGREGAÇÕES NÍVEL 2 -->
            <div class="aggregates-section" *ngIf="getGroupByField(1)">
              <div class="section-header collapsible-header" (click)="toggleAggregatesExpansion(1)">
                <div class="header-left">
                  <i class="fas fa-calculator"></i>
                  <span>Cálculos Agregados</span>
                </div>
                <div class="header-right">
                  <span class="aggregate-count" *ngIf="!aggregatesExpanded[1] && getAggregatesCountForLevel(1) > 0">
                    {{getAggregatesCountForLevel(1)}} configurados
                  </span>
                  <i class="fas toggle-icon" 
                     [class.fa-chevron-down]="!aggregatesExpanded[1]"
                     [class.fa-chevron-up]="aggregatesExpanded[1]"></i>
                </div>
              </div>
              
              <div class="aggregates-content" [class.expanded]="aggregatesExpanded[1]">
                <div class="aggregates-grid">
                  <div 
                    class="aggregate-item" 
                    *ngFor="let column of getNumericColumns(); trackBy: trackColumnByField"
                  >
                    <div class="column-name">
                      <i [class]="getColumnTypeIcon(column)"></i>
                      <span>{{ column.header }}</span>
                    </div>
                    <select
                      class="aggregate-select"
                      [(ngModel)]="groupingAggregates[1][column.field]"
                      (ngModelChange)="updateAggregates(1)"
                    >
                      <option [ngValue]="null">Nenhum</option>
                      <option value="sum">Soma</option>
                      <option value="avg">Média</option>
                      <option value="count">Contagem</option>
                      <option value="min">Mínimo</option>
                      <option value="max">Máximo</option>
                    </select>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- ✅ FOOTER COM INFORMAÇÕES E AÇÕES -->
    <div class="panel-footer">
      <div class="grouping-stats">
        <div class="stat-item">
          <i class="fas fa-layer-group text-primary"></i>
          <span>{{getActiveGroupingLevels()}} níveis ativos</span>
        </div>
        <div class="stat-item" *ngIf="getTotalAggregates() > 0">
          <i class="fas fa-calculator text-info"></i>
          <span>{{getTotalAggregates()}} cálculos configurados</span>
        </div>
      </div>
      <div class="panel-actions">
        <button class="panel-btn secondary" (click)="showGroupingMenu = false">
          Cancelar
        </button>
        <button class="panel-btn primary" (click)="applyGroupingChanges()">
          <i class="fas fa-check"></i>
          Aplicar Agrupamento
        </button>
      </div>
    </div>
  </div>
</div>

<!-- ✨ NOVO MODAL DE AÇÕES EM LOTE ✨ -->
<app-bulk-actions
  [visible]="showBulkActionsModal"
  [actions]="bulkActions"
  [selectedItems]="getSelectedRows()"
  (close)="toggleBulkActionsModal()"
  (executeAction)="handleExecuteAction($event)">
</app-bulk-actions>
