'use client';

import { useEffect, useRef, useState } from 'react';
import {
  X,
  Navigation,
  ExternalLink,
  MapPin,
  Compass,
  Clock,
  Route,
  ChevronDown,
  ChevronUp,
  Car,
  Footprints,
  Bike,
  Info,
  ShieldCheck,
  Share2,
  Check,
  LocateFixed,
  Sparkles,
  Target,
} from 'lucide-react';
import { loadGoogleMapsScript, DARK_MAP_STYLES } from '@/lib/google-maps';

interface DirectionsModalProps {
  destLat: number;
  destLng: number;
  address: string;
  orderNumber: string;
  onClose: () => void;
}

interface RouteStep {
  instructions: string;
  distance: string;
  duration: string;
}

// Haversine formula for direct distance in km
function calculateHaversineDistance(lat1: number, lon1: number, lat2: number, lon2: number): number {
  const R = 6371;
  const dLat = ((lat2 - lat1) * Math.PI) / 180;
  const dLon = ((lon2 - lon1) * Math.PI) / 180;
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos((lat1 * Math.PI) / 180) * Math.cos((lat2 * Math.PI) / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
}

// Decode Google encoded polyline string into lat/lng objects
function decodePolyline(encoded: string): { lat: number; lng: number }[] {
  const points: { lat: number; lng: number }[] = [];
  let index = 0, len = encoded.length;
  let lat = 0, lng = 0;

  while (index < len) {
    let b, shift = 0, result = 0;
    do {
      b = encoded.charCodeAt(index++) - 63;
      result |= (b & 0x1f) << shift;
      shift += 5;
    } while (b >= 0x20);
    const dlat = (result & 1) ? ~(result >> 1) : (result >> 1);
    lat += dlat;

    shift = 0;
    result = 0;
    do {
      b = encoded.charCodeAt(index++) - 63;
      result |= (b & 0x1f) << shift;
      shift += 5;
    } while (b >= 0x20);
    const dlng = (result & 1) ? ~(result >> 1) : (result >> 1);
    lng += dlng;

    points.push({ lat: lat / 1e5, lng: lng / 1e5 });
  }
  return points;
}

export default function DirectionsModal({
  destLat,
  destLng,
  address,
  orderNumber,
  onClose,
}: DirectionsModalProps) {
  const mapRef = useRef<HTMLDivElement>(null);
  const mapInstanceRef = useRef<any>(null);
  const activePolylineRef = useRef<any>(null);
  const activeMarkersRef = useRef<any[]>([]);
  const destMarkerRef = useRef<any>(null);
  const destInfoWindowRef = useRef<any>(null);

  const [locating, setLocating] = useState(true);
  const [userLat, setUserLat] = useState<number | null>(null);
  const [userLng, setUserLng] = useState<number | null>(null);

  const [loadingRoute, setLoadingRoute] = useState(false);
  const [travelMode, setTravelMode] = useState<'DRIVE' | 'WALK' | 'BICYCLE'>('DRIVE');
  const [routeInfo, setRouteInfo] = useState<{
    distance: string;
    duration: string;
    summary: string;
    steps: RouteStep[];
  } | null>(null);

  const [routeSource, setRouteSource] = useState<'ROUTES_API' | 'OSRM' | 'FALLBACK'>('ROUTES_API');
  const [showSteps, setShowSteps] = useState(false);
  const [copiedLink, setCopiedLink] = useState(false);

  // Clear existing polyline & markers from map
  const clearMapElements = () => {
    if (activePolylineRef.current) {
      activePolylineRef.current.setMap(null);
      activePolylineRef.current = null;
    }
    activeMarkersRef.current.forEach((m) => m.setMap(null));
    activeMarkersRef.current = [];
    destMarkerRef.current = null;
    destInfoWindowRef.current = null;
  };

  // 1. Get GPS coordinates with high accuracy continuous live tracking
  useEffect(() => {
    if (!navigator.geolocation) {
      setLocating(false);
      return;
    }
    const watchId = navigator.geolocation.watchPosition(
      (pos) => {
        setUserLat(pos.coords.latitude);
        setUserLng(pos.coords.longitude);
        setLocating(false);
      },
      (err) => {
        console.warn('Geolocation error:', err.message);
        setLocating(false);
      },
      { timeout: 15000, enableHighAccuracy: true, maximumAge: 0 }
    );

    return () => {
      navigator.geolocation.clearWatch(watchId);
    };
  }, []);

  // 2. Load Google Maps & Calculate Route
  useEffect(() => {
    if (locating) return;

    let mounted = true;
    setLoadingRoute(true);

    loadGoogleMapsScript()
      .then(async (google) => {
        if (!mounted || !mapRef.current) return;

        const destPosition = { lat: destLat, lng: destLng };
        const startPosition = userLat !== null && userLng !== null ? { lat: userLat, lng: userLng } : null;

        // Initialize Map
        if (!mapInstanceRef.current) {
          const map = new google.maps.Map(mapRef.current, {
            center: startPosition || destPosition,
            zoom: 14,
            styles: DARK_MAP_STYLES,
            disableDefaultUI: false,
            zoomControl: true,
            gestureHandling: 'greedy',
            mapTypeControl: false,
            streetViewControl: false,
            fullscreenControl: true,
          });
          mapInstanceRef.current = map;
        }

        const map = mapInstanceRef.current;
        clearMapElements();

        // Create InfoWindow for Customer Order Location
        const infoWindow = new google.maps.InfoWindow({
          content: `
            <div style="padding: 6px; font-family: sans-serif; color: #0f172a;">
              <strong style="color: #ef4444; font-size: 13px;">📍 Order #${orderNumber} Destination</strong>
              <p style="margin: 4px 0 2px 0; font-size: 11px; max-width: 210px;">${address}</p>
              <span style="font-size: 10px; color: #64748b; font-family: monospace;">${destLat.toFixed(5)}, ${destLng.toFixed(5)}</span>
            </div>
          `,
        });
        destInfoWindowRef.current = infoWindow;

        if (!startPosition) {
          // No driver GPS location — show single destination marker
          const destMarker = new google.maps.Marker({
            position: destPosition,
            map,
            title: address,
            icon: {
              path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
              scale: 7,
              fillColor: '#ef4444',
              fillOpacity: 1,
              strokeColor: '#ffffff',
              strokeWeight: 2,
            },
          });
          destMarkerRef.current = destMarker;
          destMarker.addListener('click', () => infoWindow.open(map, destMarker));
          activeMarkersRef.current.push(destMarker);
          map.setCenter(destPosition);
          map.setZoom(15);
          infoWindow.open(map, destMarker);
          setLoadingRoute(false);
          return;
        }

        // Place Markers
        const startMarker = new google.maps.Marker({
          position: startPosition,
          map,
          title: 'Courier Starting Location',
          icon: {
            path: google.maps.SymbolPath.CIRCLE,
            scale: 7,
            fillColor: '#10b981',
            fillOpacity: 1,
            strokeColor: '#ffffff',
            strokeWeight: 2.5,
          },
        });

        const destMarker = new google.maps.Marker({
          position: destPosition,
          map,
          title: address,
          icon: {
            path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
            scale: 7,
            fillColor: '#ef4444',
            fillOpacity: 1,
            strokeColor: '#ffffff',
            strokeWeight: 2.5,
          },
        });
        destMarkerRef.current = destMarker;
        destMarker.addListener('click', () => infoWindow.open(map, destMarker));

        activeMarkersRef.current.push(startMarker, destMarker);

        const apiKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY;
        let routeSuccess = false;

        // --- METHOD 1: Try Modern Google Routes API (New) ---
        if (apiKey) {
          try {
            const apiMode = travelMode === 'WALK' ? 'WALK' : travelMode === 'BICYCLE' ? 'BICYCLE' : 'DRIVE';
            const res = await fetch('https://routes.googleapis.com/v2/computeRoutes', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'X-Goog-Api-Key': apiKey,
                'X-Goog-FieldMask': 'routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline,routes.description',
              },
              body: JSON.stringify({
                origin: { location: { latLng: { latitude: startPosition.lat, longitude: startPosition.lng } } },
                destination: { location: { latLng: { latitude: destPosition.lat, longitude: destPosition.lng } } },
                travelMode: apiMode,
              }),
            });

            if (res.ok) {
              const data = await res.json();
              const route = data.routes?.[0];

              if (route?.polyline?.encodedPolyline) {
                const points = decodePolyline(route.polyline.encodedPolyline);
                const polyline = new google.maps.Polyline({
                  path: points,
                  geodesic: true,
                  strokeColor: '#10b981',
                  strokeOpacity: 0.95,
                  strokeWeight: 5,
                  map,
                });
                activePolylineRef.current = polyline;

                const bounds = new google.maps.LatLngBounds();
                points.forEach((p) => bounds.extend(p));
                map.fitBounds(bounds, { top: 40, bottom: 40, left: 40, right: 40 });

                const meters = route.distanceMeters || 0;
                const km = (meters / 1000).toFixed(1);
                const totalSeconds = parseInt(route.duration?.replace('s', '') || '0', 10);
                const mins = Math.round(totalSeconds / 60);

                setRouteInfo({
                  distance: `${km} km`,
                  duration: `${mins} mins`,
                  summary: route.description || 'Google Route',
                  steps: [],
                });
                setRouteSource('ROUTES_API');
                routeSuccess = true;
              }
            }
          } catch (err) {
            console.warn('Google Routes API fetch failed, trying OSRM:', err);
          }
        }

        // --- METHOD 2: Fallback to OSRM Driving/Biking/Foot Route ---
        if (!routeSuccess) {
          try {
            const modeParam = travelMode === 'WALK' ? 'foot' : travelMode === 'BICYCLE' ? 'bike' : 'driving';
            const osrmUrl = `https://router.project-osrm.org/route/v1/${modeParam}/${startPosition.lng},${startPosition.lat};${destPosition.lng},${destPosition.lat}?overview=full&geometries=geojson&steps=true`;
            const osrmRes = await fetch(osrmUrl);

            if (osrmRes.ok) {
              const osrmData = await osrmRes.json();
              const route = osrmData.routes?.[0];

              if (route) {
                const points = route.geometry.coordinates.map(([lng, lat]: [number, number]) => ({ lat, lng }));
                const polyline = new google.maps.Polyline({
                  path: points,
                  geodesic: true,
                  strokeColor: '#10b981',
                  strokeOpacity: 0.95,
                  strokeWeight: 5,
                  map,
                });
                activePolylineRef.current = polyline;

                const bounds = new google.maps.LatLngBounds();
                points.forEach((p: { lat: number; lng: number }) => bounds.extend(p));
                map.fitBounds(bounds, { top: 40, bottom: 40, left: 40, right: 40 });

                const km = (route.distance / 1000).toFixed(1);
                const mins = Math.round(route.duration / 60);
                const stepsList: RouteStep[] = (route.legs?.[0]?.steps || []).map((step: any) => ({
                  instructions: `${step.maneuver.type} ${step.name ? `onto ${step.name}` : ''}`.trim(),
                  distance: `${Math.round(step.distance)}m`,
                  duration: `${Math.round(step.duration / 60)} min`,
                }));

                setRouteInfo({
                  distance: `${km} km`,
                  duration: `${mins} mins`,
                  summary: route.legs?.[0]?.summary || 'Optimal Dispatch Route',
                  steps: stepsList,
                });
                setRouteSource('OSRM');
                routeSuccess = true;
              }
            }
          } catch (err) {
            console.warn('OSRM Route fetch failed:', err);
          }
        }

        // --- METHOD 3: Fallback to Geodesic Line ---
        if (!routeSuccess) {
          const flightPath = new google.maps.Polyline({
            path: [startPosition, destPosition],
            geodesic: true,
            strokeColor: '#38bdf8',
            strokeOpacity: 0.85,
            strokeWeight: 4,
            icons: [
              {
                icon: { path: 'M 0,-1 0,1', strokeOpacity: 1, scale: 2.5 },
                offset: '0',
                repeat: '12px',
              },
            ],
            map,
          });
          activePolylineRef.current = flightPath;

          const bounds = new google.maps.LatLngBounds();
          bounds.extend(startPosition);
          bounds.extend(destPosition);
          map.fitBounds(bounds, { top: 40, bottom: 40, left: 40, right: 40 });

          const km = calculateHaversineDistance(startPosition.lat, startPosition.lng, destPosition.lat, destPosition.lng);
          const estMins = Math.round((km / (travelMode === 'WALK' ? 5 : travelMode === 'BICYCLE' ? 15 : 35)) * 60);

          setRouteInfo({
            distance: `~${km.toFixed(1)} km`,
            duration: `~${estMins} mins`,
            summary: 'Direct Line Estimate',
            steps: [],
          });
          setRouteSource('FALLBACK');
        }

        setLoadingRoute(false);
      })
      .catch((err) => {
        if (!mounted) return;
        console.error('Google Maps API load error:', err);
        setLoadingRoute(false);
      });

    return () => {
      mounted = false;
    };
  }, [locating, userLat, userLng, destLat, destLng, address, travelMode, orderNumber]);

  // Recenter Route Bounds
  const handleRecenter = () => {
    if (mapInstanceRef.current) {
      if (userLat !== null && userLng !== null) {
        const bounds = new (window as any).google.maps.LatLngBounds();
        bounds.extend({ lat: userLat, lng: userLng });
        bounds.extend({ lat: destLat, lng: destLng });
        mapInstanceRef.current.fitBounds(bounds, { top: 40, bottom: 40, left: 40, right: 40 });
      } else {
        mapInstanceRef.current.setCenter({ lat: destLat, lng: destLng });
        mapInstanceRef.current.setZoom(15);
      }
    }
  };

  // Track & Focus Directly onto Customer Order Destination Pin
  const handleTrackOrderLocation = () => {
    if (mapInstanceRef.current && destLat != null && destLng != null) {
      const map = mapInstanceRef.current;
      map.panTo({ lat: destLat, lng: destLng });
      map.setZoom(17);
      if (destInfoWindowRef.current && destMarkerRef.current) {
        destInfoWindowRef.current.open(map, destMarkerRef.current);
      }
    }
  };

  // Mobile Google Maps App Deep Link
  const googleMapsAppUrl = userLat !== null && userLng !== null
    ? `https://www.google.com/maps/dir/?api=1&origin=${userLat},${userLng}&destination=${destLat},${destLng}&travelmode=${travelMode.toLowerCase() === 'bicycle' ? 'bicycling' : travelMode.toLowerCase()}`
    : `https://www.google.com/maps/dir/?api=1&destination=${destLat},${destLng}&travelmode=${travelMode.toLowerCase() === 'bicycle' ? 'bicycling' : travelMode.toLowerCase()}`;

  const handleShareRoute = async () => {
    if (navigator.share) {
      try {
        await navigator.share({
          title: `Delivery Route - Order #${orderNumber}`,
          text: `Navigation route to ${address}`,
          url: googleMapsAppUrl,
        });
      } catch (err) {
        // ignore abort
      }
    } else {
      navigator.clipboard.writeText(googleMapsAppUrl);
      setCopiedLink(true);
      setTimeout(() => setCopiedLink(false), 2000);
    }
  };

  return (
    <>
      {/* Backdrop */}
      <div 
        className="fixed inset-0 z-50 bg-black/85 backdrop-blur-sm transition-opacity duration-300"
        onClick={onClose}
      />

      {/* Modal Viewport Container */}
      <div className="fixed inset-0 z-50 flex items-center justify-center p-2 sm:p-4 pointer-events-none overflow-hidden">
        <div className="pointer-events-auto w-full max-h-[88vh] max-w-5xl bg-[#090d16] border border-white/10 rounded-2xl sm:rounded-3xl shadow-2xl overflow-hidden flex flex-col font-sans transition-all duration-300">
          
          {/* Header Bar */}
          <div className="relative overflow-hidden bg-gradient-to-r from-emerald-950/80 via-[#0d1322] to-blue-950/80 px-3.5 sm:px-5 py-2.5 border-b border-white/10 flex items-center justify-between gap-3 shrink-0">
            {/* Ambient Background Glows */}
            <div className="absolute -left-10 -top-10 w-40 h-40 bg-emerald-500/10 rounded-full blur-3xl pointer-events-none" />
            <div className="absolute -right-10 -bottom-10 w-40 h-40 bg-blue-500/10 rounded-full blur-3xl pointer-events-none" />

            <div className="flex items-center gap-2.5 relative z-10 min-w-0">
              <div className="h-8.5 w-8.5 rounded-lg bg-emerald-500/15 border border-emerald-500/30 flex items-center justify-center text-emerald-400 shrink-0">
                <Route className="h-4.5 w-4.5 text-emerald-400" />
              </div>
              <div className="min-w-0">
                <div className="flex items-center gap-2">
                  <h2 className="text-white font-extrabold text-sm sm:text-base tracking-tight Outfit truncate">
                    Delivery Navigation
                  </h2>
                  <span className="px-2 py-0.5 rounded-md text-[9px] font-extrabold uppercase bg-emerald-500/15 text-emerald-400 border border-emerald-500/30 hidden xs:flex items-center gap-1">
                    <ShieldCheck className="h-3 w-3" /> Active Order
                  </span>
                </div>
                <p className="text-gray-400 text-[11px] flex items-center gap-1.5 truncate mt-0.2">
                  <span className="font-mono font-bold text-emerald-400">#{orderNumber}</span>
                  <span className="text-gray-600">•</span>
                  <span className="text-gray-300 font-medium truncate">{address}</span>
                </p>
              </div>
            </div>

            <div className="flex items-center gap-2 relative z-10 shrink-0">
              <button
                onClick={handleShareRoute}
                title="Share or Copy Route Link"
                className="h-8 px-2.5 rounded-lg bg-white/5 hover:bg-white/15 border border-white/10 flex items-center gap-1.5 text-xs font-semibold text-gray-300 hover:text-white transition-all cursor-pointer"
              >
                {copiedLink ? (
                  <>
                    <Check className="h-3.5 w-3.5 text-emerald-400" />
                    <span className="hidden sm:inline text-emerald-400">Copied</span>
                  </>
                ) : (
                  <>
                    <Share2 className="h-3.5 w-3.5" />
                    <span className="hidden sm:inline">Share</span>
                  </>
                )}
              </button>

              <button
                onClick={onClose}
                className="h-8 w-8 rounded-lg bg-white/5 hover:bg-white/15 border border-white/10 flex items-center justify-center text-gray-400 hover:text-white transition-all cursor-pointer"
              >
                <X className="h-4 w-4" />
              </button>
            </div>
          </div>

          {/* Dual Column Grid: Main (Map & Controls) + Right Side Panel (Dark Tile) */}
          <div className="grid grid-cols-1 lg:grid-cols-12 flex-1 min-h-0 overflow-y-auto lg:overflow-hidden">
            
            {/* LEFT COLUMN: Controls, Interactive Map & Turn-by-Turn Steps */}
            <div className="lg:col-span-7 xl:col-span-7 flex flex-col min-h-0 border-b lg:border-b-0 lg:border-r border-white/10">
              
              {/* Transport Mode Switcher Bar */}
              <div className="px-3.5 py-2 bg-[#121824] border-b border-white/5 flex items-center justify-between gap-2 shrink-0">
                <div className="flex items-center bg-[#090d16] p-0.5 rounded-lg border border-white/10">
                  <button
                    type="button"
                    onClick={() => setTravelMode('DRIVE')}
                    className={`flex items-center gap-1 px-2.5 py-1 rounded-md text-[11px] font-bold transition-all cursor-pointer ${
                      travelMode === 'DRIVE'
                        ? 'bg-emerald-500 text-slate-950 shadow-md shadow-emerald-500/20'
                        : 'text-gray-400 hover:text-white'
                    }`}
                  >
                    <Car className="h-3 w-3" />
                    Drive
                  </button>

                  <button
                    type="button"
                    onClick={() => setTravelMode('BICYCLE')}
                    className={`flex items-center gap-1 px-2.5 py-1 rounded-md text-[11px] font-bold transition-all cursor-pointer ${
                      travelMode === 'BICYCLE'
                        ? 'bg-emerald-500 text-slate-950 shadow-md shadow-emerald-500/20'
                        : 'text-gray-400 hover:text-white'
                    }`}
                  >
                    <Bike className="h-3 w-3" />
                    Bike
                  </button>

                  <button
                    type="button"
                    onClick={() => setTravelMode('WALK')}
                    className={`flex items-center gap-1 px-2.5 py-1 rounded-md text-[11px] font-bold transition-all cursor-pointer ${
                      travelMode === 'WALK'
                        ? 'bg-emerald-500 text-slate-950 shadow-md shadow-emerald-500/20'
                        : 'text-gray-400 hover:text-white'
                    }`}
                  >
                    <Footprints className="h-3 w-3" />
                    Walk
                  </button>
                </div>

                {routeSource === 'ROUTES_API' && (
                  <div className="flex items-center gap-1 text-[10px] font-semibold text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded-md border border-emerald-500/20">
                    <Info className="h-3 w-3 shrink-0" />
                    <span>Google Routes Engine</span>
                  </div>
                )}
              </div>

              {/* Interactive Google Map Container */}
              <div className="relative flex-1 min-h-[220px] sm:min-h-[260px] md:min-h-[280px] h-[280px] sm:h-[320px] bg-[#0d1117] w-full">
                <div ref={mapRef} className="w-full h-full min-h-[220px] sm:min-h-[260px] md:min-h-[280px]" />

                {/* Floating Map Overlay Control Bar */}
                <div className="absolute top-3 left-3 right-3 z-10 flex items-center justify-between gap-2 pointer-events-auto">
                  <button
                    type="button"
                    onClick={handleTrackOrderLocation}
                    className="px-3 py-1.5 rounded-xl bg-[#090d16]/90 hover:bg-red-600 text-white font-bold text-xs border border-white/10 flex items-center gap-1.5 shadow-xl backdrop-blur-md transition-all cursor-pointer group active:scale-95"
                  >
                    <MapPin className="h-3.5 w-3.5 text-red-500 group-hover:text-white transition-colors" />
                    <span>Track Order Location</span>
                  </button>

                  <button
                    type="button"
                    onClick={handleRecenter}
                    title="Trace Full Route Bounds"
                    className="px-3 py-1.5 rounded-xl bg-[#090d16]/90 hover:bg-emerald-500 text-white hover:text-slate-950 font-bold text-xs border border-white/10 flex items-center gap-1.5 shadow-xl backdrop-blur-md transition-all cursor-pointer group active:scale-95"
                  >
                    <Route className="h-3.5 w-3.5 text-emerald-400 group-hover:text-slate-950 transition-colors" />
                    <span className="hidden xs:inline">Trace Route</span>
                  </button>
                </div>

                {/* Map Overlay Button to Recenter GPS */}
                <div className="absolute bottom-3 right-3 z-10 pointer-events-auto">
                  <button
                    type="button"
                    onClick={handleRecenter}
                    title="Recenter Route Bounds"
                    className="h-8.5 w-8.5 rounded-xl bg-[#090d16]/90 hover:bg-emerald-500 text-gray-300 hover:text-slate-950 border border-white/10 flex items-center justify-center transition-all shadow-xl backdrop-blur-md cursor-pointer"
                  >
                    <LocateFixed className="h-4 w-4" />
                  </button>
                </div>
              </div>

              {/* Turn-by-Turn Steps Accordion */}
              {routeInfo && routeInfo.steps.length > 0 && (
                <div className="border-t border-white/10 bg-[#121824] shrink-0">
                  <button
                    type="button"
                    onClick={() => setShowSteps(!showSteps)}
                    className="w-full px-3.5 py-2 flex items-center justify-between text-xs font-bold text-gray-300 hover:text-white transition-colors cursor-pointer"
                  >
                    <div className="flex items-center gap-1.5">
                      <Route className="h-3.5 w-3.5 text-emerald-400" />
                      <span>Turn-by-Turn Directions ({routeInfo.steps.length} steps)</span>
                    </div>
                    {showSteps ? <ChevronDown className="h-3.5 w-3.5 text-gray-400" /> : <ChevronUp className="h-3.5 w-3.5 text-gray-400" />}
                  </button>

                  {showSteps && (
                    <div className="px-3.5 pb-2.5 max-h-[130px] overflow-y-auto space-y-1.5 border-t border-white/5 pt-2">
                      {routeInfo.steps.map((step, idx) => (
                        <div key={idx} className="flex items-start gap-2 text-xs bg-white/2 p-1.5 rounded-lg border border-white/5">
                          <span className="h-4.5 w-4.5 rounded-full bg-emerald-500/15 border border-emerald-500/30 text-emerald-400 font-extrabold text-[9px] flex items-center justify-center shrink-0 mt-0.5">
                            {idx + 1}
                          </span>
                          <div className="flex-1 min-w-0">
                            <p className="text-gray-200 font-medium text-[11px] leading-snug">{step.instructions}</p>
                            <p className="text-[9px] text-gray-400 mt-0.2 font-mono">
                              {step.distance} • {step.duration}
                            </p>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}

              {/* Voice Navigation Launcher Action Button */}
              <div className="p-3 bg-[#090d16] border-t border-white/10 shrink-0">
                <a
                  href={googleMapsAppUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center justify-center gap-2 w-full py-2.5 bg-gradient-to-r from-emerald-500 via-teal-500 to-emerald-600 hover:brightness-110 text-slate-950 font-extrabold text-xs rounded-xl transition-all shadow-lg shadow-emerald-500/20 active:scale-98 cursor-pointer"
                >
                  <Compass className="h-4 w-4" />
                  <span>Start Live Turn-by-Turn Voice Navigation</span>
                  <ExternalLink className="h-3.5 w-3.5 opacity-80" />
                </a>
              </div>

            </div>

            {/* RIGHT SIDE PANEL: Compact Dark Theme Courier Tile & Details */}
            <div className="lg:col-span-5 xl:col-span-5 p-3.5 sm:p-4 bg-[#0d121c] flex flex-col justify-between space-y-3.5 overflow-y-auto">
              
              <div className="space-y-3">
                {/* Dedicated Side Courier GIF Showcase Tile */}
                <div className="relative rounded-2xl p-3 bg-gradient-to-b from-[#161e2e] to-[#0f1522] border border-white/10 shadow-xl overflow-hidden group">

                  {/* Compact Animated GIF Frame */}
                  <div className="relative w-full h-28 sm:h-32 rounded-xl overflow-hidden border border-white/10 bg-[#090d16] flex items-center justify-center shadow-inner my-1">
                    <img 
                      src="/assets/deliveryman.gif" 
                      alt="Deliveryman Courier" 
                      className="h-full w-full object-contain p-1 group-hover:scale-105 transition-transform duration-300"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-[#090d16] via-transparent to-transparent opacity-40" />
                    <div className="absolute bottom-1.5 left-2 right-2 flex items-center justify-between text-[9px] font-bold text-gray-300 font-mono">
                      <span>COURIER #DISPATCH-01</span>
                      <span className="text-emerald-400">ACTIVE GPS</span>
                    </div>
                  </div>

                  <div className="mt-2 space-y-0.5 relative z-10">
                    <h3 className="text-white font-extrabold text-sm Outfit">WhatsApp Order Delivery</h3>
                    <p className="text-gray-400 text-[11px] leading-snug">
                      Express courier navigation route for active order <span className="text-emerald-400 font-mono font-bold">#{orderNumber}</span>.
                    </p>
                  </div>
                </div>

                {/* ETA & Distance Metrics Card Grid */}
                {locating || loadingRoute ? (
                  <div className="p-3 bg-white/2 rounded-xl border border-white/5 flex items-center gap-2.5 text-xs text-emerald-400">
                    <div className="h-3.5 w-3.5 rounded-full border-2 border-emerald-400 border-t-transparent animate-spin" />
                    <span className="text-[11px]">Calculating delivery metrics...</span>
                  </div>
                ) : routeInfo ? (
                  <div className="grid grid-cols-2 gap-2.5">
                    {/* ETA Metric Box */}
                    <div className="p-2.5 sm:p-3 bg-[#141b2b] rounded-xl border border-white/10 flex flex-col justify-center space-y-0.5">
                      <div className="flex items-center gap-1 text-[9px] font-extrabold uppercase text-gray-400 tracking-wider">
                        <Clock className="h-3 w-3 text-emerald-400" />
                        <span>EST Duration</span>
                      </div>
                      <span className="text-white font-black text-xl Outfit tracking-tight">
                        {routeInfo.duration}
                      </span>
                    </div>

                    {/* Distance Metric Box */}
                    <div className="p-2.5 sm:p-3 bg-[#141b2b] rounded-xl border border-white/10 flex flex-col justify-center space-y-0.5">
                      <div className="flex items-center gap-1 text-[9px] font-extrabold uppercase text-gray-400 tracking-wider">
                        <Route className="h-3 w-3 text-blue-400" />
                        <span>Total Distance</span>
                      </div>
                      <span className="text-white font-black text-xl Outfit tracking-tight">
                        {routeInfo.distance}
                      </span>
                    </div>
                  </div>
                ) : null}

                {/* Customer Destination Card & Track Order Action */}
                <div className="p-3 bg-[#141b2b] rounded-xl border border-white/10 space-y-2">
                  <div className="flex items-center justify-between text-[9px] font-extrabold uppercase text-gray-400 tracking-wider">
                    <span className="flex items-center gap-1 text-red-400">
                      <MapPin className="h-3 w-3 text-red-500" />
                      Destination Address
                    </span>
                  </div>
                  <p className="text-white font-medium text-xs leading-snug">
                    {address}
                  </p>
                  
                  <button
                    type="button"
                    onClick={handleTrackOrderLocation}
                    className="w-full mt-1 flex items-center justify-center gap-1.5 py-1.5 bg-red-500/15 hover:bg-red-500/25 text-red-400 border border-red-500/30 rounded-lg text-xs font-bold transition-all cursor-pointer"
                  >
                    <Target className="h-3.5 w-3.5 text-red-400" />
                    <span>Focus Order Pin on Map</span>
                  </button>

                  <div className="text-[9px] text-gray-400 font-mono pt-1.5 border-t border-white/5">
                    GPS: {destLat.toFixed(5)}, {destLng.toFixed(5)}
                  </div>
                </div>
              </div>

              {/* Bottom Section: Info Footer */}
              <div className="pt-2 border-t border-white/5 space-y-1 text-[9px] text-gray-400 text-center shrink-0">
                <p className="flex items-center justify-center gap-1 text-emerald-400 font-semibold">
                  <ShieldCheck className="h-3 w-3" /> Google Maps API Dark System
                </p>
              </div>

            </div>

          </div>

        </div>
      </div>
    </>
  );
}
