/// <reference types="@types/google.maps" />
import React, { useEffect, useRef, useState, useCallback } from 'react';
import { io, Socket } from 'socket.io-client';
import { 
  Truck, Search, MapPin, Radio, Activity, X, Check,
  Loader2, Compass, Play, RefreshCw
} from 'lucide-react';
// import { motion } from 'framer-motion';

// --- Types ---
interface Vehicle {
  id: string;
  registration_number: string;
  chassis_number?: string | null; 
  brand?: string;
  model?: string;
  vehicle_type: string; // ALS, BLS, etc.
  status: string; // BUSY, AVAILABLE, OFFLINE
  gps_lat: string | number; 
  gps_lon: string | number;
  activeShift?: {
    id: string;
    status: string;
    staff?: {
      user?: {
        name: string;
        phone: string;
      };
    };
  } | null;
}

// --- Google Maps Script Helper ---
let mapsScriptLoaded = false;
let mapsScriptLoadingPromise: Promise<void> | null = null;

const loadGoogleMapsScript = (apiKey: string): Promise<void> => {
  if (mapsScriptLoaded) return Promise.resolve();
  if (mapsScriptLoadingPromise) return mapsScriptLoadingPromise;

  mapsScriptLoadingPromise = new Promise((resolve, reject) => {
    if ((window as any).google && (window as any).google.maps) {
      mapsScriptLoaded = true;
      resolve();
      return;
    }

    // Set dynamic callback name
    const callbackName = 'initGoogleMapsCallback';
    (window as any)[callbackName] = () => {
      mapsScriptLoaded = true;
      resolve();
    };

    const script = document.createElement('script');
    script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&callback=${callbackName}&loading=async`;
    script.async = true;
    script.defer = true;
    script.onerror = (err) => {
      console.error('Google Maps Script load failed:', err);
      reject(err);
    };

    document.head.appendChild(script);
  });

  return mapsScriptLoadingPromise;
};

// Map custom aesthetic style (sleek dark/light theme balancing high-contrast premium feel)
const mapStyles = [
  {
    "elementType": "geometry",
    "stylers": [{ "color": "#f5f5f5" }]
  },
  {
    "elementType": "labels.icon",
    "stylers": [{ "visibility": "off" }]
  },
  {
    "elementType": "labels.text.fill",
    "stylers": [{ "color": "#616161" }]
  },
  {
    "elementType": "labels.text.stroke",
    "stylers": [{ "color": "#f5f5f5" }]
  },
  {
    "featureType": "administrative.land_parcel",
    "elementType": "labels.text.fill",
    "stylers": [{ "color": "#bdbdbd" }]
  },
  {
    "featureType": "poi",
    "elementType": "geometry",
    "stylers": [{ "color": "#eeeeee" }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text.fill",
    "stylers": [{ "color": "#757575" }]
  },
  {
    "featureType": "road",
    "elementType": "geometry",
    "stylers": [{ "color": "#ffffff" }]
  },
  {
    "featureType": "road.arterial",
    "elementType": "labels.text.fill",
    "stylers": [{ "color": "#757575" }]
  },
  {
    "featureType": "road.highway",
    "elementType": "geometry",
    "stylers": [{ "color": "#dadada" }]
  },
  {
    "featureType": "road.highway",
    "elementType": "labels.text.fill",
    "stylers": [{ "color": "#616161" }]
  },
  {
    "featureType": "road.local",
    "elementType": "labels.text.fill",
    "stylers": [{ "color": "#9e9e9e" }]
  },
  {
    "featureType": "transit.line",
    "elementType": "geometry",
    "stylers": [{ "color": "#e5e5e5" }]
  },
  {
    "featureType": "transit.station",
    "elementType": "geometry",
    "stylers": [{ "color": "#eeeeee" }]
  },
  {
    "featureType": "water",
    "elementType": "geometry",
    "stylers": [{ "color": "#c9c9c9" }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text.fill",
    "stylers": [{ "color": "#9e9e9e" }]
  }
];

export const LiveDashboard: React.FC = () => {
  const [vehicles, setVehicles] = useState<Vehicle[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [isSearchFocused, setIsSearchFocused] = useState(false);
  const [loading, setLoading] = useState(true);
  const [socketStatus, setSocketStatus] = useState<'disconnected' | 'connecting' | 'connected'>('connecting');
  const [selectedVehicle, setSelectedVehicle] = useState<Vehicle | null>(null);

  // References to prevent stale closures inside socket events
  const vehiclesRef = useRef<Vehicle[]>([]);
  const selectedVehicleRef = useRef<Vehicle | null>(null);

  useEffect(() => {
    vehiclesRef.current = vehicles;
  }, [vehicles]);

  useEffect(() => {
    selectedVehicleRef.current = selectedVehicle;
  }, [selectedVehicle]);

  // Stats
  const [totalVehicles, setTotalVehicles] = useState(0);
  const [busyCount, setBusyCount] = useState(0);
  const [availableCount, setAvailableCount] = useState(0);

  // References
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const mapInstanceRef = useRef<google.maps.Map | null>(null);
  const markersRef = useRef<Record<string, google.maps.Marker>>({});
  const infoWindowRef = useRef<google.maps.InfoWindow | null>(null);
  const socketRef = useRef<Socket | null>(null);

  const API_KEY = 'AIzaSyA9fe3iFd2XxDDUQNGJLs6Tp5iRewpHdhs';
  const token = localStorage.getItem('teleems_token') || '';

  // Get status details
  const getStatusCfg = (status: string) => {
    switch ((status || '').toUpperCase()) {
      case 'BUSY':
        return { label: 'Busy', color: '#F97316', bg: '#FFF7ED', border: '#FFEDD5' };
      case 'AVAILABLE':
        return { label: 'Available', color: '#10B981', bg: '#ECFDF5', border: '#D1FAE5' };
      default:
        return { label: 'Offline', color: '#64748B', bg: '#F8FAFC', border: '#F1F5F9' };
    }
  };

  // Fetch initial list of vehicles
  const fetchVehicles = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch('https://teleems-api-gateway.onrender.com/v1/fleet/vehicles', {
        headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
      });
      const json = await res.json();
      let list: Vehicle[] = [];
      if (json?.data?.data && Array.isArray(json.data.data)) list = json.data.data;
      else if (json?.data && Array.isArray(json.data)) list = json.data;
      else if (Array.isArray(json)) list = json;

      setVehicles(list);
      setTotalVehicles(list.length);
      setBusyCount(list.filter(v => v.status === 'BUSY').length);
      setAvailableCount(list.filter(v => v.status === 'AVAILABLE').length);
    } catch (err) {
      console.error('Error fetching vehicles:', err);
    } finally {
      setLoading(false);
    }
  }, [token]);

  // Center map on specific marker
  const centerOnVehicle = (vehicle: Vehicle) => {
    const lat = parseFloat(vehicle.gps_lat as string);
    const lon = parseFloat(vehicle.gps_lon as string);
    
    if (isNaN(lat) || isNaN(lon) || (lat === 0 && lon === 0)) {
      return;
    }

    setSelectedVehicle(vehicle);

    if (mapInstanceRef.current) {
      mapInstanceRef.current.setZoom(15);
      mapInstanceRef.current.panTo({ lat, lng: lon });

      // Open infowindow
      const marker = markersRef.current[vehicle.id];
      if (marker && infoWindowRef.current) {
        const sc = getStatusCfg(vehicle.status);
        const driverName = vehicle.activeShift?.staff?.user?.name || 'No Pilot Assigned';
        const content = `
          <div style="padding: 10px; font-family: 'Inter', sans-serif; min-width: 180px; color: #0F172A;">
            <div style="font-size: 0.65rem; font-weight: 800; color: #64748B; text-transform: uppercase; margin-bottom: 3px;">${vehicle.vehicle_type} AMBULANCE</div>
            <div style="font-size: 0.95rem; font-weight: 800; color: #0F172A; margin-bottom: 6px;">${vehicle.registration_number}</div>
            <div style="font-size: 0.75rem; color: #475569; margin-bottom: 8px;">${vehicle.brand || ''} ${vehicle.model || ''}</div>
            <div style="display: flex; gap: 6px; align-items: center; margin-top: 4px;">
              <span style="display: inline-block; width: 6px; height: 6px; border-radius: 50%; background-color: ${sc.color};"></span>
              <span style="font-size: 0.72rem; font-weight: 700; color: ${sc.color};">${sc.label}</span>
            </div>
            <div style="font-size: 0.7rem; color: #64748B; margin-top: 8px; border-top: 1px solid #E2E8F0; padding-top: 6px;">
              Pilot: <strong>${driverName}</strong>
            </div>
          </div>
        `;
        infoWindowRef.current.setContent(content);
        infoWindowRef.current.open(mapInstanceRef.current, marker);
      }
    }
  };

  // Setup maps and socket connections
  useEffect(() => {
    fetchVehicles();
  }, [fetchVehicles]);

  // Google Maps setup once vehicles list is ready and element exists
  useEffect(() => {
    if (loading || vehicles.length === 0 || !mapContainerRef.current) return;

    loadGoogleMapsScript(API_KEY)
      .then(() => {
        // Find center based on active coords
        const validCoords = vehicles
          .map(v => ({ lat: parseFloat(v.gps_lat as string), lng: parseFloat(v.gps_lon as string) }))
          .filter(c => !isNaN(c.lat) && !isNaN(c.lng) && c.lat !== 0 && c.lng !== 0);

        const defaultCenter = validCoords.length > 0 
          ? validCoords[0] 
          : { lat: 18.5204, lng: 73.8567 }; // Default Pune center

        const mapOptions: google.maps.MapOptions = {
          center: defaultCenter,
          zoom: 12,
          styles: mapStyles,
          mapTypeControl: false,
          streetViewControl: false,
          fullscreenControl: false,
          zoomControl: true,
          zoomControlOptions: {
            position: google.maps.ControlPosition.RIGHT_CENTER
          }
        };

        const map = new google.maps.Map(mapContainerRef.current!, mapOptions);
        mapInstanceRef.current = map;
        infoWindowRef.current = new google.maps.InfoWindow();

        // Create Markers
        vehicles.forEach(v => {
          const lat = parseFloat(v.gps_lat as string);
          const lon = parseFloat(v.gps_lon as string);

          if (isNaN(lat) || isNaN(lon) || (lat === 0 && lon === 0)) return;

          const sc = getStatusCfg(v.status);
          
          // High quality SVG markers for vehicles
          const svgIcon = {
            path: 'M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z',
            fillColor: sc.color,
            fillOpacity: 1,
            strokeColor: '#FFFFFF',
            strokeWeight: 2,
            scale: 1.8,
            anchor: new google.maps.Point(12, 24)
          };

          const marker = new google.maps.Marker({
            position: { lat, lng: lon },
            map,
            title: v.registration_number,
            icon: svgIcon,
            animation: google.maps.Animation.DROP
          });

          marker.addListener('click', () => {
            centerOnVehicle(v);
          });

          markersRef.current[v.id] = marker;
        });
      })
      .catch(err => {
        console.error('Google Maps Load Error:', err);
      });

    return () => {
      // Cleanup markers
      Object.values(markersRef.current).forEach(m => m.setMap(null));
      markersRef.current = {};
    };
  }, [loading]);

  // Real-time socket client connection
  useEffect(() => {
    setSocketStatus('connecting');
    const socket = io('https://teleems-api-gateway.onrender.com', {
      transports: ['websocket'],
      reconnectionAttempts: 5,
      reconnectionDelay: 3000
    });

    socketRef.current = socket;

    socket.on('connect', () => {
      console.log('Socket.io connected successfully!');
      setSocketStatus('connected');
      
      // Emit subscription event
      socket.emit('subscribe_fleet');
    });

    socket.on('disconnect', () => {
      console.log('Socket.io disconnected!');
      setSocketStatus('disconnected');
    });

    // Real-time updates listener
    socket.on('fleet:location_updated', (data: any) => {
      console.log('Real-time location received:', data);
      
      const vId = data.vehicle_id || data.id;
      const regNo = data.registration_number;
      const lat = parseFloat(data.lat || data.gps_lat);
      const lon = parseFloat(data.lon || data.gps_lon);

      if (!vId || isNaN(lat) || isNaN(lon)) return;

      // Update vehicle state coordinates in vehicle array dynamically
      setVehicles(prev => {
        const index = prev.findIndex(v => v.id === vId);
        if (index === -1) return prev;
        const copy = [...prev];
        copy[index] = {
          ...copy[index],
          gps_lat: lat,
          gps_lon: lon
        };
        return copy;
      });

      // Update marker coordinates dynamically on map
      let marker = markersRef.current[vId];
      if (marker) {
        const newPos = new google.maps.LatLng(lat, lon);
        marker.setPosition(newPos);
        
        // Soft focus visual if selected
        if (selectedVehicleRef.current?.id === vId) {
          if (mapInstanceRef.current) {
            mapInstanceRef.current.panTo(newPos);
          }
        }
      } else if (mapInstanceRef.current) {
        // Create marker dynamically if it didn't exist originally due to missing coordinates
        const vehicleInfo = vehiclesRef.current.find(v => v.id === vId);
        const sc = getStatusCfg(vehicleInfo?.status || 'AVAILABLE');
        const svgIcon = {
          path: 'M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z',
          fillColor: sc.color,
          fillOpacity: 1,
          strokeColor: '#FFFFFF',
          strokeWeight: 2,
          scale: 1.8,
          anchor: new google.maps.Point(12, 24)
        };
        marker = new google.maps.Marker({
          position: { lat, lng: lon },
          map: mapInstanceRef.current,
          title: regNo || vehicleInfo?.registration_number || 'Ambulance',
          icon: svgIcon,
          animation: google.maps.Animation.DROP
        });
        marker.addListener('click', () => {
          if (vehicleInfo) centerOnVehicle(vehicleInfo);
        });
        markersRef.current[vId] = marker;
      }
    });

    return () => {
      socket.disconnect();
    };
  }, []);


  const filtered = vehicles.filter(v => 
    v.registration_number.toLowerCase().includes(searchQuery.toLowerCase()) ||
    (v.brand && v.brand.toLowerCase().includes(searchQuery.toLowerCase())) ||
    (v.model && v.model.toLowerCase().includes(searchQuery.toLowerCase()))
  );

  return (
    <div style={{ display: 'flex', height: 'calc(100vh - 128px)', gap: '20px', color: '#0F172A', fontFamily: 'sans-serif' }}>
      
      {/* Sidebar: Vehicles List Panel */}
      <div style={{ 
        width: '380px', 
        background: '#FFFFFF', 
        border: '1px solid rgba(15, 23, 42, 0.08)', 
        borderRadius: '16px', 
        display: 'flex', 
        flexDirection: 'column',
        boxShadow: '0 4px 20px rgba(15, 23, 42, 0.02)',
        overflow: 'hidden'
      }}>
        
        {/* Header / Stats */}
        <div style={{ padding: '20px', borderBottom: '1px solid rgba(15, 23, 42, 0.06)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '14px' }}>
            <h2 style={{ fontSize: '1.1rem', fontWeight: 900, color: '#0F172A', margin: 0, display: 'flex', alignItems: 'center', gap: '8px' }}>
              <Radio size={18} color="#06B6D4" style={{ animation: 'pulse 2s infinite' }} /> Active Ambulances
            </h2>
            <div style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '0.72rem', background: socketStatus === 'connected' ? '#ECFDF5' : '#FEF2F2', padding: '4px 10px', borderRadius: '50px', border: `1px solid ${socketStatus === 'connected' ? '#A7F3D0' : '#FCA5A5'}`, color: socketStatus === 'connected' ? '#047857' : '#B91C1C', fontWeight: 800 }}>
              <span style={{ width: '6px', height: '6px', borderRadius: '50%', background: socketStatus === 'connected' ? '#10B981' : '#EF4444' }} />
              {socketStatus === 'connected' ? 'Connected' : socketStatus === 'connecting' ? 'Reconnecting' : 'Disconnected'}
            </div>
          </div>

          {/* Quick Mini Stats */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>
            <div style={{ background: '#F8FAFC', padding: '8px 10px', borderRadius: '10px', border: '1px solid rgba(15, 23, 42, 0.04)', textAlign: 'center' }}>
              <div style={{ fontSize: '1.2rem', fontWeight: 900, color: '#0F172A' }}>{totalVehicles}</div>
              <div style={{ fontSize: '0.62rem', color: '#64748B', marginTop: '2px', textTransform: 'uppercase' }}>Total</div>
            </div>
            <div style={{ background: '#FFF7ED', padding: '8px 10px', borderRadius: '10px', border: '1px solid #FFEDD5', textAlign: 'center' }}>
              <div style={{ fontSize: '1.2rem', fontWeight: 900, color: '#F97316' }}>{busyCount}</div>
              <div style={{ fontSize: '0.62rem', color: '#EA580C', marginTop: '2px', textTransform: 'uppercase' }}>Busy</div>
            </div>
            <div style={{ background: '#ECFDF5', padding: '8px 10px', borderRadius: '10px', border: '1px solid #D1FAE5', textAlign: 'center' }}>
              <div style={{ fontSize: '1.2rem', fontWeight: 900, color: '#10B981' }}>{availableCount}</div>
              <div style={{ fontSize: '0.62rem', color: '#059669', marginTop: '2px', textTransform: 'uppercase' }}>Available</div>
            </div>
          </div>
        </div>

        {/* Unified borderless search bar */}
        <div style={{ padding: '16px 20px', borderBottom: '1px solid rgba(15, 23, 42, 0.06)' }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: '10px',
            background: '#FFFFFF',
            padding: '10px 14px',
            borderRadius: '12px',
            border: isSearchFocused ? '1px solid #06B6D4' : '1px solid #E2E8F0',
            boxShadow: isSearchFocused ? '0 0 0 3px rgba(6, 182, 212, 0.15)' : 'none',
            transition: 'all 0.2s ease',
            position: 'relative'
          }}>
            <Search size={15} color={isSearchFocused ? "#06B6D4" : "#94A3B8"} />
            <input 
              type="text"
              placeholder="Search registration or model..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onFocus={() => setIsSearchFocused(true)}
              onBlur={() => setIsSearchFocused(false)}
              className="stations-search-input"
              style={{
                background: 'transparent',
                border: 'none',
                color: '#0F172A',
                fontSize: '0.82rem',
                outline: 'none',
                width: '100%',
                paddingRight: searchQuery ? '24px' : '0'
              }}
            />
            {searchQuery && (
              <button 
                onClick={() => setSearchQuery('')}
                style={{ position: 'absolute', right: '12px', background: 'transparent', border: 'none', cursor: 'pointer', color: '#94A3B8', display: 'flex', padding: '2px' }}
              >
                <X size={13} />
              </button>
            )}
          </div>
        </div>

        {/* Scrollable List Container */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '14px 20px', display: 'flex', flexDirection: 'column', gap: '10px' }}>
          {loading && (
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: '160px', color: '#64748B', gap: '10px' }}>
              <Loader2 size={24} className="spin" />
              <span style={{ fontSize: '0.8rem' }}>Loading fleet list...</span>
            </div>
          )}

          {!loading && filtered.length === 0 && (
            <div style={{ textAlign: 'center', padding: '32px 10px', color: '#64748B' }}>
              <Truck size={36} style={{ opacity: 0.15, marginBottom: '10px' }} />
              <div style={{ fontSize: '0.85rem', fontWeight: 600 }}>No vehicles found</div>
            </div>
          )}

          {!loading && filtered.length > 0 && filtered.map(v => {
            const sc = getStatusCfg(v.status);
            const isSelected = selectedVehicle?.id === v.id;
            const hasCoords = parseFloat(v.gps_lat as string) !== 0 && parseFloat(v.gps_lon as string) !== 0;

            return (
              <div 
                key={v.id}
                onClick={() => { if (hasCoords) centerOnVehicle(v); }}
                style={{
                  padding: '12px 14px',
                  borderRadius: '12px',
                  border: isSelected ? '1px solid #06B6D4' : '1px solid rgba(15, 23, 42, 0.05)',
                  background: isSelected ? 'rgba(6,182,212,0.03)' : '#FFFFFF',
                  cursor: hasCoords ? 'pointer' : 'default',
                  transition: 'all 0.15s ease',
                  position: 'relative'
                }}
                onMouseEnter={e => { if (hasCoords && !isSelected) e.currentTarget.style.border = '1px solid rgba(6,182,212,0.3)'; }}
                onMouseLeave={e => { if (!isSelected) e.currentTarget.style.border = '1px solid rgba(15, 23, 42, 0.05)'; }}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '6px' }}>
                  <div>
                    <div style={{ fontSize: '0.62rem', fontWeight: 900, color: '#64748B', textTransform: 'uppercase' }}>
                      {v.vehicle_type} UNIT
                    </div>
                    <div style={{ fontSize: '0.92rem', fontWeight: 800, color: '#0F172A', marginTop: '2px' }}>
                      {v.registration_number}
                    </div>
                  </div>
                  <div style={{ padding: '3px 8px', borderRadius: '6px', fontSize: '0.62rem', fontWeight: 900, color: sc.color, background: sc.bg, border: `1px solid ${sc.border}` }}>
                    {sc.label}
                  </div>
                </div>

                <div style={{ fontSize: '0.75rem', color: '#475569' }}>
                  {v.brand} {v.model}
                </div>

                {v.activeShift?.staff?.user?.name && (
                  <div style={{ fontSize: '0.68rem', color: '#64748B', marginTop: '6px', display: 'flex', alignItems: 'center', gap: '4px' }}>
                    <Check size={12} color="#10B981" /> Active Pilot: <strong>{v.activeShift.staff.user.name}</strong>
                  </div>
                )}

                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '10px', borderTop: '1px solid rgba(15, 23, 42, 0.04)', paddingTop: '8px' }}>
                  <div style={{ fontSize: '0.65rem', color: '#64748B', display: 'flex', alignItems: 'center', gap: '4px' }}>
                    <MapPin size={11} color={hasCoords ? '#06B6D4' : '#94A3B8'} />
                    {hasCoords ? `${parseFloat(v.gps_lat as string).toFixed(4)}, ${parseFloat(v.gps_lon as string).toFixed(4)}` : 'Coords Unavailable'}
                  </div>
                  
                  {hasCoords && (
                    <button 
                      onClick={(e) => { e.stopPropagation(); centerOnVehicle(v); }}
                      style={{ background: 'transparent', border: 'none', color: '#06B6D4', fontSize: '0.68rem', fontWeight: 700, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '2px' }}
                    >
                      <Compass size={11} /> TRACK
                    </button>
                  )}
                </div>
              </div>
            );
          })}
        </div>

        {/* Refresh Button */}
        <div style={{ padding: '16px 20px', background: '#F8FAFC', borderTop: '1px solid rgba(15, 23, 42, 0.06)', display: 'flex' }}>
          <button 
            onClick={fetchVehicles}
            style={{ 
              flex: 1,
              padding: '10px', 
              background: '#FFFFFF', 
              color: '#475569', 
              border: '1px solid #CBD5E1', 
              borderRadius: '10px', 
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: '6px',
              fontWeight: 600,
              fontSize: '0.8rem'
            }}
          >
            <RefreshCw size={14} /> Refresh
          </button>
        </div>

      </div>

      {/* Main Panel: Google Map Canvas */}
      <div style={{ 
        flex: 1, 
        background: '#FFFFFF', 
        border: '1px solid rgba(15, 23, 42, 0.08)', 
        borderRadius: '16px', 
        position: 'relative',
        boxShadow: '0 4px 20px rgba(15, 23, 42, 0.02)',
        overflow: 'hidden'
      }}>
        {/* Loading Overlay */}
        {loading && (
          <div style={{ position: 'absolute', inset: 0, background: '#FFFFFF', zIndex: 10, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: '14px' }}>
            <Loader2 size={36} className="spin" color="#06B6D4" />
            <h3 style={{ fontSize: '1.05rem', fontWeight: 800, color: '#0F172A', margin: 0 }}>Initializing Google Maps...</h3>
            <p style={{ fontSize: '0.8rem', color: '#64748B', margin: 0 }}>Establishing secure connection to Dispatch Gateway</p>
          </div>
        )}

        {/* Map div container */}
        <div 
          ref={mapContainerRef} 
          style={{ width: '100%', height: '100%' }} 
        />
        
        {/* Dynamic Float Controls */}
        <div style={{ position: 'absolute', top: '16px', left: '16px', zIndex: 5, background: 'rgba(15, 23, 42, 0.95)', padding: '10px 14px', borderRadius: '10px', color: '#FFFFFF', fontSize: '0.72rem', display: 'flex', alignItems: 'center', gap: '8px', boxShadow: '0 4px 12px rgba(0,0,0,0.2)', border: '1px solid rgba(255,255,255,0.08)' }}>
          <Activity size={14} color="#06B6D4" style={{ animation: 'pulse 1.5s infinite' }} />
          <span>Real-time Telemetry Active • Channel: <strong>fleet:location_updated</strong></span>
        </div>

      </div>

      <style>{`
        @keyframes spin {
          from { transform: rotate(0deg); }
          to { transform: rotate(360deg); }
        }
        .spin {
          animation: spin 1s linear infinite;
        }
        @keyframes pulse {
          0%, 100% { opacity: 1; transform: scale(1); }
          50% { opacity: 0.5; transform: scale(0.92); }
        }
      `}</style>
    </div>
  );
};
