"use client";

import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import DashboardLayout from '@/components/layout/DashboardLayout';
import { ChevronLeft, ChevronRight, ShoppingBag, Star, MapPin, Search } from 'lucide-react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation, Pagination as SwiperPagination, Autoplay } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';

import apis, { BUCKET_ROOT } from '@/utils/apis';
import { useGlobalContext } from '@/context/Provider';
import { logEvent } from '@/utils/analytics';

import { currency, getValidImage } from '@/lib/utils';
import { useRouter, useParams, useSearchParams } from 'next/navigation';
import { Modal } from '@/components/ui/modal';
import { Button } from '@/components/ui/button';
import { parseCookies } from 'nookies';
import { Textarea } from '@/components/ui/textarea';
import { COOKIES_USER_ACCESS_TOKEN } from '@/context/actionTypes';
import { useSelector } from 'react-redux';
import { RootState } from '@/store/store';
import CartSidebar, { CartItem } from '@/components/grocery/CartSidebar';
import HeroSection from '@/components/grocery/HeroSection';
import PromoCards from '@/components/grocery/PromoCards';
import CategoryNav from '@/components/grocery/CategoryNav';
import ProductCard from '@/components/grocery/ProductCard';

const GroceryPage = () => {
    const orange = "hsl(var(--brand-500))";
    const { id: restaurantId } = useParams();
    const searchParams = useSearchParams();
    const categoryType = searchParams.get('type') || 'grocery';
    const [cartItems, setCartItems] = useState<CartItem[]>([]);
    const [isCartOpen, setIsCartOpen] = useState(false);
    const { Toast, userInfo } = useGlobalContext();
    const router = useRouter();

    const [isInitialized, setIsInitialized] = useState(false);
    const [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false);
    const [pendingProduct, setPendingProduct] = useState<any>(null);

    const [storeInfo, setStoreInfo] = useState<any>(null);
    const [reportReasons, setReportReasons] = useState<any[]>([]);
    const [selectedReason, setSelectedReason] = useState<string>("");
    const [queryText, setQueryText] = useState("");
    const [queryImage, setQueryImage] = useState("");
    const [isUploading, setIsUploading] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [uploadFile, setUploadFile] = useState<File | null>(null);
    const [isQueryModalOpen, setIsQueryModalOpen] = useState(false);
    const fileInputRef = useRef<HTMLInputElement>(null);

    useEffect(() => {
        const savedInfo = localStorage.getItem("restaurant_delivery_info");
        if (savedInfo) {
            try {
                setStoreInfo(JSON.parse(savedInfo));
            } catch (e) {
                console.error(e);
            }
        }
        const fetchReasons = async () => {
            try {
                const res = await apis.Auth.getReport("type=customer_restaurant");
                if (res?.data && res.data.length > 0) {
                    setReportReasons(res.data);
                    setSelectedReason(res.data[0]._id); // Automatically assign first reason for API payload validation
                }
            } catch (err) {
                console.error("Error fetching report reasons:", err);
            }
        };
        fetchReasons();
    }, []);

    const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        if (!file) return;

        const maxFileSize = 5 * 1024 * 1024; // 5MB Limit
        const allowedTypes = ["image/jpeg", "image/png", "image/jpg"];

        if (!allowedTypes.includes(file.type)) {
            Toast.error("Only JPG and PNG images are allowed.");
            return;
        }

        if (file.size > maxFileSize) {
            Toast.error("Image size cannot be more than 5MB.");
            return;
        }

        try {
            setIsUploading(true);
            const apiRes = await apis.Common.uploadFile("file", file);
            if (apiRes?.key) {
                setQueryImage(apiRes.key);
                setUploadFile(file);
                Toast.success("Image uploaded successfully!");
            }
        } catch (error) {
            Toast.error(error);
        } finally {
            setIsUploading(false);
        }
    };

    const handleSubmitQuery = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!userInfo) {
            Toast.error("Please log in to submit a query.");
            return;
        }
        if (!queryText.trim()) {
            Toast.error("Please describe your issue or query.");
            return;
        }

        try {
            setIsSubmitting(true);
            const payload = {
                restaurant_id: Array.isArray(restaurantId) ? restaurantId[0] : (restaurantId || ""),
                query_text: queryText.trim(),
                image: queryImage || undefined,
            };
            await apis.report.customerVendorQuery(payload);
            Toast.success("Your query has been submitted successfully to the vendor.");
            setQueryText("");
            setQueryImage("");
            setUploadFile(null);
            if (fileInputRef.current) {
                fileInputRef.current.value = "";
            }
            setIsQueryModalOpen(false);
        } catch (error) {
            Toast.error(error);
        } finally {
            setIsSubmitting(false);
        }
    };

    useEffect(() => {
        const loadCartAndCheckNotification = () => {
            const savedCart = localStorage.getItem('groceryCartItems');
            if (savedCart) {
                setCartItems(JSON.parse(savedCart));
            }
            const vendorNotification = localStorage.getItem('vendorCartNotification');
            if (vendorNotification === 'true') {
                localStorage.removeItem('vendorCartNotification');
                // Auto-open cart sidebar after a short delay so items are loaded
                setTimeout(() => setIsCartOpen(true), 300);
            }
            const savedInfo = localStorage.getItem("restaurant_delivery_info");
            if (savedInfo) {
                try {
                    setStoreInfo(JSON.parse(savedInfo));
                } catch (e) {
                    console.error(e);
                }
            }
        };

        loadCartAndCheckNotification();
        setIsInitialized(true);

        const handleToggle = () => setIsCartOpen(prev => !prev);
        window.addEventListener('toggle-grocery-cart', handleToggle);
        window.addEventListener('vendor-cart-updated', loadCartAndCheckNotification);

        return () => {
            window.removeEventListener('toggle-grocery-cart', handleToggle);
            window.removeEventListener('vendor-cart-updated', loadCartAndCheckNotification);
        };
    }, []);

    useEffect(() => {
        if (!isInitialized) return;
        localStorage.setItem('groceryCartItems', JSON.stringify(cartItems));
        window.dispatchEvent(new CustomEvent('grocery-cart-updated', { detail: cartItems.length }));
    }, [cartItems, isInitialized]);

    const addToCart = useCallback((product: any) => {
        const productId = product._id || product.id;
        const incomingRestaurantId = product.restaurant_id || product.restaurantId || restaurantId;

        const currentCartRestaurantId = cartItems.length > 0 ? String(cartItems[0].restaurantId) : undefined;
        const targetRestaurantId = incomingRestaurantId ? String(incomingRestaurantId) : undefined;

        if (currentCartRestaurantId && targetRestaurantId && currentCartRestaurantId !== targetRestaurantId) {
            setPendingProduct(product);
            setIsConfirmModalOpen(true);
            return;
        }

        const hasDiscount = (product.is_discount_active !== false) &&
            product.discounted_price !== undefined &&
            product.discounted_price !== null &&
            Number(product.discounted_price) > 0 &&
            Number(product.discounted_price) < Number(product.price);

        const effectivePrice = hasDiscount ? Number(product.discounted_price) : Number(product.price || product.base_price || product.original_price || 0);

        logEvent("add_to_cart", {
            currency: "INR",
            value: effectivePrice,
            items: [{
                item_id: productId,
                item_name: product.name || product.title,
                price: effectivePrice,
                quantity: 1,
                item_category: "grocery"
            }]
        });

        setCartItems(prev => {
            const existing = prev.find(item => item.id === productId);
            if (existing) {
                return prev.map(item =>
                    item.id === productId ? { ...item, quantity: item.quantity + 1 } : item
                );
            }

            if (product.weight && typeof product.price === 'string' && product.price.includes(currency)) {
                return [...prev, { ...product, id: productId, quantity: 1, restaurantId: targetRestaurantId }];
            }

            return [...prev, {
                id: productId,
                name: product.name,
                weight: `${product.quantity || ''} ${product.unit || ''}`.trim(),
                price: `${currency}${effectivePrice}.00`,
                originalPrice: hasDiscount ? `${currency}${product.price}.00` : undefined,
                image: getValidImage(product.imageUrl),
                quantity: 1,
                restaurantId: targetRestaurantId,
                totalStock: product.stock
            }];
        });
    }, [cartItems, restaurantId]);

    const handleConfirmClearCart = () => {
        if (pendingProduct) {
            const productId = pendingProduct._id || pendingProduct.id;
            const incomingRestaurantId = pendingProduct.restaurant_id || pendingProduct.restaurantId || restaurantId;
            const targetRestaurantId = incomingRestaurantId ? String(incomingRestaurantId) : undefined;

            const hasDiscount = (pendingProduct.is_discount_active !== false) &&
                pendingProduct.discounted_price !== undefined &&
                pendingProduct.discounted_price !== null &&
                Number(pendingProduct.discounted_price) > 0 &&
                Number(pendingProduct.discounted_price) < Number(pendingProduct.price);

            const effectivePrice = hasDiscount ? Number(pendingProduct.discounted_price) : Number(pendingProduct.price || pendingProduct.base_price || pendingProduct.original_price || 0);

            if (pendingProduct.weight && typeof pendingProduct.price === 'string' && pendingProduct.price.includes(currency)) {
                setCartItems([{ ...pendingProduct, id: productId, quantity: 1, restaurantId: targetRestaurantId }]);
            } else {
                setCartItems([{
                    id: productId,
                    name: pendingProduct.name,
                    weight: `${pendingProduct.quantity || ''} ${pendingProduct.unit || ''}`.trim(),
                    price: `${currency}${effectivePrice}.00`,
                    originalPrice: hasDiscount ? `${currency}${pendingProduct.price}.00` : undefined,
                    image: getValidImage(pendingProduct.imageUrl),
                    quantity: 1,
                    restaurantId: targetRestaurantId,
                    totalStock: pendingProduct.stock
                }]);
            }
            setPendingProduct(null);
        }
        setIsConfirmModalOpen(false);
    };

    const removeFromCart = useCallback((productId: string | number) => {
        setCartItems(prev => {
            const existing = prev.find(item => item.id === productId);
            if (existing && existing.quantity > 1) {
                return prev.map(item =>
                    item.id === productId ? { ...item, quantity: item.quantity - 1 } : item
                );
            }
            return prev.filter(item => item.id !== productId);
        });
    }, []);

    const deleteItem = useCallback((productId: string | number) => {
        setCartItems(prev => prev.filter(item => item.id !== productId));
    }, []);

    const [categories, setCategories] = useState<any[]>([]);
    const [categoriesLoading, setCategoriesLoading] = useState(true);
    const [groceryRestaurants, setGroceryRestaurants] = useState<any[]>([]);
    const [restaurantsLoading, setRestaurantsLoading] = useState(true);
    const [bannerList, setBannerList] = useState<any[]>([]);

    const selectedAddress = useSelector(
        (state: RootState) => state.user.profile.selectedAddress
    );

    const getBanners = async () => {
        try {
            if (!restaurantId) return;
            const res = await apis.Banner.getVendorBanner(String(restaurantId));
            const list = res?.banners || res?.data || (Array.isArray(res) ? res : []);
            setBannerList(list);
        } catch (error) {
            console.error("Banner fetch error:", error);
        }
    };

    const fetchGroceryRestaurants = async () => {
        try {
            setRestaurantsLoading(true);

            const fetchStores = async (lat: number, long: number) => {
                const params = new URLSearchParams({
                    page: "1",
                    limit: "10",
                });
                const payload = {
                    lat,
                    long,
                };
                const response = await apis.restaurant.getGroceryRestaurant(params.toString(), payload);
                if (response?.data) {
                    setGroceryRestaurants(response.data);
                }
                setRestaurantsLoading(false);
            };

            if (selectedAddress?.lat && selectedAddress?.long) {
                fetchStores(parseFloat(selectedAddress.lat), parseFloat(selectedAddress.long));
            } else {
                navigator.geolocation.getCurrentPosition(
                    ({ coords }) => {
                        fetchStores(coords.latitude, coords.longitude);
                    },
                    () => {
                        fetchStores(0, 0);
                    }
                );
            }
        } catch (error) {
            console.error("Error fetching grocery restaurants:", error);
            setRestaurantsLoading(false);
        }
    };


    const fetchCategories = async () => {
        try {
            setCategoriesLoading(true);
            const params = new URLSearchParams({
                store_id: String(restaurantId),
                page: "1",
                limit: "50",
                type: categoryType,
                catering_services: "false",
            });
            const response = await apis.category.get(params.toString());
            if (response?.data) {
                setCategories(response.data);
            }
        } catch (error) {
            Toast.error(error);
        } finally {
            setCategoriesLoading(false);
        }
    };

    const [selectedCategoryId, setSelectedCategoryId] = useState<string>("");
    const [groceryList, setGroceryList] = useState<any[]>([]);
    const [groceryLoading, setGroceryLoading] = useState(true);
    const [page, setPage] = useState(1);
    const [hasMore, setHasMore] = useState(true);
    const [isFetching, setIsFetching] = useState(false);
    const [searchQuery, setSearchQuery] = useState("");
    const [debouncedSearch, setDebouncedSearch] = useState("");

    useEffect(() => {
        const timer = setTimeout(() => {
            setDebouncedSearch(searchQuery);
        }, 500);
        return () => clearTimeout(timer);
    }, [searchQuery]);



    const fetchGroceryList = async (pageNumber: number, categoryId: string = "", searchTerm: string = "") => {
        try {
            if (pageNumber === 1) setGroceryLoading(true);
            setIsFetching(true);

            let query = `page=${pageNumber}&limit=10&store_id=${restaurantId}`;
            if (categoryId) {
                query += `&category_id=${categoryId}`;
            }
            if (searchTerm) {
                query += `&search=${searchTerm}`;
            }

            const response = await apis.Grocery.getGroupedByCategory(query);
            if (response?.data) {
                const grouped = response.data.map((cat: any) => ({
                    ...cat,
                    grocery_items: cat.items || []
                }));

                const allLiveItems = grouped.flatMap((cat: any) => cat.grocery_items || []);
                if (allLiveItems.length > 0) {
                    setCartItems(prevCart => {
                        if (!prevCart || prevCart.length === 0) return prevCart;
                        let hasChanges = false;
                        const updatedCart = prevCart.map(cartItem => {
                            const liveProd = allLiveItems.find((i: any) => String(i._id || i.id) === String(cartItem.id));
                            if (liveProd) {
                                const hasDiscount = (liveProd.is_discount_active !== false) &&
                                    liveProd.discounted_price !== undefined &&
                                    liveProd.discounted_price !== null &&
                                    Number(liveProd.discounted_price) > 0 &&
                                    Number(liveProd.discounted_price) < Number(liveProd.price);

                                const effectivePrice = hasDiscount ? Number(liveProd.discounted_price) : Number(liveProd.price || liveProd.base_price || liveProd.original_price || 0);

                                const newPriceStr = `${currency}${effectivePrice}.00`;
                                const newOrigPriceStr = hasDiscount ? `${currency}${liveProd.price}.00` : undefined;

                                if (cartItem.price !== newPriceStr || cartItem.originalPrice !== newOrigPriceStr) {
                                    hasChanges = true;
                                    return {
                                        ...cartItem,
                                        price: newPriceStr,
                                        originalPrice: newOrigPriceStr,
                                        name: liveProd.name || cartItem.name,
                                        totalStock: liveProd.stock,
                                    };
                                }
                            }
                            return cartItem;
                        });
                        return hasChanges ? updatedCart : prevCart;
                    });
                }

                setGroceryList(prev => {
                    if (pageNumber === 1) return grouped;
                    const merged = [...prev];
                    grouped.forEach((newCategory: any) => {
                        const existingIdx = merged.findIndex(c => c._id === newCategory._id);
                        if (existingIdx !== -1) {
                            const existingIds = new Set(merged[existingIdx].grocery_items?.map((i: any) => i._id) || []);
                            const uniqueItems = (newCategory.grocery_items || []).filter((i: any) => !existingIds.has(i._id));
                            merged[existingIdx] = {
                                ...merged[existingIdx],
                                grocery_items: [...(merged[existingIdx].grocery_items || []), ...uniqueItems]
                            };
                        } else {
                            merged.push(newCategory);
                        }
                    });
                    return merged;
                });

                const pagination = response?.pagination;
                if (pagination) {
                    setHasMore(pageNumber < pagination.totalPages);
                } else if (response.data.length < 10) {
                    setHasMore(false);
                } else {
                    setHasMore(true);
                }

                if (response?.restaurant) {
                    setStoreInfo(response.restaurant);
                    localStorage.setItem("restaurant_delivery_info", JSON.stringify(response.restaurant));
                }
            }
        } catch (error) {
            Toast.error(error);
        } finally {
            setGroceryLoading(false);
            setIsFetching(false);
        }
    };

    useEffect(() => {
        fetchCategories();
        fetchGroceryRestaurants();
        getBanners();
    }, [selectedAddress]);

    useEffect(() => {
        setPage(1);
        setGroceryList([]);
    }, [selectedCategoryId, debouncedSearch]);

    useEffect(() => {
        fetchGroceryList(page, selectedCategoryId, debouncedSearch);
    }, [page, selectedCategoryId, debouncedSearch]);

    const handleCategorySelect = (categoryId: string) => {
        if (selectedCategoryId === categoryId) {
            setSelectedCategoryId("");
        } else {
            setSelectedCategoryId(categoryId);
        }
        setPage(1);
        setGroceryList([]);
    };

    const observerTarget = useRef(null);

    useEffect(() => {
        const observer = new IntersectionObserver(
            entries => {
                if (entries[0].isIntersecting && hasMore && !isFetching) {
                    setPage(prev => prev + 1);
                }
            },
            { threshold: 0.1 }
        );

        if (observerTarget.current) {
            observer.observe(observerTarget.current);
        }

        return () => {
            if (observerTarget.current) {
                observer.unobserve(observerTarget.current);
            }
        };
    }, [hasMore, isFetching]);

    const cartQuantities = useMemo(() => {
        const quantities: Record<string | number, number> = {};
        cartItems.forEach(item => {
            if (String(item.restaurantId) === String(restaurantId)) {
                quantities[item.id] = item.quantity;
            }
        });
        return quantities;
    }, [cartItems, restaurantId]);

    const handleToggleFavorite = useCallback((updatedProduct: any) => {
        setGroceryList(prevList => prevList.map(category => ({
            ...category,
            grocery_items: (category.grocery_items || []).map((item: any) =>
                item._id === updatedProduct._id ? { ...item, is_fav: updatedProduct.is_fav } : item
            )
        })));
    }, []);

    return (
        <div className="relative overflow-x-hidden">
            <div className={`max-w-7xl mx-auto px-4 py-8 space-y-12 transition-all duration-300 ${isCartOpen ? 'mr-[400px]' : ''}`}>
                <HeroSection orange={orange} />

                {/* Dynamic Banners from API */}
                {bannerList.length > 0 && (
                    <div className="w-full">
                        <Swiper
                            slidesPerView={1}
                            spaceBetween={20}
                            pagination={{ clickable: true }}
                            modules={[SwiperPagination, Autoplay]}
                            autoplay={{ delay: 4000, disableOnInteraction: false }}
                            className="w-full h-[250px] rounded-2xl"
                        >
                            {bannerList.map((banner: any) => (
                                <SwiperSlide key={banner._id}>
                                    <div
                                        className="relative w-full h-[250px] rounded-2xl overflow-hidden"
                                    >
                                        <img
                                            src={banner?.banner_url ? (banner.banner_url.startsWith("http") ? banner.banner_url : `${BUCKET_ROOT}${banner.banner_url.startsWith("/") ? banner.banner_url.slice(1) : banner.banner_url}`) : ""}
                                            alt={banner?.title}
                                            className="object-cover w-full h-full rounded-2xl"
                                        />
                                        <div className="absolute inset-0 bg-gradient-to-r from-black/50 to-transparent flex items-center justify-start rounded-2xl">
                                            <div className="p-6 ms-8 max-w-[60%]">
                                                <h3 className="text-white text-2xl font-bold break-words">
                                                    {banner?.title}
                                                </h3>
                                                <p className="text-white/90 text-sm mt-2 break-words">
                                                    {banner?.description}
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                </SwiperSlide>
                            ))}
                        </Swiper>
                    </div>
                )}

                <PromoCards />

                {/* Contact Vendor Trigger Card */}
                <section className="bg-gradient-to-br from-white to-brand-50/20 p-6 md:p-8 rounded-[2.5rem] border border-brand-100/60 shadow-md mt-6 flex flex-col md:flex-row md:items-center justify-between gap-6 transition-all duration-300 hover:scale-[1.005] hover:shadow-lg">
                    <div className="space-y-1">
                        <div className="flex items-center gap-2">
                            <span className="px-3 py-1 bg-brand-100 text-brand-700 text-[10px] font-bold rounded-full uppercase tracking-wider">
                                Vendor Support
                            </span>
                        </div>
                        <h2 className="text-xl font-bold text-gray-900 mt-1">
                            Having an <span className="text-brand-500">Issue or Query</span>?
                        </h2>
                        <p className="text-gray-500 text-sm max-w-2xl">
                            Need help with an order, item availability, or have a question? Ask {storeInfo?.restaurant_name || "the vendor"} directly.
                        </p>
                    </div>
                    <button
                        onClick={() => setIsQueryModalOpen(true)}
                        className="px-6 py-3 bg-brand-500 hover:bg-brand-600 text-white font-bold rounded-xl transition-all shadow-md active:scale-95 whitespace-nowrap text-sm"
                    >
                        Contact Vendor
                    </button>
                </section>

                {/* Store List Section - Now as a Dropdown */}
                <section className="bg-brand-50/50 p-6 rounded-3xl border border-brand-100/50 space-y-4">
                    <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                        <div className="space-y-1">
                            <h2 className="text-2xl font-bold text-gray-900">
                                <span className="text-brand-500">Search Products</span>
                            </h2>
                            <p className="text-sm text-gray-500">Search for products in this store</p>
                        </div>

                        <div className="w-full md:flex-1 flex flex-col md:flex-row justify-end gap-4">
                            <div className="relative w-full md:w-[320px]">
                                <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                                <input
                                    type="text"
                                    placeholder={"Search for products..."}
                                    className="w-full bg-white border border-brand-100 shadow-sm rounded-2xl h-14 pl-12 pr-4 hover:border-brand-300 transition-all focus:ring-2 focus:ring-brand-500 outline-none"
                                    value={searchQuery}
                                    onChange={(e) => setSearchQuery(e.target.value)}
                                />
                            </div>
                        </div>
                    </div>
                </section>

                <CategoryNav
                    categories={categories}
                    loading={categoriesLoading}
                    selectedCategoryId={selectedCategoryId}
                    onCategorySelect={handleCategorySelect}
                />

                {groceryLoading ? (
                    <div className="space-y-12">
                        {Array.from({ length: 2 }).map((_, i) => (
                            <section key={i} className="space-y-8">
                                <div className="h-10 w-48 bg-gray-200 rounded animate-pulse" />
                                <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-6">
                                    {Array.from({ length: 5 }).map((_, j) => (
                                        <div key={j} className="aspect-square bg-gray-100 rounded-[2rem] animate-pulse" />
                                    ))}
                                </div>
                            </section>
                        ))}
                    </div>
                ) : groceryList.length > 0 ? (
                    groceryList.map((category) => (
                        <section key={category._id} className="space-y-8">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-4">
                                    <h2 className="text-3xl font-bold text-gray-900">{category.category_name}</h2>
                                </div>
                                <div className="flex gap-3">
                                    <button className={`prev-${category._id} w-11 h-11 rounded-full border border-gray-200 bg-white flex items-center justify-center hover:border-brand-200 hover:text-brand-500 transition-all active:scale-90 disabled:opacity-30 disabled:cursor-not-allowed group shadow-sm`}>
                                        <ChevronLeft className="w-5 h-5 text-gray-500 group-hover:text-brand-500" />
                                    </button>
                                    <button
                                        className={`next-${category._id} w-11 h-11 rounded-full bg-brand-500 flex items-center justify-center text-white transition-all active:scale-90 shadow-lg shadow-brand-200/50 hover:bg-brand-600 disabled:opacity-30 disabled:cursor-not-allowed`}
                                    >
                                        <ChevronRight className="w-5 h-5" />
                                    </button>
                                </div>
                            </div>

                            <div className="relative group">
                                <Swiper
                                    modules={[Navigation]}
                                    spaceBetween={25}
                                    slidesPerView={1}
                                    navigation={{
                                        prevEl: `.prev-${category._id}`,
                                        nextEl: `.next-${category._id}`,
                                    }}
                                    breakpoints={{
                                        480: { slidesPerView: 2 },
                                        768: { slidesPerView: 3 },
                                        1024: { slidesPerView: 4 },
                                        1280: { slidesPerView: 5 },
                                    }}
                                    className="product-swiper !py-4"
                                >
                                    {(category.grocery_items || []).map((product: any) => (
                                        <SwiperSlide key={product._id}>
                                            <ProductCard
                                                product={{ ...product, restaurant_id: restaurantId }}
                                                quantity={cartQuantities[product._id] || 0}
                                                onAdd={addToCart}
                                                onRemove={removeFromCart}
                                                onToggleFavorite={handleToggleFavorite}
                                            />
                                        </SwiperSlide>
                                    ))}
                                </Swiper>
                            </div>
                            {(category.grocery_items || []).length > 5 && (
                                <div className="flex justify-center mt-6">
                                    <button
                                        onClick={() => router.push(`/grocery/category/${category.slug?.toLowerCase() || category.category_name.toLowerCase()}?restaurantId=${restaurantId}`)}
                                        className="px-8 py-3 rounded-full bg-brand-50 text-brand-500 font-bold hover:bg-brand-100 transition-all flex items-center gap-2 shadow-sm border border-brand-100"
                                    >
                                        {"See All " + category.category_name} <ChevronRight className="w-5 h-5 ml-1" />
                                    </button>
                                </div>
                            )}
                        </section>
                    ))
                ) : (
                    <div className="flex flex-col items-center justify-center py-20 text-center animate-in fade-in zoom-in duration-500">
                        <div className="relative mb-8">
                            {/* Brand purple glow effect */}
                            <div className="absolute inset-0 bg-brand-500/10 blur-3xl rounded-full" />

                            {/* Icon Container */}
                            <div className="relative w-32 h-32 bg-white rounded-full flex items-center justify-center border-4 border-brand-100 shadow-xl shadow-brand-50">
                                <svg width="64" height="64" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M30 35H70V75C70 77.7614 67.7614 80 65 80H35C32.2386 80 30 77.7614 30 75V35Z" stroke="#000000" strokeWidth="5" strokeLinejoin="round" />
                                    <path d="M40 35V30C40 24.4772 44.4772 20 50 20C55.5228 20 60 24.4772 60 30V35" stroke="#000000" strokeWidth="5" strokeLinecap="round" />
                                    <path d="M45 55C45 55 47 62 50 62C53 62 55 55 55 55" stroke="#000000" strokeWidth="5" strokeLinecap="round" />
                                </svg>
                            </div>
                        </div>

                        <h3 className="text-3xl font-black text-gray-900 mb-3">No Items Found</h3>
                        <p className="text-gray-500 max-w-sm mx-auto mb-10 text-lg leading-relaxed">
                            We couldn't find any items matching your search or in this category. Try a different term or clear the filter.
                        </p>

                        {(selectedCategoryId || searchQuery) && (
                            <button
                                onClick={() => {
                                    if (selectedCategoryId) setSelectedCategoryId("");
                                    if (searchQuery) setSearchQuery("");
                                }}
                                className="px-12 py-4 bg-brand-500 text-white rounded-full font-bold shadow-2xl shadow-brand-200 hover:bg-brand-600 hover:-translate-y-1 transition-all active:scale-95 text-lg"
                            >
                                Clear Filters
                            </button>
                        )}
                    </div>
                )}
                {isFetching && page > 1 && (
                    <div className="flex justify-center py-8">
                        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                    </div>
                )}
                <div ref={observerTarget} className="h-4 w-full" />


            </div>

            <Modal
                title={`Contact ${storeInfo?.restaurant_name || "Vendor"}`}
                description="Describe your issue or query below. You can also attach an image to help explain."
                isOpen={isQueryModalOpen}
                onClose={() => {
                    setIsQueryModalOpen(false);
                    setQueryText("");
                    setQueryImage("");
                    setUploadFile(null);
                    if (fileInputRef.current) {
                        fileInputRef.current.value = "";
                    }
                }}
                disableOverflow={false}
            >
                <form onSubmit={handleSubmitQuery} className="space-y-6 pt-4">
                    <div className="space-y-2">
                        <label className="block text-sm font-bold text-gray-700">
                            Describe your issue or query <span className="text-red-500">*</span>
                        </label>
                        <Textarea
                            placeholder="Provide details about your query..."
                            value={queryText}
                            onChange={(e: any) => setQueryText(e.target.value)}
                            maxLength={500}
                            className="w-full min-h-[120px] bg-white border border-brand-100 rounded-2xl p-4 hover:border-brand-300 transition-all focus:ring-2 focus:ring-brand-500 outline-none resize-none"
                        />
                        <div className="text-right text-xs text-gray-400">
                            {queryText.length}/500 characters
                        </div>
                    </div>

                    <div className="space-y-2">
                        <label className="block text-sm font-bold text-gray-700">
                            Attach an image (Optional)
                        </label>

                        {uploadFile || queryImage ? (
                            <div className="border border-brand-200 bg-white rounded-3xl p-4 flex flex-col items-center justify-center relative min-h-[180px]">
                                <button
                                    type="button"
                                    onClick={() => {
                                        setUploadFile(null);
                                        setQueryImage("");
                                        if (fileInputRef.current) {
                                            fileInputRef.current.value = "";
                                        }
                                    }}
                                    className="absolute top-3 right-3 w-8 h-8 rounded-full bg-red-50 text-red-500 hover:bg-red-100 flex items-center justify-center transition-all"
                                >
                                    ✖
                                </button>
                                <img
                                    src={uploadFile ? URL.createObjectURL(uploadFile) : (queryImage ? (queryImage.startsWith("http") ? queryImage : `${BUCKET_ROOT}${queryImage.startsWith("/") ? queryImage.slice(1) : queryImage}`) : "")}
                                    alt="Preview"
                                    className="max-h-[140px] w-auto rounded-2xl object-contain shadow-md"
                                />
                                <p className="text-xs text-gray-500 mt-2 font-medium">
                                    {uploadFile?.name || "Uploaded image"}
                                </p>
                            </div>
                        ) : (
                            <div
                                onClick={() => document.getElementById("modal-query-image-upload")?.click()}
                                className="border-2 border-dashed border-brand-200 bg-brand-50/20 hover:bg-brand-50/50 hover:border-brand-400 rounded-3xl p-6 flex flex-col items-center justify-center cursor-pointer transition-all min-h-[180px] group"
                            >
                                <div className="w-12 h-12 rounded-full bg-brand-100 flex items-center justify-center mb-3 group-hover:scale-110 transition-transform">
                                    {isUploading ? (
                                        <span className="w-5 h-5 border-2 border-brand-500 border-t-transparent rounded-full animate-spin" />
                                    ) : (
                                        <svg className="w-6 h-6 text-brand-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                        </svg>
                                    )}
                                </div>
                                <p className="text-sm font-bold text-gray-700">
                                    {isUploading ? "Uploading file..." : "Click to upload an image"}
                                </p>
                                <p className="text-xs text-gray-400 mt-1">
                                    Supports JPG, JPEG, PNG (Max 5MB)
                                </p>
                            </div>
                        )}
                        <input
                            ref={fileInputRef}
                            type="file"
                            id="modal-query-image-upload"
                            accept=".jpg,.jpeg,.png"
                            className="hidden"
                            onChange={handleFileChange}
                            disabled={isUploading}
                        />
                    </div>

                    <div className="flex gap-3 pt-2">
                        <Button
                            type="button"
                            variant="outline"
                            className="flex-1 rounded-2xl h-12"
                            onClick={() => {
                                setIsQueryModalOpen(false);
                                setQueryText("");
                                setQueryImage("");
                                setUploadFile(null);
                                if (fileInputRef.current) {
                                    fileInputRef.current.value = "";
                                }
                            }}
                        >
                            Cancel
                        </Button>
                        <button
                            type="submit"
                            disabled={isSubmitting || isUploading}
                            className="flex-grow flex-1 h-12 bg-brand-500 hover:bg-brand-600 text-white font-bold rounded-2xl transition-all shadow-lg shadow-brand-500/25 active:scale-95 disabled:opacity-50 disabled:pointer-events-none flex items-center justify-center gap-2"
                        >
                            {isSubmitting ? (
                                <>
                                    <span className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" />
                                    Submitting...
                                </>
                            ) : (
                                "Send to Vendor"
                            )}
                        </button>
                    </div>
                </form>
            </Modal>

            <CartSidebar
                isOpen={isCartOpen}
                onClose={() => setIsCartOpen(false)}
                items={cartItems}
                onAdd={addToCart}
                onRemove={removeFromCart}
                onDeleteItem={deleteItem}
                orange={orange}
                onClearCart={() => setCartItems([])}
            />

            <Modal
                title="Replace cart item?"
                description="Your cart contains items from another store. Do you want to discard the selection and add items from this store instead?"
                isOpen={isConfirmModalOpen}
                onClose={() => setIsConfirmModalOpen(false)}
            >
                <div className="flex justify-end gap-3 mt-4">
                    <Button variant="outline" onClick={() => setIsConfirmModalOpen(false)}>
                        Cancel
                    </Button>
                    <Button
                        style={{ backgroundColor: orange }}
                        className="text-white"
                        onClick={handleConfirmClearCart}
                    >
                        OK
                    </Button>
                </div>
            </Modal>
        </div>
    );
};

export default function Grocery() {
    return (
        <DashboardLayout>
            <GroceryPage />
        </DashboardLayout>
    );
}