/**
 * 🗺️ RouteMapComponent - Mapa Interativo de Rotas
 * 
 * Componente responsável por exibir o mapa com:
 * - Marcador de origem (verde)
 * - Marcadores de paradas (azul)
 * - Marcador de destino (vermelho)
 * - Linha da rota conectando todos os pontos
 */

import { Component, Input, Output, EventEmitter, OnInit, OnDestroy, OnChanges, SimpleChanges, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { GpsTrackPoint } from "../../interfaces/vehicle-gps.interface";

import { environment } from '../../../../../../environments/environment';
import { RouteStep } from '../../../route-steps/route-steps.interface';

// 🗺️ Interface para estatísticas do mapa
export interface MapStats {
  totalStops: number;
  intermediateStops: number;
  totalDistance: string;
  estimatedTime: string;
}

// 📍 Declaração do Google Maps para TypeScript
declare global {
  interface Window {
    google: any;
    initMap: () => void;
  }
}

@Component({
  selector: 'app-route-map',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './route-map.component.html',
  styleUrl: './route-map.component.scss'
})
export class RouteMapComponent implements OnInit, OnDestroy, OnChanges, AfterViewInit {
  @Input() routeSteps: RouteStep[] = [];
  @Input() selectedStopId: string | null = null;
  @Input() isOnline: boolean = true;
  @Input() vehicleGpsTrack: { lat: number; lng: number; timestamp: Date }[] = [];
  @Input() showGpsTrack: boolean = true;
  @Input() showPlannedRoute: boolean = true;
  @Input() showCurrentRoute: boolean = true;
  @Input() currentRouteOrigin: string = 'São Paulo, SP';
  @Input() currentRouteDestination: string = 'Campinas, SP';

  @Output() stopSelected = new EventEmitter<RouteStep>();
  @Output() mapReady = new EventEmitter<boolean>();
  @Output() currentRouteCalculated = new EventEmitter<any>();
  @Output() plannedRouteToggled = new EventEmitter<boolean>();
  @Output() gpsTrackToggled = new EventEmitter<boolean>();
  @Output() currentRouteToggled = new EventEmitter<boolean>();
  @Output() mapStatsUpdated = new EventEmitter<MapStats>();

  @ViewChild('googleMapDiv', { static: false }) googleMapDiv!: ElementRef;

  private googleMap: any = null;
  private mapMarkers: any[] = [];
  private directionsService: any = null;
  private directionsRenderer: any = null;
  private routePolyline: any = null;
  private gpsTrackPolyline: any = null;
  private gpsTrackMarkers: any[] = [];
  private currentRoutePolyline: any = null;
  private currentRouteMarkers: any[] = [];

  // 🎯 SISTEMA DE FLAGS para resolver condição de corrida
  private apiLoaded = false;
  private viewReady = false;

  isMapLoading = true;
  mapStats: MapStats = {
    totalStops: 0,
    intermediateStops: 0,
    totalDistance: '0 km',
    estimatedTime: '0 min'
  };

  private readonly mapOptions = {
    zoom: 12,
    center: { lat: -23.5505, lng: -46.6333 }, // São Paulo centro
    mapTypeId: 'roadmap',
    disableDefaultUI: false,
    zoomControl: true,
    streetViewControl: true,
    fullscreenControl: true,
    mapTypeControl: true,
    styles: [
      {
        featureType: 'poi',
        elementType: 'labels',
        stylers: [{ visibility: 'off' }]
      }
    ]
  };

  private readonly pinConfig = {
    pickup: { color: '#28a745', icon: 'play', label: 'Coleta', symbol: '🟢' },
    delivery: { color: '#dc3545', icon: 'flag-checkered', label: 'Entrega', symbol: '🔴' },
    rest: { color: '#ffc107', icon: 'bed', label: 'Descanso', symbol: '🟡' },
    fuel: { color: '#007bff', icon: 'gas-pump', label: 'Combustível', symbol: '🔵' }
  };

  constructor() {
    console.log('🗺️ [RouteMapComponent] Constructor executado');
    console.log('🎯 [FLAGS] Estado inicial (apiLoaded:', this.apiLoaded, 'viewReady:', this.viewReady, ')');
  }

  ngOnInit(): void {
    console.log('🗺️ [RouteMapComponent] ngOnInit - Inicializando componente');
    console.log('🔍 Debug - Número de paradas recebidas:', this.routeSteps.length);
    console.log('🔍 Debug - Componente online:', this.isOnline);
    console.log('🎯 [FLAGS] Iniciando carregamento da API (apiLoaded:', this.apiLoaded, 'viewReady:', this.viewReady, ')');
    
    this.updateMapStats(); 
    this.loadGoogleMapsAPI(); // Inicia carregamento da API
  }

  ngAfterViewInit(): void {
    console.log('🗺️ [RouteMapComponent] ngAfterViewInit - View inicializada');
    console.log('🔍 Debug - googleMapDiv disponível:', !!this.googleMapDiv?.nativeElement);
    
    // ✅ Marca que a view está pronta
    this.viewReady = true;
    // console.log('🎯 [FLAGS] View pronta (apiLoaded:', this.apiLoaded, 'viewReady:', this.viewReady, ')');
    // Tenta inicializar se API já carregou
    this.tryInitializeMap();
  }

  ngOnChanges(changes: SimpleChanges): void {
    console.log('🔄 RouteMapComponent - Mudanças detectadas:', changes);

    // Mudança nas paradas da rota
    if (changes['routeSteps'] && this.googleMap) {
      console.log('🔄 Paradas da rota mudaram:', this.routeSteps.length);
      this.updateMapMarkers();
      
      // Força ajuste de zoom após um delay
      setTimeout(() => {
       this.forceMapFit();
      }, 300);
    }

    // Mudança na parada selecionada
    if (changes['selectedStopId'] && this.googleMap) {
      console.log('🔄 Parada selecionada mudou:', this.selectedStopId);
      this.highlightSelectedStop();
    }

    // Mudança no traço GPS
    if (changes['vehicleGpsTrack'] && this.googleMap) {
      console.log('🔄 Traço GPS mudou:', this.vehicleGpsTrack?.length || 0, 'pontos');
      //this.updateGpsTrack();
    }

    // Mudanças na visibilidade das rotas
    if (changes['showGpsTrack'] && this.googleMap) {
      console.log('🔄 Visibilidade GPS mudou:', this.showGpsTrack);
      this.toggleGpsTrackVisibility();
    }

    if (changes['showPlannedRoute'] && this.googleMap) {
      console.log('🔄 Visibilidade rota planejada mudou:', this.showPlannedRoute);
      this.togglePlannedRouteVisibility();
    }

    if (changes['showCurrentRoute'] && this.googleMap) {
      console.log('🔄 Visibilidade rota atual mudou:', this.showCurrentRoute);
      this.toggleCurrentRouteVisibility();
    }

    // Mudanças na rota atual
    if ((changes['currentRouteOrigin'] || changes['currentRouteDestination']) && this.googleMap) {
      console.log('🔄 Origem/destino da rota atual mudou');
      this.updateCurrentRoute();
    }
  }

  ngOnDestroy(): void {
    console.log('🗺️ [RouteMapComponent] ngOnDestroy - Limpando recursos');
    console.log('🎯 [FLAGS] Resetando flags na destruição');
    
    // Reset das flags
    this.apiLoaded = false;
    this.viewReady = false;
    
    this.clearMapMarkers();
  }

  private loadGoogleMapsAPI(): void {
    // 🔍 DEBUG: Verificar configurações
    console.log('🔍 Debug - API Key:', environment.googleMapsApiKey ? 'CONFIGURADA' : 'NÃO CONFIGURADA');
    console.log('🔍 Debug - Window Google existe:', !!window.google);
    
    // ✅ CORREÇÃO 1: Verificar se API key existe
    if (!environment.googleMapsApiKey) {
      console.error('❌ Google Maps API Key não configurada no environment');
      this.isMapLoading = false;
      this.showApiKeyError();
      return;
    }

    if (window.google && window.google.maps) {
      console.log('✅ Google Maps API já carregada');
      this.initializeMap();
      return;
    }

    console.log('📦 Carregando Google Maps API...');
    
    // ✅ CORREÇÃO 2: Callback único por instância para evitar conflitos
    const callbackName = `initMap_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    console.log('🎯 Callback criado:', callbackName);
    
    (window as any)[callbackName] = () => {
      console.log('✅ Google Maps API carregada com sucesso via callback:', callbackName);
      
      // ✅ Marca que a API carregou
      this.apiLoaded = true;
      console.log('🎯 [FLAGS] API carregada (apiLoaded:', this.apiLoaded, 'viewReady:', this.viewReady, ')');
      
      // Tenta inicializar se view já está pronta
      this.tryInitializeMap();
      
      // Limpa callback após uso para evitar vazamentos de memória
      delete (window as any)[callbackName];
    };

    const script = document.createElement('script');
    // ✅ CORREÇÃO 3: Removida library 'marker' para melhor compatibilidade
    script.src = `https://maps.googleapis.com/maps/api/js?key=${environment.googleMapsApiKey}&callback=${callbackName}&libraries=geometry,places`;
    script.async = true;
    script.defer = true;
    
    console.log('🔍 Debug - Script URL:', script.src);
    
    script.onerror = (error) => {
      console.error('❌ Erro ao carregar Google Maps API:', error);
      console.error('🔍 Verifique se a API Key é válida e se o domínio está autorizado');
      console.log('🎯 [FLAGS] Erro na API (apiLoaded:', this.apiLoaded, 'viewReady:', this.viewReady, ')');
      this.isMapLoading = false;
      this.showFallbackMap();
      // Limpa callback em caso de erro
      delete (window as any)[callbackName];
    };
    
    document.head.appendChild(script);
  }

  // 🎯 SISTEMA DE FLAGS: Tenta inicializar apenas quando ambas as condições são atendidas
  private tryInitializeMap(): void {

    this.initializeMap();

    // console.log('🎯 [FLAGS] Tentando inicializar mapa (apiLoaded:', this.apiLoaded, 'viewReady:', this.viewReady, ')');
    
    // if (this.apiLoaded && this.viewReady) {
    //   console.log('✅ [FLAGS] Ambas as condições atendidas - Inicializando mapa');
    //   this.initializeMap();
    // } else {
    //   console.log('⏳ [FLAGS] Aguardando condições:', {
    //     apiLoaded: this.apiLoaded ? '✅' : '❌',
    //     viewReady: this.viewReady ? '✅' : '❌'
    //   });
    // }
  }

  private initializeMap(): void {
    console.log('🗺️ Iniciando initializeMap...');
    
    // 🔍 DEBUG: Verificar estado do ViewChild
    console.log('🔍 Debug - googleMapDiv existe:', !!this.googleMapDiv);
    console.log('🔍 Debug - nativeElement existe:', !!this.googleMapDiv?.nativeElement);
    
    // ✅ Com sistema de flags, o ViewChild deve estar sempre disponível aqui
    if (!this.googleMapDiv?.nativeElement) {
      console.error('❌ ERRO CRÍTICO: Container do mapa não encontrado mesmo com sistema de flags');
      this.isMapLoading = false;
      this.showFallbackMap();
      return;
    }

    try {
      console.log('🗺️ Inicializando Google Maps com container válido...');
      
      // Configurações otimizadas do mapa
      const optimizedMapOptions = {
        ...this.mapOptions,
        zoom: 8, // Zoom inicial menor para mostrar mais área
        center: { lat: -23.5505, lng: -46.6333 }, // São Paulo centro
        restriction: {
          latLngBounds: {
            north: -20.0,
            south: -26.0,
            west: -50.0,
            east: -42.0
          },
          strictBounds: false
        }
      };
      
      this.googleMap = new window.google.maps.Map(
        this.googleMapDiv.nativeElement,
        optimizedMapOptions
      );

      // Inicializa serviços do Google Maps
      this.directionsService = new window.google.maps.DirectionsService();
      this.directionsRenderer = new window.google.maps.DirectionsRenderer({
        suppressMarkers: true,
        polylineOptions: {
          strokeColor: '#007bff',
          strokeWeight: 4,
          strokeOpacity: 0.8
        }
      });

      this.directionsRenderer.setMap(this.googleMap);

      console.log('✅ Google Maps inicializado com sucesso');
      console.log('🔍 Debug - Mapa criado:', !!this.googleMap);
      console.log('🔍 Debug - DirectionsService criado:', !!this.directionsService);
      console.log('🔍 Debug - DirectionsRenderer criado:', !!this.directionsRenderer);
      
      this.isMapLoading = false;
      this.mapReady.emit(true);

      // Aguarda um pouco para garantir que o mapa está totalmente carregado
      setTimeout(() => {
        this.updateMapMarkers();
        this.updateGpsTrack();
        this.updateCurrentRoute();
        
        // Ajusta automaticamente o zoom para mostrar todas as paradas
        if (this.routeSteps.length > 0) {
          this.fitMapBounds();
        }
      }, 500);

    } catch (error) {
      console.error('❌ Erro ao inicializar Google Maps:', error);
      this.isMapLoading = false;
      this.showFallbackMap();
    }
  }

  private updateMapMarkers(): void {
    if (!this.googleMap) {
      console.warn('⚠️ Mapa não inicializado ainda');
      return;
    }

    console.log('📍 Atualizando markers do mapa:', this.routeSteps.length, 'paradas');

    // Remove markers anteriores
    this.clearMapMarkers();

    if (this.routeSteps.length === 0) {
      console.log('ℹ️ Nenhuma parada para exibir');
      return;
    }

    // Cria markers para cada parada usando AdvancedMarkerElement
    this.routeSteps.forEach((stop, index) => {
      // 🎯 VALIDAÇÃO: Verifica se a parada tem dados válidos
      if (!stop || !stop.location || !stop.location.coordinates) {
        console.warn('⚠️ Parada com localização inválida ignorada:', stop);
        return;
      }

      if (!stop.type || !['pickup', 'delivery', 'rest', 'fuel'].includes(stop.type)) {
        console.warn('⚠️ Parada com tipo inválido, usando "delivery" como padrão:', stop.type);
        stop.type = 'delivery';
      }

      if (!stop.status || !['pending', 'completed', 'failed', 'skipped'].includes(stop.status)) {
        console.warn('⚠️ Parada com status inválido, usando "pending" como padrão:', stop.status);
        stop.status = 'pending';
      }

      try {
        const position = {
          lat: stop.location.coordinates.lat,
          lng: stop.location.coordinates.lng
        };

        // Verifica se as coordenadas são números válidos
        if (isNaN(position.lat) || isNaN(position.lng)) {
          console.warn('⚠️ Coordenadas inválidas para parada:', stop.id, position);
          return;
        }

        // ⚠️ NOTA: google.maps.Marker está depreciado desde 21/02/2024
        // Recomendação: migrar para google.maps.marker.AdvancedMarkerElement
        // Por enquanto mantemos funcional para compatibilidade
        const marker = new window.google.maps.Marker({
          position: position,
          map: this.googleMap,
          icon: this.getCustomMarkerIcon(stop.type, stop.sequence),
          title: stop.location.address || `Parada #${stop.sequence}`,
          zIndex: 1000 + index
        });

        const infoWindow = new window.google.maps.InfoWindow({
          content: this.getMarkerInfoContent(stop),
          maxWidth: 350
        });

        // 🎯 NOVA API: Event listener para AdvancedMarkerElement
        marker.addListener('click', () => {
          // Fecha outras InfoWindows
          this.mapMarkers.forEach(({ infoWindow: iw }) => iw.close());
          
          // Abre a InfoWindow clicada
          infoWindow.open(this.googleMap, marker);
          
          // Emite evento de seleção
          this.stopSelected.emit(stop);
        });

        this.mapMarkers.push({ marker, infoWindow, stop });

      } catch (error) {
        console.error('❌ Erro ao criar marker para parada:', stop.id, error);
        // Fallback para Marker tradicional se AdvancedMarkerElement falhar
        this.createFallbackMarker(stop, index);
      }
    });

    // Desenha a rota conectando as paradas
    this.drawEnhancedRoute();

    // Atualiza estatísticas
    this.updateMapStats();

    // Ajusta automaticamente o zoom para mostrar todas as paradas
    setTimeout(() => {
      this.fitMapBounds();
    }, 100);

    console.log('✅ Markers atualizados e bounds ajustados');
  }

  private getCustomMarkerIcon(type: RouteStep['type'], sequence: number): any {
    // 🎯 VALIDAÇÃO: Garante que o tipo existe, senão usa 'delivery' como padrão
    const config = this.pinConfig[type] || this.pinConfig['delivery'];
    
    return {
      url: `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(`
        <svg width="40" height="50" viewBox="0 0 40 50" xmlns="http://www.w3.org/2000/svg">
          <defs>
            <filter id="shadow" x="-50%" y="-50%" width="200%" height="200%">
              <dropShadow dx="2" dy="4" stdDeviation="3" flood-color="rgba(0,0,0,0.3)"/>
            </filter>
          </defs>
          
          <!-- Pin principal -->
          <path d="M20 0C8.95 0 0 8.95 0 20c0 15 20 30 20 30s20-15 20-30C40 8.95 31.05 0 20 0z" 
                fill="${config.color}" stroke="white" stroke-width="2" filter="url(#shadow)"/>
          
          <!-- Círculo interno branco -->
          <circle cx="20" cy="20" r="12" fill="white"/>
          
          <!-- Número da sequência -->
          <text x="20" y="26" text-anchor="middle" font-family="Arial, sans-serif" 
                font-size="14" font-weight="bold" fill="${config.color}">${sequence}</text>
        </svg>
      `)}`,
      scaledSize: new window.google.maps.Size(40, 50),
      anchor: new window.google.maps.Point(20, 50)
    };
  }

  private getMarkerInfoContent(stop: RouteStep): string {
    const config = this.pinConfig[stop.type] || this.pinConfig["delivery"];
    const estimatedTime = stop.estimatedDuration ? `${stop.estimatedDuration}min` : '';
    
    // Cores para diferentes status
    const statusConfig = {
      pending: { color: '#ffc107', label: 'Pendente', icon: '⏳' },
      completed: { color: '#28a745', label: 'Concluída', icon: '✅' },
      failed: { color: '#dc3545', label: 'Falhada', icon: '❌' },
      skipped: { color: '#6c757d', label: 'Pulada', icon: '⏭️' }
    };

    // 🎯 VALIDAÇÃO: Garante que o status existe, senão usa 'pending' como padrão
    const statusInfo = statusConfig[stop.status] || statusConfig['pending'];
    
    // Tipo de parada com ícones
    const typeConfig = {
      pickup: { label: 'Coleta', icon: '📦', color: '#28a745' },
      delivery: { label: 'Entrega', icon: '🚚', color: '#dc3545' },
      rest: { label: 'Descanso', icon: '☕', color: '#ffc107' },
      fuel: { label: 'Combustível', icon: '⛽', color: '#007bff' }
    };

    // 🎯 VALIDAÇÃO: Garante que o tipo existe, senão usa 'delivery' como padrão
    const typeInfo = typeConfig[stop.type] || typeConfig['delivery'];

    // 🎯 VALIDAÇÃO: Garante que config existe (do pinConfig)
    const pinInfo = config || this.pinConfig['delivery'];

    return `
      <div style="
        min-width: 280px; 
        max-width: 320px;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 8px 32px rgba(0,0,0,0.12);
        background: white;
        margin: -8px -12px;
      ">
        
        <!-- Header do Card -->
        <div style="
          background: linear-gradient(135deg, ${typeInfo.color} 0%, ${this.darkenColor(typeInfo.color, 20)} 100%);
          color: white;
          padding: 16px 20px;
          position: relative;
          overflow: hidden;
        ">
          <div style="
            position: absolute;
            top: -20px;
            right: -20px;
            width: 80px;
            height: 80px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
          "></div>
          
          <div style="display: flex; align-items: center; justify-content: space-between; position: relative; z-index: 1;">
            <div>
              <h3 style="
                margin: 0 0 4px 0; 
                font-size: 18px; 
                font-weight: 700;
                text-shadow: 0 1px 2px rgba(0,0,0,0.1);
              ">
                ${typeInfo.icon} ${typeInfo.label} #${stop.sequence}
              </h3>
              <div style="
                background: rgba(255,255,255,0.2);
                padding: 4px 12px;
                border-radius: 20px;
                font-size: 12px;
                font-weight: 500;
                display: inline-block;
              ">
                ${statusInfo.icon} ${statusInfo.label}
              </div>
            </div>
            
            <div style="
              background: rgba(255,255,255,0.15);
              border-radius: 50%;
              width: 48px;
              height: 48px;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: 20px;
              backdrop-filter: blur(10px);
            ">
              ${typeInfo.icon}
            </div>
          </div>
        </div>

        <!-- Conteúdo do Card -->
        <div style="padding: 20px;">
          
          <!-- Endereço -->
          <div style="margin-bottom: 16px;">
            <div style="
              display: flex;
              align-items: center;
              margin-bottom: 6px;
              color: #666;
              font-size: 12px;
              font-weight: 600;
              text-transform: uppercase;
              letter-spacing: 0.5px;
            ">
              📍 Endereço
            </div>
            <div style="
              font-size: 15px;
              font-weight: 500;
              color: #333;
              line-height: 1.4;
            ">
              ${stop.location?.address || 'Endereço não informado'}
            </div>
            ${stop.location?.city ? `
              <div style="
                font-size: 13px;
                color: #666;
                margin-top: 4px;
              ">
                ${stop.location.city} - ${stop.location.state || ''}
              </div>
            ` : ''}
          </div>

          <!-- Informações da Parada -->
          <div style="
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
            margin-bottom: 16px;
          ">
            ${estimatedTime ? `
              <div style="
                background: #f8f9fa;
                padding: 12px;
                border-radius: 8px;
                border-left: 3px solid #007bff;
              ">
                <div style="
                  font-size: 11px;
                  color: #666;
                  font-weight: 600;
                  text-transform: uppercase;
                  margin-bottom: 4px;
                ">
                  ⏱️ Tempo
                </div>
                <div style="
                  font-size: 14px;
                  font-weight: 600;
                  color: #333;
                ">
                  ${estimatedTime}
                </div>
              </div>
            ` : ''}
            
            ${stop.packages ? `
              <div style="
                background: #f8f9fa;
                padding: 12px;
                border-radius: 8px;
                border-left: 3px solid #28a745;
              ">
                <div style="
                  font-size: 11px;
                  color: #666;
                  font-weight: 600;
                  text-transform: uppercase;
                  margin-bottom: 4px;
                ">
                  📦 Pacotes
                </div>
                <div style="
                  font-size: 14px;
                  font-weight: 600;
                  color: #333;
                ">
                  ${stop.packages}
                </div>
              </div>
            ` : ''}
          </div>

          <!-- Documento Fiscal (se existir) -->
          ${stop.fiscalDocument ? `
            <div style="
              background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
              border: 1px solid #e1bee7;
              padding: 16px;
              border-radius: 10px;
              margin-bottom: 16px;
            ">
              <div style="
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 8px;
              ">
                <div style="
                  font-size: 13px;
                  font-weight: 600;
                  color: #1976d2;
                  display: flex;
                  align-items: center;
                  gap: 6px;
                ">
                  📄 ${stop.fiscalDocument.documentType}
                </div>
                <div style="
                  background: #1976d2;
                  color: white;
                  padding: 2px 8px;
                  border-radius: 12px;
                  font-size: 10px;
                  font-weight: 600;
                ">
                  ${stop.fiscalDocument.status}
                </div>
              </div>
              <div style="
                font-size: 12px;
                color: #666;
                margin-bottom: 4px;
              ">
                Nº ${stop.fiscalDocument.documentNumber}
              </div>
              ${stop.fiscalDocument.totalValue ? `
                <div style="
                  font-size: 14px;
                  font-weight: 600;
                  color: #2e7d32;
                ">
                  R$ ${stop.fiscalDocument.totalValue.toLocaleString('pt-BR', { minimumFractionDigits: 2 })}
                </div>
              ` : ''}
            </div>
          ` : ''}

          <!-- Notas adicionais -->
          ${stop.notes ? `
            <div style="
              background: #fff3cd;
              border: 1px solid #ffeaa7;
              padding: 12px;
              border-radius: 8px;
              margin-bottom: 16px;
            ">
              <div style="
                font-size: 11px;
                color: #856404;
                font-weight: 600;
                text-transform: uppercase;
                margin-bottom: 6px;
              ">
                📝 Observações
              </div>
              <div style="
                font-size: 13px;
                color: #856404;
                line-height: 1.4;
              ">
                ${stop.notes}
              </div>
            </div>
          ` : ''}

          <!-- Footer com ação -->
          <div style="
            text-align: center;
            padding-top: 12px;
            border-top: 1px solid #f0f0f0;
          ">
            <div style="
              color: #999;
              font-size: 12px;
              margin-bottom: 8px;
            ">
              Clique para selecionar esta parada
            </div>
            <div style="
              background: linear-gradient(135deg, ${typeInfo.color} 0%, ${this.darkenColor(typeInfo.color, 10)} 100%);
              color: white;
              padding: 8px 16px;
              border-radius: 20px;
              font-size: 12px;
              font-weight: 600;
              display: inline-block;
              cursor: pointer;
              transition: all 0.2s ease;
            ">
              ${typeInfo.icon} Ver Detalhes
            </div>
          </div>
        </div>
      </div>
    `;
  }

  // 🎨 Função auxiliar para escurecer cores
  private darkenColor(color: string, percent: number): string {
    const num = parseInt(color.replace("#", ""), 16);
    const amt = Math.round(2.55 * percent);
    const R = (num >> 16) - amt;
    const G = (num >> 8 & 0x00FF) - amt;
    const B = (num & 0x0000FF) - amt;
    return "#" + (0x1000000 + (R < 255 ? R < 1 ? 0 : R : 255) * 0x10000 +
      (G < 255 ? G < 1 ? 0 : G : 255) * 0x100 +
      (B < 255 ? B < 1 ? 0 : B : 255)).toString(16).slice(1);
  }

  private drawEnhancedRoute(): void {
    if (!this.directionsService || !this.directionsRenderer || this.routeSteps.length < 2) {
      return;
    }

    const sortedStops = [...this.routeSteps].sort((a, b) => a.sequence - b.sequence);
    
    const waypoints = sortedStops
      .slice(1, -1)
      .map(stop => ({
        location: { lat: stop.location.coordinates.lat, lng: stop.location.coordinates.lng },
        stopover: true
      }));

    const request = {
      origin: { lat: sortedStops[0].location.coordinates.lat, lng: sortedStops[0].location.coordinates.lng },
      destination: { lat: sortedStops[sortedStops.length - 1].location.coordinates.lat, lng: sortedStops[sortedStops.length - 1].location.coordinates.lng },
      waypoints: waypoints,
      travelMode: window.google.maps.TravelMode.DRIVING,
      optimizeWaypoints: false,
      avoidHighways: false,
      avoidTolls: false
    };

    this.directionsService.route(request, (result: any, status: any) => {
      if (status === 'OK') {
        this.directionsRenderer.setOptions({
          suppressMarkers: true,
          polylineOptions: {
            strokeColor: '#007bff',
            strokeWeight: 6,
            strokeOpacity: 0.8,
            geodesic: true,
            icons: [{
              icon: {
                path: window.google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
                scale: 3,
                fillColor: '#007bff',
                fillOpacity: 1,
                strokeColor: 'white',
                strokeWeight: 1
              },
              offset: '100%',
              repeat: '50px'
            }]
          }
        });
        
        this.directionsRenderer.setDirections(result);
        this.updateRouteStats(result);
        
        this.addTripAnnotations(result);
        
        console.log('✅ Rota calculada e desenhada com sucesso');
      } else {
        console.warn('⚠️ Não foi possível calcular a rota:', status);
        this.drawFallbackRoute();
      }
    });
  }

  private addTripAnnotations(directionsResult: any): void {
    const route = directionsResult.routes[0];
    
    new window.google.maps.Marker({
      position: route.legs[0].start_location,
      map: this.googleMap,
      icon: {
        url: `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(`
          <svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
            <circle cx="12" cy="12" r="10" fill="#28a745" stroke="white" stroke-width="2"/>
            <path d="M8 12l2 2 4-4" stroke="white" stroke-width="2" fill="none"/>
          </svg>
        `)}`,
        scaledSize: new window.google.maps.Size(24, 24),
        anchor: new window.google.maps.Point(12, 12)
      },
      title: 'Início da Viagem',
      zIndex: 2000
    });

    new window.google.maps.Marker({
      position: route.legs[route.legs.length - 1].end_location,
      map: this.googleMap,
      icon: {
        url: `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(`
          <svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
            <circle cx="12" cy="12" r="10" fill="#dc3545" stroke="white" stroke-width="2"/>
            <rect x="8" y="8" width="8" height="8" fill="white"/>
          </svg>
        `)}`,
        scaledSize: new window.google.maps.Size(24, 24),
        anchor: new window.google.maps.Point(12, 12)
      },
      title: 'Fim da Viagem',
      zIndex: 2000
    });
  }

  private drawFallbackRoute(): void {
    if (this.routeSteps.length < 2) return;

    const sortedStops = [...this.routeSteps].sort((a, b) => a.sequence - b.sequence);
    const path = sortedStops.map(stop => ({
      lat: stop.location.coordinates.lat,
      lng: stop.location.coordinates.lng
    }));

    this.routePolyline = new window.google.maps.Polyline({
      path: path,
      geodesic: true,
      strokeColor: '#007bff',
      strokeOpacity: 0.8,
      strokeWeight: 4,
      icons: [{
        icon: {
          path: window.google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
          scale: 2,
          fillColor: '#007bff',
          fillOpacity: 1
        },
        offset: '100%',
        repeat: '80px'
      }]
    });

    this.routePolyline.setMap(this.googleMap);
  }

  // 🎯 Ajusta o mapa para mostrar todas as paradas
  private fitMapBounds(): void {
    if (!this.googleMap || this.routeSteps.length === 0) {
      return;
    }

    console.log('🎯 Ajustando bounds do mapa para', this.routeSteps.length, 'paradas');

    const bounds = new window.google.maps.LatLngBounds();
    
    // Adiciona todas as paradas aos bounds
    this.routeSteps.forEach(stop => {
      const position = new window.google.maps.LatLng(
        stop.location.coordinates.lat,
        stop.location.coordinates.lng
      );
      bounds.extend(position);
    });

    // Adiciona pontos do GPS track se disponível e visível
    if (this.showGpsTrack && this.vehicleGpsTrack && this.vehicleGpsTrack.length > 0) {
      this.vehicleGpsTrack.forEach(point => {
        const position = new window.google.maps.LatLng(point.lat, point.lng);
        bounds.extend(position);
      });
    }

    // Verifica se temos bounds válidos
    if (bounds.isEmpty()) {
      console.warn('⚠️ Bounds vazios, usando posição padrão');
      this.googleMap.setCenter({ lat: -23.5505, lng: -46.6333 });
      this.googleMap.setZoom(12);
      return;
    }

    // Aplica os bounds com padding generoso para dar espaço visual
    const padding = {
      top: 80,
      right: 80,
      bottom: 150, // Mais espaço embaixo por causa dos controles
      left: 80
    };

    // Força o ajuste dos bounds
    this.googleMap.fitBounds(bounds, padding);

    // Aguarda um pouco e força novamente para garantir
    setTimeout(() => {
      this.googleMap.fitBounds(bounds, padding);
      
      // Garante um zoom máximo para não ficar muito próximo
      const currentZoom = this.googleMap.getZoom();
      const maxZoom = 16;
      const minZoom = 10;
      
      if (currentZoom > maxZoom) {
        this.googleMap.setZoom(maxZoom);
      } else if (currentZoom < minZoom) {
        this.googleMap.setZoom(minZoom);
      }
      
      console.log('✅ Bounds ajustados - Zoom atual:', this.googleMap.getZoom());
    }, 200);

    console.log('✅ Bounds ajustados com padding:', padding);
  }

  private updateRouteStats(directionsResult?: any): void {
    this.mapStats = {
      totalStops: this.routeSteps.length,
      intermediateStops: Math.max(0, this.routeSteps.length - 2),
      totalDistance: directionsResult ? this.formatDistance(directionsResult.routes[0].legs) : '0 km',
      estimatedTime: directionsResult ? this.formatDuration(directionsResult.routes[0].legs) : '0 min'
    };
    this.mapStatsUpdated.emit(this.mapStats);
  }

  private highlightSelectedStop(): void {
    this.mapMarkers.forEach(({ marker, infoWindow, stop }) => {
      if (stop.id === this.selectedStopId) {
        infoWindow.open(this.googleMap, marker);
        this.googleMap.panTo(marker.getPosition());
        this.googleMap.setZoom(15);
      } else {
        infoWindow.close();
      }
    });
  }

  // 📍 Atualiza o traço GPS real do veículo
  private updateGpsTrack(): void {
    if (!this.googleMap || this.vehicleGpsTrack.length === 0) {
      return;
    }

    console.log('📍 Desenhando traço GPS com', this.vehicleGpsTrack.length, 'pontos');

    // Remove traço GPS anterior
    this.clearGpsTrack();

    // Ordena pontos por timestamp
    const sortedGpsPoints = [...this.vehicleGpsTrack].sort((a, b) => 
      new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
    );

    // Cria path para o traço GPS
    const gpsPath = sortedGpsPoints.map(point => ({
      lat: point.lat,
      lng: point.lng
    }));

    // Desenha traço GPS principal (vermelho/laranja)
    this.gpsTrackPolyline = new window.google.maps.Polyline({
      path: gpsPath,
      geodesic: true,
      strokeColor: '#ff4444', // Vermelho para GPS real
      strokeOpacity: 0.8,
      strokeWeight: 4,
      icons: [{
        icon: {
          path: window.google.maps.SymbolPath.CIRCLE,
          scale: 2,
          fillColor: '#ff4444',
          fillOpacity: 1,
          strokeColor: '#ffffff',
          strokeWeight: 1
        },
        offset: '0%',
        repeat: '30px'
      }],
      zIndex: 100 // Menor que a rota planejada para ficar por baixo
    });

    this.gpsTrackPolyline.setMap(this.googleMap);

    // Adiciona markers para início e fim do traço GPS
    if (sortedGpsPoints.length > 1) {
      // Marker de início do GPS (verde)
      const startGpsMarker = new window.google.maps.Marker({
        position: { lat: sortedGpsPoints[0].lat, lng: sortedGpsPoints[0].lng },
        map: this.googleMap,
        icon: {
          url: `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(`
            <svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
              <circle cx="10" cy="10" r="8" fill="#28a745" stroke="white" stroke-width="2"/>
              <circle cx="10" cy="10" r="3" fill="white"/>
            </svg>
          `)}`,
          scaledSize: new window.google.maps.Size(20, 20),
          anchor: new window.google.maps.Point(10, 10)
        },
        title: `Início do Traço GPS`,
        zIndex: 2000
      });

      // Marker de fim do GPS (vermelho)
      const endGpsMarker = new window.google.maps.Marker({
        position: { lat: sortedGpsPoints[sortedGpsPoints.length - 1].lat, lng: sortedGpsPoints[sortedGpsPoints.length - 1].lng },
        map: this.googleMap,
        icon: {
          url: `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(`
            <svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
              <circle cx="10" cy="10" r="8" fill="#dc3545" stroke="white" stroke-width="2"/>
              <circle cx="10" cy="10" r="3" fill="white"/>
            </svg>
          `)}`,
          scaledSize: new window.google.maps.Size(20, 20),
          anchor: new window.google.maps.Point(10, 10)
        },
        title: `Fim do Traço GPS`,
        zIndex: 2000
      });
    }
  }

  // 🎯 NOVA API: Método para criar conteúdo HTML customizado para AdvancedMarkerElement
  private createCustomMarkerContent(type: RouteStep['type'], sequence: number): HTMLElement {
    const config = this.pinConfig[type] || this.pinConfig['delivery'];
    
    // Cria elemento div para o marker
    const markerDiv = document.createElement('div');
    markerDiv.style.cssText = `
      position: relative;
      width: 40px;
      height: 50px;
      cursor: pointer;
      transform-origin: center bottom;
      transition: transform 0.2s ease;
    `;
    
    // Adiciona efeito hover
    markerDiv.addEventListener('mouseenter', () => {
      markerDiv.style.transform = 'scale(1.1)';
    });
    
    markerDiv.addEventListener('mouseleave', () => {
      markerDiv.style.transform = 'scale(1)';
    });
    
    // Cria SVG interno
    markerDiv.innerHTML = `
      <svg width="40" height="50" viewBox="0 0 40 50" style="filter: drop-shadow(0 2px 4px rgba(0,0,0,0.3));">
        <!-- Pin principal -->
        <path d="M20 0C8.95 0 0 8.95 0 20c0 15 20 30 20 30s20-15 20-30C40 8.95 31.05 0 20 0z" 
              fill="${config.color}" stroke="white" stroke-width="2"/>
        
        <!-- Círculo interno branco -->
        <circle cx="20" cy="20" r="12" fill="white"/>
        
        <!-- Número da sequência -->
        <text x="20" y="26" text-anchor="middle" font-family="Arial, sans-serif" 
              font-size="14" font-weight="bold" fill="${config.color}">${sequence}</text>
      </svg>
    `;
    
    return markerDiv;
  }


  // 🎯 Método fallback para criar marker tradicional quando AdvancedMarkerElement falha
  private createFallbackMarker(stop: RouteStep, index: number): void {
    console.warn('⚠️ createFallbackMarker: Erro já tratado no catch, marker não será criado para:', stop.id);
  }

  // 🧹 Remove markers anteriores
  private clearMapMarkers(): void {
    this.mapMarkers.forEach(({ marker, infoWindow }) => {
      infoWindow.close();
      marker.setMap(null);
    });
    this.mapMarkers = [];
  }

  // 🧹 Remove traço GPS
  private clearGpsTrack(): void {
    if (this.gpsTrackPolyline) {
      this.gpsTrackPolyline.setMap(null);
      this.gpsTrackPolyline = null;
    }
    
    this.gpsTrackMarkers.forEach(marker => {
      marker.setMap(null);
    });
    this.gpsTrackMarkers = [];
  }

  // 🎯 Força o ajuste do mapa para mostrar tudo
  forceMapFit(): void {
    if (!this.googleMap) {
      return;
    }
    
    setTimeout(() => {
      window.google.maps.event.trigger(this.googleMap, 'resize');
      this.fitMapBounds();
    }, 100);
  }

  // 🎯 Centraliza o mapa
  centerMap(): void {
    if (this.googleMap && this.routeSteps.length > 0) {
      this.fitMapBounds();
    }
  }

  // 🔄 Recarrega o mapa
  reloadMap(): void {
    if (this.googleMap) {
      this.updateMapMarkers();
    }
  }

  // 🎯 Método público para debug das flags
  getInitializationStatus(): { apiLoaded: boolean; viewReady: boolean; mapReady: boolean } {
    return {
      apiLoaded: this.apiLoaded,
      viewReady: this.viewReady,
      mapReady: !!this.googleMap
    };
  }

  // 🗺️ Alterna tipo de mapa
  toggleMapType(): void {
    if (!this.googleMap) return;
    
    const currentType = this.googleMap.getMapTypeId();
    const newType = currentType === 'roadmap' ? 'satellite' : 'roadmap';
    this.googleMap.setMapTypeId(newType);
  }

  // 📊 Atualiza estatísticas do mapa
  private updateMapStats(): void {
    this.mapStats = {
      totalStops: this.routeSteps.length,
      intermediateStops: Math.max(0, this.routeSteps.length - 2),
      totalDistance: '0 km',
      estimatedTime: '0 min'
    };
    this.mapStatsUpdated.emit(this.mapStats);
  }

  // 👁️ Alterna visibilidade da rota planejada
  togglePlannedRouteVisibility(): void {
    console.log('👁️ Alternando visibilidade da rota planejada:', this.showPlannedRoute);
  }

  // 👁️ Alterna visibilidade do traço GPS
  toggleGpsTrackVisibility(): void {
    console.log('👁️ Alternando visibilidade do traço GPS:', this.showGpsTrack);
  }

  // 👁️ Alterna visibilidade da rota atual
  toggleCurrentRouteVisibility(): void {
    console.log('👁️ Alternando visibilidade da rota atual:', this.showCurrentRoute);
  }

  // 🌍 Atualiza a rota atual
  private updateCurrentRoute(): void {
    console.log('🌍 Atualizando rota atual');
  }

  // 🔄 Mostra mapa de fallback quando Google Maps falha
  private showFallbackMap(): void {
    console.log('🔄 Mostrando mapa de fallback...');
    this.isMapLoading = false;
    
    // TODO: Implementar mapa SVG simples ou mensagem de erro adequada
    // Por enquanto, apenas garante que o loading seja removido
    console.warn('⚠️ Google Maps não disponível - implementar fallback SVG ou OpenStreetMap');
  }

  // 🔑 Mostra erro de API Key não configurada  
  private showApiKeyError(): void {
    console.error('🔑 Erro de configuração - API Key do Google Maps não encontrada');
    this.isMapLoading = false;
    
    // TODO: Mostrar mensagem de erro específica para API Key
    console.warn('⚠️ Configure a API Key do Google Maps no arquivo environment.ts');
  }

  // 📏 Formata distância
  private formatDistance(legs: any[]): string {
    const totalDistance = legs.reduce((sum, leg) => sum + leg.distance.value, 0);
    return totalDistance > 1000 
      ? `${(totalDistance / 1000).toFixed(1)} km`
      : `${totalDistance} m`;
  }

  // ⏱️ Formata duração
  private formatDuration(legs: any[]): string {
    const totalDuration = legs.reduce((sum, leg) => sum + leg.duration.value, 0);
    const hours = Math.floor(totalDuration / 3600);
    const minutes = Math.floor((totalDuration % 3600) / 60);
    
    if (hours > 0) {
      return `${hours}h ${minutes}min`;
    }
    return `${minutes}min`;
  }

  private updateVehicleGpsTrack(points: GpsTrackPoint[]) {
    // Só atualiza se mudou de verdade
    const newTrack = points.map(point => ({
      lat: point.lat,
      lng: point.lng,
      timestamp: point.timestamp instanceof Date ? point.timestamp : new Date(point.timestamp)
    }));
    if (JSON.stringify(this.vehicleGpsTrack) !== JSON.stringify(newTrack)) {
      this.vehicleGpsTrack = newTrack;
    }
  }

}
