import { useState, useEffect, useCallback, useRef } from "react";
import { useIsMobile } from "@/hooks/use-mobile";
import { useNavigate } from "react-router-dom";
import { useOptimisticUpdate } from "@/hooks/useOptimisticUpdate";
import { useCurrentLocation } from "@/hooks/useCurrentLocation";
import { useAutoSave } from "@/hooks/useAutoSave";
import { base44 } from "@/api/base44Client";
import { Button } from "@/components/ui/button";
import SEOSchema from "@/components/SEOSchema";
import { ShoppingCart, Plus, Minus, Utensils, Clock, MapPin, ChevronLeft, CheckCircle, Search, AlertTriangle, X, Home, Store } from "lucide-react";
import { validateMMGPhone, validateEmail } from "@/lib/paymentValidator";
import { isDuplicateOrder } from "@/lib/idempotencyV2";
import { withRetry } from "@/lib/networkRetry";

import CancellationPolicyBanner from "@/components/CancellationPolicyBanner";
import SuspendedAccountGate from "@/components/SuspendedAccountGate";
import { generateIdempotencyKey, storeIdempotencyKey, getIdempotencyKey, clearIdempotencyKey } from "@/lib/idempotencyKeys";

import ErrorReporter from "@/components/ErrorReporter";
import FoodCheckoutSheet from "../components/food/FoodCheckoutSheet";
import FoodCheckoutFooter from "../components/food/FoodCheckoutFooter";
import MMGNumberInputModal from "@/components/MMGNumberInputModal";
import { toast } from "sonner";
import { getDistanceKm } from "@/utils/distance";
import { enforceProfileCompletion } from "@/components/ProfileCompletionGate";
import { useAuth } from "@/lib/AuthContext";

const CUISINE_ICONS = {
  "Creole": "🇬🇾",
  "Chinese": "🥡",
  "Indian": "🍛",
  "Fast Food": "🍔",
  "Italian": "🍕",
  "Desserts": "🍰",
  "Drinks": "🥤",
  "Local": "🍲",
  "Other": "🍽️"
};

// Check if restaurant is open based on hours
const isRestaurantOpen = (hoursStart, hoursEnd) => {
  if (!hoursStart || !hoursEnd) return true; // Assume open if no hours specified
  try {
    const now = new Date();
    const currentTime = now.getHours() * 60 + now.getMinutes();
    const [startH, startM] = hoursStart.split(':').map(Number);
    const [endH, endM] = hoursEnd.split(':').map(Number);
    const startMins = startH * 60 + startM;
    const endMins = endH * 60 + endM;
    return currentTime >= startMins && currentTime < endMins;
  } catch {
    return true;
  }
};

// Get restaurant status badge
const getRestaurantStatus = (hoursStart, hoursEnd) => {
  if (!hoursStart || !hoursEnd) return null;
  const isOpen = isRestaurantOpen(hoursStart, hoursEnd);
  if (isOpen) return { label: "Open now", color: "bg-green-100 text-green-700", emoji: "✓" };
  return { label: `Closed (${hoursStart}–${hoursEnd})`, color: "bg-red-100 text-red-700", emoji: "🔴" };
};

const CATEGORY_ICONS = {
  "Mains": "🍽️",
  "Appetizers": "🥗",
  "Sides": "🍟",
  "Desserts": "🍰",
  "Drinks": "🥤",
  "Other": "🍽️"
};

export default function OrderFood() {
  return <SuspendedAccountGate><OrderFoodWithAuth /></SuspendedAccountGate>;
}

function OrderFoodWithAuth() {
  const { isAuthenticated, isLoadingAuth } = useAuth();
  
  // Show loading while checking auth
  if (isLoadingAuth) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-white">
        <div className="w-8 h-8 animate-spin text-emerald-600 border-2 border-emerald-600 border-t-transparent rounded-full" />
      </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 order food</h1>
        <p className="text-gray-600 mb-6 text-center">You need to sign in before ordering</p>
        <button
          onClick={() => base44.auth.redirectToLogin('/order-food')}
          className="bg-emerald-600 text-white font-bold py-3 px-6 rounded-xl active:scale-95 transition-transform"
        >
          Sign In
        </button>
      </div>
    );
  }
  
  return <OrderFoodContent />;
}

function OrderFoodContent() {
  const { user: authUser } = useAuth();
  const isMobile = useIsMobile();
  const navigate = useNavigate();
  const [restaurants, setRestaurants] = useState([]);
  const [selected, setSelected] = useState(null);
  const [menuItems, setMenuItems] = useState([]);
  const [cart, setCart] = useState({});
  const [showCart, setShowCart] = useState(false);
  const [loading, setLoading] = useState(false);
  const [userCoords, setUserCoords] = useState(null);
  const [placing, setPlacing] = useState(false);
  const [menuSearch, setMenuSearch] = useState("");
  const { optimisticState: success, runOptimistic: runOptimisticOrder } = useOptimisticUpdate(null);
  const { address: currentAddress } = useCurrentLocation();
  const [form, setForm] = useState({ customer_name: "", customer_phone: "", customer_email: "", delivery_address: "", notes: "", promo_code: "" });
  const [promoError, setPromoError] = useState("");
  const [promoValidating, setPromoValidating] = useState(false);
  const [searchText, setSearchText] = useState("");
  const [filterCuisine, setFilterCuisine] = useState("");
  const [error, setError] = useState(null);
  const [paymentMethod, setPaymentMethod] = useState('cash');
  const { isSaving, clearDraft } = useAutoSave(form, "FoodOrder", "draft_food_order_id");
  const [menuCache, setMenuCache] = useState({});
  const [appliedPromo, setAppliedPromo] = useState(null);
  const [showMMGModal, setShowMMGModal] = useState(false);
  const [orderError, setOrderError] = useState(null); // NEW: track order errors
  const pendingOrderRef = useRef(null);
  const isOrderInFlightRef = useRef(false);
  const isCheckingPromoRef = useRef(false);

  // Auto-select CASH if restaurant has no MMG wallet (only on first restaurant selection)
  useEffect(() => {
    if (selected && !selected.mmg_wallet_number && paymentMethod !== 'cash') {
      setPaymentMethod('cash');
      toast.info('This restaurant does not accept MMG - payment will be cash on delivery');
    }
  }, [selected?.id]);

  // Auto-prefill form with logged-in user's info
  useEffect(() => {
    if (authUser) {
      setForm(prev => ({
        ...prev,
        customer_name: prev.customer_name || authUser.full_name || "",
        customer_email: prev.customer_email || authUser.email || "",
        customer_phone: prev.customer_phone || authUser.phone || authUser.data?.phone || "",
      }));
    }
  }, [authUser?.email]);

  // Auto-prefill delivery address
  useEffect(() => {
    if (currentAddress) {
      setForm(prev => ({ ...prev, delivery_address: prev.delivery_address || currentAddress }));
    }
  }, [currentAddress]);

  const loadRestaurants = useCallback(() => {
    return base44.entities.Restaurant.filter({ status: "active" }).then((r) => {
      // Show restaurants immediately
      setRestaurants(r);
      setLoading(false);
      
      // Then get location and sort by distance in background
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(({ coords }) => {
          const { latitude, longitude } = coords;
          setUserCoords({ latitude, longitude });
          const sorted = [...r].sort((a, b) => {
            const distA = a.latitude && a.longitude ? Math.hypot(a.latitude - latitude, a.longitude - longitude) : 999;
            const distB = b.latitude && b.longitude ? Math.hypot(b.latitude - latitude, b.longitude - longitude) : 999;
            return distA - distB;
          });
          setRestaurants(sorted);
        }, () => {}, { enableHighAccuracy: false, timeout: 5000, maximumAge: 120000 });
      }
    }).catch(() => {
      setLoading(false);
    });
  }, []);

  useEffect(() => {
    loadRestaurants();
  }, [loadRestaurants]);

  // No prefetch — menus load on-demand when user selects a restaurant

  const getDeliveryTime = (restaurant) => {
    if (!userCoords || !restaurant.latitude || !restaurant.longitude) return "30-45 min";
    const km = getDistanceKm(userCoords.latitude, userCoords.longitude, restaurant.latitude, restaurant.longitude);
    if (km < 2) return "15-25 min";
    if (km < 5) return "25-35 min";
    return "35-50 min";
  };

  const selectRestaurant = async (r) => {
    console.log('[OrderFood] Selecting restaurant:', r.restaurant_name, r.id);
    // Scroll to top smoothly
    window.scrollTo({ top: 0, behavior: 'smooth' });
    setSelected(r);
    setCart({});
    setShowCart(false);
    if (Object.keys(cart).length > 0) {
      toast.success('Cart cleared - selecting new restaurant');
    }

    if (menuCache[r.id]) {
      console.log('[OrderFood] Loading menu from cache for', r.restaurant_name);
      setMenuItems(menuCache[r.id]);
      return;
    }

    try {
      console.log('[OrderFood] Fetching menu for', r.restaurant_name);
      setMenuItems([]); // Clear previous menu items while fetching
      const items = await base44.entities.MenuItem.filter({ restaurant_id: r.id, is_available: true });
      console.log('[OrderFood] Loaded menu items:', items.length, 'items', items);
      setMenuItems(items || []);
      setMenuCache(prevCache => ({ ...prevCache, [r.id]: items || [] }));
    } catch (err) {
      console.error('[OrderFood] Failed to load menu items:', err);
      setMenuItems([]);
    }
  };

  const addToCart = useCallback((item) => {
    setCart(c => ({
      ...c,
      [item.id]: { ...item, qty: (c[item.id]?.qty || 0) + 1 }
    }));
  }, []);
  
  const removeFromCart = useCallback((item) => {
    setCart(c => {
      const newCart = { ...c };
      if (newCart[item.id]?.qty > 1) {
        newCart[item.id].qty -= 1;
      } else {
        delete newCart[item.id];
      }
      return newCart;
    });
  }, []);

  const cartItems = Object.values(cart).filter((i) => i.qty > 0);
  const subtotal = cartItems.reduce((s, i) => s + i.price * i.qty, 0);

  const [deliveryFee, setDeliveryFee] = useState(500);
  useEffect(() => {
    if (selected) {
      setDeliveryFee(selected.delivery_fee || 500);
    }
  }, [selected]);
  
  const total = subtotal + deliveryFee;

  // Live tracking on success screen
  const [finalTotal, setFinalTotal] = useState(0);
  const [liveOrder, setLiveOrder] = useState(null);
  const [orderCancelled, setOrderCancelled] = useState(false);
  const [trackingToken, setTrackingToken] = useState("");
  
  // Mobile: Skip success screen, go straight to tracking
  useEffect(() => {
    if (success?.id && isMobile && !orderCancelled) {
      navigate(`/track-food?id=${success.id}`, { replace: true });
    }
  }, [success?.id, isMobile, orderCancelled]);

  // Live order tracking - subscription only (no polling to avoid rate limits)
  useEffect(() => {
    if (!success?.id || success.id?.startsWith('pending-')) return;
    
    let isMounted = true;
    
    // Store tracking token from success order
    if (success.tracking_token && !trackingToken) {
      setTrackingToken(success.tracking_token);
    }
    
    const unsub = base44.entities.FoodOrder.subscribe((ev) => {
      if (isMounted && ev.type === "update" && ev.id === success.id) {
        setLiveOrder(ev.data);
        if (ev.data?.status === "cancelled") setOrderCancelled(true);
        // Also capture token from live updates
        if (ev.data?.tracking_token && !trackingToken) {
          setTrackingToken(ev.data.tracking_token);
        }
      }
    });
    
    return () => {
      isMounted = false;
      unsub();
    };
  }, [success?.id]);
  
  const displayOrder = liveOrder || success;

  // Continue order after MMG number is saved
  const continueAfterMMGSaved = () => {
    if (pendingOrderRef.current) {
      pendingOrderRef.current();
      pendingOrderRef.current = null;
    }
  };

  const placeOrder = async () => {
    console.log('[OrderFood] placeOrder called, paymentMethod:', paymentMethod);
    console.log('[OrderFood] Form data:', form);
    console.log('[OrderFood] Cart items:', cartItems.length);
    
    // Single lock prevents all race conditions
    if (isOrderInFlightRef.current) {
      console.log('[OrderFood] Order in flight - blocked');
      return;
    }
    
    isOrderInFlightRef.current = true;
    setPlacing(true);
    
    try {
      // VALIDATION: Duplicate check
      console.log('[OrderFood] Checking duplicate orders...');
      const isDup = await isDuplicateOrder(base44, 'food', authUser?.email || form.customer_email, 5);
      if (isDup) {
        console.log('[OrderFood] Duplicate order detected');
        toast.error("You already have a recent food order.");
        throw new Error('Duplicate order');
      }
      
      // VALIDATION: Profile
      console.log('[OrderFood] Checking profile completion...');
      try {
        await enforceProfileCompletion();
      } catch (err) {
        if (err.message?.startsWith('PROFILE_INCOMPLETE:')) {
          console.log('[OrderFood] Profile incomplete:', err.message);
          toast.error(err.message.replace('PROFILE_INCOMPLETE:', ''));
          throw err;
        }
        console.log('[OrderFood] Profile check error:', err);
        throw err;
      }
      
      // VALIDATION: Fields
      console.log('[OrderFood] Validating fields...');
      if (!form.customer_name?.trim()) {
        console.log('[OrderFood] Missing name');
        throw new Error('Name required');
      }
      // Simple phone validation - any valid phone number (not just Guyana MMG)
      if (!form.customer_phone?.trim() || form.customer_phone.replace(/[\s\-\(\)]/g, '').length < 7) {
        console.log('[OrderFood] Invalid phone:', form.customer_phone);
        throw new Error('Valid phone number required (minimum 7 digits)');
      }
      // For CASH orders, skip strict email validation - just check it has @ symbol
      if (paymentMethod === 'mmg') {
        const emailValidation = validateEmail(form.customer_email);
        if (!emailValidation.valid) {
          console.log('[OrderFood] Invalid email:', emailValidation.error);
          throw new Error(emailValidation.error);
        }
      } else {
        // For cash, just check it's not empty and has @ symbol
        if (!form.customer_email?.trim() || !form.customer_email.includes('@')) {
          console.log('[OrderFood] Invalid email for cash order');
          throw new Error('Valid email required');
        }
      }
      if (!form.delivery_address?.trim()) {
        console.log('[OrderFood] Missing address');
        throw new Error('Address required');
      }
      if (cartItems.length === 0) {
        console.log('[OrderFood] Empty cart');
        throw new Error('Cart empty');
      }
      console.log('[OrderFood] All validations passed');
      
      // Idempotency
      const idempotencyKey = generateIdempotencyKey();
      const existing = getIdempotencyKey(idempotencyKey);
      if (existing && Date.now() - existing.timestamp < 300000) {
        console.log('[OrderFood] Duplicate submission detected');
        toast.error("Order already submitted");
        throw new Error('Duplicate submission');
      }
      storeIdempotencyKey(idempotencyKey, { type: 'food', timestamp: Date.now() });

      // MMG check
      if (paymentMethod === 'mmg') {
        console.log('[OrderFood] MMG payment selected, checking user...');
        const currentUser = await base44.auth.me().catch(() => null);
        if (!currentUser?.mmg_number) {
          console.log('[OrderFood] No MMG, showing modal');
          setShowMMGModal(true);
          pendingOrderRef.current = () => executeOrder(idempotencyKey);
          isOrderInFlightRef.current = false;
          setPlacing(false);
          return;
        }
      }

      console.log('[OrderFood] Calling executeOrder...');
      await executeOrder(idempotencyKey);
    } catch (err) {
      console.error('[OrderFood] placeOrder CAUGHT ERROR:', err.message, err.stack);
      toast.error(err.message || 'Order failed');
      isOrderInFlightRef.current = false;
      setPlacing(false);
      throw err;
    }
  };

  const executeOrder = async (idempotencyKey) => {
    try {
      console.log('[OrderFood] executeOrder START, paymentMethod:', paymentMethod);
      console.log('[OrderFood] Selected restaurant:', selected?.id, selected?.restaurant_name, selected?.phone);
      
      const deliveryType = selected.uses_inhouse_delivery ? 'inhouse' : 'driver';
      let finalTotal = total;
      let discountPercent = 0;

      // Apply promo (discount applies to subtotal only, not delivery fee)
      if (form.promo_code) {
        console.log('[OrderFood] Applying promo code:', form.promo_code);
        const promos = await base44.entities.PromoCode.filter({ code: form.promo_code, is_active: true });
        const validPromo = promos.find(p => {
          const hasUses = p.uses_count < (p.max_uses || 999);
          const notExpired = !p.expires_at || new Date(p.expires_at) > new Date();
          return hasUses && notExpired;
        });
        
        if (validPromo) {
          discountPercent = validPromo.discount_percent;
          const discountedSubtotal = subtotal - subtotal * discountPercent / 100;
          finalTotal = discountedSubtotal + deliveryFee;
          await base44.entities.PromoCode.update(validPromo.id, { uses_count: (validPromo.uses_count || 0) + 1 });
          console.log('[OrderFood] Promo applied, new total:', finalTotal);
        }
      }

      // MMG Payment
      if (paymentMethod === 'mmg') {
        console.log('[OrderFood] Processing MMG payment...');
        const currentUser = await base44.auth.me().catch(() => null);
        if (!currentUser?.mmg_number) throw new Error('MMG required');
        if (!selected.mmg_wallet_number) throw new Error('Restaurant MMG not set');
        
        await base44.functions.invoke("processMmgPayment", {
          orderId: "pending-" + Date.now(),
          orderType: 'food',
          customerMmg: currentUser.mmg_number,
          businessMmg: selected.mmg_wallet_number,
          businessName: selected.restaurant_name,
          amount: finalTotal,
          customerName: form.customer_name,
          customerPhone: form.customer_phone,
          businessPhone: selected.phone,
        });
        console.log('[OrderFood] MMG payment initiated');
      } else {
        console.log('[OrderFood] Cash payment selected - no MMG processing needed');
      }

      // Create order
      console.log('[OrderFood] Creating FoodOrder entity...');
      console.log('[OrderFood] Order data:', {
        restaurant_id: selected.id,
        restaurant_name: selected.restaurant_name,
        items: cartItems.map((i) => ({ id: i.id, name: i.name, price: i.price, qty: i.qty })),
        subtotal,
        delivery_fee: selected.delivery_fee,
        total: finalTotal,
        payment_method: paymentMethod,
        customer_email: authUser?.email || form.customer_email,
        customer_name: form.customer_name,
        customer_phone: form.customer_phone,
        delivery_address: form.delivery_address,
      });
      
      // Generate unique tracking token for guest access
      const trackingToken = 'tok_' + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
      
      // Always use authenticated user's email for RLS to work correctly
      const customerEmail = authUser?.email || form.customer_email;

      const orderPayload = {
        restaurant_id: selected.id,
        restaurant_name: selected.restaurant_name,
        items: JSON.stringify(cartItems.map((i) => ({ id: i.id, name: i.name, price: i.price, qty: i.qty }))),
        subtotal,
        delivery_fee: selected.delivery_fee || 0,
        total: finalTotal,
        payment_method: paymentMethod,
        status: 'pending',
        delivery_type: deliveryType,
        customer_email: customerEmail,
        customer_name: form.customer_name,
        customer_phone: form.customer_phone,
        delivery_address: form.delivery_address,
        tracking_token: trackingToken,
      };
      // Only add optional fields if they have values
      if (form.promo_code) orderPayload.promo_code = form.promo_code;
      if (discountPercent) orderPayload.discount_percent = discountPercent;
      if (form.notes) orderPayload.notes = form.notes;
      if (deliveryType === 'inhouse') orderPayload.inhouse_delivery_status = 'preparing';
      if (paymentMethod === 'mmg') orderPayload.mmg_payment_confirmed = false;

      const order = await base44.entities.FoodOrder.create(orderPayload);

      if (!order?.id) {
        throw new Error('Order was not created properly. Please try again.');
      }
      
      console.log('[OrderFood] ✅ Order created successfully:', order.id);
      
      // Store tracking token for success screen
      setTrackingToken(trackingToken);

      // Notifications
      if (form.customer_email) {
        console.log('[OrderFood] Sending booking email to:', form.customer_email);
        base44.functions.invoke("sendBookingEmail", {
          email: form.customer_email, name: form.customer_name, type: "food",
          orderId: order.id, from: selected.restaurant_name, to: form.delivery_address, cost: finalTotal
        }).catch(err => console.error('[OrderFood] Email failed:', err));
      }
      
      if (selected.owner_email) {
        console.log('[OrderFood] Notifying restaurant:', selected.owner_email);
        base44.functions.invoke("notifyRestaurant", {
          restaurantEmail: selected.owner_email, restaurantName: selected.restaurant_name,
          orderId: order.id, customerName: form.customer_name,
          total: finalTotal, items: order.items, deliveryAddress: form.delivery_address,
          restaurantPhone: selected.phone,
          deliveryType: deliveryType
        }).catch(err => console.error('[OrderFood] Restaurant notification failed:', err));
      }
      
      if (paymentMethod === 'cash' && selected.phone) {
        console.log('[OrderFood] Sending cash order WhatsApp to restaurant:', selected.phone);
        base44.functions.invoke("sendWhatsApp", {
          to: selected.phone,
          message: `💵 CASH ORDER\nOrder ID: ${order.id}\nCustomer: ${form.customer_name}\nPhone: ${form.customer_phone}\nTotal: GYD ${finalTotal}\n\n⚠️ CALL CUSTOMER to verify before preparing!`
        }).catch(err => console.error('[OrderFood] WhatsApp failed:', err));
      } else {
        console.log('[OrderFood] Not sending cash WhatsApp - paymentMethod:', paymentMethod, 'has phone:', !!selected.phone);
      }
      
      if (deliveryType === 'inhouse' && selected.phone) {
        const itemList = cartItems.map(i => `• ${i.qty}x ${i.name}`).join("\n");
        console.log('[OrderFood] Sending in-house delivery WhatsApp');
        base44.functions.invoke("sendWhatsApp", {
          to: selected.phone,
          message: `🍽️ NEW ORDER\nCustomer: ${form.customer_name}\nItems:\n${itemList}\nTotal: GYD ${finalTotal}\n\n⚠️ YOU HANDLE DELIVERY`
        }).catch(() => {});
      }

      clearDraft();
      setFinalTotal(finalTotal);
      if (!authUser && form.customer_email) {
        base44.users.inviteUser(form.customer_email, "user").catch(() => {});
      }

      console.log('[OrderFood] ✅ Navigating to track page, order id:', order.id);
      
      // SUCCESS: Navigate away
      setShowCart(false);
      setSelected(null);
      setPlacing(false);
      isOrderInFlightRef.current = false;
      
      // Small delay to ensure order is committed before tracking page loads it
      const orderId = order.id;
      setTimeout(() => {
        navigate(`/track-food?id=${orderId}`);
      }, 500);
      
      return order;
      
    } catch (err) {
      console.error('❌ [OrderFood] executeOrder CAUGHT ERROR:', err.message);
      console.error('Stack:', err.stack);
      clearIdempotencyKey(idempotencyKey);
      setOrderError(err);
      isOrderInFlightRef.current = false;
      setPlacing(false);
      throw err;
    }
  };

  // Map state
  const [mapSrc, setMapSrc] = useState("");

  useEffect(() => {
    base44.functions.invoke('getMapsEmbedKey', {}).then(res => {
      if (res.data?.apiKey) {
        setMapSrc(`https://www.google.com/maps/embed/v1/place?key=${res.data.apiKey}&q=Georgetown,Guyana&zoom=13`);
      }
    }).catch(() => {});
  }, []);

  // Error recovery screen
  if (orderError && !success) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background px-4">
        <div className="text-center max-w-sm animate-in zoom-in duration-300">
          <div className="w-16 h-16 rounded-full bg-red-100 mx-auto mb-4 flex items-center justify-center">
            <X className="w-8 h-8 text-red-600" />
          </div>
          <h2 className="font-heading font-bold text-2xl mb-2 text-red-600">Order Failed</h2>
          <p className="text-muted-foreground mb-4">{orderError?.message || "Something went wrong. Please try again."}</p>
          <div className="space-y-3">
            <Button 
              className="w-full bg-primary hover:bg-primary/90 rounded-full"
              onClick={() => { setOrderError(null); setPlacing(false); }}
            >
              🔄 Retry Order
            </Button>
            <Button 
              variant="outline" 
              className="w-full rounded-full"
              onClick={() => navigate('/home')}
            >
              📞 Contact Support
            </Button>
            <Button 
              variant="ghost" 
              className="w-full rounded-full"
              onClick={() => { setOrderError(null); setSelected(null); setCart({}); }}
            >
              🏠 Back to Home
            </Button>
          </div>
        </div>
      </div>
    );
  }

  // Success screen (desktop only)
  if (success && !orderCancelled && !isMobile) {
    const isLive = displayOrder?.status === "preparing" || displayOrder?.status === "picked_up";
    const restaurantName = selected?.restaurant_name || displayOrder?.restaurant_name || "the restaurant";
    
    // Hide success screen immediately if cancelled
    if (orderCancelled) return null;
    
    return (
      <div className="min-h-screen flex items-center justify-center bg-background px-4" style={{ paddingBottom: 'max(16px, env(safe-area-inset-bottom, 16px))' }}>
        <div className="text-center max-w-sm animate-in zoom-in duration-300">
          <CheckCircle className="w-16 h-16 text-primary mx-auto mb-4" />
          <h2 className="font-heading font-bold text-2xl mb-2 flex items-center justify-center gap-2">
            {isLive && <span className="w-2.5 h-2.5 bg-red-600 rounded-full animate-pulse" />}
            {displayOrder?.delivery_type === 'inhouse' ? "Restaurant Delivery" : (displayOrder?.driver_name ? "Preparing & Delivery" : "Order Placed!")}
          </h2>
          <p className="text-muted-foreground mb-1">
            {displayOrder?.delivery_type === 'inhouse' ?
              <><strong>{restaurantName}</strong> will handle your delivery directly.</> :
              displayOrder?.driver_name ?
              <><strong>{displayOrder.driver_name}</strong> is {displayOrder.status === "picked_up" ? "delivering your order" : "preparing it"}.</> :
              <><>Your order has been sent to <strong>{restaurantName}</strong>.</></>
            }
          </p>
          <div className="mb-4 bg-blue-50 border border-blue-200 rounded-xl p-3 text-left">
            <div className="flex items-start gap-2">
              <AlertTriangle className="w-4 h-4 text-blue-500 flex-shrink-0 mt-0.5" />
              <div className="text-xs text-blue-700">
                <p className="font-semibold mb-0.5">
                  {displayOrder?.payment_method === 'mmg' ? '💳 MMG Payment Required' : '💵 Cash on Delivery'}
                </p>
                <p className="text-blue-600">
                  {displayOrder?.payment_method === 'mmg' 
                    ? 'Check WhatsApp for payment instructions. You\'ll receive a message from MMG shortly.'
                    : `The restaurant will call you at ${form.customer_phone} to verify your order before preparing.`
                  }
                </p>
              </div>
            </div>
          </div>
          <p className="text-muted-foreground text-sm mb-6">
            {displayOrder?.payment_method === 'mmg' ? (
              <><span className="text-emerald-600 font-semibold">✓ MMG Payment Required.</span> Total: <strong className="text-foreground">GYD {finalTotal.toLocaleString()}</strong></>
            ) : (
              <><span className="text-blue-600 font-semibold">💵 Cash on Delivery.</span> Total: <strong className="text-foreground">GYD {finalTotal.toLocaleString()}</strong></>
            )}
          </p>
          {displayOrder?.driver_name &&
            <div className="bg-blue-50 border border-blue-200 rounded-xl p-3 mb-4 text-left text-sm">
              <p className="text-blue-700 font-medium">{displayOrder.driver_name}</p>
              {displayOrder.driver_phone && <p className="text-xs text-blue-600">📱 {displayOrder.driver_phone}</p>}
            </div>
          }
          <Button
            className="w-full rounded-full mb-3"
            onClick={() => {
              if (!success?.id) return;
              authUser
                ? navigate(`/track-food?id=${success.id}`)
                : base44.auth.redirectToLogin(`/track-food?id=${success.id}`);
            }}
          >Track My Order</Button>
          <div className="mb-4 bg-amber-50 border border-amber-200 rounded-xl p-3 text-left">
            <div className="flex items-start gap-2">
              <AlertTriangle className="w-4 h-4 text-amber-500 flex-shrink-0 mt-0.5" />
              <div className="text-xs text-amber-700">
                <p className="font-semibold mb-0.5">Important: Food Delivery</p>
                <p className="text-amber-600">Delivery times may vary. Confirm your order with the restaurant via WhatsApp after placing.</p>
              </div>
            </div>
          </div>
          <CancellationPolicyBanner
            orderId={success.id}
            orderType="food"
            bookedAt={success.created_date || new Date().toISOString()}
            userEmail={authUser?.email || form.customer_email}
            onEntityUpdate={(id, data) => base44.entities.FoodOrder.update(id, data)}
            onCancelled={() => {
              // Immediately clear active order state before navigating
              window.dispatchEvent(new CustomEvent('order-cancelled', { detail: { orderId: success.id, type: 'food' } }));
              // Navigate to home after cancellation
              setTimeout(() => navigate('/home'), 500);
            }} />
          {authUser &&
            <Button variant="outline" className="w-full rounded-full mt-3" onClick={() => {setSelected(null);setCart({});setForm({ customer_name: "", customer_phone: "", customer_email: "", delivery_address: "", notes: "", promo_code: "" });setPaymentMethod('mmg');}}>
              Order More Food
            </Button>
          }
          {!authUser &&
            <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 order, receive updates, and get your GYD 1,000 welcome bonus.</p>
              <button onClick={() => base44.auth.redirectToLogin(`/track-food?id=${success.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>
          }
        </div>
      </div>
    );
  }

  // Restaurant list - map background
  if (!selected) {
    const filtered = restaurants.filter((r) => {
      const matchesSearch = r.restaurant_name.toLowerCase().includes(searchText.toLowerCase()) || (r.area || '').toLowerCase().includes(searchText.toLowerCase());
      const matchesCuisine = !filterCuisine || r.cuisine_type === filterCuisine;
      return matchesSearch && matchesCuisine;
    });

    return (
      <div className="relative w-full bg-gray-200" style={{ height: "100dvh", overflow: "hidden" }}>
        <SEOSchema page="food" />
        <div className="absolute inset-0">
          {mapSrc ? (<iframe key={mapSrc} src={mapSrc} width="100%" height="100%" style={{ border: 0 }} loading="lazy" allowFullScreen referrerPolicy="no-referrer-when-downgrade" />) : (<div className="w-full h-full flex items-center justify-center bg-gray-200"><div className="text-center"><div className="text-4xl mb-2">🗺️</div><p className="text-xs text-gray-500">Loading map…</p></div></div>)}
        </div>
        <div className="absolute top-0 left-0 right-0 z-30 px-4" style={{ paddingTop: 'max(12px, env(safe-area-inset-top, 12px))' }}>
          <button onClick={() => navigate("/home")} className="w-12 h-12 rounded-full bg-white shadow-xl flex items-center justify-center active:scale-95 transition-transform touch-manipulation -ml-1"><ChevronLeft className="w-6 h-6 text-gray-800" strokeWidth={2.5} /></button>
        </div>
        <div className="absolute bottom-0 left-0 right-0 z-20 bg-white rounded-t-3xl shadow-2xl overflow-hidden animate-in slide-in-from-bottom duration-300" style={{ maxHeight: "85vh" }}>
          <div className="flex justify-center pt-3 pb-0.5"><div className="w-10 h-1 bg-gray-200 rounded-full" /></div>
          <div className="overflow-y-auto overflow-x-hidden" style={{ maxHeight: "calc(85vh - 24px)", paddingBottom: "env(safe-area-inset-bottom, 16px)" }}>
            <div className="px-5 pt-3 pb-4">
              <div className="flex items-center gap-3 mb-5">
                <div className="w-12 h-12 rounded-2xl bg-gradient-to-br from-orange-500 to-red-500 flex items-center justify-center text-white flex-shrink-0 shadow-lg"><Utensils className="w-6 h-6" /></div>
                <div><h2 className="font-black text-xl text-gray-900 leading-tight">Order Food</h2><p className="text-sm text-gray-600 font-semibold mt-0.5">Hot meals from local restaurants</p></div>
              </div>
              <div className="flex items-center gap-2 bg-gray-50 border-2 border-gray-200 rounded-xl px-4 py-3 mb-4">
                <Search className="w-5 h-5 text-gray-400 flex-shrink-0" />
                <input placeholder="Search restaurants or area..." value={searchText} onChange={(e) => setSearchText(e.target.value)} className="flex-1 bg-transparent outline-none text-base text-gray-800 placeholder:text-gray-400 font-semibold" />
              </div>
              <div className="flex gap-2.5 overflow-x-auto pb-2 scrollbar-hide -mx-1 px-1 mb-5">
                {[{ label: "All", emoji: "🍽️", value: "" }, { label: "Creole", emoji: "🇬🇾", value: "Creole" }, { label: "Chinese", emoji: "🥡", value: "Chinese" }, { label: "Indian", emoji: "🍛", value: "Indian" }, { label: "Fast Food", emoji: "🍔", value: "Fast Food" }, { label: "Italian", emoji: "🍕", value: "Italian" }, { label: "Desserts", emoji: "🍰", value: "Desserts" }, { label: "Drinks", emoji: "🥤", value: "Drinks" }, { label: "Local", emoji: "🍲", value: "Local" }].map(cat => (
                  <button key={cat.value} onClick={() => setFilterCuisine(cat.value)} className={`flex-shrink-0 flex items-center gap-2 px-4 py-2.5 rounded-2xl text-sm font-extrabold transition-all shadow-md ${filterCuisine === cat.value ? "bg-gradient-to-r from-orange-500 to-red-500 text-white shadow-orange-500/40" : "bg-white text-gray-700 border-2 border-gray-200 hover:bg-gray-50"}`}><span className="text-lg">{cat.emoji}</span>{cat.label}</button>
                ))}
              </div>
            </div>
            <div className="px-5 pb-3 border-t border-gray-100">
               <div className="flex items-center gap-2 overflow-x-auto pb-1 scrollbar-hide -mx-1 px-1">
                  <button onClick={() => navigate("/home")} className="flex items-center gap-1.5 px-3 py-1.5 bg-emerald-50 hover:bg-emerald-100 active:bg-emerald-150 rounded-full text-xs font-semibold text-emerald-700 whitespace-nowrap transition-all shadow-sm"><Home className="w-3.5 h-3.5" /> Home</button>
                  <button onClick={() => navigate("/order-groceries")} className="flex items-center gap-1.5 px-3 py-1.5 bg-blue-50 hover:bg-blue-100 active:bg-blue-150 rounded-full text-xs font-semibold text-blue-700 whitespace-nowrap transition-all shadow-sm"><Store className="w-3.5 h-3.5" /> Grocery</button>
                  <button onClick={() => navigate("/order-food")} className="flex items-center gap-1.5 px-3 py-1.5 bg-orange-500 hover:bg-orange-600 active:bg-orange-700 rounded-full text-xs font-semibold text-white whitespace-nowrap transition-all shadow-md"><Utensils className="w-3.5 h-3.5" /> Food</button>
                  <button onClick={() => navigate("/booking?service=taxi")} className="flex items-center gap-1.5 px-3 py-1.5 bg-purple-50 hover:bg-purple-100 active:bg-purple-150 rounded-full text-xs font-semibold text-purple-700 whitespace-nowrap transition-all shadow-sm"><span className="text-sm">🚕</span> Taxi</button>
              </div>
            </div>
            <div className="px-5 pt-2 pb-6">
              {loading ? ( <div className="space-y-3">{[1, 2, 3].map((i) => (<div key={i} className="bg-white border border-gray-200 rounded-2xl overflow-hidden"><div className="h-20 bg-gray-100 animate-pulse" /><div className="p-3 space-y-2"><div className="h-4 bg-gray-100 animate-pulse rounded w-3/4" /><div className="h-3 bg-gray-100 animate-pulse rounded w-1/2" /></div></div>))}</div>) : filtered.length === 0 ? (<div className="text-center py-12 text-muted-foreground"><Utensils className="w-12 h-12 mx-auto mb-2 opacity-30" /><p className="text-sm">No restaurants found.</p></div>) : (<div className="space-y-2">{filtered.map((r) => { const deliveryTime = getDeliveryTime(r); const distance = userCoords && r.latitude && r.longitude ? getDistanceKm(userCoords.latitude, userCoords.longitude, r.latitude, r.longitude) : null; return (<button key={r.id} onClick={() => selectRestaurant(r)} className="w-full text-left bg-white border border-gray-200 rounded-2xl overflow-hidden hover:shadow-xl transition-all active:scale-[0.98]"><div className="flex"><div className="h-20 w-20 flex-shrink-0 bg-gradient-to-br from-orange-100 to-red-100 relative overflow-hidden flex items-center justify-center">{r.logo_url ? (<img src={r.logo_url} alt={r.restaurant_name} className="w-full h-full object-cover" loading="lazy" />) : (<div className="w-full h-full flex items-center justify-center flex-col p-1 text-center"><span className="text-2xl mb-0.5">{CUISINE_ICONS[r.cuisine_type] || "🍽️"}</span></div>)}</div><div className="flex-1 p-3 flex flex-col justify-between"><div><h3 className="font-heading font-extrabold text-sm text-gray-900 truncate leading-tight">{r.restaurant_name}</h3><div className="inline-flex items-center gap-1 mt-1 px-2 py-0.5 bg-orange-50 rounded-full border border-orange-200"><span className="text-xs">{CUISINE_ICONS[r.cuisine_type] || "🍽️"}</span><span className="text-xs font-normal text-orange-700">{r.cuisine_type}</span></div><div className="flex items-center gap-2 mt-1.5"><div className="flex items-center gap-1"><Clock className="w-3 h-3 text-gray-400" /><span className="text-xs text-gray-600 font-medium">{deliveryTime}</span></div>{distance && (<div className="flex items-center gap-1"><MapPin className="w-3 h-3 text-gray-400" /><span className="text-xs text-gray-600 font-medium">{distance < 1 ? `${Math.round(distance * 1000)}m` : `${distance.toFixed(1)}km`}</span></div>)}</div></div></div></div></button>);})}</div>)}
              <ErrorReporter error={error} page="food" orderId={success?.id} onClose={() => setError(null)} />
            </div>
          </div>
        </div>
      </div>
    );
  }
  
  // Selected restaurant - menu view
  if (selected) {
    const filteredMenu = menuItems.filter((i) => i.name.toLowerCase().includes(menuSearch.toLowerCase()));
    const categories = [...new Set(filteredMenu.map((i) => i.category || "Other"))];

    return (
      <div className="min-h-screen bg-background pb-24">
        <SEOSchema page="food" />
        
        {/* Checkout Bottom Sheet */}
        {showCart && <FoodCheckoutSheet
          cartItems={cartItems}
          subtotal={subtotal}
          total={total}
          deliveryFee={deliveryFee}
          form={form}
          setForm={setForm}
          appliedPromo={appliedPromo}
          setAppliedPromo={setAppliedPromo}
          placing={placing}
          onPlaceOrder={placeOrder}
          onClose={() => setShowCart(false)}
          addToCart={addToCart}
          removeFromCart={removeFromCart}
          paymentMethod={paymentMethod}
          onPaymentMethodChange={setPaymentMethod}
          restaurantName={selected.restaurant_name}
          restaurantMMG={selected.mmg_wallet_number || ""}
          restaurantDescription={selected.description || ""}
          restaurantLogo={selected.logo_url || ""}
        />}
        
        {/* Sticky Checkout Footer (Mobile) */}
        <FoodCheckoutFooter
          cartItems={cartItems}
          subtotal={subtotal}
          onCheckout={() => setShowCart(true)}
        />
        
        {/* Desktop Checkout Bar */}
        {cartItems.length > 0 && (
          <div className="hidden md:block fixed bottom-0 left-0 right-0 z-40 bg-white border-t border-gray-200 shadow-2xl">
            <div className="max-w-4xl mx-auto px-6 py-4 flex items-center justify-between">
              <div className="flex items-center gap-4">
                <div className="flex items-center gap-2">
                  <div className="w-10 h-10 rounded-full bg-emerald-100 flex items-center justify-center">
                    <ShoppingCart className="w-5 h-5 text-emerald-700" />
                  </div>
                  <div>
                    <p className="text-sm font-semibold text-gray-700">{cartItems.length} {cartItems.length === 1 ? 'item' : 'items'} in cart</p>
                    <p className="text-lg font-bold text-gray-900">GYD {subtotal.toLocaleString()}</p>
                  </div>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <Button
                  variant="outline"
                  className="h-12 px-6 font-semibold rounded-xl"
                  onClick={() => setCart({})}
                >
                  Clear Cart
                </Button>
                <Button
                  className="h-12 px-8 font-bold text-base rounded-xl bg-emerald-600 hover:bg-emerald-700 active:scale-[0.98] transition-transform shadow-lg"
                  onClick={() => setShowCart(true)}
                >
                  Proceed to Checkout · GYD {total.toLocaleString()}
                </Button>
              </div>
            </div>
          </div>
        )}
        
        {/* ── STOREFRONT HEADER — MOBILE ── */}
        <div className="fixed top-0 left-0 right-0 z-[9999] md:hidden" style={{ filter: 'drop-shadow(0 4px 16px rgba(0,0,0,0.5))', background: '#0f172a', paddingTop: 'max(12px, env(safe-area-inset-top, 12px))', pointerEvents: 'auto' }}>
          {/* Awning stripe bar */}
          <div className="h-2 w-full" style={{
            background: 'repeating-linear-gradient(90deg, #1a1a2e 0px, #1a1a2e 24px, #c41e3a 24px, #c41e3a 48px)'
          }} />
          {/* Main façade */}
          <div style={{ background: '#0f172a' }}>
            <div className="px-4 pt-2 pb-0">
              {/* Top nav row */}
              <div className="flex items-center justify-between mb-3">
                <button onClick={() => setSelected(null)} className="flex items-center gap-1.5 text-white/70 hover:text-white active:opacity-60 transition-colors z-[10001] relative" aria-label="Go back" style={{ pointerEvents: 'auto' }}>
                  <ChevronLeft className="w-5 h-5" />
                  <span className="text-sm font-semibold">Back</span>
                </button>
                <div className="flex items-center gap-2">
                  {/* Payment selector badge */}
                  <div className="flex items-center gap-1 px-3 py-1.5 rounded-full text-xs font-bold text-white/80 border border-white/20">
                    <span>{paymentMethod === 'mmg' ? '💳 MMG' : '💵 Cash'}</span>
                  </div>
                  <button
                    onClick={() => {
                      if (cartItems.length === 0) {
                        toast.error('Add items to your cart first!');
                        return;
                      }
                      setShowCart(true);
                    }}
                    className="flex items-center gap-2 px-4 py-2 rounded-xl text-white font-bold text-sm transition-all active:scale-95 z-[10001] relative"
                    style={{ background: '#16a34a', pointerEvents: 'auto' }}
                  >
                    <ShoppingCart className="w-4 h-4" />
                    View Cart
                  </button>
                </div>
              </div>
              {/* Store sign area */}
              <div className="flex items-center gap-3 pb-3">
                {/* Logo / storefront icon */}
                <div className="w-14 h-14 rounded-2xl flex-shrink-0 flex items-center justify-center text-3xl shadow-lg border-2 overflow-hidden"
                  style={{ background: '#1e293b', borderColor: 'rgba(255,255,255,0.1)' }}>
                  {selected.logo_url
                    ? <img src={selected.logo_url} alt="" className="w-full h-full object-cover" />
                    : <span>{CUISINE_ICONS[selected.cuisine_type] || '🍽️'}</span>
                  }
                </div>
                <div className="flex-1 min-w-0">
                  <h1 className="text-xl font-black text-white tracking-tight leading-tight truncate">{selected.restaurant_name}</h1>
                  <div className="flex items-center gap-1.5 mt-1 flex-wrap">
                    {selected.cuisine_type && (
                      <span className="px-2.5 py-0.5 rounded-full text-xs font-bold text-amber-300 border border-amber-500/40" style={{ background: 'rgba(245,158,11,0.15)' }}>
                        {CUISINE_ICONS[selected.cuisine_type] || '🍽️'} {selected.cuisine_type}
                      </span>
                    )}
                    {selected.area && (
                      <span className="px-2.5 py-0.5 rounded-full text-xs font-semibold text-white/60" style={{ background: '#1e293b' }}>
                        📍 {selected.area}
                      </span>
                    )}
                    {selected.hours_start && selected.hours_end && (() => {
                      const status = getRestaurantStatus(selected.hours_start, selected.hours_end);
                      return status ? (
                        <span className={`px-2.5 py-0.5 rounded-full text-xs font-semibold ${status.color}`}>
                          {status.emoji} {status.label}
                        </span>
                      ) : (
                        <span className="px-2.5 py-0.5 rounded-full text-xs font-semibold text-white/60" style={{ background: '#1e293b' }}>
                          🕐 {selected.hours_start}–{selected.hours_end}
                        </span>
                      );
                    })()}
                  </div>
                  {selected.description && (
                    <p className="text-xs text-white/45 mt-1 leading-snug line-clamp-1">{selected.description}</p>
                  )}
                </div>
              </div>
            </div>
          </div>
          {/* Storefront curved bottom edge (awning drip) */}
          <svg viewBox="0 0 400 18" xmlns="http://www.w3.org/2000/svg" className="w-full block" style={{ display: 'block', marginTop: -1 }}>
            <path d="M0,0 Q50,18 100,8 Q150,-2 200,10 Q250,20 300,8 Q350,-2 400,10 L400,0 Z" fill="#0f172a" />
          </svg>
        </div>

        {/* ── STOREFRONT HEADER — DESKTOP ── */}
        <div className="hidden md:block sticky top-0 z-40" style={{ filter: 'drop-shadow(0 6px 20px rgba(0,0,0,0.5))' }}>
          {/* Awning stripe */}
          <div className="h-3 w-full" style={{
            background: 'repeating-linear-gradient(90deg, #1a1a2e 0px, #1a1a2e 32px, #c41e3a 32px, #c41e3a 64px)'
          }} />
          {/* Main façade */}
          <div style={{ background: '#0f172a' }}>
            <div className="px-8 py-4 flex items-center gap-6">
              {/* Back */}
              <button onClick={() => setSelected(null)} className="flex items-center gap-1.5 text-white/70 hover:text-white transition-colors flex-shrink-0" aria-label="Go back">
                <ChevronLeft className="w-5 h-5" />
                <span className="text-sm font-semibold">Back</span>
              </button>
              {/* Logo */}
              <div className="w-14 h-14 rounded-2xl flex-shrink-0 flex items-center justify-center text-3xl shadow-lg border-2 overflow-hidden"
                style={{ background: '#1e293b', borderColor: 'rgba(255,255,255,0.1)' }}>
                {selected.logo_url
                  ? <img src={selected.logo_url} alt="" className="w-full h-full object-cover" />
                  : <span>{CUISINE_ICONS[selected.cuisine_type] || '🍽️'}</span>
                }
              </div>
              {/* Info */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-3 flex-wrap">
                  <h1 className="text-2xl font-black text-white tracking-tight">{selected.restaurant_name}</h1>
                  {selected.cuisine_type && (
                    <span className="px-3 py-1 rounded-full text-sm font-bold text-amber-300 border border-amber-500/40 flex-shrink-0" style={{ background: 'rgba(245,158,11,0.15)' }}>
                      {CUISINE_ICONS[selected.cuisine_type] || '🍽️'} {selected.cuisine_type}
                    </span>
                  )}
                  {selected.area && (
                    <span className="px-3 py-1 rounded-full text-sm font-semibold flex-shrink-0" style={{ background: '#1e293b', color: 'rgba(255,255,255,0.55)' }}>
                      📍 {selected.area}
                    </span>
                  )}
                  {selected.hours_start && selected.hours_end && (() => {
                    const status = getRestaurantStatus(selected.hours_start, selected.hours_end);
                    return status ? (
                      <span className={`px-3 py-1 rounded-full text-sm font-semibold flex-shrink-0 ${status.color}`}>
                        {status.emoji} {status.label}
                      </span>
                    ) : (
                      <span className="px-3 py-1 rounded-full text-sm font-semibold flex-shrink-0" style={{ background: '#1e293b', color: 'rgba(255,255,255,0.55)' }}>
                        🕐 {selected.hours_start}–{selected.hours_end}
                      </span>
                    );
                  })()}
                </div>
                {selected.description && (
                  <p className="text-sm mt-1 leading-snug" style={{ color: 'rgba(255,255,255,0.45)' }}>{selected.description}</p>
                )}
              </div>
              {/* Cart */}
              <button
                onClick={() => {
                  if (cartItems.length === 0) {
                    toast.error('Add items to your cart first!');
                    return;
                  }
                  setShowCart(true);
                }}
                className="flex items-center gap-2.5 px-5 py-2.5 rounded-xl text-white font-bold text-sm flex-shrink-0 transition-all hover:opacity-90 active:scale-95"
                style={{ background: '#16a34a' }}
              >
                <ShoppingCart className="w-5 h-5" />
                View Cart
              </button>
            </div>
          </div>
          {/* Storefront curved bottom edge */}
          <svg viewBox="0 0 1440 20" xmlns="http://www.w3.org/2000/svg" className="w-full block" style={{ display: 'block', marginTop: -1 }}>
            <path d="M0,0 Q180,20 360,10 Q540,0 720,14 Q900,24 1080,10 Q1260,-2 1440,12 L1440,0 Z" fill="#0f172a" />
          </svg>
        </div>
        
        {/* Search box - positioned in flow, not sticky */}
        <div className="mb-5 px-3 max-w-2xl mx-auto" style={{ paddingTop: '220px' }}>
          <div className="flex items-center gap-3 bg-card border-2 border-border rounded-xl px-4 py-3.5 shadow-md">
            <Search className="w-5 h-5 text-muted-foreground" />
            <input
              placeholder="Search menu items..."
              value={menuSearch}
              onChange={(e) => setMenuSearch(e.target.value)}
              className="flex-1 bg-transparent outline-none text-base font-semibold" />
            {menuSearch &&
            <button onClick={() => setMenuSearch("")} className="text-muted-foreground hover:text-foreground">
                <X className="w-5 h-5" />
              </button>
            }
          </div>
        </div>
        
        <div className="px-3 pb-32 max-w-2xl mx-auto">
          {menuItems.length === 0 ?
          <div className="text-center py-20 text-muted-foreground">
              <Utensils className="w-12 h-12 mx-auto mb-3 opacity-30" />
              <p className="font-heading font-semibold text-lg mb-1">Menu Coming Soon</p>
              <p className="text-sm">{selected.restaurant_name} is setting up their menu. Check back later!</p>
              <Button variant="outline" className="mt-4 rounded-full" onClick={() => setSelected(null)}>
                Back to Restaurants
              </Button>
            </div> :
          categories.length === 0 ?
          <div className="text-center py-20 text-muted-foreground">
              <p className="font-semibold text-sm">No items found for "{menuSearch}"</p>
              <p className="text-xs mt-0.5">Try a different search term</p>
            </div> :

          categories.map((cat) => {
            const catItems = filteredMenu.filter((i) => i.category === cat);
            if (catItems.length === 0) return null;
            return (
              <div key={cat} className="mb-5 px-3">
                  <h3 className="font-heading font-black text-lg mb-3 flex items-center gap-2">
                    <span className="text-xl">{CATEGORY_ICONS[cat] || "🍽️"}</span>
                    {cat}
                  </h3>
                  <div className="space-y-3">
                    {catItems.map((item) =>
                  <div key={item.id} className="flex gap-4 bg-card border-2 border-border rounded-xl p-4 active:scale-[0.98] transition-transform hover:border-primary/30 shadow-sm">
                        {item.photo_url ?
                    <img src={item.photo_url} alt={item.name} className="w-24 h-24 rounded-xl object-cover flex-shrink-0 shadow-md" loading="lazy" /> :

                    <div className="w-24 h-24 rounded-xl bg-muted flex items-center justify-center text-3xl flex-shrink-0 shadow-md">
                            {CATEGORY_ICONS[item.category] || "🍽️"}
                          </div>
                    }
                        <div className="flex-1 min-w-0 flex flex-col justify-between">
                          <div>
                            <p className="font-bold text-base">{item.name}</p>
                            {item.description && <p className="text-xs text-muted-foreground mt-1 truncate font-medium">{item.description}</p>}
                          </div>
                          <div className="flex items-center justify-between">
                            <p className="text-primary font-black text-lg">GYD {item.price.toLocaleString()}</p>
                            {cart[item.id]?.qty > 0 ?
                        <div className="flex items-center gap-2">
                                <button onClick={() => removeFromCart(item)} className="w-8 h-8 rounded-full bg-muted flex items-center justify-center active:scale-95 hover:bg-muted/80 shadow-sm"><Minus className="w-4 h-4" /></button>
                                <span className="font-black text-base w-7 text-center">{cart[item.id].qty}</span>
                                <button onClick={() => addToCart(item)} className="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center active:scale-95 hover:bg-primary/90 shadow-md"><Plus className="w-4 h-4" /></button>
                              </div> :

                        <button onClick={() => addToCart(item)} className="px-4 py-2 rounded-full bg-primary text-white text-sm font-bold active:scale-95 hover:bg-primary/90 shadow-md">
                                Add
                              </button>
                        }
                          </div>
                        </div>
                      </div>
                  )}
                  </div>
                </div>);

          })
          }
          <ErrorReporter error={error} page="food" orderId={success?.id} onClose={() => setError(null)} />
        </div>

        {/* MMG Number Input Modal */}
        <MMGNumberInputModal
          isOpen={showMMGModal}
          onClose={() => {
            setShowMMGModal(false);
            pendingOrderRef.current = null;
            isOrderInFlightRef.current = false;
          }}
          onSaved={continueAfterMMGSaved}
        />
      </div>
    );
  }

  return null;
}