import { useState, useEffect, useCallback, useRef } from "react";
import CancellationPolicyBanner from "@/components/CancellationPolicyBanner";
import SuspendedAccountGate from "@/components/SuspendedAccountGate";
import { useOptimisticUpdate } from "@/hooks/useOptimisticUpdate";
import { useCurrentLocation } from "@/hooks/useCurrentLocation";
import { useAutoSave } from "@/hooks/useAutoSave";
import { useConnectionState } from "@/hooks/useConnectionState";
import { useBatteryStatus } from "@/hooks/useBatteryStatus";
import { base44 } from "@/api/base44Client";
import { generateIdempotencyKey, storeIdempotencyKey, getIdempotencyKey, clearIdempotencyKey } from "@/lib/idempotencyKeys";
import { captureError } from "@/lib/errorMonitoring";
import { withRetry } from "@/lib/retryFetch";
import { cacheInvalidatePattern } from "@/lib/cacheManager";
import { a11yAttrs, handleKeyboardNav, announce } from "@/lib/accessibilityHelpers";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Car, MapPin, ArrowRight, Loader2, Calculator, Route, Wallet, Map, ArrowRightLeft, ChevronLeft, Home, Package, Store, Utensils, AlertTriangle, Shield } from "lucide-react";
import ZipgyLogo from "@/components/ZipgyLogo";
import MapAddressPicker from "../components/MapAddressPicker";
import ErrorReporter from "@/components/ErrorReporter";
import WhatsAppNotice from "../components/WhatsAppNotice";
import SEOSchema from "@/components/SEOSchema";
import { motion } from "framer-motion";
import { useNavigate, Navigate } from "react-router-dom";
import { useIsMobile } from "@/hooks/use-mobile";
import { toast } from "sonner";
import { geocodeAddress, haversineKm, calculateFare, getPeakHourMultiplier, isNightRate, isAirportLocation } from "@/utils/fareCalculator";
import { useLowDataMode } from "@/lib/LowDataContext";
import PostRideSharePrompt from "@/components/PostRideSharePrompt";
import RideStatusScreen from "@/components/taxi/RideStatusScreen";
import MMGPaymentGuide from "@/components/booking/MMGPaymentGuide";
import SOSButton from "@/components/safety/SOSButton";
import { getLanguage, t } from "@/lib/i18n";
import { enforceProfileCompletion } from "@/components/ProfileCompletionGate";
import { useAuth } from "@/lib/AuthContext";
import MMGConfirmationModal from "@/components/food/MMGConfirmationModal";
import { useMmgPayment } from "@/hooks/useMmgPayment";
import { useNightRideMode } from "@/hooks/useNightRideMode";

const getRideTypes = (lang) => [
{ value: "standard", label: t('booking.standard', lang), description: t('booking.affordable_everyday', lang), icon: "🚗", badge: null },
{ value: "premium", label: t('booking.premium', lang), description: t('booking.comfortable_newer', lang), icon: "🚘", badge: t('booking.popular', lang) },
{ value: "shared", label: t('booking.shared', lang), description: t('booking.split_fare', lang), icon: "👥", badge: t('booking.save', lang) }];


export default function BookRide() {
  const isMobile = useIsMobile();
  if (!isMobile) return <Navigate to="/booking?service=taxi" replace />;
  return <BookRideWithAuth />;
}

function BookRideWithAuth() {
  const { isAuthenticated, isLoadingAuth } = useAuth();
  
  // Show loading while checking auth
  if (isLoadingAuth) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-white">
        <Loader2 className="w-8 h-8 animate-spin text-emerald-600" />
      </div>
    );
  }
  
  // Redirect to login if not authenticated
  if (!isAuthenticated) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center bg-white px-4">
        <h1 className="text-2xl font-bold text-gray-900 mb-2">Sign in to book a ride</h1>
        <p className="text-gray-600 mb-6 text-center">You need to sign in before booking a taxi</p>
        <button
          onClick={() => base44.auth.redirectToLogin('/book-ride')}
          className="bg-emerald-600 text-white font-bold py-3 px-6 rounded-xl active:scale-95 transition-transform"
        >
          Sign In
        </button>
      </div>
    );
  }
  
  return <SuspendedAccountGate><BookRideInner /></SuspendedAccountGate>;
}

function BookRideInner() {
  const { user: authUser } = useAuth();
  const navigate = useNavigate();
  const { isDarkMode, isNightTime } = useNightRideMode();
  const [deferredPrompt, setDeferredPrompt] = useState(null);
  const [appInstalled, setAppInstalled] = useState(false);
  const isIos = /iphone|ipad|ipod/i.test(navigator.userAgent);
  const isStandalone = typeof window !== "undefined" && window.matchMedia("(display-mode: standalone)").matches;

  // Phase 2: Connection monitoring, battery optimization, accessibility
  const { isOnline } = useConnectionState();
  const { isLowPowerMode } = useBatteryStatus();
  const lowBattery = isLowPowerMode;

  useEffect(() => {
    const handleInstallPrompt = (e) => {e.preventDefault();setDeferredPrompt(e);};
    const handleAppInstalled = () => setAppInstalled(true);
    window.addEventListener("beforeinstallprompt", handleInstallPrompt);
    window.addEventListener("appinstalled", handleAppInstalled);

    return () => {
      window.removeEventListener("beforeinstallprompt", handleInstallPrompt);
      window.removeEventListener("appinstalled", handleAppInstalled);
    };
  }, []);

  const handleInstall = useCallback(() => {
    if (deferredPrompt) {
      deferredPrompt.prompt().then(() => {
        deferredPrompt.userChoice.then(() => {
          if (isMountedRef.current) setDeferredPrompt(null);
        }).catch(() => {});
      }).catch(() => {});
    }
  }, [deferredPrompt]);

  const isMountedRef = useRef(true);
  const { address: currentAddress } = useCurrentLocation();
  const [loading, setLoading] = useState(false);
  const { optimisticState: bookedRide, runOptimistic } = useOptimisticUpdate(null);
  const [selectedType, setSelectedType] = useState("standard");
  const [recentAddresses, setRecentAddresses] = useState([]);

  // Load recent addresses scoped to current user (use AuthContext, no API call)
  useEffect(() => {
    const key = authUser?.id ? `zipgy_recent_addresses_${authUser.id}` : 'zipgy_recent_addresses_guest';
    try { setRecentAddresses(JSON.parse(localStorage.getItem(key) || '[]')); } catch { setRecentAddresses([]); }
  }, [authUser]);
  const [form, setForm] = useState({ pickup_location: "", dropoff_location: "", passenger_name: "", passenger_phone: "", passenger_email: "", notes: "", family_email: "" });
  const [userProfile, setUserProfile] = useState(null);
  const { isSaving, clearDraft } = useAutoSave(form, "Ride", "draft_ride_id");

  // User load: use AuthContext user (already loaded, no API call needed)
  useEffect(() => {
    if (authUser) {
      setUserProfile(authUser);
      const userPhone = authUser.phone || authUser.data?.phone || '';
      const defaultPickup = authUser.default_pickup_address || '';
      
      setForm((prev) => ({
        ...prev,
        passenger_name: prev.passenger_name || authUser.full_name || "",
        passenger_phone: prev.passenger_phone || userPhone,
        passenger_email: prev.passenger_email || authUser.email || "",
        pickup_location: prev.pickup_location || defaultPickup
      }));
      
      // Update cache for next visit
      localStorage.setItem('zipgy_user_prefill', JSON.stringify({
        full_name: authUser.full_name || '',
        phone: userPhone,
        default_pickup_address: defaultPickup
      }));
    }
  }, [authUser]);

  // Real-time form validation
  const [validationErrors, setValidationErrors] = useState({});
  useEffect(() => {
    const errors = {};
    if (form.passenger_name && form.passenger_name.trim().length < 2) errors.name = 'Name must be at least 2 characters';
    if (form.passenger_phone && !/^\+?[0-9\s\-()]+$/.test(form.passenger_phone)) errors.phone = 'Invalid phone format';
    if (form.passenger_email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.passenger_email)) errors.email = 'Invalid email format';
    setValidationErrors(errors);
  }, [form.passenger_name, form.passenger_phone, form.passenger_email]);
  const [fareInfo, setFareInfo] = useState(null);
  const [calcLoading, setCalcLoading] = useState(false);
  const [promoCode, setPromoCode] = useState("");
  const [promoResult, setPromoResult] = useState(null); // { discount, code } or { error }
  const [promoChecking, setPromoChecking] = useState(false);
  const [error, setError] = useState(null);
  const [scheduledAt, setScheduledAt] = useState("");
  const [paymentMethod, setPaymentMethod] = useState("cash");
  const [mapPicker, setMapPicker] = useState(null); // 'pickup' | 'dropoff'
  const [gpsLoading, setGpsLoading] = useState(false);
  const [showPostRideShare, setShowPostRideShare] = useState(false);
  const [validationMessage, setValidationMessage] = useState("");
  const [makeOffer, setMakeOffer] = useState(false);
  const [passengerOffer, setPassengerOffer] = useState("");
  const { lowDataMode } = useLowDataMode();
  const [userCoords, setUserCoords] = useState(null);
  const [lang, setLang] = useState(getLanguage());
  const [selectedBusiness, setSelectedBusiness] = useState(null);
  const [showMmgModal, setShowMmgModal] = useState(false);
  const { initiatePayment: initiateMmgPayment, processing: mmgProcessing } = useMmgPayment();
  const isBookingInFlightRef = useRef(false);
  const isCheckingPromoRef = useRef(false);
  
  // Auto-enable dark mode for night rides (Guyana: 7pm-5am)
  const [isNightRide, setIsNightRide] = useState(false);
  useEffect(() => {
    const checkNightTime = () => {
      const hour = new Date().getHours();
      // Guyana sunset/sunrise: 7pm-5am
      setIsNightRide(hour >= 19 || hour < 5);
    };
    checkNightTime();
    const interval = setInterval(checkNightTime, 60000); // Check every minute
    return () => clearInterval(interval);
  }, []);

  // Fetch active taxi business for rate calculation
  useEffect(() => {
    const loadBusiness = async () => {
      try {
        const businesses = await base44.entities.Business.filter({ business_type: "taxi", status: "active" });
        if (businesses.length > 0) {
          setSelectedBusiness(businesses[0]);
        }
      } catch (err) {
        console.error('Failed to load business rates:', err);
      }
    };
    loadBusiness();
  }, []);

  // Listen for language changes
  useEffect(() => {
    const handleLanguageChange = (e) => setLang(e.detail.lang);
    window.addEventListener('languagechange', handleLanguageChange);
    return () => window.removeEventListener('languagechange', handleLanguageChange);
  }, []);

  // Instant geolocation with 3s timeout (fail silently, non-blocking)
  useEffect(() => {
    let cancelled = false;
    const geoTimeout = new Promise((_, reject) => setTimeout(() => reject(new Error('Geo timeout')), 3000));
    const geoPromise = new Promise((resolve) =>
    navigator.geolocation?.getCurrentPosition(resolve, () => {}, { enableHighAccuracy: false, timeout: 3000, maximumAge: 120000 })
    );
    Promise.race([geoPromise, geoTimeout]).then(({ coords }) => {
      if (!cancelled && isMountedRef.current) {
        setUserCoords({ latitude: coords.latitude, longitude: coords.longitude });
      }
    }).catch(() => {});
    return () => {cancelled = true;};
  }, []);

  useEffect(() => {
    if (userProfile?.payment_method) setPaymentMethod(userProfile.payment_method);
  }, [userProfile]);

  // Auto-prefill pickup location with current GPS address
  useEffect(() => {
    if (currentAddress) {
      setForm((prev) => ({ ...prev, pickup_location: prev.pickup_location || currentAddress }));
    }
  }, [currentAddress]);

  // Flush offline queue when back online
  useEffect(() => {
    const handleOnline = () => {
      (() => {
        const pendingKey = userProfile?.id ? `zipgy_pending_rides_${userProfile.id}` : 'zipgy_pending_rides_guest';
        const pending = JSON.parse(localStorage.getItem(pendingKey) || '[]');
        if (!pending.length) return;
        localStorage.removeItem(pendingKey);
        Promise.all(pending.map((item) => {
          const baseFare = item.fareInfo?.fare || calculateFare(0, item.selectedType, item.selectedBiz);
          const discount = item.promoResult?.discount || 0;
          const fare = Math.round(baseFare * (1 - discount / 100));
          return base44.entities.Ride.create({
            ...item.form, ride_type: item.selectedType,
            estimated_fare: baseFare, final_fare: fare,
            promo_code: item.promoResult?.code || "",
            discount_percent: discount || undefined,
            payment_method: item.paymentMethod,
            status: 'pending',
            business_id: item.selectedBiz?.id || '',
            business_name: item.selectedBiz?.business_name || ''
          });
        })).then(() => {
          toast.success(`${pending.length} offline ride${pending.length > 1 ? 's' : ''} submitted!`);
        }).catch(() => {});
      })();
    };
    window.addEventListener('online', handleOnline);
    return () => {window.removeEventListener('online', handleOnline);};
  }, []);



  // Recalculate fare whenever pickup, dropoff, or type changes (instant, no delay)
  useEffect(() => {
    if (!form.pickup_location || !form.dropoff_location) {setFareInfo(null);return;}
    estimateFare();
  }, [form.pickup_location, form.dropoff_location, selectedType, selectedBusiness]);

  const estimateFare = async () => {
    setCalcLoading(true);
    setFareInfo(null);
    try {
      const [pickup, dropoff] = await Promise.all([
      geocodeAddress(form.pickup_location),
      geocodeAddress(form.dropoff_location)]
      );
      if (!pickup || !dropoff) {
        setFareInfo({ error: "Could not locate one or both addresses. Try being more specific." });
        setCalcLoading(false);
        return;
      }
      const distanceKm = haversineKm(pickup.lat, pickup.lon, dropoff.lat, dropoff.lon);

      // Use selectedBusiness or fetch fallback
      let business = selectedBusiness;
      if (!business) {
        const businesses = await base44.entities.Business.filter({ business_type: "taxi", status: "active" }).catch(() => []);
        business = businesses.length > 0 ? businesses[0] : null;
      }

      // Check if night rate applies (10pm-6am)
      const isNight = isNightRate();
      // Check if airport pickup
      const isAirport = isAirportLocation(form.pickup_location);

      const fare = calculateFare(distanceKm, selectedType, business, isNight, isAirport);
      const etaMinutes = Math.round(distanceKm / 1.5);

      setFareInfo({
        fare,
        distanceKm: distanceKm.toFixed(1),
        eta_minutes: etaMinutes,
        isNight,
        isAirport
      });
    } catch (err) {
      console.error('Fare estimation error:', err);
      setFareInfo({ error: "Could not calculate fare. Please check addresses." });
    } finally {
      setCalcLoading(false);
    }
  };

  const updateField = (field, value) => setForm((prev) => ({ ...prev, [field]: value }));

  const useMyLocation = async () => {
    if (!navigator.geolocation) {
      toast.error("Geolocation not supported on this device.");
      return;
    }
    
    try {
      // Request permission first
      const permission = await navigator.permissions?.query({ name: 'geolocation' });
      if (permission?.state === 'denied') {
        toast.error("Location permission denied. Please enable in browser settings.");
        return;
      }
      
      setGpsLoading(true);
      const position = await new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject, {
          enableHighAccuracy: false,
          timeout: 10000,
          maximumAge: 60000
        });
      });
      
      const { latitude, longitude } = position.coords;
      const res = await fetch(`https://nominatim.openstreetmap.org/reverse?lat=${latitude}&lon=${longitude}&format=json`);
      const data = await res.json();
      const address = data.display_name?.split(",").slice(0, 3).join(", ") || `${latitude.toFixed(5)}, ${longitude.toFixed(5)}`;
      updateField("pickup_location", address);
      setGpsLoading(false);
    } catch (err) {
      console.error('Geolocation error:', err);
      toast.error(err.name === 'PermissionDeniedError' ? "Location permission denied. Please enable in browser settings." : "Could not get your location.");
      setGpsLoading(false);
    }
  };

  const applyPromo = async () => {
    if (!promoCode.trim() || isCheckingPromoRef.current) return;
    
    isCheckingPromoRef.current = true;
    setPromoChecking(true);
    setPromoResult(null);
    try {
      const results = await base44.entities.PromoCode.filter({ code: promoCode.trim().toUpperCase(), is_active: true });
      if (!results.length) {
        setPromoResult({ error: "Invalid or expired promo code." });
        setPromoChecking(false);
        isCheckingPromoRef.current = false;
        return;
      }
      const promo = results[0];
      if (promo.max_uses && promo.uses_count >= promo.max_uses) {
        setPromoResult({ error: "This promo code has reached its limit." });
        setPromoChecking(false);
        isCheckingPromoRef.current = false;
        return;
      }
      if (promo.expires_at && new Date(promo.expires_at) < new Date()) {
        setPromoResult({ error: "This promo code has expired." });
        setPromoChecking(false);
        isCheckingPromoRef.current = false;
        return;
      }
      // Rate limit: check if user already used this promo
      const usedRides = await base44.entities.Ride.filter({ promo_code: promo.code }).catch(() => []);
      const userEmail = userProfile?.email;
      if (userEmail && usedRides.some((r) => r.created_by === userEmail || r.passenger_email === userEmail)) {
        setPromoResult({ error: "You've already used this promo code." });
        setPromoChecking(false);
        isCheckingPromoRef.current = false;
        return;
      }
      setPromoResult({ discount: promo.discount_percent, code: promo.code, id: promo.id });
      setPromoChecking(false);
      toast.success(`Promo applied! ${promo.discount_percent}% off 🎉`);
    } catch (err) {
      setPromoResult({ error: "Could not validate promo code." });
      setPromoChecking(false);
    } finally {
      isCheckingPromoRef.current = false;
    }
  };



  // Live tracking on success screen
  const [liveRide, setLiveRide] = useState(null);
  useEffect(() => {
    if (!bookedRide?.id) return;
    let isMounted = true;
    let unsubscribe = undefined;

    // Try to subscribe for real-time updates
    try {
      unsubscribe = base44.entities.Ride.subscribe((ev) => {
        if (isMounted && ev.type === "update" && ev.id === bookedRide.id) setLiveRide(ev.data);
      });
    } catch {
      // Subscription failed — will fall back to polling only
    }
    // Poll for updates every 3 seconds as fallback
    const interval = setInterval(() => {if (isMounted) {
          base44.entities.Ride.filter({ id: bookedRide.id }).
          then((results) => {if (results[0]) setLiveRide(results[0]);}).
          catch(() => {});
        }
      }, 3000);

    return () => {
      isMounted = false;
      clearInterval(interval);
      if (typeof unsubscribe === 'function') unsubscribe();
    };
  }, [bookedRide?.id]);
  const displayRide = liveRide || bookedRide;

  if (bookedRide) {
    return (
      <>
        {/* SOS Button during active ride */}
        <SOSButton rideId={bookedRide.id} rideStatus={bookedRide.status} />
        <RideStatusScreen
          bookedRide={bookedRide}
          userProfile={userProfile}
          form={form}
          onBookAnother={() => {
            setLiveRide(null);
            setForm({ pickup_location: "", dropoff_location: "", passenger_name: form.passenger_name, passenger_phone: form.passenger_phone, notes: "" });
            setFareInfo(null);
            setPromoCode("");
            setPromoResult(null);
          }} />
      </>
    );
  }

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // Prevent concurrent booking submissions
    if (isBookingInFlightRef.current) {
      toast.error("Ride already being booked. Please wait...");
      return;
    }
    isBookingInFlightRef.current = true;
    
    // CRITICAL: Enforce profile completion before allowing booking
    try {
      await enforceProfileCompletion();
    } catch (err) {
      if (err.message?.startsWith('PROFILE_INCOMPLETE:')) {
        const msg = err.message.replace('PROFILE_INCOMPLETE:', '');
        setValidationMessage(`⚠️ ${msg}`);
        announce("Please complete your profile before booking.", "alert");
        toast.error(msg);
        isBookingInFlightRef.current = false;
        return;
      }
      isBookingInFlightRef.current = false;
      throw err;
    }
    
    if (!form.passenger_name?.trim() || !form.passenger_email?.trim() || !form.passenger_phone?.trim() || !form.pickup_location?.trim() || !form.dropoff_location?.trim()) {
      setValidationMessage("⚠️ Please fill out all required fields to continue.");
      announce("Please fill out all required fields to continue.", "alert");
      isBookingInFlightRef.current = false;
      return;
    }

    const idempotencyKey = generateIdempotencyKey();
    const existing = getIdempotencyKey(idempotencyKey);
    if (existing && Date.now() - existing.timestamp < 60000) {
      // Only block if within 60 seconds
      toast.error("Ride already submitted. Check your dashboard.");
      isBookingInFlightRef.current = false;
      return;
    }
    storeIdempotencyKey(idempotencyKey, { type: 'ride', timestamp: Date.now() });

    // For MMG, show confirmation modal first
    if (paymentMethod === 'mmg') {
      setShowMmgModal(true);
      isBookingInFlightRef.current = false;
      return;
    }

    await handleBookingRequest(idempotencyKey);
  };

  const handleMmgConfirmed = async () => {
    setShowMmgModal(false);
    const idempotencyKey = generateIdempotencyKey();
    const existing = getIdempotencyKey(idempotencyKey);
    if (existing && Date.now() - existing.timestamp < 60000) {
      toast.error("Ride already submitted. Check your dashboard.");
      return;
    }
    await handleBookingRequest(idempotencyKey);
  };

  const handleMmgCancelled = () => {
    setShowMmgModal(false);
    setLoading(false);
    isBookingInFlightRef.current = false;
  };

  const handleBookingRequest = async (idempotencyKey) => {
    setValidationMessage("");
    setError(null);
    setLoading(true);
    // Idempotency key already stored in handleSubmit

    const optimisticRide = {
      id: "pending-" + Date.now(),
      pickup_location: form.pickup_location,
      dropoff_location: form.dropoff_location,
      passenger_name: form.passenger_name,
      status: "pending"
    };

    try {
      await runOptimistic(optimisticRide, async () => {
        // Offline queue: save to localStorage if no network
        if (!navigator.onLine) {
          const pendingKey = userProfile?.id ? `zipgy_pending_rides_${userProfile.id}` : 'zipgy_pending_rides_guest';
          const pending = JSON.parse(localStorage.getItem(pendingKey) || '[]');
          pending.push({ form, selectedType, paymentMethod, scheduledAt, promoResult, fareInfo, timestamp: Date.now() });
          localStorage.setItem(pendingKey, JSON.stringify(pending));
          isBookingInFlightRef.current = false;
          setLoading(false);
          toast.error('You are offline! Your ride request has been saved and will be submitted automatically when you reconnect.');
          return;
        }
        const baseFare = fareInfo?.fare || calculateFare(0, selectedType, null);
        const discount = promoResult?.discount || 0;
        const fare = Math.round(baseFare * (1 - discount / 100));
        const distanceKm = fareInfo?.distanceKm || 0;

        // Geocode pickup so passengers can see the pin on the tracking map
        const pickupCoords = await geocodeAddress(form.pickup_location).catch(() => null);

        // Generate PIN synchronously before creating ride
        const rideCode = String(Math.floor(Math.random() * 9000) + 1000);

        // CREATE RIDE FIRST - this is critical!
        const ride = await base44.entities.Ride.create({
          passenger_name: form.passenger_name,
          passenger_email: form.passenger_email,
          passenger_phone: form.passenger_phone,
          pickup_location: form.pickup_location,
          dropoff_location: form.dropoff_location,
          notes: form.notes,
          family_email: form.family_email,
          ride_type: selectedType,
          payment_method: paymentMethod,
          status: 'requested',
          estimated_fare: baseFare,
          final_fare: fare,
          promo_code: promoResult?.code || "",
          discount_percent: discount || undefined,
          business_id: selectedBusiness?.id || '',
          business_name: selectedBusiness?.business_name || '',
          scheduled_at: scheduledAt || undefined,
          ride_code: rideCode
        });

        // Send email confirmation to passenger
        if (form.passenger_email || userProfile?.email) {
          base44.functions.invoke('sendBookingEmail', {
            email: form.passenger_email || userProfile?.email,
            name: form.passenger_name,
            type: 'ride',
            orderId: ride.id,
            from: form.pickup_location,
            to: form.dropoff_location,
            fare
          }).catch(() => {});
        }

        // Send family notification email if provided
        if (form.family_email?.trim()) {
          base44.functions.invoke('sendWhatsApp', {
            to: form.family_email,
            message: `🚨 ZIP.GY Ride Safety Alert\n\nYour family member has booked a ride:\n\n👤 Passenger: ${form.passenger_name}\n📍 Pickup: ${form.pickup_location}\n🏁 Dropoff: ${form.dropoff_location}\n💰 Fare: GYD ${fare}\n🆔 Ride ID: ${ride.id}\n\n📍 Track their ride in real-time:\n${window.location.origin}/track-ride?id=${ride.id}\n\n⚠️ If the ride doesn't arrive within 15 minutes of the estimated time, contact ZIP.GY support immediately.\n\nStay safe!`
          }).catch(() => {});
        }

        // increment promo uses (with retry)
        if (promoResult?.id) {
          withRetry(async () => {
            const promos = await base44.entities.PromoCode.filter({ code: promoResult.code });
            if (promos.length) await base44.entities.PromoCode.update(promos[0].id, { uses_count: (promos[0].uses_count || 0) + 1 });
          }, { maxRetries: 2 }).catch(() => {});

          // Invalidate promo cache on success
          cacheInvalidatePattern(/^promo:/);
        }

        // Notify available taxi services
        base44.functions.invoke('notifyAvailableTaxis', {
          ride_id: ride.id,
          pickup_location: form.pickup_location,
          dropoff_location: form.dropoff_location,
          passenger_name: form.passenger_name,
          passenger_phone: form.passenger_phone,
          estimated_fare: fare,
          ride_type: selectedType
        }).catch(() => {
          // Notification failed silently - driver will see ride in dashboard
        });

        // Trigger automatic geo-targeted assignment
        base44.functions.invoke('assignClosestTaxi', {
          ride_id: ride.id,
          pickup_lat: pickupCoords?.lat,
          pickup_lng: pickupCoords?.lon
        }).catch(() => {
          // Auto-assignment failed silently - fallback to manual dispatch
        });

        // Send WhatsApp receipt + PIN to passenger via UltraMsg
        if (form.passenger_phone) {
          const payLabel = paymentMethod === 'mmg' ? 'MMG Mobile Money' : paymentMethod === 'card' ? 'Card' : 'Cash';
          const trackingUrl = `${window.location.origin}/track-ride?id=${ride.id}`;
          const pinText = `\n🔐 Your Safety PIN: ${rideCode}\n\n⚠️ IMPORTANT: Show this PIN to your driver when they arrive. They must verify it before starting the ride. This keeps you safe!`;
          const receiptMsg = `🧾 ZIP.GY Ride Receipt\n\n✅ Ride Booked!\n\n👤 Name: ${form.passenger_name}\n📍 From: ${form.pickup_location}\n🏁 To: ${form.dropoff_location}\n💰 Fare: GYD ${fare}\n💳 Payment: ${payLabel}\n🆔 Ride ID: ${ride.id}${pinText}\n\n📍 Track your ride:\n${trackingUrl}\n\n⚡ Thank you for using ZIP.GY!`;
          base44.functions.invoke('sendWhatsApp', { to: form.passenger_phone, message: receiptMsg }).catch(() => {});
        }

        // Send SMS with PIN to passenger
        if (form.passenger_phone) {
          const smsMsg = `ZIP.GY Ride: Your 4-digit PIN is ${rideCode}. Show this to your driver when they arrive. Stay safe!`;
          base44.functions.invoke('sendSmsNotification', { to: form.passenger_phone, message: smsMsg }).catch(() => {});
        }

        // Save addresses to recent — scoped by user ID
        const addrKey = userProfile?.id ? `zipgy_recent_addresses_${userProfile.id}` : 'zipgy_recent_addresses_guest';
        const addrs = [form.pickup_location, form.dropoff_location].filter(Boolean);
        const updated = [...new Set([...addrs, ...recentAddresses])].slice(0, 8);
        setRecentAddresses(updated);
        localStorage.setItem(addrKey, JSON.stringify(updated));

        clearDraft();

        // For guest users, invite them silently
        if (!userProfile && form.passenger_email) {
          base44.users.inviteUser(form.passenger_email, "user").catch(() => {});
        }

        // Navigate to tracking page using React Router (preserves app state)
        navigate(`/track-ride?id=${ride.id}`, { replace: true });

        return ride;
      });
    } catch (err) {
      clearIdempotencyKey(idempotencyKey);
      captureError(err, 'BookRide', form.pickup_location);
      setError(err);
      isBookingInFlightRef.current = false;
      setLoading(false);
    }
    // Don't reset in finally - only reset on error or after success
  };

  return (
    <>
    {showMmgModal && (
      <MMGConfirmationModal
        userPhone={authUser?.mmg_number || form.passenger_phone}
        businessPhone=""
        businessName="ZIP.GY Taxi Service"
        amount={fareInfo?.fare || 0}
        isProcessing={loading || mmgProcessing}
        onConfirm={handleMmgConfirmed}
        onCancel={handleMmgCancelled}
      />
    )}
    <SEOSchema page="booking" />
    <div className={`min-h-screen pb-12 overflow-y-auto transition-colors duration-500 ${isNightRide ? 'bg-slate-900' : 'bg-background'}`} style={{ WebkitOverflowScrolling: "touch" }}>

      {/* Enhanced Taxi Header Banner - ZIP.GY Branding */}
      <div 
        className={`sticky top-0 z-50 flex-shrink-0 md:hidden shadow-xl transition-colors duration-500 ${isNightRide ? 'bg-slate-800' : ''}`}
        style={{ paddingTop: 'max(8px, env(safe-area-inset-top, 8px))' }}
      >
        {/* Main Banner */}
        <div className={`bg-gradient-to-r px-4 pt-3 pb-3 relative overflow-hidden transition-colors duration-500 ${isNightRide ? 'from-slate-700 via-slate-800 to-slate-900' : 'from-emerald-600 via-teal-600 to-emerald-700'}`}>
          <div className="absolute inset-0 opacity-10">
            <div className="absolute top-0 right-0 w-32 h-32 bg-white rounded-full -translate-y-1/2 translate-x-1/2" />
            <div className="absolute bottom-0 left-0 w-24 h-24 bg-white rounded-full translate-y-1/2 -translate-x-1/2" />
          </div>
          <div className="relative z-10 flex items-center gap-3">
            <button onClick={() => window.history.back()} className="w-12 h-12 flex items-center justify-center hover:bg-white/20 active:bg-white/30 rounded-full transition-all flex-shrink-0 shadow-lg touch-manipulation" aria-label="Go back">
              <ChevronLeft className="w-6 h-6 text-white" />
            </button>
            <div className="flex-1 flex items-center gap-3">
              <div className="bg-white/20 backdrop-blur-sm rounded-xl p-2 shadow-lg">
                <ZipgyLogo className="h-6 w-auto" />
              </div>
              <div className="flex-1">
                <p className="text-lg font-extrabold text-white leading-tight">Book a Ride</p>
                <p className="text-sm text-white/90 font-medium mt-0.5">Fast & reliable taxi service</p>
              </div>
            </div>
            <div className="text-3xl">🚕</div>
          </div>
        </div>
        <div className={`border-b px-4 py-2.5 transition-colors duration-500 ${isNightRide ? 'bg-slate-800 border-slate-700' : 'bg-white border-gray-100'}`}>
          <div className="flex items-center gap-2 overflow-x-auto pb-0.5 scrollbar-hide">
            <button onClick={(e) => { e.preventDefault(); e.stopPropagation(); navigate("/home"); }} className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-all shadow-sm ${isNightRide ? 'bg-slate-700 hover:bg-slate-600 text-emerald-400' : 'bg-emerald-50 hover:bg-emerald-100 text-emerald-700'}`}>
              <Home className="w-3.5 h-3.5" /> Home
            </button>
            <button onClick={(e) => { e.preventDefault(); e.stopPropagation(); navigate("/order-food"); }} className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-all shadow-sm ${isNightRide ? 'bg-slate-700 hover:bg-slate-600 text-orange-400' : 'bg-orange-50 hover:bg-orange-100 text-orange-700'}`}>
              <Utensils className="w-3.5 h-3.5" /> Food
            </button>
            <button onClick={(e) => { e.preventDefault(); e.stopPropagation(); navigate("/order-groceries"); }} className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-all shadow-sm ${isNightRide ? 'bg-slate-700 hover:bg-slate-600 text-blue-400' : 'bg-blue-50 hover:bg-blue-100 text-blue-700'}`}>
              <Store className="w-3.5 h-3.5" /> Grocery
            </button>
            <button onClick={(e) => { e.preventDefault(); e.stopPropagation(); navigate("/request-delivery"); }} className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-all shadow-sm ${isNightRide ? 'bg-slate-700 hover:bg-slate-600 text-purple-400' : 'bg-purple-50 hover:bg-purple-100 text-purple-700'}`}>
              <Package className="w-3.5 h-3.5" /> Delivery
            </button>
          </div>
        </div>
      </div>






















<div className={`max-w-2xl mx-auto px-4 py-6 transition-colors duration-500 ${isNightRide ? 'bg-slate-900' : ''}`}>
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}>
          <WhatsAppNotice variant="user" />

          {/* SOS Safety Banner */}
          <div className={`bg-gradient-to-r border-2 rounded-2xl px-4 py-3 mb-4 shadow-sm transition-colors duration-500 ${isNightRide ? 'from-red-900/30 to-orange-900/30 border-red-700' : 'from-red-50 to-orange-50 border-red-200'}`}>
            <div className="flex items-start gap-3">
              <div className="w-10 h-10 rounded-full bg-gradient-to-br from-red-500 to-red-600 flex items-center justify-center flex-shrink-0 shadow-lg">
                <Shield className="w-5 h-5 text-white" />
              </div>
              <div className="flex-1">
                <p className={`font-heading font-bold text-sm ${isNightRide ? 'text-red-300' : 'text-red-800'}`}>🛡️ Your Safety is Our Priority</p>
                <p className={`text-xs mt-1 ${isNightRide ? 'text-red-400' : 'text-red-700'}`}>Every ride includes live GPS tracking, driver verification, and an emergency SOS button. Share your trip with family anytime.</p>
                <a href="/safety-features" className={`inline-flex items-center gap-1 text-xs font-semibold mt-2 ${isNightRide ? 'text-red-400 hover:text-red-300' : 'text-red-600 hover:text-red-800'}`}>
                  View all safety features →
                </a>
              </div>
            </div>
          </div>

          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Ride Type */}
            <div>
              <p className="font-heading font-bold text-base mb-3 text-foreground">{t('booking.select_ride_type', lang)}</p>
              <div className="grid grid-cols-3 gap-2.5">
                {getRideTypes(lang).map((type) => {
                    const bizPreview = calculateFare(0, type.value, null);
                    const isSelected = selectedType === type.value;
                    return (
                      <button
                        key={type.value}
                        type="button"
                        onClick={() => setSelectedType(type.value)}
                        className={`relative p-3 rounded-2xl border-2 text-left transition-all duration-200 active:scale-95 ${
                        isSelected ? "border-primary bg-primary/5 shadow-md" : isNightRide ? "border-slate-600 bg-slate-800 hover:border-primary/40" : "border-border bg-card hover:border-primary/40"}`
                        }>
                        
                      {type.badge &&
                        <span className={`absolute -top-2 -right-1 text-[10px] font-bold px-1.5 py-0.5 rounded-full ${isSelected ? 'bg-primary text-white' : 'bg-muted text-muted-foreground'}`}>
                          {type.badge}
                        </span>
                        }
                      <div className="text-xl mb-1">{type.icon}</div>
                      <div className={`font-heading font-bold text-sm leading-tight ${isNightRide ? 'text-slate-200' : 'text-foreground'}`}>{type.label}</div>
                      <p className={`text-xs leading-tight mt-0.5 mb-1.5 ${isNightRide ? 'text-slate-400' : 'text-muted-foreground'}`}>{type.description}</p>
                      <p className="text-xs font-bold text-primary">GYD {bizPreview}+</p>
                    </button>);

                  })}
              </div>
            </div>

            {/* Locations */}
            <div className="relative grid sm:grid-cols-2 gap-4">
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <Label htmlFor="pickup" className="font-medium">{t('booking.pickup_location', lang)}</Label>
                  <button type="button" onClick={useMyLocation} disabled={gpsLoading}
                    className="flex items-center gap-1 text-xs text-primary hover:underline disabled:opacity-50">
                    {gpsLoading ? <Loader2 className="w-3 h-3 animate-spin" /> : <MapPin className="w-3 h-3" />}
                    {t('booking.use_my_location', lang)}
                  </button>
                </div>
                <div className="relative w-full">
                  <MapPin className="absolute left-3 top-3 w-4 h-4 text-primary" />
                  <Input
                      id="pickup"
                      placeholder={lang === 'es' ? 'ej. Mercado Stabroek, Georgetown' : 'e.g. Stabroek Market, Georgetown'}
                      className="pl-10 pr-10 h-14 rounded-xl text-base w-full"
                      style={{ fontSize: '16px', maxWidth: '100%' }}
                      value={form.pickup_location}
                      onChange={(e) => updateField("pickup_location", e.target.value)}
                      onKeyDown={(e) => handleKeyboardNav(e, {
                        onEnter: handleSubmit,
                        onEscape: () => setForm((prev) => ({ ...prev, pickup_location: '' }))
                      })}
                      {...a11yAttrs.pickupInput}
                      required />
                    
                  <button type="button" onClick={() => setMapPicker('pickup')} className="absolute right-3 top-3 text-muted-foreground hover:text-primary transition-colors" title={t('booking.pick_on_map', lang)}>
                    <Map className="w-4 h-4" />
                  </button>
                </div>
              </div>
              {/* Swap button */}
              <button
                  type="button"
                  onClick={() => setForm((prev) => ({ ...prev, pickup_location: prev.dropoff_location, dropoff_location: prev.pickup_location }))}
                  className="hidden sm:flex absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-10 w-8 h-8 rounded-full bg-card border border-border shadow hover:bg-muted transition-colors items-center justify-center"
                  title={t('booking.swap', lang)}>
                  
                <ArrowRightLeft className="w-3.5 h-3.5 text-muted-foreground" />
              </button>

              <div className="space-y-2 w-full">
                <Label htmlFor="dropoff" className="font-medium">{t('booking.dropoff_location', lang)}</Label>
                <div className="relative w-full">
                  <MapPin className="absolute left-3 top-3 w-4 h-4 text-destructive" />
                  <Input
                      id="dropoff"
                      placeholder={lang === 'es' ? 'ej. Estadio Providence' : 'e.g. Providence Stadium'}
                      className="pl-10 pr-10 h-14 rounded-xl text-base w-full"
                      style={{ fontSize: '16px', maxWidth: '100%' }}
                      value={form.dropoff_location}
                      onChange={(e) => updateField("dropoff_location", e.target.value)}
                      onKeyDown={(e) => handleKeyboardNav(e, { onEnter: handleSubmit })}
                      {...a11yAttrs.dropoffInput}
                      required />
                    
                  <button type="button" onClick={() => setMapPicker('dropoff')} className="absolute right-3 top-3 text-muted-foreground hover:text-primary transition-colors" title={t('booking.pick_on_map', lang)}>
                    <Map className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>
            {/* Recent Addresses */}
            {recentAddresses.length > 0 && !form.pickup_location && !form.dropoff_location &&
              <div className="space-y-2">
                <Label className="text-xs text-muted-foreground">{t('booking.recent_addresses', lang)}</Label>
                <div className="flex flex-wrap gap-2">
                  {recentAddresses.slice(0, 5).map((addr, i) =>
                  <button
                    key={i}
                    type="button"
                    onClick={() => !form.pickup_location ? updateField("pickup_location", addr) : updateField("dropoff_location", addr)}
                    className="flex items-center gap-1.5 px-3 py-1.5 rounded-full border border-border text-xs text-muted-foreground hover:border-primary/40 hover:text-foreground transition-all bg-card">
                    
                      <MapPin className="w-3 h-3 flex-shrink-0" /> <span className="truncate max-w-[180px]">{addr}</span>
                    </button>
                  )}
                </div>
              </div>
              }

            {mapPicker &&
              <MapAddressPicker
                label={mapPicker === 'pickup' ? 'Pickup' : 'Dropoff'}
                onSelect={(addr) => updateField(mapPicker === 'pickup' ? 'pickup_location' : 'dropoff_location', addr)}
                onClose={() => setMapPicker(null)} />

              }

            {/* Personal Info */}
            <div className="grid sm:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="name" className="font-medium">{t('booking.your_name', lang)} <span className="text-red-500">*</span></Label>
                <Input
                    id="name"
                    placeholder={t('booking.full_name', lang)}
                    className={`h-14 rounded-xl ${!form.passenger_name?.trim() ? 'border-red-500 focus-visible:ring-red-500 bg-red-50' : ''}`}
                    value={form.passenger_name}
                    onChange={(e) => updateField("passenger_name", e.target.value)}
                    required />
                  {!form.passenger_name?.trim() && (
                    <p className="text-xs text-red-600 font-semibold flex items-center gap-1">
                      <AlertTriangle className="w-3 h-3" /> Name is required
                    </p>
                  )}
              </div>
              <div className="space-y-2">
                <Label htmlFor="phone" className="font-medium">{t('booking.phone_number', lang)} <span className="text-red-500">*</span></Label>
                <Input
                    id="phone"
                    placeholder={lang === 'es' ? '+592-000-0000' : '+592-000-0000'}
                    className={`h-14 rounded-xl ${!form.passenger_phone?.trim() ? 'border-red-500 focus-visible:ring-red-500 bg-red-50' : ''}`}
                    value={form.passenger_phone}
                    onChange={(e) => updateField("passenger_phone", e.target.value)}
                    required />
                  {!form.passenger_phone?.trim() && (
                    <p className="text-xs text-red-600 font-semibold flex items-center gap-1">
                      <AlertTriangle className="w-3 h-3" /> Phone is required
                    </p>
                  )}
              </div>
              <div className="space-y-2">
                <Label htmlFor="email" className="font-medium">{t('booking.email_address', lang)} <span className="text-red-500">*</span></Label>
                <Input
                    id="email"
                    type="email"
                    placeholder={lang === 'es' ? 'tu@correo.com' : 'your@email.com'}
                    className={`h-14 rounded-xl ${!form.passenger_email?.trim() ? 'border-red-500 focus-visible:ring-red-500 bg-red-50' : ''}`}
                    value={form.passenger_email}
                    onChange={(e) => updateField("passenger_email", e.target.value)}
                    required />
                  {!form.passenger_email?.trim() && (
                    <p className="text-xs text-red-600 font-semibold flex items-center gap-1">
                      <AlertTriangle className="w-3 h-3" /> Email is required
                    </p>
                  )}
              </div>
            </div>

            {/* Scheduled Ride */}
            <div className="space-y-2">
              <Label htmlFor="scheduled" className="font-medium">{t('booking.schedule_pickup', lang)}</Label>
              <Input
                  id="scheduled"
                  type="datetime-local"
                  className="h-14 rounded-xl"
                  value={scheduledAt}
                  min={new Date().toISOString().slice(0, 16)}
                  onChange={(e) => setScheduledAt(e.target.value)} />
                
              <p className="text-xs text-muted-foreground">{t('booking.book_now_desc', lang)}</p>
            </div>

            {/* Promo Code */}
            <div className="space-y-2">
              <Label className="font-medium">{t('booking.promo_code', lang)}</Label>
              <div className="flex gap-2">
                <Input
                    placeholder={t('booking.enter_promo', lang)}
                    className="h-14 rounded-xl flex-1 uppercase"
                    value={promoCode}
                    onChange={(e) => {setPromoCode(e.target.value.toUpperCase());setPromoResult(null);}} />
                  
                <Button type="button" variant="outline" className="h-14 rounded-xl px-5 font-heading font-semibold" onClick={applyPromo} disabled={promoChecking || !promoCode.trim()}>
                  {promoChecking ? <Loader2 className="w-4 h-4 animate-spin" /> : t('booking.apply', lang)}
                </Button>
              </div>
              {promoResult?.error && <p className="text-xs text-destructive">{promoResult.error}</p>}
              {promoResult?.discount && <p className="text-xs text-green-600 font-medium">{t('booking.promo_applied', lang).replace('{}', promoResult.discount)}</p>}
            </div>

            {/* Live Fare Estimate */}
            {(calcLoading || fareInfo) &&
              <motion.div
                initial={{ opacity: 0, y: -6 }}
                animate={{ opacity: 1, y: 0 }}
                transition={lowBattery ? { duration: 0 } : { duration: 0.2 }}
                className={`rounded-2xl border p-4 flex items-center gap-4 ${
                fareInfo?.error ? "bg-destructive/5 border-destructive/20" : "bg-primary/5 border-primary/20"}`
                }
                {...a11yAttrs.fareDisplay}>
                <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center flex-shrink-0">
                  {calcLoading ? <Loader2 className="w-5 h-5 text-primary animate-spin" /> : <Calculator className="w-5 h-5 text-primary" />}
                </div>
                <div>
                  {calcLoading && <p className="text-sm text-muted-foreground">{t('booking.calculating_fare', lang)}</p>}
                  {fareInfo?.error && <p className="text-sm text-destructive">{fareInfo.error}</p>}
                  {fareInfo?.fare &&
                  <>
                      {promoResult?.discount ?
                    <div className="flex items-center gap-2">
                          <p className="font-heading font-bold text-xl text-foreground line-through text-muted-foreground">GYD {fareInfo.fare}</p>
                          <p className="font-heading font-bold text-xl text-green-600">GYD {Math.round(fareInfo.fare * (1 - promoResult.discount / 100))}</p>
                        </div> :

                    <p className="font-heading font-bold text-xl text-foreground">GYD {fareInfo.fare}</p>
                    }
                      <div className="flex flex-wrap gap-2 mt-1">
                        {getPeakHourMultiplier() > 1 &&
                      <p className="text-xs text-accent font-semibold">⚡ {t('booking.peak_hours', lang)}</p>
                      }
                        {fareInfo?.isNight &&
                      <p className="text-xs text-amber-600 font-semibold">🌙 Night rate (+20%)</p>
                      }
                        {fareInfo?.isAirport &&
                      <p className="text-xs text-blue-600 font-semibold">✈️ Airport fee (GYD 500)</p>
                      }
                      </div>
                      <div className="flex items-center gap-1 text-xs text-muted-foreground mt-1">
                        <Route className="w-3 h-3" /> {fareInfo.distanceKm} km
                        {fareInfo.eta_minutes && <span>· {t('booking.eta_minutes', lang).replace('{}', fareInfo.eta_minutes)}</span>}
                      </div>
                    </>
                  }
                </div>
              </motion.div>
              }

            {/* Fare Negotiation */}
            <div className="space-y-3">
              <button
                  type="button"
                  onClick={() => {setMakeOffer(!makeOffer);setPassengerOffer("");}}
                  className={`flex items-center gap-2 px-4 py-2.5 rounded-xl border-2 text-sm font-heading font-semibold transition-all w-full ${
                  makeOffer ? "border-accent bg-accent/10 text-foreground" : "border-border text-muted-foreground hover:border-primary/30"}`
                  }>
                  
                <ArrowRightLeft className="w-4 h-4 text-primary" />
                {makeOffer ? t('booking.negotiating', lang) : t('booking.make_offer', lang)}
              </button>
              {makeOffer &&
                <div className="space-y-1">
                  <Label className="font-medium text-sm">{t('booking.your_offer', lang)}</Label>
                  <Input
                    type="number"
                    placeholder={fareInfo?.fare ? `${t('booking.suggested', lang)}: ${fareInfo.fare}` : lang === 'es' ? 'ej. 1200' : 'e.g. 1200'}
                    className="h-12 rounded-xl"
                    value={passengerOffer}
                    onChange={(e) => setPassengerOffer(e.target.value)}
                    min="100" />
                  
                  <p className="text-xs text-muted-foreground">{t('booking.drivers_will_see', lang)}</p>
                </div>
                }
            </div>

            {/* Payment Method */}
            <div className="space-y-3">
              <Label className="font-medium flex items-center gap-2"><Wallet className="w-4 h-4" /> {t('booking.payment_method', lang)}</Label>
              <div className="grid grid-cols-3 gap-3">
                {[
                  { value: "cash", label: t('booking.cash', lang) },
                  { value: "mmg", label: t('booking.mmg_mobile', lang) },
                  { value: "card", label: t('booking.card', lang) }].
                  map((opt) =>
                  <button
                    key={opt.value}
                    type="button"
                    onClick={() => setPaymentMethod(opt.value)}
                    className={`p-3 rounded-xl border-2 text-sm font-heading font-medium transition-all ${
                    paymentMethod === opt.value ?
                    "border-primary bg-primary/5 text-foreground" :
                    "border-border text-muted-foreground hover:border-primary/30"}`
                    }>
                    
                    {opt.label}
                  </button>
                  )}
              </div>
              
              {/* MMG Payment Guide - shown when MMG is selected */}
              {paymentMethod === "mmg" &&
                <div className="mt-2">
                  <MMGPaymentGuide />
                </div>
                }
            </div>

            {/* Family Notification */}
            <div className="bg-blue-50 border-2 border-blue-200 rounded-2xl p-4 space-y-3">
              <div className="flex items-center gap-2">
                <Shield className="w-5 h-5 text-blue-600" />
                <div>
                  <Label className="font-semibold text-blue-900">👨‍👩‍👧‍👦 Family Safety Notification</Label>
                  <p className="text-xs text-blue-700 mt-0.5">Automatically send ride details & tracking link to a family member</p>
                </div>
              </div>
              <div className="space-y-1">
                <Input
                  type="email"
                  placeholder="Family member's email (e.g. mom@email.com)"
                  className="h-12 rounded-xl bg-white border-blue-200"
                  value={form.family_email}
                  onChange={(e) => updateField("family_email", e.target.value)}
                />
                <p className="text-xs text-blue-600">They'll receive an email with your pickup, dropoff, and live tracking link.</p>
              </div>
            </div>

            {/* Notes */}
            <div className="space-y-2">
              <Label htmlFor="notes" className="font-medium">{t('booking.notes', lang)}</Label>
              <Textarea
                  id="notes"
                  placeholder={t('booking.special_requests', lang)}
                  className="rounded-xl resize-none"
                  rows={3}
                  value={form.notes}
                  onChange={(e) => updateField("notes", e.target.value)} />
                
            </div>

            {/* Book a Taxi Button */}
            {validationMessage &&
              <p className="text-center text-sm font-medium text-destructive bg-destructive/10 border border-destructive/20 rounded-xl px-4 py-3">
                {validationMessage}
              </p>
              }
            <button
                type="submit"
                disabled={loading || lowBattery && !fareInfo}
                className="w-full flex items-center justify-center gap-2.5 bg-primary text-primary-foreground font-heading font-bold text-base py-4 rounded-2xl shadow-lg active:scale-[0.98] transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                {...a11yAttrs.bookButton}>
                
              {loading ? <Loader2 className="w-5 h-5 animate-spin" /> : <Car className="w-5 h-5" />}
              {loading ? t('booking.booking_taxi', lang) : lowBattery ? t('booking.low_battery', lang) : t('booking.book_taxi', lang)}
              {!loading && <ArrowRight className="w-4 h-4" />}
            </button>
          </form>
        </motion.div>
      </div>
    </div>
      <ErrorReporter error={error} page="booking" orderId={bookedRide?.id} onClose={() => setError(null)} />
      <PostRideSharePrompt
        open={showPostRideShare}
        onOpenChange={setShowPostRideShare}
        rideData={bookedRide ? { fare: { total: bookedRide.final_fare }, distance: bookedRide.distance_km } : null} />
      
    </>);

}