import { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { useIsMobile } from "@/hooks/use-mobile";
import { useCurrentLocation } from "@/hooks/useCurrentLocation";
import { useAuth } from "@/lib/AuthContext";
import { base44 } from "@/api/base44Client";
import { MapPin, ArrowLeft, ArrowRight, Package, CheckCircle, Loader2 } from "lucide-react";
import ZipgyLogo from "@/components/ZipgyLogo";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";

import { geocodeAddress, haversineKm, calculateDeliveryCost } from "@/utils/fareCalculator";
import ErrorReporter from "@/components/ErrorReporter";
import { enforceProfileCompletion } from "@/components/ProfileCompletionGate";
import MMGConfirmationModal from "@/components/food/MMGConfirmationModal";
import { useMmgPayment } from "@/hooks/useMmgPayment";
import { isDuplicateOrder } from "@/lib/idempotencyV2";

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

export default function RequestDelivery() {
  const navigate = useNavigate();
  const { user: authUser } = useAuth();
  const isMobile = useIsMobile();
  const { address: currentAddress } = useCurrentLocation();
  
  const [loading, setLoading] = useState(false);
  const [bookedDelivery, setBookedDelivery] = useState(null);
  const [showMmgModal, setShowMmgModal] = useState(false);
  const { initiatePayment: initiateMmgPayment, processing: mmgProcessing } = useMmgPayment();
  const [pendingSubmit, setPendingSubmit] = useState(false);
  const isSubmittingRef = useRef(false);
  const [step, setStep] = useState("address");
  const [pickup, setPickup] = useState("");
  const [destination, setDestination] = useState("");
  const [packageSize, setPackageSize] = useState("small");
  const [paymentMethod, setPaymentMethod] = useState("cash");
  const [costInfo, setCostInfo] = useState(null);
  const [distance, setDistance] = useState(null);
  const [form, setForm] = useState({
    package_description: "",
    receiver_name: "",
    receiver_phone: "",
    notes: ""
  });
  const [error, setError] = useState(null);

  // Auto-detect pickup location
  useEffect(() => {
    if (!pickup && navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        async (pos) => {
          try {
            const res = await fetch(`https://nominatim.openstreetmap.org/reverse?lat=${pos.coords.latitude}&lon=${pos.coords.longitude}&format=json`);
            const data = await res.json();
            const addr = data.display_name || `${pos.coords.latitude.toFixed(4)}, ${pos.coords.longitude.toFixed(4)}`;
            setPickup(addr);
          } catch (err) {
            console.error("Failed to resolve address:", err);
          }
        },
        () => {},
        { timeout: 5000 }
      );
    }
  }, []);

  // Auto-fill from current address
  useEffect(() => {
    if (currentAddress && !pickup) {
      setPickup(currentAddress);
    }
  }, [currentAddress]);

  // Auto-prefill sender info from logged-in user profile
  useEffect(() => {
    if (authUser) {
      setForm(prev => ({
        ...prev,
        receiver_name: prev.receiver_name || authUser.full_name || "",
        receiver_phone: prev.receiver_phone || authUser.phone || authUser.data?.phone || "",
      }));
    }
  }, [authUser?.email]);

  // Auto-calculate cost
  useEffect(() => {
    if (!pickup || !destination) {
      setCostInfo(null);
      setDistance(null);
      return;
    }
    const timer = setTimeout(() => estimateCost(), 900);
    return () => clearTimeout(timer);
  }, [pickup, destination, packageSize]);

  const estimateCost = async () => {
    const [pickupCoords, dropoffCoords] = await Promise.all([
      geocodeAddress(pickup),
      geocodeAddress(destination)
    ]);
    if (!pickupCoords || !dropoffCoords) {
      setCostInfo({ error: "Could not locate addresses" });
      return;
    }
    const distanceKm = haversineKm(pickupCoords.lat, pickupCoords.lon, dropoffCoords.lat, dropoffCoords.lon);
    const cost = calculateDeliveryCost(distanceKm, packageSize, null, true);
    setCostInfo({ cost, distanceKm: distanceKm.toFixed(1) });
    setDistance(distanceKm.toFixed(1));
  };

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

  const handleBack = () => {
    if (step === "address") navigate("/");
    else if (step === "details") setStep("address");
  };

  const handleContinue = () => {
    if (!destination.trim()) { toast.error("Please enter a destination"); return; }
    if (!costInfo?.cost) { toast.warning("Could not calculate cost"); return; }
    setStep("details");
    window.scrollTo(0, 0);
  };

  const createDelivery = async () => {
    const finalCost = costInfo?.cost || calculateDeliveryCost(0, packageSize, null, true);
    const pickupCoords = await geocodeAddress(pickup).catch(() => null);

    const delivery = await base44.entities.Delivery.create({
      pickup_address: pickup,
      dropoff_address: destination,
      package_description: form.package_description || "Package",
      package_size: packageSize,
      sender_name: authUser.full_name,
      sender_phone: authUser.phone || "",
      sender_email: authUser.email,
      receiver_name: form.receiver_name || "Recipient",
      receiver_phone: form.receiver_phone || "",
      notes: form.notes,
      estimated_cost: finalCost,
      distance_km: costInfo?.distanceKm ? parseFloat(costInfo.distanceKm) : undefined,
      payment_method: paymentMethod,
      status: 'pending',
      pickup_lat: pickupCoords?.lat || undefined,
      pickup_lng: pickupCoords?.lon || undefined
    });

    // Send notifications
    if (authUser.email) {
      base44.functions.invoke('sendBookingEmail', {
        email: authUser.email,
        name: authUser.full_name,
        type: 'delivery',
        orderId: delivery.id,
        from: pickup,
        to: destination,
        cost: finalCost
      }).catch(() => {});
    }

    if (authUser.phone) {
      const trackingUrl = `${window.location.origin}/track-delivery?id=${delivery.id}`;
      const receiptMsg = `📦 ZIP.GY Delivery Receipt\n\n✅ Delivery Requested!\n\n👤 From: ${authUser.full_name}\n📍 Pickup: ${pickup}\n🏁 Dropoff: ${destination}\n💰 Cost: GYD ${finalCost}\n🆔 ID: ${delivery.id}\n\n📍 Track: ${trackingUrl}`;
      base44.functions.invoke('sendWhatsApp', { to: authUser.phone, message: receiptMsg }).catch(() => {});
    }

    setBookedDelivery(delivery);
    return delivery;
  };

  const handleSubmit = async () => {
    // Prevent concurrent submissions
    if (isSubmittingRef.current || loading) {
      toast.error("Delivery request already being submitted. Please wait...");
      return;
    }
    isSubmittingRef.current = true;

    if (!authUser) {
      base44.auth.redirectToLogin(`/request-delivery`);
      isSubmittingRef.current = false;
      return;
    }
    
    // CRITICAL: Enforce profile completion before allowing delivery request
    try {
      await enforceProfileCompletion();
    } catch (err) {
      if (err.message?.startsWith('PROFILE_INCOMPLETE:')) {
        const msg = err.message.replace('PROFILE_INCOMPLETE:', '');
        toast.error(msg);
        isSubmittingRef.current = false;
        return;
      }
      throw err;
    }

    // Check for duplicate deliveries in last 5 minutes
    const isDup = await isDuplicateOrder(base44, 'delivery', authUser.email, 5);
    if (isDup) {
      toast.error("You already have a recent delivery request. Check your dashboard.");
      isSubmittingRef.current = false;
      return;
    }

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

    setError(null);

    try {
      await createDelivery();
      setLoading(false);
      window.scrollTo(0, 0);
    } catch (err) {
      setError(err);
      setLoading(false);
    } finally {
      isSubmittingRef.current = false;
    }
  };

  const handleMmgDeliveryConfirmed = async () => {
    setShowMmgModal(false);
    setPendingSubmit(false);
    setLoading(true);
    setError(null);
    
    try {
      await createDelivery();
      window.scrollTo(0, 0);
    } catch (err) {
      setError(err);
    } finally {
      setLoading(false);
    }
  };

  // Success screen
  if (bookedDelivery) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center px-4">
        <div className="bg-card border border-border rounded-2xl p-8 max-w-md w-full text-center shadow-xl animate-in zoom-in duration-300">
          <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">Delivery Requested!</h2>
          <p className="text-muted-foreground text-sm mb-6">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>
            <p className="font-mono text-sm font-semibold text-foreground truncate">{bookedDelivery.id}</p>
          </div>
          <a href={`/track-delivery?id=${bookedDelivery.id}`}>
            <Button className="w-full rounded-full mb-3">Track My Delivery</Button>
          </a>
                    {authUser && (
            <button onClick={() => {setBookedDelivery(null); setPickup(""); setDestination(""); setForm({package_description: "", receiver_name: "", receiver_phone: "", notes: ""}); setCostInfo(null);}} className="text-sm text-primary hover:underline transition-colors mt-2 block">
              + Request another delivery
            </button>
          )}
        </div>
      </div>
    );
  }

  // ── MMG Modal ──
  const mmgModalEl = showMmgModal && (
    <MMGConfirmationModal
      userPhone={authUser?.mmg_number || authUser?.phone}
      businessPhone=""
      businessName="ZIP.GY Delivery"
      amount={costInfo?.cost || 0}
      isProcessing={loading || mmgProcessing}
      onConfirm={handleMmgDeliveryConfirmed}
      onCancel={() => { setShowMmgModal(false); setPendingSubmit(false); }}
    />
  );

  // ── DESKTOP LAYOUT ──
  if (!isMobile) {
    return (
      <><div className="min-h-screen bg-gray-50 px-4 pt-24 pb-12">
        <div className="max-w-2xl mx-auto">
          {/* Header */}
          <div className="mb-6 flex items-center gap-4">
            <button onClick={() => navigate(-1)} className="p-2 rounded-full hover:bg-gray-200 transition-colors">
              <ArrowLeft className="w-5 h-5 text-gray-700" />
            </button>
            <div>
              <h1 className="font-heading font-bold text-3xl text-gray-900 flex items-center gap-3">
                <Package className="w-8 h-8 text-emerald-600" /> Request Delivery
              </h1>
              <p className="text-gray-500 text-sm mt-1">Send packages anywhere across Guyana</p>
            </div>
          </div>

          <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-8 space-y-6">
            {/* Step indicator */}
            <div className="flex items-center gap-3 mb-2">
              <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold ${step === "address" ? "bg-emerald-600 text-white" : "bg-emerald-100 text-emerald-600"}`}>1</div>
              <div className="flex-1 h-1 bg-gray-200 rounded">
                <div className={`h-1 rounded bg-emerald-500 transition-all ${step === "details" ? "w-full" : "w-0"}`} />
              </div>
              <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold ${step === "details" ? "bg-emerald-600 text-white" : "bg-gray-100 text-gray-400"}`}>2</div>
              <span className="text-xs text-gray-500 ml-1">{step === "address" ? "Addresses" : "Package Details"}</span>
            </div>

            {step === "address" && (
              <div className="space-y-4">
                <div>
                  <Label className="text-sm font-semibold text-gray-700 mb-1.5 block">Pickup Location</Label>
                  <div className="relative">
                    <MapPin className="absolute left-3 top-3 w-4 h-4 text-emerald-500" />
                    <Input placeholder="Enter pickup address" value={pickup} onChange={(e) => setPickup(e.target.value)} className="pl-10 h-11 rounded-xl" />
                  </div>
                </div>
                <div>
                  <Label className="text-sm font-semibold text-gray-700 mb-1.5 block">Dropoff Location</Label>
                  <div className="relative">
                    <MapPin className="absolute left-3 top-3 w-4 h-4 text-red-500" />
                    <Input placeholder="Enter dropoff address" value={destination} onChange={(e) => setDestination(e.target.value)} className="pl-10 h-11 rounded-xl" />
                  </div>
                </div>

                {costInfo && (
                  <div className={`rounded-xl border px-5 py-4 ${costInfo.error ? "bg-red-50 border-red-200" : "bg-emerald-50 border-emerald-200"}`}>
                    {!costInfo.error ? (
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="text-sm font-semibold text-emerald-700">Estimated Cost</p>
                          {distance && <p className="text-xs text-gray-500 mt-0.5">~{distance} km route</p>}
                        </div>
                        <p className="text-3xl font-black text-emerald-700">GYD {costInfo.cost.toLocaleString()}</p>
                      </div>
                    ) : (
                      <p className="text-sm text-red-600">{costInfo.error}</p>
                    )}
                  </div>
                )}

                <Button onClick={handleContinue} disabled={!destination.trim() || !costInfo?.cost} className="w-full h-11 rounded-xl bg-emerald-600 hover:bg-emerald-700 font-bold text-base">
                  Continue <ArrowRight className="w-4 h-4 ml-1" />
                </Button>
              </div>
            )}

            {step === "details" && (
              <div className="space-y-5">
                <div>
                  <Label className="text-sm font-semibold text-gray-700 mb-2 block">Package Size</Label>
                  <div className="grid grid-cols-2 gap-3">
                    {packageSizes.map((size) => (
                      <button key={size.value} onClick={() => setPackageSize(size.value)}
                        className={`p-3 rounded-xl border-2 text-left transition-all ${packageSize === size.value ? "border-emerald-600 bg-emerald-50" : "border-gray-200 hover:border-gray-300"}`}>
                        <p className="font-bold text-sm text-gray-900">{size.label}</p>
                        <p className="text-xs text-gray-500 mt-0.5">{size.description}</p>
                        <p className="text-sm font-bold text-emerald-600 mt-1">GYD {size.baseCost}+</p>
                      </button>
                    ))}
                  </div>
                </div>

                <div>
                  <Label className="text-sm font-semibold text-gray-700 mb-1.5 block">What are you sending?</Label>
                  <Input placeholder="e.g., Documents, clothes, books" value={form.package_description} onChange={(e) => updateField("package_description", e.target.value)} className="h-11 rounded-xl" />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-sm font-semibold text-gray-700 mb-1.5 block">Receiver Name</Label>
                    <Input placeholder="Full name" value={form.receiver_name} onChange={(e) => updateField("receiver_name", e.target.value)} className="h-11 rounded-xl" />
                  </div>
                  <div>
                    <Label className="text-sm font-semibold text-gray-700 mb-1.5 block">Receiver Phone</Label>
                    <Input placeholder="Phone number" value={form.receiver_phone} onChange={(e) => updateField("receiver_phone", e.target.value)} className="h-11 rounded-xl" />
                  </div>
                </div>

                <div>
                  <Label className="text-sm font-semibold text-gray-700 mb-2 block">Payment Method</Label>
                  <div className="grid grid-cols-3 gap-3">
                    {[{ id: "cash", label: "💵 Cash" }, { id: "mmg", label: "📱 MMG" }, { id: "card", label: "💳 Card" }].map((pm) => (
                      <button key={pm.id} onClick={() => setPaymentMethod(pm.id)}
                        className={`py-3 rounded-xl border-2 text-sm font-semibold transition-all ${paymentMethod === pm.id ? "border-emerald-600 bg-emerald-50 text-emerald-700" : "border-gray-200 hover:border-gray-300 text-gray-700"}`}>
                        {pm.label}
                      </button>
                    ))}
                  </div>
                  {paymentMethod === 'mmg' && (
                    <div className="mt-3 bg-emerald-50 border-2 border-emerald-200 rounded-xl p-4 space-y-2">
                      <div className="flex items-center gap-2">
                        <div className="w-8 h-8 bg-emerald-600 rounded-lg flex items-center justify-center flex-shrink-0">
                          <Package className="w-4 h-4 text-white" />
                        </div>
                        <p className="font-bold text-emerald-900 text-sm">Sending payment to driver's MMG wallet</p>
                      </div>
                      <div className="bg-white rounded-lg border border-emerald-200 p-3 text-sm">
                        <div className="flex justify-between items-center">
                          <span className="text-gray-500">Amount</span>
                          <span className="font-extrabold text-emerald-700">GYD {costInfo?.cost?.toLocaleString() || "—"}</span>
                        </div>
                      </div>
                      <p className="text-xs text-gray-500">Your driver will share their MMG wallet number when they arrive. Dial <strong>*592#</strong> to send payment.</p>
                    </div>
                  )}
                </div>

                <div className="flex gap-3 pt-2">
                  <Button variant="outline" onClick={handleBack} className="flex-1 h-11 rounded-xl">
                    <ArrowLeft className="w-4 h-4 mr-1" /> Back
                  </Button>
                  <Button onClick={handleSubmit} disabled={loading || !authUser} className="flex-2 h-11 rounded-xl bg-emerald-600 hover:bg-emerald-700 font-bold px-8">
                    {loading ? <><Loader2 className="w-4 h-4 mr-2 animate-spin" />Booking...</> : !authUser ? "Login to Book" : costInfo?.cost ? `Book Now · GYD ${costInfo.cost.toLocaleString()}` : "Book Delivery"}
                  </Button>
                </div>
              </div>
            )}
          </div>
        </div>
        <ErrorReporter error={error} page="delivery" orderId={bookedDelivery?.id} onClose={() => setError(null)} />
      </div>{mmgModalEl}</>
    );
  }

  // ── MOBILE LAYOUT ──
  return (
    <div className="min-h-screen bg-white flex flex-col overflow-hidden">
      {/* STEP 1: ADDRESS */}
      {step === "address" && (
        <>
          {/* Header */}
          <div className="flex-shrink-0" style={{ paddingTop: 'max(12px, env(safe-area-inset-top, 12px))' }}>
            <div className="px-4 py-4 bg-[#0a1628] border-b border-white/10">
              <div className="flex items-center gap-3">
                <button onClick={handleBack} className="p-2.5 hover:bg-white/10 rounded-full border border-white/10">
                  <ArrowLeft className="w-5 h-5 text-white" />
                </button>
                <div className="bg-white/10 border border-white/15 backdrop-blur-sm rounded-2xl p-2">
                  <ZipgyLogo className="h-6 w-auto invert brightness-[3]" />
                </div>
                <div className="flex-1">
                  <p className="text-lg font-extrabold text-white">Request Delivery</p>
                  <p className="text-sm text-white/60">Send packages anywhere</p>
                </div>
                <div className="text-3xl">📦</div>
              </div>
            </div>
          </div>

          <div className="flex-1 overflow-y-auto pb-32">
            {/* Pickup & Destination */}
            <div className="px-4 pt-4 space-y-2.5">
              <div className="relative">
                <MapPin className="absolute left-3 top-3.5 w-4 h-4 text-emerald-500" />
                <Input
                  placeholder="Pickup location"
                  value={pickup}
                  onChange={(e) => setPickup(e.target.value)}
                  className="pl-10 pr-10 h-12 rounded-xl text-base"
                />
              </div>
              <div className="relative">
                <MapPin className="absolute left-3 top-3.5 w-4 h-4 text-red-500" />
                <Input
                  placeholder="Dropoff location"
                  value={destination}
                  onChange={(e) => setDestination(e.target.value)}
                  className="pl-10 pr-10 h-12 rounded-xl text-base"
                />
              </div>
            </div>

            {/* Cost Estimate */}
            {costInfo && (
              <div className="px-4 mt-3">
                <div className={`rounded-xl border px-4 py-3 ${costInfo.error ? "bg-red-50 border-red-200" : "bg-emerald-50 border-emerald-200"}`}>
                  {!costInfo.error ? (
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="text-xs font-semibold text-emerald-700">Estimated Cost</p>
                        {distance && <p className="text-xs text-gray-400">~{distance} km</p>}
                      </div>
                      <p className="text-2xl font-extrabold text-emerald-700">GYD {costInfo.cost.toLocaleString()}</p>
                    </div>
                  ) : (
                    <p className="text-xs text-red-600">{costInfo.error}</p>
                  )}
                </div>
              </div>
            )}

            {/* Continue Button */}
            {destination && costInfo?.cost && !costInfo.error && (
              <div className="px-4 mt-3">
                <button onClick={handleContinue} className="w-full bg-emerald-600 text-white py-3 rounded-xl font-bold text-sm active:scale-[0.98] transition-all shadow-lg">
                  Continue <ArrowRight className="w-4 h-4 inline" />
                </button>
              </div>
            )}
          </div>
        </>
      )}

      {/* STEP 2: DETAILS */}
      {step === "details" && (
        <>
          {/* Header */}
          <div className="flex-shrink-0" style={{ paddingTop: 'max(12px, env(safe-area-inset-top, 12px))' }}>
            <div className="px-4 py-4 bg-[#0a1628] border-b border-white/10">
              <div className="flex items-center gap-3">
                <button onClick={handleBack} className="p-2.5 hover:bg-white/10 rounded-full border border-white/10">
                  <ArrowLeft className="w-5 h-5 text-white" />
                </button>
                <div className="bg-white/10 border border-white/15 backdrop-blur-sm rounded-2xl p-2">
                  <ZipgyLogo className="h-6 w-auto invert brightness-[3]" />
                </div>
                <div className="flex-1">
                  <p className="text-lg font-extrabold text-white">Package Details</p>
                  <p className="text-sm text-white/60">Tell us about your package</p>
                </div>
                <div className="text-3xl">📦</div>
              </div>
            </div>
          </div>

          <div className="flex-1 overflow-y-auto pb-32">
            <div className="px-4 pt-4 space-y-4">
              {/* Package Size */}
              <div>
                <p className="text-sm font-semibold text-gray-600 mb-2">Package Size</p>
                <div className="grid grid-cols-2 gap-2">
                  {packageSizes.map((size) => (
                    <button
                      key={size.value}
                      onClick={() => setPackageSize(size.value)}
                      className={`p-2.5 rounded-xl border-2 text-left ${packageSize === size.value ? "border-emerald-600 bg-emerald-50" : "border-gray-200"}`}
                    >
                      <p className="font-bold text-sm">{size.label}</p>
                      <p className="text-xs text-gray-500">{size.description}</p>
                      <p className="text-sm font-bold text-emerald-600 mt-1">GYD {size.baseCost}+</p>
                    </button>
                  ))}
                </div>
              </div>

              {/* Package Description */}
              <div>
                <Label className="text-sm font-semibold text-gray-700">What are you sending?</Label>
                <Input
                  placeholder="e.g., Documents, clothes, books"
                  value={form.package_description}
                  onChange={(e) => updateField("package_description", e.target.value)}
                  className="h-12 rounded-xl text-base mt-1"
                />
              </div>

              {/* Receiver Info */}
              <div className="space-y-2">
                <p className="text-sm font-semibold text-gray-600">Receiver</p>
                <Input
                  placeholder="Receiver name"
                  value={form.receiver_name}
                  onChange={(e) => updateField("receiver_name", e.target.value)}
                  className="h-12 rounded-xl text-base"
                />
                <Input
                  placeholder="Receiver phone"
                  value={form.receiver_phone}
                  onChange={(e) => updateField("receiver_phone", e.target.value)}
                  className="h-12 rounded-xl text-base"
                />
              </div>

              {/* Payment Method */}
              <div>
                <p className="text-sm font-semibold text-gray-600 mb-2">Payment</p>
                <div className="grid grid-cols-3 gap-2">
                  {[
                    { id: "cash", label: "💵 Cash" },
                    { id: "mmg", label: "📱 MMG" },
                    { id: "card", label: "💳 Card" }
                  ].map((pm) => (
                    <button
                      key={pm.id}
                      onClick={() => setPaymentMethod(pm.id)}
                      className={`py-2.5 rounded-xl border-2 text-sm font-semibold ${paymentMethod === pm.id ? "border-emerald-600 bg-emerald-50" : "border-gray-200"}`}
                    >
                      {pm.label}
                    </button>
                  ))}
                </div>
                {paymentMethod === 'mmg' && (
                  <div className="mt-3 bg-emerald-50 border-2 border-emerald-200 rounded-xl p-3 space-y-2">
                    <div className="flex items-center gap-2">
                      <div className="w-7 h-7 bg-emerald-600 rounded-lg flex items-center justify-center flex-shrink-0">
                        <Package className="w-3.5 h-3.5 text-white" />
                      </div>
                      <p className="font-bold text-emerald-900 text-xs">Sending payment to driver's MMG wallet</p>
                    </div>
                    <div className="bg-white rounded-lg border border-emerald-200 p-2.5 text-sm flex justify-between items-center">
                      <span className="text-gray-500 text-xs">Amount</span>
                      <span className="font-extrabold text-emerald-700">GYD {costInfo?.cost?.toLocaleString() || "—"}</span>
                    </div>
                    <p className="text-xs text-gray-500">Your driver will share their MMG wallet number on arrival. Dial <strong>*592#</strong> to send payment.</p>
                  </div>
                )}
              </div>

              {/* Book Button */}
              <button
                onClick={handleSubmit}
                disabled={loading || !authUser}
                className="w-full bg-emerald-600 text-white py-3 rounded-xl font-bold text-sm active:scale-[0.98] transition-all disabled:opacity-50 shadow-lg"
              >
                {loading ? "Booking..." : !authUser ? "Login to Book" : costInfo?.cost ? `Book Now - GYD ${costInfo.cost.toLocaleString()}` : "Book Delivery"}
              </button>
            </div>
          </div>
        </>
      )}

      <ErrorReporter error={error} page="delivery" orderId={bookedDelivery?.id} onClose={() => setError(null)} />
      {mmgModalEl}
    </div>
  );
}