<div class="vehicle-fuelcontroll">
  <!-- 📊 Header -->
  <div class="fuelcontroll-header">
    <h3>
      <i class="fas fa-gas-pump"></i>
      Abastecimentos
    </h3>
    <div class="fuelcontroll-summary" *ngIf="fuelcontrollRecords$ | async as records">
      <span class="badge badge-info">
        {{getRecordCount(records)}} {{getRecordCount(records) === 1 ? 'abastecimento' : 'abastecimentos'}}
      </span>
      <span class="badge badge-success" *ngIf="getTotalValue(records) as totalValue">
        <i class="fas fa-dollar-sign"></i>
        Total: R$ {{totalValue.toFixed(2)}}
      </span>
      <span class="badge badge-warning" *ngIf="getLastFuel(records) as lastFuel">
        Último: {{lastFuel.date | date:'dd/MM/yyyy'}}
      </span>
    </div>
  </div>

  <!-- 📋 Data Table -->
  <app-data-table
    [config]="{ columns: columns }"
    [data]="(fuelcontrollRecords$ | async) || []"
    [loading]="loading"
    [showFilters]="true"
    [serverSidePagination]="false">
  </app-data-table>

  <!-- 📊 Cards de Análise -->
  <div class="analytics-section" *ngIf="fuelcontrollRecords$ | async as records; else emptyOrError">
    <div class="analytics-header">
      <h4>
        <i class="fas fa-chart-bar"></i>
        Análises de Combustível
      </h4>
    </div>

    <!-- Cards de Resumo Geral -->
    <div class="analytics-cards">
      <div class="analytics-card">
        <div class="card-icon">
          <i class="fas fa-tint"></i>
        </div>
        <div class="card-content">
          <span class="card-value">{{ getTotalLiters(records).toFixed(1) }}L</span>
          <span class="card-label">Total de Litros</span>
        </div>
      </div>

      <div class="analytics-card">
        <div class="card-icon">
          <i class="fas fa-calculator"></i>
        </div>
        <div class="card-content">
          <span class="card-value">R$ {{ getAvgPricePerLiter(records).toFixed(2) }}</span>
          <span class="card-label">Preço Médio/Litro</span>
        </div>
      </div>

      <div class="analytics-card" *ngIf="getConsumptionAnalysis(records) as consumption">
        <div class="card-icon">
          <i class="fas fa-road"></i>
        </div>
        <div class="card-content">
          <span class="card-value">{{ consumption.avgConsumption.toFixed(1) }}L</span>
          <span class="card-label">Consumo Médio/100km</span>
        </div>
      </div>

      <div class="analytics-card" *ngIf="getConsumptionAnalysis(records) as efficiencyData">
        <div class="card-icon">
          <i class="fas fa-leaf"></i>
        </div>
        <div class="card-content">
          <span class="card-value">{{ efficiencyData.bestEfficiency.toFixed(1) }}L</span>
          <span class="card-label">Melhor Eficiência/100km</span>
        </div>
      </div>
    </div>

    <!-- 👨‍💼 Análise por Motorista -->
    <div class="analysis-section" *ngIf="driverAnalysis.length > 0">
      <h5>
        <i class="fas fa-user-tie"></i>
        Análise por Motorista
      </h5>
      <div class="driver-analysis">
        <div 
          class="driver-card" 
          *ngFor="let driver of driverAnalysis; let i = index"
        >
          <div class="driver-rank">
            <span class="rank-number">{{ i + 1 }}º</span>
            <div class="rank-icon" *ngIf="i === 0">
              <i class="fas fa-medal"></i>
            </div>
          </div>
          <div class="driver-info">
            <span class="driver-name">{{ driver.driverName }}</span>
            <div class="driver-stats">
              <span class="stat">
                <i class="fas fa-shopping-cart"></i>
                {{ driver.totalSupplies }} abastecimentos
              </span>
              <span class="stat">
                <i class="fas fa-tint"></i>
                {{ driver.totalQuantity.toFixed(1) }}L
              </span>
              <span class="stat">
                <i class="fas fa-dollar-sign"></i>
                Maior: R$ {{ driver.maxSingleValue.toFixed(2) }}
              </span>
              <span class="stat">
                <i class="fas fa-road"></i>
                {{ driver.totalKilometers.toLocaleString('pt-BR') }} km
              </span>
            </div>
          </div>
          <div class="driver-total">
            <span class="total-value">R$ {{ driver.totalValue.toFixed(2) }}</span>
            <span class="avg-per-supply">
              Média: R$ {{ (driver.totalValue / driver.totalSupplies).toFixed(2) }}
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 🏪 Análise por Fornecedor -->
    <div class="analysis-section" *ngIf="supplierAnalysis.length > 0">
      <h5>
        <i class="fas fa-building"></i>
        Análise por Fornecedor
      </h5>
      <div class="supplier-analysis">
        <div 
          class="supplier-card" 
          *ngFor="let supplier of supplierAnalysis.slice(0, 5); let i = index"
          [class.top-supplier]="i === 0"
        >
          <div class="supplier-rank">
            <span class="rank-number">{{ i + 1 }}º</span>
            <div class="rank-icon" *ngIf="i === 0">
              <i class="fas fa-crown"></i>
            </div>
          </div>
          <div class="supplier-info">
            <span class="supplier-name">{{ supplier.supplierName }}</span>
            <div class="supplier-stats">
              <span class="stat">
                <i class="fas fa-shopping-cart"></i>
                {{ supplier.count }} abastecimentos
              </span>
              <span class="stat">
                <i class="fas fa-tint"></i>
                {{ supplier.totalLiters.toFixed(1) }}L
              </span>
            </div>
          </div>
          <div class="supplier-total">
            <span class="total-value">R$ {{ supplier.totalValue.toFixed(2) }}</span>
            <span class="avg-per-supply">
              Média: R$ {{ (supplier.totalValue / supplier.count).toFixed(2) }}
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- ⛽ Análise por Marca de Posto -->
    <div class="analysis-section" *ngIf="gasStationAnalysis.length > 0">
      <h5>
        <i class="fas fa-gas-pump"></i>
        Análise por Marca de Posto
      </h5>
      <div class="gasstation-analysis">
        <div 
          class="gasstation-card" 
          *ngFor="let station of gasStationAnalysis.slice(0, 5); let i = index"
          [class.top-gasstation]="i === 0"
        >
          <div class="gasstation-rank">
            <span class="rank-number">{{ i + 1 }}º</span>
            <div class="rank-icon" *ngIf="i === 0">
              <i class="fas fa-trophy"></i>
            </div>
          </div>
          <div class="gasstation-info">
            <span class="gasstation-name">{{ station.gasStationName }}</span>
            <div class="gasstation-stats">
              <span class="stat">
                <i class="fas fa-shopping-cart"></i>
                {{ station.count }} abastecimentos
              </span>
              <span class="stat">
                <i class="fas fa-tint"></i>
                {{ station.totalLiters.toFixed(1) }}L
              </span>
            </div>
          </div>
          <div class="gasstation-total">
            <span class="total-value">R$ {{ station.totalValue.toFixed(2) }}</span>
            <span class="avg-per-supply">
              Média: R$ {{ (station.totalValue / station.count).toFixed(2) }}
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- ⛽ ANÁLISE POR TIPO DE COMBUSTÍVEL - LAYOUT LIMPO -->
    <div class="fuel-analysis-clean" *ngIf="productAnalysis.length > 0">
      <!-- Header Simples -->
      <div class="fuel-header">
        <div class="fuel-icon">
          <i class="fas fa-gas-pump"></i>
        </div>
        <div class="fuel-title">
          <h4>Análise por Tipo de Combustível</h4>
          <p>Detalhamento completo do consumo por produto</p>
        </div>
        <div class="fuel-counter" *ngIf="fuelSummary">
          <span class="counter-badge">{{ fuelSummary.totalProducts }} tipos</span>
        </div>
      </div>

      <!-- Cards de Combustível -->
      <div class="fuel-cards-grid">
        <div 
          class="fuel-card" 
          *ngFor="let product of productAnalysis; let i = index"
          [class.primary-fuel]="i === 0"
        >
          <!-- Cabeçalho do Card -->
          <div class="fuel-card-header">
            <div class="fuel-info">
              <h5 class="fuel-name">{{ product.productName }}</h5>
              <span class="fuel-badge" 
                    [class.badge-primary]="i === 0"
                    [class.badge-secondary]="i > 0">
                {{ i === 0 ? 'Combustível Principal' : 'Secundário' }}
              </span>
            </div>
            <div class="fuel-percentage">
              <span class="percentage-large">{{ product.percentage.toFixed(1) }}%</span>
            </div>
          </div>

          <!-- Métricas do Card -->
          <div class="fuel-card-metrics">
            <div class="metric-item">
              <span class="metric-label">Total Investido</span>
              <span class="metric-value">R$ {{ product.totalValue.toFixed(2) }}</span>
            </div>
            
            <div class="metric-item">
              <span class="metric-label">Volume Total</span>
              <span class="metric-value">{{ product.totalQuantity.toFixed(1) }}L</span>
            </div>
            
            <div class="metric-item">
              <span class="metric-label">Preço Médio/L</span>
              <span class="metric-value">R$ {{ product.avgPricePerLiter.toFixed(2) }}</span>
            </div>
            
            <div class="metric-item">
              <span class="metric-label">Abastecimentos</span>
              <span class="metric-value">{{ product.count }}x</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 🍃 SEÇÃO: Eficiência Renovada -->
    <div class="efficiency-section" *ngIf="efficiencyAnalysis.length > 0">
      <div class="section-header">
        <div class="header-content">
          <div class="header-icon efficiency">
            <i class="fas fa-leaf"></i>
          </div>
          <div class="header-text">
            <h4>Análise de Eficiência</h4>
            <p>Consumo por 100km para cada tipo de combustível</p>
          </div>
        </div>
      </div>

      <div class="efficiency-grid">
        <div 
          class="efficiency-card-modern" 
          *ngFor="let efficiency of efficiencyAnalysis; let i = index"
        >
          <div class="efficiency-card-header">
            <div class="fuel-info">
              <h6>{{ efficiency.productName }}</h6>
              <span class="samples-badge">{{ efficiency.samplesCount }} amostras</span>
            </div>
            <div class="efficiency-icon">
              <i class="fas fa-leaf"></i>
            </div>
          </div>

          <div class="efficiency-metrics">
            <!-- Consumo Médio (Principal) -->
            <div class="main-efficiency">
              <div class="efficiency-value-large">
                {{ efficiency.avgConsumption.toFixed(1) }}
                <span class="unit">L/100km</span>
              </div>
              <div class="efficiency-label-main">Consumo Médio</div>
            </div>

            <!-- Melhor e Pior -->
            <div class="efficiency-range">
              <div class="range-item best">
                <div class="range-icon">
                  <i class="fas fa-arrow-down"></i>
                </div>
                <div class="range-data">
                  <span class="range-value">{{ efficiency.bestEfficiency.toFixed(1) }}L</span>
                  <span class="range-label">Melhor</span>
                </div>
              </div>
              
              <div class="range-separator"></div>
              
              <div class="range-item worst">
                <div class="range-icon">
                  <i class="fas fa-arrow-up"></i>
                </div>
                <div class="range-data">
                  <span class="range-value">{{ efficiency.worstEfficiency.toFixed(1) }}L</span>
                  <span class="range-label">Pior</span>
                </div>
              </div>
            </div>
          </div>

          <!-- Indicador Visual de Eficiência -->
          <div class="efficiency-indicator">
            <div class="indicator-track">
              <div class="indicator-fill" 
                   [style.width.%]="Math.min((20 / efficiency.avgConsumption) * 100, 100)"
                   [class.excellent]="efficiency.avgConsumption <= 8"
                   [class.good]="efficiency.avgConsumption > 8 && efficiency.avgConsumption <= 12"
                   [class.average]="efficiency.avgConsumption > 12 && efficiency.avgConsumption <= 16"
                   [class.poor]="efficiency.avgConsumption > 16">
              </div>
            </div>
            <div class="indicator-labels">
              <span class="label-excellent">Excelente</span>
              <span class="label-poor">Alto Consumo</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Análise Mensal -->
    <div class="analysis-section" *ngIf="monthlyAnalysis.length > 0">
      <h5>
        <i class="fas fa-calendar-alt"></i>
        Análise Mensal
      </h5>
      <div class="monthly-analysis">
        <div 
          class="monthly-card" 
          *ngFor="let month of monthlyAnalysis.slice(-3)"
        >
          <div class="month-info">
            <span class="month-name">{{ getMonthName(month.month) }}</span>
            <div class="month-stats">
              <span class="stat">{{ month.count }} abastecimentos</span>
              <span class="stat">{{ month.liters.toFixed(1) }}L</span>
              <span class="stat">{{ month.totalKilometers.toLocaleString('pt-BR') }} km</span>
            </div>
          </div>
          <div class="month-total">
            <span class="total-value">R$ {{ month.total.toFixed(2) }}</span>
          </div>
        </div>
      </div>
    </div>

  </div>

  <!-- Template para estados vazios e erro -->
  <ng-template #emptyOrError>
    <!-- ⚠️ Estado Vazio -->
    <div class="empty-state" *ngIf="!loading && !(fuelcontrollRecords$ | async)?.length">
      <i class="fas fa-gas-pump fa-3x"></i>
      <h4>Nenhum abastecimento encontrado</h4>
      <p>Este veículo não possui registros de abastecimento.</p>
    </div>

    <!-- ❌ Estado de Erro -->
    <div class="error-state" *ngIf="hasError">
      <i class="fas fa-exclamation-triangle fa-2x"></i>
      <h4>Erro ao carregar abastecimentos</h4>
      <p>Não foi possível carregar os abastecimentos deste veículo. Tente novamente.</p>
      <button class="btn btn-outline-primary" (click)="retryLoad()">
        <i class="fas fa-sync-alt"></i>
        Tentar Novamente
      </button>
    </div>
  </ng-template>
</div>
