'use client';

import React, { useEffect, useRef, useState, Suspense } from 'react';
import dynamic from 'next/dynamic';
import { useSearchParams } from 'next/navigation';
import { apiRequest } from '@/lib/api';
import { useAuth } from '@/context/auth-context';
import Icons8Icon from '@/components/icons/Icons8Icon';
import { loadGoogleMapsScript, DARK_MAP_STYLES } from '@/lib/google-maps';
import {
  Truck,
  MapPin,
  Clock,
  CheckCircle,
  Package,
  Phone,
  User,
  Navigation,
  RefreshCw,
  Search,
  ChevronDown,
  LocateFixed,
  Star,
  MessageSquare,
  Edit,
  Layers,
  ArrowUp,
  CornerUpLeft,
  Compass,
  ExternalLink,
  Volume2,
} from 'lucide-react';

const TrackingModal = dynamic(() => import('@/components/dashboard/TrackingModal'), {
  ssr: false,
});

interface OrderItem {
  id: string;
  productName: string;
  quantity: number;
  unitPrice: number;
  lineTotal: number;
}

interface Customer {
  id: string;
  name: string | null;
  whatsappNumber: string;
}

interface Order {
  id: string;
  orderNumber: string;
  status: string;
  paymentStatus: string;
  totalAmount: number;
  currency: string;
  customerPhone: string;
  customerName: string;
  deliveryMethod: string | null;
  deliveryAddress: string | null;
  deliveryLat: number | null;
  deliveryLng: number | null;
  createdAt: string;
  customer: Customer;
  items: OrderItem[];
}

interface RouteInfo {
  distance: string;
  duration: string;
  etaTime: string;
  currentInstruction: string;
  nextManeuver?: string;
}

function DeliveriesContent() {
  const { user } = useAuth();
  const searchParams = useSearchParams();
  const initialOrderId = searchParams.get('orderId');

  const [orders, setOrders] = useState<Order[]>([]);
  const [selectedOrderId, setSelectedOrderId] = useState<string | null>(initialOrderId);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [toast, setToast] = useState<{ message: string; type: 'info' | 'success' } | null>(null);
  const [trackingModalOrder, setTrackingModalOrder] = useState<Order | null>(null);

  // Live Navigation & Google Map States
  const [isTrackingRoute, setIsTrackingRoute] = useState(true);
  const [mapType, setMapType] = useState<'hybrid' | 'dark'>('hybrid');
  const [routeInfo, setRouteInfo] = useState<RouteInfo | null>(null);

  // Map DOM reference & instances
  const mapContainerRef = useRef<HTMLDivElement>(null);
  const leafletMapRef = useRef<any>(null);
  const googleMapRef = useRef<any>(null);
  const directionsRendererRef = useRef<any>(null);
  const driverMarkerRef = useRef<any>(null);
  const destMarkerRef = useRef<any>(null);

  const activePolylineRef = useRef<any>(null);

  const [deviceGps, setDeviceGps] = useState<{ lat: number; lng: number } | null>(null);

  // High-accuracy live GPS tracking
  useEffect(() => {
    if (!navigator.geolocation) return;
    const watchId = navigator.geolocation.watchPosition(
      (pos) => {
        setDeviceGps({
          lat: pos.coords.latitude,
          lng: pos.coords.longitude,
        });
      },
      (err) => console.warn('Device GPS tracking warning:', err.message),
      { enableHighAccuracy: true, maximumAge: 0, timeout: 15000 }
    );
    return () => navigator.geolocation.clearWatch(watchId);
  }, []);

  useEffect(() => {
    if (toast) {
      const timer = setTimeout(() => setToast(null), 5000);
      return () => clearTimeout(timer);
    }
  }, [toast]);

  useEffect(() => {
    if (initialOrderId) {
      setSelectedOrderId(initialOrderId);
    }
  }, [initialOrderId]);

  useEffect(() => {
    if (!user || user.subscriptionStatus === 'UNSUBSCRIBED' || user.subscriptionStatus === 'EXPIRED') {
      setLoading(false);
      return;
    }

    loadOrders();

    // SSE Event Listener for live delivery updates
    const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
    if (!token) return;

    const getApiUrl = () => {
      if (typeof window !== 'undefined') {
        const { hostname } = window.location;
        return `http://${hostname}:3001`;
      }
      return 'http://localhost:3001';
    };
    const API_URL = process.env.NEXT_PUBLIC_API_URL || getApiUrl();
    const eventSource = new EventSource(`${API_URL}/api/orders/events?token=${token}`);

    eventSource.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.type === 'order_created' || data.type === 'order_updated') {
          setToast({
            message: `🚚 Delivery Update: Order ${data.orderNumber} is ${data.status}`,
            type: 'info',
          });
          loadOrders();
        }
      } catch (err) {
        console.error('Error parsing SSE event:', err);
      }
    };

    return () => {
      eventSource.close();
    };
  }, [user?.id, user?.subscriptionStatus]);

  const loadOrders = async () => {
    if (!user || user.subscriptionStatus === 'UNSUBSCRIBED' || user.subscriptionStatus === 'EXPIRED') {
      setLoading(false);
      return;
    }
    try {
      setLoading(true);
      const data: Order[] = await apiRequest('api/orders');
      setOrders(data);

      if (data.length > 0) {
        const active = data.find((o) => ['PREPARING', 'DISPATCHED', 'IN_TRANSIT'].includes(o.status));
        setSelectedOrderId((prev) => prev || (active ? active.id : data[0].id));
      }
    } catch (err) {
      console.error('Failed to load orders:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleUpdateStatus = async (orderId: string, newStatus: string) => {
    try {
      await apiRequest(`api/orders/${orderId}/status`, 'PATCH', { status: newStatus });
      setOrders((prev) =>
        prev.map((o) => (o.id === orderId ? { ...o, status: newStatus } : o))
      );
      setToast({ message: `Status updated to ${newStatus}`, type: 'success' });
    } catch (err) {
      console.error('Failed to update order status:', err);
    }
  };

  const activeOrder = orders.find((o) => o.id === selectedOrderId) || orders[0] || null;

  const filteredOrders = orders.filter((o) =>
    o.orderNumber.toLowerCase().includes(searchQuery.toLowerCase()) ||
    o.customerName.toLowerCase().includes(searchQuery.toLowerCase()) ||
    o.customerPhone.includes(searchQuery)
  );

  // Google Maps API Live Navigation & Turn-by-Turn Route Renderer
  useEffect(() => {
    if (!mapContainerRef.current || !activeOrder) return;
    let mounted = true;

    const destLat = activeOrder.deliveryLat ?? -17.8252;
    const destLng = activeOrder.deliveryLng ?? 31.0335;
    const driverLat = deviceGps ? deviceGps.lat : (activeOrder.deliveryLat ? activeOrder.deliveryLat - 0.015 : -17.8350);
    const driverLng = deviceGps ? deviceGps.lng : (activeOrder.deliveryLng ? activeOrder.deliveryLng - 0.015 : 31.0220);

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

        const driverPos = { lat: driverLat, lng: driverLng };
        const destPos = { lat: destLat, lng: destLng };

        if (!googleMapRef.current) {
          const map = new google.maps.Map(mapContainerRef.current, {
            center: destPos,
            zoom: 15,
            mapTypeId: mapType === 'hybrid' ? google.maps.MapTypeId.HYBRID : google.maps.MapTypeId.ROADMAP,
            styles: mapType === 'dark' ? DARK_MAP_STYLES : [],
            disableDefaultUI: false,
            zoomControl: false,
            mapTypeControl: false,
            streetViewControl: false,
            fullscreenControl: false,
            gestureHandling: 'greedy',
          });
          googleMapRef.current = map;
        } else {
          googleMapRef.current.setMapTypeId(
            mapType === 'hybrid' ? google.maps.MapTypeId.HYBRID : google.maps.MapTypeId.ROADMAP
          );
          if (mapType === 'dark') {
            googleMapRef.current.setOptions({ styles: DARK_MAP_STYLES });
          } else {
            googleMapRef.current.setOptions({ styles: [] });
          }
        }

        const map = googleMapRef.current;

        // Clear markers & active polyline
        if (driverMarkerRef.current) driverMarkerRef.current.setMap(null);
        if (destMarkerRef.current) destMarkerRef.current.setMap(null);
        if (activePolylineRef.current) {
          activePolylineRef.current.setMap(null);
          activePolylineRef.current = null;
        }

        // Driver Marker (Where I am)
        driverMarkerRef.current = new google.maps.Marker({
          position: driverPos,
          map,
          title: `Where I Am (Driver Live GPS)`,
          icon: {
            path: google.maps.SymbolPath.CIRCLE,
            scale: 10,
            fillColor: '#10b981',
            fillOpacity: 1,
            strokeColor: '#ffffff',
            strokeWeight: 3,
          },
        });

        const driverInfoWindow = new google.maps.InfoWindow({
          content: `
            <div style="padding: 6px; font-family: sans-serif; color: #0f172a;">
              <strong style="color: #10b981; font-size: 12px;">🟢 Where I Am (Driver GPS)</strong>
              <p style="margin: 2px 0 0 0; font-size: 10px; color: #475569;">${deviceGps ? 'Live Device Hardware GPS' : 'Simulated Driver Position'}</p>
            </div>
          `,
        });
        driverMarkerRef.current.addListener('click', () => driverInfoWindow.open(map, driverMarkerRef.current));

        // Destination Marker (Where person order is)
        destMarkerRef.current = new google.maps.Marker({
          position: destPos,
          map,
          title: `Order #${activeOrder.orderNumber}: ${activeOrder.customerName}`,
          icon: {
            path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
            scale: 8,
            fillColor: '#2563eb',
            fillOpacity: 1,
            strokeColor: '#ffffff',
            strokeWeight: 2,
          },
        });

        const destInfoWindow = new google.maps.InfoWindow({
          content: `
            <div style="padding: 6px; font-family: sans-serif; color: #0f172a;">
              <strong style="color: #2563eb; font-size: 12px;">📍 Order #${activeOrder.orderNumber} Destination</strong>
              <p style="margin: 2px 0; font-size: 11px; font-weight: bold; color: #1e293b;">${activeOrder.customerName}</p>
              <p style="margin: 0; font-size: 10px; color: #64748b;">${activeOrder.deliveryAddress || 'Customer Address'}</p>
            </div>
          `,
        });
        destMarkerRef.current.addListener('click', () => destInfoWindow.open(map, destMarkerRef.current));

        // Compute Driving Route safely (OSRM / REST / Polyline fallback to avoid Google DirectionsService UNKNOWN_ERROR)
        if (isTrackingRoute) {
          const computeRoute = async () => {
            let routeSuccess = false;

            // Method 1: OSRM Driving Route (free, fast, no Google Directions API dependency)
            try {
              const osrmUrl = `https://router.project-osrm.org/route/v1/driving/${driverLng},${driverLat};${destLng},${destLat}?overview=full&geometries=geojson&steps=true`;
              const res = await fetch(osrmUrl);
              if (res.ok) {
                const data = await res.json();
                const route = data.routes?.[0];
                if (route && mounted) {
                  const points = route.geometry.coordinates.map(([lng, lat]: [number, number]) => ({ lat, lng }));
                  const polyline = new google.maps.Polyline({
                    path: points,
                    geodesic: true,
                    strokeColor: '#2563eb',
                    strokeOpacity: 0.9,
                    strokeWeight: 7,
                    map,
                  });
                  activePolylineRef.current = polyline;

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

                  const km = (route.distance / 1000).toFixed(1);
                  const mins = Math.round(route.duration / 60);
                  const etaTime = new Date(new Date().getTime() + route.duration * 1000).toLocaleTimeString([], {
                    hour: '2-digit',
                    minute: '2-digit',
                  });

                  const steps = route.legs?.[0]?.steps || [];
                  const step1 = steps[0]?.name ? `Head ${steps[0].maneuver.type || 'on'} ${steps[0].name}` : 'Head towards destination';
                  const step2 = steps[1]?.name ? `Turn onto ${steps[1].name}` : 'Approaching destination';

                  setRouteInfo({
                    distance: `${km} km`,
                    duration: `${mins} min`,
                    etaTime,
                    currentInstruction: step1,
                    nextManeuver: step2,
                  });
                  routeSuccess = true;
                }
              }
            } catch (err) {
              console.warn('OSRM routing fetch failed:', err);
            }

            // Method 2: Geodesic Polyline Fallback
            if (!routeSuccess && mounted) {
              const line = [driverPos, destPos];
              const polyline = new google.maps.Polyline({
                path: line,
                geodesic: true,
                strokeColor: '#2563eb',
                strokeOpacity: 0.8,
                strokeWeight: 5,
                map,
              });
              activePolylineRef.current = polyline;

              const bounds = new google.maps.LatLngBounds();
              bounds.extend(driverPos);
              bounds.extend(destPos);
              map.fitBounds(bounds, { top: 60, bottom: 60, left: 60, right: 60 });

              const dLat = ((destLat - driverLat) * Math.PI) / 180;
              const dLon = ((destLng - driverLng) * Math.PI) / 180;
              const a =
                Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos((driverLat * Math.PI) / 180) * Math.cos((destLat * Math.PI) / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
              const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
              const distKm = (6371 * c).toFixed(1);
              const mins = Math.max(3, Math.round((parseFloat(distKm) / 30) * 60));
              const etaTime = new Date(new Date().getTime() + mins * 60 * 1000).toLocaleTimeString([], {
                hour: '2-digit',
                minute: '2-digit',
              });

              setRouteInfo({
                distance: `${distKm} km`,
                duration: `${mins} min`,
                etaTime,
                currentInstruction: 'Direct path to delivery location',
                nextManeuver: 'Arriving at destination',
              });
            }
          };

          computeRoute();
        } else {
          if (activePolylineRef.current) {
            activePolylineRef.current.setMap(null);
            activePolylineRef.current = null;
          }
          if (directionsRendererRef.current) {
            directionsRendererRef.current.setMap(null);
          }
          map.setCenter(destPos);
          map.setZoom(15);
        }
      })
      .catch(() => {
        // Fallback to Leaflet if Google Maps API key is not provided
        if (!mounted || !mapContainerRef.current) return;
        const container = mapContainerRef.current as any;

        import('leaflet').then((L) => {
          if (!mounted || !mapContainerRef.current) return;

          delete (L.Icon.Default.prototype as any)._getIconUrl;
          L.Icon.Default.mergeOptions({
            iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon.png',
            iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon-2x.png',
            shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png',
          });

          if (!leafletMapRef.current && !container._leaflet_id) {
            const map = L.map(mapContainerRef.current, {
              center: [destLat, destLng],
              zoom: 14,
              zoomControl: false,
              scrollWheelZoom: true,
            });

            const tileUrl = mapType === 'hybrid'
              ? 'https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}'
              : 'https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}';

            L.tileLayer(tileUrl, {
              attribution: '&copy; Google Maps',
              maxZoom: 20,
              subdomains: ['mt0', 'mt1', 'mt2', 'mt3'],
            }).addTo(map);

            leafletMapRef.current = map;
          }

          const map = leafletMapRef.current;
          if (!map) return;

          if (driverMarkerRef.current && driverMarkerRef.current.remove) driverMarkerRef.current.remove();
          if (destMarkerRef.current && destMarkerRef.current.remove) destMarkerRef.current.remove();

          const driverIcon = L.divIcon({
            className: '',
            html: `<div style="position:relative; width:44px; height:44px; display:flex; align-items:center; justify-content:center;">
              <div style="position:absolute; width:44px; height:44px; background:rgba(16,185,129,0.3); border-radius:50%; animation:ping 1.5s infinite;"></div>
              <div style="position:relative; width:36px; height:36px; background:#10b981; border:3px solid #ffffff; border-radius:50%; box-shadow:0 4px 14px rgba(0,0,0,0.4); display:flex; align-items:center; justify-content:center;">🚚</div>
            </div>`,
            iconSize: [44, 44],
            iconAnchor: [22, 22],
          });
          driverMarkerRef.current = L.marker([driverLat, driverLng], { icon: driverIcon }).addTo(map);

          const destIcon = L.divIcon({
            className: '',
            html: `<div style="position:relative; width:38px; height:38px; display:flex; flex-direction:column; align-items:center;">
              <div style="background:#2563eb; color:white; font-size:10px; font-weight:bold; padding:2px 6px; border-radius:6px; box-shadow:0 2px 6px rgba(0,0,0,0.3); white-space:nowrap; margin-bottom:2px;">Home</div>
              <div style="width:24px; height:24px; background:#2563eb; border:2px solid #ffffff; border-radius:50%; box-shadow:0 2px 8px rgba(0,0,0,0.3); display:flex; align-items:center; justify-content:center; color:white; font-size:12px;">📍</div>
            </div>`,
            iconSize: [38, 44],
            iconAnchor: [19, 44],
          });
          destMarkerRef.current = L.marker([destLat, destLng], { icon: destIcon }).addTo(map);

          map.setView([destLat, destLng], 14);
        });
      });

    return () => {
      mounted = false;
    };
  }, [activeOrder, isTrackingRoute, mapType, deviceGps]);

  const recenterMap = () => {
    if (!activeOrder) return;
    const destLat = activeOrder.deliveryLat ?? -17.8252;
    const destLng = activeOrder.deliveryLng ?? 31.0335;
    const driverLat = deviceGps ? deviceGps.lat : (activeOrder.deliveryLat ? activeOrder.deliveryLat - 0.015 : -17.8350);
    const driverLng = deviceGps ? deviceGps.lng : (activeOrder.deliveryLng ? activeOrder.deliveryLng - 0.015 : 31.0220);

    if (googleMapRef.current && (window as any).google) {
      const bounds = new (window as any).google.maps.LatLngBounds();
      bounds.extend({ lat: driverLat, lng: driverLng });
      bounds.extend({ lat: destLat, lng: destLng });
      googleMapRef.current.fitBounds(bounds, { top: 60, bottom: 60, left: 60, right: 60 });
    } else if (leafletMapRef.current) {
      leafletMapRef.current.fitBounds(
        [
          [driverLat, driverLng],
          [destLat, destLng],
        ],
        { padding: [60, 60] }
      );
    }
  };

  const zoomIn = () => {
    try {
      if (googleMapRef.current) {
        const currentZoom = googleMapRef.current.getZoom();
        const validZoom = typeof currentZoom === 'number' && !isNaN(currentZoom) ? currentZoom : 15;
        googleMapRef.current.setZoom(Math.min(validZoom + 1, 20));
      } else if (leafletMapRef.current && typeof leafletMapRef.current.zoomIn === 'function') {
        leafletMapRef.current.zoomIn();
      }
    } catch (err) {
      console.warn('Map zoomIn error:', err);
    }
  };

  const zoomOut = () => {
    try {
      if (googleMapRef.current) {
        const currentZoom = googleMapRef.current.getZoom();
        const validZoom = typeof currentZoom === 'number' && !isNaN(currentZoom) ? currentZoom : 15;
        googleMapRef.current.setZoom(Math.max(validZoom - 1, 1));
      } else if (leafletMapRef.current && typeof leafletMapRef.current.zoomOut === 'function') {
        leafletMapRef.current.zoomOut();
      }
    } catch (err) {
      console.warn('Map zoomOut error:', err);
    }
  };

  const toggleMapLayer = () => {
    setMapType((prev) => (prev === 'hybrid' ? 'dark' : 'hybrid'));
  };

  const cleanPhone = activeOrder ? activeOrder.customerPhone.replace(/[^0-9]/g, '') : '';
  const gmapsDirectionsUrl = activeOrder?.deliveryLat && activeOrder?.deliveryLng
    ? `https://www.google.com/maps/dir/?api=1&destination=${activeOrder.deliveryLat},${activeOrder.deliveryLng}&travelmode=driving`
    : `https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(activeOrder?.deliveryAddress || 'Harare')}`;

  return (
    <div className="space-y-4 max-w-7xl mx-auto font-sans">
      {/* Toast Notification */}
      {toast && (
        <div className="fixed top-6 right-6 z-50 animate-bounce">
          <div
            className={`px-4 py-3 rounded-xl shadow-2xl border backdrop-blur-md flex items-center gap-3 text-sm font-medium ${
              toast.type === 'success'
                ? 'bg-emerald-950/90 text-emerald-200 border-emerald-500/30'
                : 'bg-blue-950/90 text-blue-200 border-blue-500/30'
            }`}
          >
            <Truck className="h-5 w-5 text-emerald-400" />
            <span>{toast.message}</span>
          </div>
        </div>
      )}

      {/* HEADER BAR */}
      <div className="glass-panel p-3.5 sm:p-4 rounded-xl border border-white/5 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 sm:gap-4">
        <div className="flex items-center gap-2.5 min-w-0">
          <img src="/assets/deliveryman.gif" alt="Deliveries" className="h-10 w-10 sm:h-14 sm:w-14 object-contain shrink-0" />
          <div className="min-w-0">
            <h1 className="text-base sm:text-lg font-black tracking-tight text-white Outfit leading-tight truncate">
              Deliveries & Live Navigation
            </h1>
            <p className="text-[11px] sm:text-xs text-gray-400 mt-0.5 line-clamp-1">
              Google Maps turn-by-turn driving navigation and route tracking.
            </p>
          </div>
        </div>

        <div className="flex items-center gap-2 shrink-0">
          <button
            onClick={loadOrders}
            disabled={loading}
            className="flex items-center gap-1.5 sm:gap-2 px-3 sm:px-3.5 py-2 rounded-xl bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-400 text-xs font-semibold border border-emerald-500/20 transition-all cursor-pointer"
          >
            <RefreshCw className={`h-3.5 w-3.5 ${loading ? 'animate-spin' : ''}`} />
            <span>Refresh</span>
          </button>
        </div>
      </div>

      {/* SIDE-BY-SIDE RESPONSIVE LAYOUT */}
      <div className="flex flex-col lg:flex-row items-stretch gap-4 sm:gap-5 min-h-[500px]">
        {/* LEFT COLUMN: ORDER DETAILS & DISPATCH CARD */}
        <div className="w-full lg:w-[380px] xl:w-[420px] flex flex-col shrink-0">
          <div className="glass-panel bg-slate-900/90 border border-white/10 rounded-2xl p-4 sm:p-5 shadow-xl space-y-4 flex-1 flex flex-col justify-between">
            
            {/* Active Shipment Selector */}
            <div className="space-y-1">
              <label className="text-[10px] font-bold uppercase tracking-widest text-gray-400">
                Select Active Shipment
              </label>
              <div className="relative">
                <select
                  value={selectedOrderId || ''}
                  onChange={(e) => setSelectedOrderId(e.target.value)}
                  className="w-full bg-slate-950 border border-white/10 text-white text-xs font-semibold rounded-xl px-3 py-2.5 outline-none focus:border-blue-500 cursor-pointer appearance-none pr-8 truncate"
                >
                  {filteredOrders.length === 0 ? (
                    <option value="">No Active Deliveries</option>
                  ) : (
                    filteredOrders.map((o) => (
                      <option key={o.id} value={o.id}>
                        Order #{o.orderNumber} - {o.customerName} ({o.status})
                      </option>
                    ))
                  )}
                </select>
                <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 pointer-events-none" />
              </div>
            </div>

            {activeOrder ? (
              <div className="space-y-4 flex-1 flex flex-col justify-between pt-1">
                {/* Header */}
                <div className="flex items-center justify-between border-b border-white/5 pb-3">
                  <div>
                    <span className="text-[10px] uppercase font-bold text-gray-400 tracking-wider">Tracking Number</span>
                    <h2 className="text-lg sm:text-xl font-black text-white Outfit">Order #{activeOrder.orderNumber}</h2>
                  </div>
                  <span className="px-2.5 py-1 rounded-md bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 text-[11px] sm:text-xs font-bold uppercase">
                    {activeOrder.status}
                  </span>
                </div>

                {/* Customer & Address Details */}
                <div className="p-3.5 sm:p-4 rounded-xl bg-black/20 border border-white/5 space-y-2">
                  <div className="flex items-center justify-between gap-2">
                    <span className="text-[10px] font-bold uppercase tracking-wider text-gray-400 shrink-0">Customer</span>
                    <span className="text-xs font-bold text-white truncate">{activeOrder.customerName}</span>
                  </div>
                  <div className="flex items-center justify-between gap-2">
                    <span className="text-[10px] font-bold uppercase tracking-wider text-gray-400 shrink-0">Phone</span>
                    <span className="text-xs font-medium text-gray-300 truncate">{activeOrder.customerPhone}</span>
                  </div>
                  <div className="flex items-center justify-between gap-2">
                    <span className="text-[10px] font-bold uppercase tracking-wider text-gray-400 shrink-0">Method</span>
                    <span className="text-xs font-bold text-emerald-400 uppercase truncate">
                      {activeOrder.deliveryMethod === 'pickup' ? 'Store Pickup' : 'Home Delivery'}
                    </span>
                  </div>
                </div>

                {/* Items & Total Summary */}
                <div className="p-3.5 sm:p-4 rounded-xl bg-black/20 border border-white/5 space-y-2">
                  <div className="flex items-center justify-between text-xs">
                    <span className="text-gray-400">{activeOrder.items?.length || 0} Item(s)</span>
                    <span className="font-bold text-white text-sm">
                      {activeOrder.currency} ${activeOrder.totalAmount.toFixed(2)}
                    </span>
                  </div>
                  <div className="space-y-1 pt-1 border-t border-white/5 max-h-[100px] overflow-y-auto pr-1">
                    {activeOrder.items?.map((item) => (
                      <div key={item.id} className="flex justify-between text-[11px] text-gray-400">
                        <span className="truncate max-w-[180px]">{item.quantity}x {item.productName}</span>
                        <span className="shrink-0">${item.lineTotal.toFixed(2)}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            ) : (
              <div className="py-16 text-center text-gray-500 space-y-2">
                <Package className="h-8 w-8 mx-auto text-gray-600" />
                <p className="text-xs">No active deliveries to display.</p>
              </div>
            )}
          </div>
        </div>

        {/* RIGHT COLUMN: INTERACTIVE GOOGLE MAPS NAVIGATION CANVAS */}
        <div className="flex-1 min-h-[350px] sm:min-h-[420px] lg:min-h-[500px] relative rounded-2xl border border-white/10 overflow-hidden bg-slate-950 shadow-xl flex flex-col justify-between">
          
          {/* TOP TEAL TURN-BY-TURN NAVIGATION INSTRUCTION BANNER */}
          {isTrackingRoute && (
            <div className="absolute top-2.5 left-1/2 -translate-x-1/2 w-[calc(100%-6.5rem)] sm:w-[calc(100%-8rem)] max-w-lg z-20 bg-[#005c4b] text-white p-2.5 sm:p-3.5 rounded-xl sm:rounded-2xl shadow-2xl border border-emerald-400/30 flex items-center justify-between gap-2 sm:gap-3 animate-fade-in">
              <div className="flex items-center gap-2 sm:gap-3 min-w-0">
                <div className="h-7 w-7 sm:h-9 sm:w-9 rounded-full bg-white/10 flex items-center justify-center shrink-0">
                  <ArrowUp className="h-4 w-4 sm:h-5 sm:w-5 text-white stroke-[3]" />
                </div>
                <div className="min-w-0">
                  <h3 className="text-xs sm:text-sm font-black tracking-tight leading-tight Outfit truncate">
                    {routeInfo?.currentInstruction || 'Livingstone Ave towards Sixth St'}
                  </h3>
                  <p className="text-[10px] sm:text-xs text-emerald-100/80 font-medium truncate">
                    {routeInfo?.nextManeuver || 'Then ↰ Turn left'}
                  </p>
                </div>
              </div>
              <div className="h-6 w-6 sm:h-8 sm:w-8 rounded-full bg-white/10 flex items-center justify-center text-white shrink-0">
                <Volume2 className="h-3 w-3 sm:h-4 sm:w-4" />
              </div>
            </div>
          )}

          {/* GOOGLE MAP CANVAS */}
          <div ref={mapContainerRef} className="w-full h-full min-h-[350px] sm:min-h-[420px] lg:min-h-[500px] z-0" />

          {/* MAP CONTROL BUTTONS OVERLAY (Right Side) */}
          <div className="absolute right-2.5 top-2.5 sm:right-4 sm:top-4 z-20 flex flex-col gap-1.5 sm:gap-2">
            <button
              type="button"
              onClick={(e) => { e.preventDefault(); zoomIn(); }}
              title="Zoom In"
              className="h-8 w-8 sm:h-9 sm:w-9 rounded-lg sm:rounded-xl glass-panel border border-white/10 bg-slate-900/90 text-white flex items-center justify-center font-bold text-sm sm:text-base hover:bg-slate-800 transition-all cursor-pointer shadow-xl select-none"
            >
              +
            </button>
            <button
              type="button"
              onClick={(e) => { e.preventDefault(); zoomOut(); }}
              title="Zoom Out"
              className="h-8 w-8 sm:h-9 sm:w-9 rounded-lg sm:rounded-xl glass-panel border border-white/10 bg-slate-900/90 text-white flex items-center justify-center font-bold text-sm sm:text-base hover:bg-slate-800 transition-all cursor-pointer shadow-xl select-none"
            >
              -
            </button>
            <button
              onClick={recenterMap}
              title="Recenter Map"
              className="h-8 w-8 sm:h-9 sm:w-9 rounded-lg sm:rounded-xl glass-panel border border-white/10 bg-slate-900/90 text-emerald-400 flex items-center justify-center hover:bg-slate-800 transition-all cursor-pointer shadow-xl"
            >
              <LocateFixed className="h-3.5 w-3.5 sm:h-4 sm:w-4" />
            </button>
            <button
              onClick={toggleMapLayer}
              title="Toggle Map Style (Satellite / Hybrid / Dark)"
              className="h-8 w-8 sm:h-9 sm:w-9 rounded-lg sm:rounded-xl glass-panel border border-white/10 bg-slate-900/90 text-blue-400 flex items-center justify-center hover:bg-slate-800 transition-all cursor-pointer shadow-xl"
            >
              <Layers className="h-3.5 w-3.5 sm:h-4 sm:w-4" />
            </button>
          </div>

          {/* BOTTOM LIVE ROUTE STATUS BAR (COMPACT & SMALL) */}
          <div className="absolute bottom-2.5 left-2.5 right-2.5 sm:right-auto sm:max-w-xs z-20 bg-slate-900/95 backdrop-blur-xl border border-white/10 p-2 sm:p-2.5 rounded-xl shadow-xl flex items-center justify-between gap-2 sm:gap-3">
            <div className="flex items-center gap-2.5 min-w-0">
              <div className="min-w-0">
                <p className="text-xs font-bold text-white Outfit truncate">
                  {routeInfo?.duration || '7 min'} <span className="text-gray-400 font-normal">({routeInfo?.distance || '1.7 km'})</span>
                </p>
                <p className="text-[10px] text-gray-400 truncate">
                  ETA: {routeInfo?.etaTime || '09:38 AM'}
                </p>
              </div>
            </div>

            <button
              type="button"
              onClick={recenterMap}
              className="flex items-center gap-1.5 px-2.5 py-1.5 bg-blue-600 hover:bg-blue-500 text-white font-bold text-[11px] rounded-lg shadow-md shadow-blue-600/20 active:scale-95 transition-all cursor-pointer border-0 shrink-0"
            >
              <LocateFixed className="h-3 w-3" />
              <span>Center</span>
            </button>
          </div>
        </div>
      </div>

      {/* Driver Dispatch Modal */}
      {trackingModalOrder && (
        <TrackingModal
          orderId={trackingModalOrder.id}
          orderNumber={trackingModalOrder.orderNumber}
          customerPhone={trackingModalOrder.customerPhone}
          onClose={() => setTrackingModalOrder(null)}
          onSaved={(updatedTracking) => {
            if (updatedTracking.status) {
              handleUpdateStatus(trackingModalOrder.id, updatedTracking.status);
            }
            setTrackingModalOrder(null);
          }}
        />
      )}
    </div>
  );
}

export default function DeliveriesPage() {
  return (
    <Suspense fallback={
      <div className="h-[calc(100vh-5rem)] w-full flex items-center justify-center bg-slate-950 text-emerald-400">
        <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-emerald-500 border-t-transparent"></div>
      </div>
    }>
      <DeliveriesContent />
    </Suspense>
  );
}
