import { useState, useEffect, useRef } from "react";
import { useCurrentLocation } from "@/hooks/useCurrentLocation";
import { useAutoSave } from "@/hooks/useAutoSave";
import { base44 } from "@/api/base44Client";
import { generateIdempotencyKey, storeIdempotencyKey, getIdempotencyKey, clearIdempotencyKey } from "@/lib/idempotencyKeys";
import { captureError } from "@/lib/errorMonitoring";
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 { Package, MapPin, ArrowRight, CheckCircle, Loader2, Copy, Map, Wallet, Calculator, Route, ArrowRightLeft, ChevronLeft } from "lucide-react";
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 } from "react-router-dom";
import { toast } from "sonner";
import { geocodeAddress, haversineKm, calculateDeliveryCost } from "@/utils/fareCalculator";
import { useLowDataMode } from "@/lib/LowDataContext";

const packageSizes = [
  { value: "small", label: "Small", description: "Documents, letters, small items", baseCost: 500 },
  { value: "medium", label: "Medium", description: "Shoe box sized packages", baseCost: 1000 },
  { value: "large", label: "Large", description: "Suitcase or appliance sized", baseCost: 2000 },
  { value: "extra_large", label: "Extra Large", description: "Furniture, large equipment", baseCost: 3500 },
];

export default function RequestDelivery() {
  const navigate = useNavigate();
  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;

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

  const handleInstall = async () => {
    if (deferredPrompt) {
      deferredPrompt.prompt();
      await deferredPrompt.userChoice;
      setDeferredPrompt(null);
    }
  };

  const { address: currentAddress } = useCurrentLocation();
  const [loading, setLoading] = useState(false);
  const [bookedDelivery, setBookedDelivery] = useState(null);
  const [selectedSize, setSelectedSize] = useState("small");
  const [recentAddresses, setRecentAddresses] = useState(() => {
    try { return JSON.parse(localStorage.getItem('zipgy_recent_delivery_addresses') || '[]'); } catch { return []; }
  });
  const [form, setForm] = useState({
    pickup_address: "",
    dropoff_address: "",
    package_description: "",
    sender_name: "",
    sender_phone: "",
    sender_email: "",
    receiver_name: "",
    receiver_phone: "",
    notes: "",
  });
  const [userProfile, setUserProfile] = useState(null);
  const { isSaving, clearDraft } = useAutoSave(form, "Delivery", "draft_delivery_id");

  useEffect(() => {
    let isMounted = true;
    const checkUser = async () => {
      try {
        const u = await base44.auth.me();
        if (isMounted && u) {
          setUserProfile(u);
          setForm(prev => ({
            ...prev,
            sender_name: prev.sender_name || u.full_name || "",
            sender_phone: prev.sender_phone || u.phone || "",
            sender_email: prev.sender_email || u.email || "",
          }));
        }
      } catch (error) {
        // User not authenticated, silently ignore
      }
    };
    checkUser();
    return () => { isMounted = false; };
  }, []);

  useEffect(() => {
    if (currentAddress) {
      setForm(prev => ({ ...prev, pickup_address: prev.pickup_address || currentAddress }));
    }
  }, [currentAddress]);

  // Flush offline queue when back online
  useEffect(() => {
    const handleOnline = async () => {
      const pending = JSON.parse(localStorage.getItem('zipgy_pending_deliveries') || '[]');
      if (!pending.length) return;
      localStorage.removeItem('zipgy_pending_deliveries');
      try {
        await Promise.all(pending.map(item => {
          const cost = item.costInfo?.cost || calculateDeliveryCost(0, item.selectedSize);
          const discount = item.promoResult?.discount || 0;
          const finalCost = Math.round(cost * (1 - discount / 100));
          return base44.entities.Delivery.create({
            ...item.form,
            package_size: item.selectedSize,
            estimated_cost: finalCost,
            promo_code: item.promoResult?.code || "",
            discount_percent: discount || undefined,
            payment_method: item.paymentMethod,
            status: 'pending',
          });
        }));
        toast.success(`${pending.length} offline delivery${pending.length > 1 ? 's' : ''} submitted!`);
      } catch {}
    };
    window.addEventListener('online', handleOnline);
    return () => { window.removeEventListener('online', handleOnline); };
  }, []);

  const [costInfo, setCostInfo] = useState(null);
  const [calcLoading, setCalcLoading] = useState(false);
  const [promoCode, setPromoCode] = useState("");
  const [promoResult, setPromoResult] = useState(null);
  const [promoChecking, setPromoChecking] = useState(false);
  const [error, setError] = useState(null);
  const [paymentMethod, setPaymentMethod] = useState("cash");
  const [mapPicker, setMapPicker] = useState(null);
  const [gpsLoading, setGpsLoading] = useState(false);
  const [validationMessage, setValidationMessage] = useState("");
  const [step, setStep] = useState("location"); // "location" | "details"
  const { lowDataMode } = useLowDataMode();

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

  // Auto-calculate cost with debounce
  useEffect(() => {
    if (!form.pickup_address || !form.dropoff_address) {
      setCostInfo(null);
      return;
    }
    const timer = setTimeout(() => estimateCost(), 900);
    return () => clearTimeout(timer);
  }, [form.pickup_address, form.dropoff_address, selectedSize]);

  const estimateCost = async () => {
    setCalcLoading(true);
    setCostInfo(null);
    const [pickup, dropoff] = await Promise.all([
      geocodeAddress(form.pickup_address),
      geocodeAddress(form.dropoff_address),
    ]);
    if (!pickup || !dropoff) {
      setCostInfo({ 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);
    
    // Fetch business rates if user has a business
    let business = null;
    if (userProfile?.business_id) {
      const businesses = await base44.entities.Business.filter({ id: userProfile.business_id }).catch(() => []);
      if (businesses.length) business = businesses[0];
    }
    
    const cost = calculateDeliveryCost(distanceKm, selectedSize, business, true);
    setCostInfo({ cost, distanceKm: distanceKm.toFixed(1), business });
    setCalcLoading(false);
  };

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

  const useMyLocation = () => {
    if (!navigator.geolocation) return toast.error("Geolocation not supported on this device.");
    setGpsLoading(true);
    navigator.geolocation.getCurrentPosition((pos) => {
      const { latitude, longitude } = pos.coords;
      fetch(`https://nominatim.openstreetmap.org/reverse?lat=${latitude}&lon=${longitude}&format=json`)
        .then(res => res.json())
        .then(data => {
          const address = data.display_name?.split(",").slice(0, 3).join(", ") || `${latitude.toFixed(5)}, ${longitude.toFixed(5)}`;
          updateField("pickup_address", address);
          setGpsLoading(false);
        })
        .catch(() => { toast.error("Could not get your location."); setGpsLoading(false); });
    }, () => { toast.error("Could not get your location."); setGpsLoading(false); });
  };

  const applyPromo = async () => {
    if (!promoCode.trim()) return;
    setPromoChecking(true);
    setPromoResult(null);
    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); 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); return; }
    if (promo.expires_at && new Date(promo.expires_at) < new Date()) { setPromoResult({ error: "This promo code has expired." }); setPromoChecking(false); return; }
    const usedDeliveries = await base44.entities.Delivery.filter({ promo_code: promo.code }).catch(() => []);
    const userEmail = userProfile?.email;
    if (userEmail && usedDeliveries.some(d => d.created_by === userEmail || d.sender_email === userEmail)) {
      setPromoResult({ error: "You've already used this promo code." }); setPromoChecking(false); return;
    }
    setPromoResult({ discount: promo.discount_percent, code: promo.code, id: promo.id });
    setPromoChecking(false);
    toast.success(`Promo applied! ${promo.discount_percent}% off 🎉`);
  };

  // Live tracking on success screen
  const [liveDelivery, setLiveDelivery] = useState(null);
  useEffect(() => {
    if (!bookedDelivery?.id) return;
    let isMounted = true;
    let unsubscribe;
    try {
      unsubscribe = base44.entities.Delivery.subscribe?.((ev) => {
        if (isMounted && ev.type === "update" && ev.id === bookedDelivery.id) setLiveDelivery(ev.data);
      });
    } catch {}
    const interval = setInterval(() => {
      if (isMounted) {
        base44.entities.Delivery.filter({ id: bookedDelivery.id })
          .then(list => { if (list[0]) setLiveDelivery(list[0]); })
          .catch(() => {});
      }
    }, 3000);
    return () => {
      isMounted = false;
      clearInterval(interval);
      if (typeof unsubscribe === 'function') unsubscribe();
    };
  }, [bookedDelivery?.id]);
  const displayDelivery = liveDelivery || bookedDelivery;



  if (bookedDelivery) {
    const trackingUrl = `${window.location.origin}/track-delivery?id=${bookedDelivery.id}`;
    const waMessage = encodeURIComponent(`📦 Your ZIP.GY delivery is booked!\n\nTrack your package live here:\n${trackingUrl}\n\nDelivery ID: ${bookedDelivery.id}`);
    const waUrl = `https://wa.me/?text=${waMessage}`;
    const isLive = displayDelivery?.status === "picked_up" || displayDelivery?.status === "in_transit";

    return (
      <div className="min-h-screen bg-background flex items-center justify-center px-4">
        <motion.div initial={{ opacity: 0, scale: 0.95 }} animate={{ opacity: 1, scale: 1 }} className="bg-card border border-border rounded-2xl p-8 max-w-md w-full text-center shadow-xl">
          <div className="w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-4">
            <CheckCircle className="w-9 h-9 text-primary" />
          </div>
          <h2 className="font-heading font-bold text-2xl text-foreground mb-2 flex items-center justify-center gap-2">
            {isLive && <span className="w-2.5 h-2.5 bg-green-600 rounded-full animate-pulse" />}
            {displayDelivery?.status === "in_transit" ? "On The Way!" : "Delivery Requested!"}
          </h2>
          <p className="text-muted-foreground text-sm mb-6">
            {displayDelivery?.status === "in_transit" ? "Your package is on the way." : "Your delivery request has been submitted."}
          </p>

          <div className="bg-muted rounded-xl p-3 mb-4 text-left">
            <p className="text-xs text-muted-foreground mb-1">Delivery ID</p>
            <div className="flex items-center justify-between gap-2">
              <p className="font-mono text-sm font-semibold text-foreground truncate">{bookedDelivery.id}</p>
              <button onClick={() => { navigator.clipboard.writeText(bookedDelivery.id); toast.success('Copied!'); }} className="text-muted-foreground hover:text-foreground">
                <Copy className="w-4 h-4" />
              </button>
            </div>
          </div>

          <div className="bg-muted rounded-xl p-3 mb-6 text-left">
            <p className="text-xs text-muted-foreground mb-1">Tracking Link</p>
            <div className="flex items-center justify-between gap-2">
              <p className="text-xs text-foreground truncate">{trackingUrl}</p>
              <button onClick={() => { navigator.clipboard.writeText(trackingUrl); toast.success('Copied!'); }} className="text-muted-foreground hover:text-foreground flex-shrink-0">
                <Copy className="w-4 h-4" />
              </button>
            </div>
          </div>

          <a href={waUrl} target="_blank" rel="noopener noreferrer" className="flex items-center justify-center gap-3 w-full bg-[#25D366] hover:bg-[#1ebe5d] text-white font-heading font-semibold py-3 px-6 rounded-full transition-colors mb-3">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
            Share on WhatsApp
          </a>

          <button onClick={() => navigate('/track-delivery?id=' + bookedDelivery.id)} className="flex items-center justify-center gap-2 w-full border border-border text-foreground font-heading font-semibold py-3 px-6 rounded-full hover:bg-muted transition-colors mb-3 mt-3">
            <MapPin className="w-4 h-4" /> Track My Delivery
          </button>

          {!isStandalone && !appInstalled && (
            <div className="mt-4 p-4 bg-primary/5 border border-primary/20 rounded-2xl text-left">
              <p className="font-heading font-semibold text-sm text-foreground mb-1">📲 Install ZIP.GY on your phone</p>
              <p className="text-xs text-muted-foreground mb-3">Get faster access, push notifications, and request deliveries offline.</p>
              {isIos ? (
                <p className="text-xs text-primary font-medium">Tap <strong>Share</strong> → <strong>"Add to Home Screen"</strong> in Safari</p>
              ) : (
                <button onClick={handleInstall} disabled={!deferredPrompt} className="w-full py-2 rounded-xl bg-primary text-primary-foreground text-sm font-heading font-semibold hover:bg-primary/90 transition-colors disabled:opacity-40">
                  ⬇️ Download App
                </button>
              )}
            </div>
          )}
          {userProfile ? (
            <>
              <button onClick={() => { setBookedDelivery(null); setLiveDelivery(null); setForm({ ...form, pickup_address: "", dropoff_address: "", package_description: "" }); setCostInfo(null); setPromoCode(""); setPromoResult(null); }} className="text-sm text-primary hover:underline transition-colors mt-2 block">
                + Request another delivery
              </button>
              <button onClick={() => navigate('/dashboard')} className="text-sm text-muted-foreground hover:text-foreground transition-colors mt-2 block">
                Go to Dashboard →
              </button>
            </>
          ) : (
            <div className="mt-4 p-4 bg-primary border border-primary/80 rounded-2xl text-left">
              <p className="font-heading font-bold text-sm text-primary-foreground mb-1">⚡ One last step — create your free account</p>
              <p className="text-xs text-primary-foreground/80 mb-3">Required to track your delivery, receive updates, and get your GYD 1,000 welcome bonus.</p>
              <button onClick={() => base44.auth.redirectToLogin(`/track-delivery?id=${bookedDelivery.id}`)} className="w-full py-2.5 rounded-xl bg-white text-primary text-sm font-heading font-bold hover:bg-white/90 transition-colors">
                Create Free Account →
              </button>
            </div>
          )}
        </motion.div>
      </div>
    );
  }

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!selectedSize) { setValidationMessage("⚠️ Please select a package size."); return; }
    if (!form.sender_name?.trim()) { setValidationMessage("⚠️ Sender name is required."); return; }
    if (!form.sender_email?.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.sender_email)) { setValidationMessage("⚠️ Valid sender email is required."); return; }
    if (!form.sender_phone?.trim()) { setValidationMessage("⚠️ Sender phone is required."); return; }
    if (!form.pickup_address?.trim()) { setValidationMessage("⚠️ Pickup address is required."); return; }
    if (!form.dropoff_address?.trim()) { setValidationMessage("⚠️ Dropoff address is required."); return; }
    if (!form.receiver_name?.trim()) { setValidationMessage("⚠️ Receiver name is required."); return; }
    if (!form.receiver_phone?.trim()) { setValidationMessage("⚠️ Receiver phone is required."); return; }

    const idempotencyKey = generateIdempotencyKey();
    const existing = getIdempotencyKey(idempotencyKey);
    if (existing) {
      setValidationMessage("⚠️ Delivery already submitted. Check your orders.");
      return;
    }
    setValidationMessage("");
    setError(null);
    setLoading(true);
    storeIdempotencyKey(idempotencyKey, { type: 'delivery', timestamp: Date.now() });
    
    try {
      if (!navigator.onLine) {
        const pending = JSON.parse(localStorage.getItem('zipgy_pending_deliveries') || '[]');
        pending.push({ form, selectedSize, paymentMethod, promoResult, costInfo, timestamp: Date.now() });
        localStorage.setItem('zipgy_pending_deliveries', JSON.stringify(pending));
        setLoading(false);
        toast.error('You are offline! Your delivery will be submitted when you reconnect.');
        return;
      }

      const baseCost = costInfo?.cost || calculateDeliveryCost(0, selectedSize, null, true);
      const discount = promoResult?.discount || 0;
      const finalCost = Math.round(baseCost * (1 - discount / 100));
      const pickupCoords = await geocodeAddress(form.pickup_address).catch(() => null);

      const delivery = await base44.entities.Delivery.create({
        ...form,
        package_size: selectedSize,
        estimated_cost: finalCost,
        promo_code: promoResult?.code || "",
        discount_percent: discount || undefined,
        distance_km: costInfo?.distanceKm ? parseFloat(costInfo.distanceKm) : undefined,
        payment_method: paymentMethod,
        status: 'pending',
        pickup_lat: pickupCoords?.lat || undefined,
        pickup_lng: pickupCoords?.lon || undefined,
      });

      // Send email confirmation
      if (form.sender_email || userProfile?.email) {
        base44.functions.invoke('sendBookingEmail', {
          email: form.sender_email || userProfile?.email,
          name: form.sender_name,
          type: 'delivery',
          orderId: delivery.id,
          from: form.pickup_address,
          to: form.dropoff_address,
          cost: finalCost,
        }).catch(() => {});
      }

      // Update promo usage
      if (promoResult?.id) {
        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 });
        }
      }

      // Send WhatsApp receipt
      if (form.sender_phone) {
        const payLabel = paymentMethod === 'mmg' ? 'MMG Mobile Money' : paymentMethod === 'card' ? 'Card' : 'Cash';
        const trackingUrl = `${window.location.origin}/track-delivery?id=${delivery.id}`;
        const receiptMsg = `📦 ZIP.GY Delivery Receipt\n\n✅ Delivery Requested!\n\n👤 From: ${form.sender_name}\n📍 Pickup: ${form.pickup_address}\n🏁 Dropoff: ${form.dropoff_address}\n📦 Package: ${form.package_description}\n💰 Cost: GYD ${finalCost}\n💳 Payment: ${payLabel}\n🆔 ID: ${delivery.id}\n\n📍 Track: ${trackingUrl}\n\n⚡ Thank you for using ZIP.GY!`;
        base44.functions.invoke('sendWhatsApp', { to: form.sender_phone, message: receiptMsg }).catch(() => {});
      }

      // Save recent addresses
      const addrs = [form.pickup_address, form.dropoff_address].filter(Boolean);
      const updated = [...new Set([...addrs, ...recentAddresses])].slice(0, 8);
      setRecentAddresses(updated);
      localStorage.setItem('zipgy_recent_delivery_addresses', JSON.stringify(updated));

      clearDraft();
      setLoading(false);
      setBookedDelivery(delivery);
      window.scrollTo(0, 0);

      if (!userProfile && form.sender_email) {
        base44.users.inviteUser(form.sender_email, "user").catch(() => {});
      }
    } catch (err) {
      clearIdempotencyKey(idempotencyKey);
      captureError(err, 'RequestDelivery', form.pickup_address);
      setError(err);
      setLoading(false);
    }
      };

  return (
    <>
    <SEOSchema page="delivery" />
    <div className="min-h-screen bg-background pb-12 overflow-y-auto" style={{ WebkitOverflowScrolling: "touch" }}>

      <div className="max-w-2xl mx-auto px-4 py-6">
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}>
          <div className="mb-4">
            <div className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-accent/10 text-accent text-xs font-semibold mb-2">
              <Package className="w-3.5 h-3.5" /> Delivery Service
            </div>
            <h1 className="font-bold text-xl leading-tight text-gray-900">Request a Delivery</h1>
            <p className="text-gray-500 mt-1 text-xs">Fast, safe package delivery across Guyana.</p>
          </div>

          <WhatsAppNotice variant="user" />

          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Package Size */}
            <div>
              <p className="font-semibold text-xs text-gray-600 mb-2">Select Package Size</p>
              <div className="grid grid-cols-2 gap-2">
                {packageSizes.map((size) => (
                  <button
                    key={size.value}
                    type="button"
                    onClick={() => setSelectedSize(size.value)}
                    className={`relative p-2.5 rounded-xl border-2 text-left transition-all active:scale-[0.98] ${
                      selectedSize === size.value ? "border-emerald-600 bg-emerald-50 shadow-sm" : "border-gray-200 bg-white hover:border-gray-300"
                    }`}
                  >
                    <div className="font-bold text-xs text-gray-900 leading-tight">{size.label}</div>
                    <p className="text-[10px] text-gray-500 leading-tight mt-0.5 mb-1">{size.description}</p>
                    <p className="text-xs font-bold text-emerald-600">GYD {size.baseCost}+</p>
                  </button>
                ))}
              </div>
            </div>

            {/* Locations */}
            <div className="space-y-3">
              <div>
                <div className="flex items-center justify-between mb-1.5">
                  <Label htmlFor="pickup" className="text-xs font-semibold text-gray-700">Pickup Address</Label>
                  <button type="button" onClick={useMyLocation} disabled={gpsLoading}
                    className="flex items-center gap-1 text-[10px] text-emerald-600 hover:underline disabled:opacity-50">
                    {gpsLoading ? <Loader2 className="w-3 h-3 animate-spin" /> : <MapPin className="w-3 h-3" />}
                    Use my location
                  </button>
                </div>
                <div className="relative">
                  <MapPin className="absolute left-3 top-2.5 w-3.5 h-3.5 text-emerald-500" />
                  <Input
                    id="pickup"
                    placeholder="e.g. Regent Street, Georgetown"
                    className="pl-9 pr-9 h-9 rounded-xl w-full text-xs border-gray-200"
                    value={form.pickup_address}
                    onChange={(e) => updateField("pickup_address", e.target.value)}
                    required
                  />
                  <button type="button" onClick={() => setMapPicker('pickup')} className="absolute right-3 top-2.5 text-gray-400 hover:text-emerald-600 transition-colors" title="Pick on map">
                    <Map className="w-3.5 h-3.5" />
                  </button>
                </div>
              </div>

              <div>
                <Label htmlFor="dropoff" className="text-xs font-semibold text-gray-700 mb-1.5">Dropoff Address</Label>
                <div className="relative">
                  <MapPin className="absolute left-3 top-2.5 w-3.5 h-3.5 text-red-500" />
                  <Input
                    id="dropoff"
                    placeholder="e.g. Main Street, Linden"
                    className="pl-9 pr-9 h-9 rounded-xl w-full text-xs border-gray-200"
                    value={form.dropoff_address}
                    onChange={(e) => updateField("dropoff_address", e.target.value)}
                    required
                  />
                  <button type="button" onClick={() => setMapPicker('dropoff')} className="absolute right-3 top-2.5 text-gray-400 hover:text-emerald-600 transition-colors" title="Pick on map">
                    <Map className="w-3.5 h-3.5" />
                  </button>
                </div>
              </div>

              <button
                type="button"
                onClick={() => setForm(prev => ({ ...prev, pickup_address: prev.dropoff_address, dropoff_address: prev.pickup_address }))}
                className="w-full flex items-center justify-center gap-1.5 py-2 rounded-xl border border-gray-200 text-xs text-gray-600 hover:bg-gray-50 transition-colors"
              >
                <ArrowRightLeft className="w-3.5 h-3.5" /> Swap addresses
              </button>
            </div>

            {/* Recent Addresses */}
            {recentAddresses.length > 0 && !form.pickup_address && !form.dropoff_address && (
              <div className="space-y-1.5">
                <Label className="text-[10px] font-semibold text-gray-400 uppercase tracking-wide">Recent Addresses</Label>
                <div className="flex flex-wrap gap-1.5">
                  {recentAddresses.slice(0, 5).map((addr, i) => (
                    <button
                      key={i}
                      type="button"
                      onClick={() => !form.pickup_address ? updateField("pickup_address", addr) : updateField("dropoff_address", addr)}
                      className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border border-gray-200 text-[10px] text-gray-600 hover:border-emerald-300 hover:text-emerald-700 transition-all bg-white"
                    >
                      <MapPin className="w-3 h-3 flex-shrink-0" /> <span className="truncate max-w-[150px]">{addr}</span>
                    </button>
                  ))}
                </div>
              </div>
            )}

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

            {/* Live Cost Estimate - Shows right after locations */}
            {(calcLoading || costInfo) && step === "location" && (
              <motion.div initial={{ opacity: 0, y: -6 }} animate={{ opacity: 1, y: 0 }}
                className={`rounded-xl border p-3 flex items-center gap-3 ${
                  costInfo?.error ? "bg-red-50 border-red-200" : "bg-emerald-50 border-emerald-200"
                }`}>
                <div className="w-9 h-9 rounded-lg bg-emerald-100 flex items-center justify-center flex-shrink-0">
                  {calcLoading ? <Loader2 className="w-4 h-4 text-emerald-600 animate-spin" /> : <Calculator className="w-4 h-4 text-emerald-600" />}
                </div>
                <div className="flex-1">
                  {calcLoading && <p className="text-xs text-gray-600">Calculating cost…</p>}
                  {costInfo?.error && <p className="text-xs text-red-600">{costInfo.error}</p>}
                  {costInfo?.cost && (
                    <>
                      <p className="font-bold text-base text-gray-900">GYD {costInfo.cost}</p>
                      <div className="flex items-center gap-1 text-[10px] text-gray-500 mt-0.5">
                        <Route className="w-3 h-3" /> {costInfo.distanceKm} km
                      </div>
                    </>
                  )}
                </div>
              </motion.div>
            )}

            {/* Continue to Details Button - Shows right after cost estimate */}
            {step === "location" && costInfo?.cost && !costInfo?.error && (
              <div className="pt-2">
                <button
                  type="button"
                  onClick={() => setStep("details")}
                  className="w-full bg-emerald-600 text-white py-3 rounded-xl font-bold text-sm flex items-center justify-center gap-2 active:scale-[0.98] transition-all shadow-lg"
                >
                  Continue <ArrowRight className="w-4 h-4" />
                </button>
              </div>
            )}

            {/* Step 2: Package & Contact Details */}
            {step === "details" && (
              <>
            {/* Back button */}
            <button
              type="button"
              onClick={() => setStep("location")}
              className="w-full flex items-center justify-center gap-2 py-2.5 rounded-xl border-2 border-gray-200 text-gray-700 font-semibold text-sm active:scale-[0.98] transition-all"
            >
              <ArrowRightLeft className="w-4 h-4" /> Back to Locations
            </button>

            {/* Package Description */}
            <div className="space-y-1.5">
              <Label htmlFor="desc" className="text-xs font-semibold text-gray-700">Package Description</Label>
              <Input
                id="desc"
                placeholder="What are you sending?"
                className="h-9 rounded-xl text-xs border-gray-200"
                value={form.package_description}
                onChange={(e) => updateField("package_description", e.target.value)}
                required
              />
            </div>

            {/* Sender Info */}
            <div className="space-y-3">
              <p className="text-xs font-semibold text-gray-600">Sender Information</p>
              <div className="grid grid-cols-2 gap-2">
                <div className="space-y-1.5">
                  <Label htmlFor="sender_name" className="text-[10px] font-semibold text-gray-600">Name</Label>
                  <Input
                    id="sender_name"
                    placeholder="Full name"
                    className="h-9 rounded-xl text-xs border-gray-200"
                    value={form.sender_name}
                    onChange={(e) => updateField("sender_name", e.target.value)}
                    required
                  />
                </div>
                <div className="space-y-1.5">
                  <Label htmlFor="sender_phone" className="text-[10px] font-semibold text-gray-600">Phone</Label>
                  <Input
                    id="sender_phone"
                    placeholder="+592-000-0000"
                    className="h-9 rounded-xl text-xs border-gray-200"
                    value={form.sender_phone}
                    onChange={(e) => updateField("sender_phone", e.target.value)}
                    required
                  />
                </div>
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="sender_email" className="text-[10px] font-semibold text-gray-600">Email</Label>
                <Input
                  id="sender_email"
                  type="email"
                  placeholder="your@email.com"
                  className="h-9 rounded-xl text-xs border-gray-200"
                  value={form.sender_email}
                  onChange={(e) => updateField("sender_email", e.target.value)}
                  required
                />
              </div>
            </div>

            {/* Receiver Info */}
            <div className="space-y-3">
              <p className="text-xs font-semibold text-gray-600">Receiver Information</p>
              <div className="grid grid-cols-2 gap-2">
                <div className="space-y-1.5">
                  <Label htmlFor="receiver_name" className="text-[10px] font-semibold text-gray-600">Name</Label>
                  <Input
                    id="receiver_name"
                    placeholder="Full name"
                    className="h-9 rounded-xl text-xs border-gray-200"
                    value={form.receiver_name}
                    onChange={(e) => updateField("receiver_name", e.target.value)}
                    required
                  />
                </div>
                <div className="space-y-1.5">
                  <Label htmlFor="receiver_phone" className="text-[10px] font-semibold text-gray-600">Phone</Label>
                  <Input
                    id="receiver_phone"
                    placeholder="+592-000-0000"
                    className="h-9 rounded-xl text-xs border-gray-200"
                    value={form.receiver_phone}
                    onChange={(e) => updateField("receiver_phone", e.target.value)}
                    required
                  />
                </div>
              </div>
            </div>

            {/* Promo Code */}
            <div className="space-y-1.5">
              <Label className="text-xs font-semibold text-gray-700">Promo Code</Label>
              <div className="flex gap-2">
                <Input
                  placeholder="Enter promo code"
                  className="h-9 rounded-xl flex-1 text-xs uppercase border-gray-200"
                  value={promoCode}
                  onChange={(e) => { setPromoCode(e.target.value.toUpperCase()); setPromoResult(null); }}
                />
                <Button type="button" variant="outline" className="h-9 rounded-xl px-3 text-xs font-semibold border-gray-200" onClick={applyPromo} disabled={promoChecking || !promoCode.trim()}>
                  {promoChecking ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : "Apply"}
                </Button>
              </div>
              {promoResult?.error && <p className="text-xs text-red-600">{promoResult.error}</p>}
              {promoResult?.discount && <p className="text-xs text-green-600 font-semibold">✅ {promoResult.discount}% off applied!</p>}
            </div>

            {/* Live Cost Estimate with Promo */}
            {(calcLoading || costInfo) && (
              <motion.div initial={{ opacity: 0, y: -6 }} animate={{ opacity: 1, y: 0 }}
                className={`rounded-xl border p-3 flex items-center gap-3 ${
                  costInfo?.error ? "bg-red-50 border-red-200" : "bg-emerald-50 border-emerald-200"
                }`}>
                <div className="w-9 h-9 rounded-lg bg-emerald-100 flex items-center justify-center flex-shrink-0">
                  {calcLoading ? <Loader2 className="w-4 h-4 text-emerald-600 animate-spin" /> : <Calculator className="w-4 h-4 text-emerald-600" />}
                </div>
                <div className="flex-1">
                  {calcLoading && <p className="text-xs text-gray-600">Calculating cost…</p>}
                  {costInfo?.error && <p className="text-xs text-red-600">{costInfo.error}</p>}
                  {costInfo?.cost && (
                    <>
                      {promoResult?.discount ? (
                        <div className="flex items-center gap-2">
                          <p className="font-bold text-sm text-gray-400 line-through">GYD {costInfo.cost}</p>
                          <p className="font-bold text-base text-green-600">GYD {Math.round(costInfo.cost * (1 - promoResult.discount / 100))}</p>
                        </div>
                      ) : (
                        <p className="font-bold text-base text-gray-900">GYD {costInfo.cost}</p>
                      )}
                      <div className="flex items-center gap-1 text-[10px] text-gray-500 mt-0.5">
                        <Route className="w-3 h-3" /> {costInfo.distanceKm} km
                      </div>
                    </>
                  )}
                </div>
              </motion.div>
            )}

            {/* Payment Method */}
            <div className="space-y-2">
              <Label className="text-xs font-semibold text-gray-700 flex items-center gap-1.5"><Wallet className="w-3.5 h-3.5" /> Payment Method</Label>
              <div className="grid grid-cols-3 gap-2">
                {[
                  { value: "cash", label: "💵 Cash" },
                  { value: "mmg", label: "📱 MMG" },
                  { value: "card", label: "💳 Card" },
                ].map((opt) => (
                  <button
                    key={opt.value}
                    type="button"
                    onClick={() => setPaymentMethod(opt.value)}
                    className={`p-2.5 rounded-xl border-2 text-xs font-semibold transition-all ${
                      paymentMethod === opt.value
                        ? "border-emerald-600 bg-emerald-50 text-gray-900"
                        : "border-gray-200 bg-white text-gray-600 hover:border-gray-300"
                    }`}
                  >
                    {opt.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Notes */}
            <div className="space-y-1.5">
              <Label htmlFor="notes" className="text-xs font-semibold text-gray-700">Notes (optional)</Label>
              <Textarea
                id="notes"
                placeholder="Fragile items, delivery instructions, etc..."
                className="rounded-xl resize-none text-xs border-gray-200"
                rows={3}
                value={form.notes}
                onChange={(e) => updateField("notes", e.target.value)}
              />
            </div>

            {/* Submit 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}
              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"
            >
              {loading ? <Loader2 className="w-5 h-5 animate-spin" /> : <Package className="w-5 h-5" />}
              {loading ? "Booking your delivery..." : costInfo?.cost ? `Book Now - GYD ${costInfo.cost}` : "Book Delivery"}
              {!loading && <ArrowRight className="w-4 h-4" />}
            </button>
            </>
            )}
          </form>
        </motion.div>
      </div>
    </div>
    <ErrorReporter error={error} page="delivery" orderId={bookedDelivery?.id} onClose={() => setError(null)} />
    </>
  );
}