import { useState, useEffect, useRef, useCallback } 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 { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { ShoppingCart, Plus, Minus, Utensils, Clock, MapPin, ChevronLeft, CheckCircle, Search, AlertTriangle, X, Home, Store, Package, Star } from "lucide-react";
import ZipgyLogo from "@/components/ZipgyLogo";
import { Link } from "react-router-dom";
import CancellationPolicyBanner from "@/components/CancellationPolicyBanner";
import SuspendedAccountGate from "@/components/SuspendedAccountGate";

import ErrorReporter from "@/components/ErrorReporter";
import WhatsAppNotice from "../components/WhatsAppNotice";
import FavoritesManager from "../components/FavoritesManager";
import FoodCheckoutDrawer from "../components/FoodCheckoutDrawer";
import PaymentMethodSelector from "../components/PaymentMethodSelector";
import { toast } from "sonner";
import { getDistanceKm } from "@/utils/distance";

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

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

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

function OrderFoodContent() {
  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(true);
  const [userCoords, setUserCoords] = useState(null);
  const [placing, setPlacing] = useState(false);
  const [refreshing, setRefreshing] = 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 [searchText, setSearchText] = useState("");
  const [filterCuisine, setFilterCuisine] = useState("");
  const [favorites, setFavorites] = useState([]);
  const [user, setUser] = useState(null);
  const [appliedPromo, setAppliedPromo] = useState(null);
  const [error, setError] = useState(null);
  const [paymentMethod, setPaymentMethod] = useState('mmg');
  const { isSaving, clearDraft } = useAutoSave(form, "FoodOrder", "draft_food_order_id");

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

  // Load user and favorites
  useEffect(() => {
    let isMounted = true;
    base44.auth.me().then((u) => {
      if (isMounted) {
        setUser(u);
        if (u) {
          base44.entities.Favorite.filter({ user_email: u.email, type: "restaurant" }).
          then((favs) => {if (isMounted) setFavorites(favs.map((f) => f.item_id));}).
          catch(() => {});
        }
      }
      if (isMounted) setLoading(false);
    }).catch(() => {
      if (isMounted) setLoading(false);
    });
    return () => {isMounted = false;};
  }, []);

  const loadRestaurants = useCallback(() => {
    return base44.entities.Restaurant.filter({ status: "active" }).then((r) => {
      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);
        }, () => {setRestaurants(r); setLoading(false);}, { enableHighAccuracy: false, timeout: 5000, maximumAge: 120000 });
      } else {
        setRestaurants(r);
        setLoading(false);
      }
    });
  }, []);

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

  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) => {
    setSelected(r);
    setCart({});
    const items = await base44.entities.MenuItem.filter({ restaurant_id: r.id, is_available: true });
    setMenuItems(items);
  };

  const addToCart = (item) => setCart((c) => ({ ...c, [item.id]: { ...item, qty: (c[item.id]?.qty || 0) + 1 } }));
  const removeFromCart = (item) => {
    const newCart = { ...cart };
    if (newCart[item.id] && newCart[item.id].qty > 1) {
      newCart[item.id].qty -= 1;
    } else {
      delete newCart[item.id];
    }
    setCart(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 || !userCoords) return;
    const fee = selected.delivery_fee || 500;
    setDeliveryFee(fee);
  }, [selected, userCoords]);
  
  const total = subtotal + deliveryFee;

  // Live tracking on success screen
  const [finalTotal, setFinalTotal] = useState(0);
  const [liveOrder, setLiveOrder] = useState(null);
  useEffect(() => {
    if (!success?.id) return undefined;
    let isMounted = true;
    const unsub = base44.entities.FoodOrder.subscribe((ev) => {
      if (isMounted && ev.type === "update" && ev.id === success.id) setLiveOrder(ev.data);
    });
    const interval = setInterval(async () => {
      if (isMounted) {
        const list = await base44.entities.FoodOrder.filter({ id: success.id });
        if (list[0]) setLiveOrder(list[0]);
      }
    }, 3000);
    return () => {isMounted = false;clearInterval(interval);if (typeof unsub === 'function') unsub();};
  }, [success?.id]);
  const displayOrder = liveOrder || success;

  const placeOrder = async () => {
    if (!form.customer_name?.trim()) {
      toast.error("Please enter your name.");
      return;
    }
    if (!form.customer_phone?.trim()) {
      toast.error("Please enter your phone number.");
      return;
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.customer_email)) {
      toast.error("Please enter a valid email address.");
      return;
    }
    if (!form.delivery_address?.trim()) {
      toast.error("Please enter your delivery address.");
      return;
    }
    if (cartItems.length === 0) {
      toast.error("Please add items to your cart.");
      return;
    }
    setError(null);
    setPlacing(true);

    const optimisticOrder = {
      id: "pending-" + Date.now(),
      restaurant_id: selected.id,
      restaurant_name: selected.restaurant_name,
      status: "pending",
      customer_name: form.customer_name
    };

    try {
      runOptimisticOrder(optimisticOrder, async () => {
        let finalTotal = total;
        let discountPercent = 0;

        if (form.promo_code) {
          const promos = await base44.entities.PromoCode.filter({ code: form.promo_code, is_active: true });
          if (promos.length > 0 && promos[0].uses_count < (promos[0].max_uses || 999)) {
            discountPercent = promos[0].discount_percent;
            finalTotal = total - total * discountPercent / 100;
            await base44.entities.PromoCode.update(promos[0].id, { uses_count: (promos[0].uses_count || 0) + 1 });
          }
        }

        const order = await base44.entities.FoodOrder.create({
          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,
          total: finalTotal,
          promo_code: form.promo_code || null,
          discount_percent: discountPercent,
          payment_method: paymentMethod,
          status: "pending",
          ...form
        });

        if (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(() => {});
        }

        if (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
          }).catch(() => {});
        }

        clearDraft();
        setFinalTotal(finalTotal);

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

        setTimeout(() => {
          navigate(`/track-food?id=${order.id}`);
        }, 1000);

        return order;
      });
    } catch (err) {
      setError(err);
    } finally {
      setPlacing(false);
    }
  };

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

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

  // Success screen
  if (success) {
    const isLive = displayOrder?.status === "preparing" || displayOrder?.status === "picked_up";
    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">
          <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?.driver_name ? "Preparing & Delivery" : "Order Placed!"}
          </h2>
          <p className="text-muted-foreground mb-1">
            {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>{selected.restaurant_name}</strong>.</></>
            }
          </p>
          <p className="text-muted-foreground text-sm mb-6">
            {paymentMethod === 'mmg' ? 'Pay via MMG Mobile Money.' : paymentMethod === 'card' ? 'Pay by card on delivery.' : 'Pay cash to the driver on delivery.'} 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>
          }
          <a href={`/track-food?id=${success.id}`}>
            <Button className="w-full rounded-full mb-3">Track My Order</Button>
          </a>
          <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={user?.email || form.customer_email}
            onEntityUpdate={(id, data) => base44.entities.FoodOrder.update(id, data)}
            onCancelled={() => {}} />
          {user &&
            <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>
          }
          {!user &&
            <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 pt-[max(12px,env(safe-area-inset-top,12px))]">
          <button onClick={() => navigate("/home")} className="w-11 h-11 rounded-full bg-white shadow-lg flex items-center justify-center active:scale-95 transition-transform"><ChevronLeft className="w-5 h-5 text-gray-800" /></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">
        <SEOSchema page="food" />
        {showCart &&
        <FoodCheckoutDrawer
          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 || ""} />
        }
        {/* Restaurant Branded Header */}
        <div 
          className="sticky top-0 z-50 px-0 flex-shrink-0 pt-[max(12px,env(safe-area-inset-top,12px))] md:hidden shadow-2xl"
          style={{ 
            background: selected.brand_primary_color || selected.brand_secondary_color ?
              `linear-gradient(135deg, ${selected.brand_secondary_color || '#FF6B6B'} 0%, ${selected.brand_primary_color || '#EE5A6F'} 50%, ${selected.brand_secondary_color || '#FF6B6B'} 100%)` :
              'linear-gradient(135deg, #FF6B6B 0%, #EE5A6F 50%, #FF8787 100%)'
          }}
        >
          <div className="bg-gradient-to-b from-white/15 to-white/5 backdrop-blur-md px-4 py-4">
            <div className="flex items-center gap-3">
              <button onClick={() => setSelected(null)} className="p-3 hover:bg-white/25 active:bg-white/35 rounded-full transition-all flex-shrink-0 shadow-md" aria-label="Go back">
                <ChevronLeft className="w-7 h-7 text-white drop-shadow-md" />
              </button>
              <div className="flex-1 min-w-0 flex flex-col">
                <p className="text-2xl font-black text-white truncate leading-tight drop-shadow-lg tracking-tight">{selected.restaurant_name}</p>
                <p className="text-base text-white/95 font-bold mt-1 flex items-center gap-2">
                  <span className="text-xl">{selected.cuisine_type ? '🍽️' : '🏪'}</span>
                  {selected.cuisine_type || 'Restaurant'}
                </p>
              </div>
              <button 
                onClick={() => setShowCart(!showCart)} 
                className="relative flex items-center gap-3 bg-white text-gray-900 rounded-full px-6 py-3.5 text-base font-black flex-shrink-0 shadow-xl active:scale-95 transition-all hover:bg-white/95 hover:shadow-2xl border-2 border-white/50"
              >
                <ShoppingCart className="w-6 h-6" />
                {cartItems.length > 0 && (
                  <>
                    <span className="font-black text-base">{cartItems.reduce((s, i) => s + i.qty, 0)}</span>
                    <span className="absolute -top-2 -right-2 w-7 h-7 bg-gradient-to-r from-orange-500 to-red-500 border-2 border-white rounded-full text-xs flex items-center justify-center font-black shadow-lg text-white">
                      {cartItems.reduce((s, i) => s + i.qty, 0)}
                    </span>
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
        
        {/* Search box */}
        <div className="mb-5 sticky top-[80px] z-10 bg-background pb-3 px-3 max-w-2xl mx-auto">
          <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-24 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 sticky top-[128px] bg-background py-2 z-10 border-b border-border">
                    <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>
      </div>
    );
  }

  return null;
}