import React, { useState, useEffect, useMemo } from "react"; import { View, ScrollView, Image, Alert, Platform, TouchableOpacity, } from "react-native"; import { useRouter } from "expo-router"; import { tw, useManualRefresh, AppContainer, useMarkDataFetchers, MyText, MyTextInput, MyTouchableOpacity, BottomDropdown, BottomDialog , Quantifier } from "common-ui"; import MaterialIcons from "@expo/vector-icons/MaterialIcons"; import { useHideTabNav } from "@/src/hooks/useHideTabNav"; import { useAuth } from "@/src/contexts/AuthContext"; import TestingPhaseNote from "@/components/TestingPhaseNote"; import dayjs from "dayjs"; import { trpc } from "@/src/trpc-client"; import { useCentralProductStore } from '@/src/store/centralProductStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks'; import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks'; import CheckoutAddressSelector from '@/components/CheckoutAddressSelector'; import LoginWall from '@/components/LoginWall'; import { useAddressStore } from '@/src/store/addressStore'; import { useCheckoutStore } from '@/src/store/checkoutStore'; import type { FlashDeliveryProps } from '@packages/shared'; const formatDeliverySlot = (deliveryTime: string): string => { const time = dayjs(deliveryTime); const endTime = time.add(1, 'hour'); const startPeriod = time.format('A'); const endPeriod = endTime.format('A'); const range = startPeriod === endPeriod ? `${time.format('h')}-${endTime.format('h')} ${startPeriod}` : `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}`; return `${time.format('ddd, DD MMM ')}${range}`; }; interface DeliverySlotGroupItem { id: number; name: string; quantity: number; unitNotation?: string; image?: string; } interface DeliverySlotGroup { slotId: number; label: string; items: DeliverySlotGroupItem[]; } interface DeliverySlotMergeSuggestion { slotId: number; label: string; } function DeliverySlotSummary({ groups, mergeSuggestion, onMerge, }: { groups: DeliverySlotGroup[]; mergeSuggestion?: DeliverySlotMergeSuggestion | null; onMerge?: () => void; }) { const [openGroup, setOpenGroup] = useState(null); if (groups.length === 0) return null; return ( Delivery Slot {groups.map((group, index) => ( 0 ? tw`border-t border-gray-100` : {}, ]} > {group.label} setOpenGroup(group)} activeOpacity={0.7} > {group.items.length} {group.items.length === 1 ? 'item' : 'items'} ))} {!!mergeSuggestion && ( Deliver All items at {mergeSuggestion.label} )} setOpenGroup(null)}> Items {openGroup?.label} setOpenGroup(null)} style={tw`p-1`}> {openGroup?.items.map((item) => ( {item.name} {!!item.unitNotation && ( {item.unitNotation} )} x{item.quantity} ))} ); } export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps) { // Hide tabs when cart page is active useHideTabNav(); const { isAuthenticated, isLoading: isAuthLoading } = useAuth(); const cartType: "regular" | "flash" = isFlashDelivery ? "flash" : "regular"; const { selectedAddressId, setSelectedAddressId } = useAddressStore(); const userNotes = useCheckoutStore((state) => state.userNotes); const setUserNotes = useCheckoutStore((state) => state.setUserNotes); const [quantities, setQuantities] = useState>({}); const { data: cartData, isLoading, error, refetch: refetchCart, } = useGetCart({ refetchOnWindowFocus: true }, cartType); // Extract product IDs from cart items const productIds = cartData?.items.map(item => item.skuId) || []; // Get cart slots for the products in cart const { data: slotsData, refetch: refetchSlots, isLoading: isSlotsLoading } = trpc.user.cart.getCartSlots.useQuery( { productIds }, { enabled: productIds.length > 0, refetchOnWindowFocus: false } ); const generateCouponDescription = (coupon: any): string => { let desc = ""; if (coupon.discountPercent) { desc += `${coupon.discountPercent}% off`; } else if (coupon.flatDiscount) { desc += `₹${coupon.flatDiscount} off`; } if (coupon.minOrder) { desc += ` on orders above ₹${coupon.minOrder}`; } if (coupon.maxValue) { desc += ` (max discount ₹${coupon.maxValue})`; } return desc; }; const { data: couponsRaw, error: couponsError } = trpc.user.coupon.getEligible.useQuery( undefined, { enabled: isAuthenticated } ); const constsData = useRegionalConsts(); const products = useCentralProductStore((state) => state.products); const productsById = useCentralProductStore((state) => state.productsById); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); const cartItems = cartData?.items || []; // Memoized flash-eligible product IDs const flashEligibleProductIds = useMemo(() => { if (!products.length) return new Set(); return new Set( products .filter((product) => productSlotsMap[product.id]?.isFlashAvailable) .map((product) => product.id) ); }, [products, productSlotsMap]); // Base total price without discounts for coupon eligibility check const baseTotalPrice = useMemo( () => cartItems .filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock) .reduce((sum, item) => { const product = productsById[item.skuId]; const price = product?.price || 0; return sum + price * (quantities[item.id] || item.quantity); }, 0), [cartItems, quantities, productsById] ); const eligibleCoupons = useMemo(() => { if (!couponsRaw?.data) return []; return couponsRaw.data .map((coupon) => { let isEligible = true; let ineligibilityReason = ""; if ( coupon.maxLimitForUser && coupon.usages.length >= coupon.maxLimitForUser ) { isEligible = false; ineligibilityReason = "Usage limit exceeded"; } if (coupon.minOrder && parseFloat(coupon.minOrder) > baseTotalPrice) { isEligible = false; ineligibilityReason = `Min order ₹${coupon.minOrder}`; } return { id: coupon.id, code: coupon.couponCode, discountType: coupon.discountPercent ? "percentage" : "flat", discountValue: parseFloat( coupon.discountPercent || coupon.flatDiscount || "0" ), maxValue: coupon.maxValue ? parseFloat(coupon.maxValue) : undefined, minOrder: coupon.minOrder ? parseFloat(coupon.minOrder) : undefined, description: generateCouponDescription(coupon), exclusiveApply: coupon.exclusiveApply, isEligible, ineligibilityReason: isEligible ? undefined : ineligibilityReason, }; }) .filter( (coupon) => coupon.ineligibilityReason !== "Usage limit exceeded" ); }, [couponsRaw, baseTotalPrice]); const updateCartItem = useUpdateCartItem({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true }, cartType); const removeFromCart = useRemoveFromCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true }, cartType); useMarkDataFetchers(() => { refetchCart(); refetchSlots(); }); useManualRefresh(() => { refetchCart(); refetchSlots(); }); const [selectedSlots, setSelectedSlots] = useState>({}); const [selectedCouponId, setSelectedCouponId] = useState(null); const [couponDialogOpen, setCouponDialogOpen] = useState(false); const router = useRouter(); // Get available slots for a specific product const getAvailableSlotsForProduct = React.useMemo(() => { return (productId: number) => { if (!slotsData || !slotsData[productId]) return []; return slotsData[productId] .filter((slot) => dayjs(slot.deliveryTime).isAfter(dayjs())) .map((slot) => { const formatTimeRange = (deliveryTime: string) => { const time = dayjs(deliveryTime); const endTime = time.add(1, 'hour'); const startPeriod = time.format('A'); const endPeriod = endTime.format('A'); let timeRange; if (startPeriod === endPeriod) { timeRange = `${time.format('h')}-${endTime.format('h')} ${startPeriod}`; } else { timeRange = `${time.format('h:mm')} ${startPeriod} - ${endTime.format('h:mm')} ${endPeriod}`; } return `${time.format('ddd, DD MMM ')}${timeRange}`; }; return { label: `Delivery: ${formatTimeRange(slot.deliveryTime)} - Close time: ${dayjs(slot.freezeTime).format("h:mm a")}`, value: slot.id, }; }); }; }, [slotsData]); // Calculate coupon discount const selectedCoupons = useMemo( () => selectedCouponId ? eligibleCoupons?.filter( (coupon) => coupon.id === selectedCouponId && coupon.isEligible ) : [], [eligibleCoupons, selectedCouponId] ); const totalPrice = cartItems .filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock) .reduce((sum, item) => { const product = productsById[item.skuId]; const quantity = quantities[item.id] || item.quantity; const price = isFlashDelivery ? (product?.flashPrice ?? product?.price ?? 0) : (product?.price || 0); return sum + Number(price) * quantity; }, 0); // Total savings = sum of (market price - offered price) * quantity, per in-stock item. const totalSavings = cartItems .filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock) .reduce((sum, item) => { const product = productsById[item.skuId]; const quantity = quantities[item.id] || item.quantity; const marketPrice = Number(product?.marketPrice || 0); const price = isFlashDelivery ? (product?.flashPrice ?? product?.price ?? 0) : (product?.price || 0); const saving = marketPrice - Number(price); return sum + (saving > 0 ? saving : 0) * quantity; }, 0); const dropdownData = useMemo( () => eligibleCoupons?.map((coupon) => { const discount = coupon.discountType === "percentage" ? Math.min( (totalPrice * coupon.discountValue) / 100, coupon.maxValue || Infinity ) : Math.min(coupon.discountValue, coupon.maxValue || totalPrice); const saveString = !isNaN(discount) ? ` (Save ₹${discount})` : ""; const baseLabel = `${coupon.code} - ${coupon.description}${coupon.isEligible ? saveString : "" }`; const label = coupon.isEligible ? baseLabel : `${baseLabel} (${coupon.ineligibilityReason})`; return { label, value: coupon.id, disabled: !coupon.isEligible, }; }) || [], [eligibleCoupons, totalPrice] ); const discountAmount = useMemo( () => selectedCoupons?.reduce( (sum, coupon) => sum + (coupon.discountType === "percentage" ? Math.min( (totalPrice * coupon.discountValue) / 100, coupon.maxValue || Infinity ) : Math.min(coupon.discountValue, coupon.maxValue || totalPrice)), 0 ) || 0, [selectedCoupons, totalPrice] ); const finalTotal = totalPrice - discountAmount; const deliveryCharge = useMemo( () => { const threshold = isFlashDelivery ? constsData?.flashFreeDeliveryThreshold : constsData?.freeDeliveryThreshold; const charge = isFlashDelivery ? constsData?.flashDeliveryCharge : constsData?.deliveryCharge; return finalTotal < threshold ? charge : 0; }, [finalTotal, constsData, isFlashDelivery] ); const freeDeliveryThreshold = useMemo( () => { return isFlashDelivery ? constsData?.flashFreeDeliveryThreshold : constsData?.freeDeliveryThreshold; }, [constsData, isFlashDelivery] ); const finalTotalWithDelivery = finalTotal + deliveryCharge; const hasAvailableItems = cartItems.some(item => !productSlotsMap[item.skuId]?.isOutOfStock); const slotGroups = useMemo(() => { if (isFlashDelivery || cartItems.length === 0) return []; const groupMap = new Map(); cartItems.forEach((item) => { const slotId = selectedSlots[item.id]; if (slotId === undefined || slotId === null) return; if (!groupMap.has(slotId)) { let label = ''; if (slotsData) { for (const productId of Object.keys(slotsData)) { const slot = slotsData[Number(productId)]?.find((s) => s.id === slotId); if (slot) { label = formatDeliverySlot(slot.deliveryTime); break; } } } groupMap.set(slotId, { slotId, label, items: [] }); } const product = productsById[item.skuId]; groupMap.get(slotId)!.items.push({ id: item.id, name: product?.name || 'Item', quantity: quantities[item.id] || item.quantity, unitNotation: product?.unitNotation, image: product?.images?.[0], }); }); return Array.from(groupMap.values()).sort((a, b) => a.slotId - b.slotId); }, [isFlashDelivery, cartItems, selectedSlots, slotsData, productsById, quantities]); const mergeSuggestion = useMemo(() => { if (isFlashDelivery || slotGroups.length <= 1) return null; // slotGroups is sorted by slot id, so ties keep the lowest id. const majority = slotGroups.reduce((best, group) => group.items.length > best.items.length ? group : best ); const inStockItems = cartItems.filter( (item) => !productSlotsMap[item.skuId]?.isOutOfStock ); const now = dayjs(); const feasible = inStockItems.length > 0 && inStockItems.every((item) => (slotsData?.[item.skuId] || []).some( (slot) => slot.id === majority.slotId && dayjs(slot.deliveryTime).isAfter(now) ) ); if (!feasible) return null; return { slotId: majority.slotId, label: majority.label }; }, [isFlashDelivery, slotGroups, cartItems, productSlotsMap, slotsData]); const handleMergeSlots = () => { if (!mergeSuggestion) return; setSelectedSlots((prev) => { const next = { ...prev }; cartItems.forEach((item) => { if (!productSlotsMap[item.skuId]?.isOutOfStock) { next[item.id] = mergeSuggestion.slotId; } }); return next; }); }; useEffect(() => { const initial: Record = {}; cartItems.forEach((item) => { initial[item.id] = item.quantity; }); setQuantities(initial); }, [cartData]); // Auto-select delivery slots for each cart item useEffect(() => { const cartSlotIds = cartData?.items.reduce((acc,item) => { acc[item.id] = item.slotId; return acc; }, {} as Record); if (cartItems.length > 0) { const newSelectedSlots = { ...selectedSlots }; cartItems.forEach(item => { // const existingSlotId = selectedSlots[item.id]; const existingSlotId = cartSlotIds ? cartSlotIds[item.id] : undefined; if (isFlashDelivery) { newSelectedSlots[item.id] = 0; } else { const productSlots = slotsData?.[item.skuId]; if (!productSlots || productSlots.length === 0) return; const now = dayjs(); const upcomingSlots = productSlots.filter(slot => dayjs(slot.deliveryTime).isAfter(now) ).sort((a, b) => dayjs(a.deliveryTime).diff(dayjs(b.deliveryTime)) ); if (upcomingSlots.length > 0) { if (existingSlotId) { const slotStillValid = upcomingSlots.some(slot => slot.id === existingSlotId); if (slotStillValid) { newSelectedSlots[item.id] = existingSlotId; } else { newSelectedSlots[item.id] = upcomingSlots[0].id; } } else { newSelectedSlots[item.id] = upcomingSlots[0].id; } } } }); setSelectedSlots(newSelectedSlots); } }, [slotsData, cartItems, isFlashDelivery]); // Login wall: render the prompt inline instead of redirecting, so the user can // still navigate back out of the cart (a push-based redirect would loop). if (isAuthLoading) { return ( Loading... ); } if (!isAuthenticated) { return ( router.back()} /> ); } if (isLoading || (isSlotsLoading && !isFlashDelivery)) { return ( Loading cart... ); } if (error) { return ( Oops! Failed to load your cart ); } return ( {/* Fixed Cart Type Header */} router.back()} style={tw`p-2 -ml-2 mr-1`} activeOpacity={0.7} > {isFlashDelivery ? "1 Hr Delivery Cart" : "Scheduled Delivery Cart"} {/* Cart Items */} {cartItems.length === 0 ? ( Your cart is empty Looks like you haven't added anything to your cart yet. router.push("/(drawer)/(tabs)/home")} > Start Shopping ) : ( <> {cartItems.map((item, index) => { const productSlots = getAvailableSlotsForProduct(item.skuId); const selectedSlotForItem = selectedSlots[item.id]; const isFlashEligible = isFlashDelivery ? flashEligibleProductIds.has(item.skuId) : true; const product = productsById[item.skuId]; const productSlotInfo = productSlotsMap[item.skuId]; // const isAvailable = (productSlots.length > 0 || isFlashDelivery) && !item.product?.isOutOfStock && isFlashEligible; let isAvailable = true; if (productSlotInfo?.isOutOfStock) { isAvailable = false; } else if(isFlashDelivery) { if(!isFlashEligible) { isAvailable = false; } } else { if(productSlots.length === 0) { isAvailable = false; } } // if (item.product?.isOutOfStock) { // isAvailable = false; // } else if (isFlashDelivery) { // isAvailable = isFlashEligible; // } const quantity = quantities[item.id] || item.quantity; const price = isFlashDelivery ? (product?.flashPrice ?? product?.price ?? 0) : (product?.price || 0); const itemPrice = (Number(price)) * quantity; return ( router.push( isFlashDelivery ? `/(drawer)/(tabs)/flash-delivery/product-detail/${item.skuId}` as any : `/(drawer)/(tabs)/home/product-detail/${item.skuId}` as any ) } activeOpacity={0.7} > router.push( isFlashDelivery ? `/(drawer)/(tabs)/flash-delivery/product-detail/${item.skuId}` as any : `/(drawer)/(tabs)/home/product-detail/${item.skuId}` as any ) } activeOpacity={0.7} style={tw`flex-1 mr-3`} > {product?.name} {product?.productType !== 'combo' ? (product?.unitNotation || '') : ''} { if (value === 0) { // Show confirmation alert before removing item Alert.alert( "Remove Item", "Are you sure you want to remove this item from your cart?", [ { text: "Cancel", style: "cancel", onPress: () => { // Reset quantity back to 1 setQuantities((prev) => ({ ...prev, [item.id]: 1 })); } }, { text: "Remove", style: "destructive", onPress: () => { // Proceed with removal removeFromCart.mutate( { itemId: item.id }, { onSuccess: () => { refetchCart(); }, onError: (error: any) => { Alert.alert("Error", error.message || "Failed to remove item"); // Restore quantity on error setQuantities((prev) => ({ ...prev, [item.id]: 1 })); }, } ); } } ] ); } else { // Update quantity normally setQuantities((prev) => ({ ...prev, [item.id]: value, })); updateCartItem.mutate({ itemId: item.id, quantity: value, }); } }} step={product?.incrementStep} unit={product?.unitNotation} /> {/* Delivery Slot Selection per Product - Hidden for 1 Hr Delivery */} {!isFlashDelivery && ( { setSelectedSlots((prev) => ({ ...prev, [item.id]: Number(value) })); }} disabled={productSlots.length === 0} triggerComponent={({ onPress, disabled, displayText }) => { const selectedSlotForItem = selectedSlots[item.id]; const selectedSlot = productSlots.find(slot => slot.value === selectedSlotForItem); const deliveryTimeText = selectedSlot ? selectedSlot.label.split(' - ')[0].replace('Delivery: ', '') : null; return ( {deliveryTimeText || (productSlots.length === 0 ? "No delivery slots available" : "Choose delivery slot")} Change ); }} /> ₹{itemPrice} { Alert.alert( "Remove Item", `Remove ${product?.name} from cart?`, [ { text: "Cancel", style: "cancel" }, { text: "Remove", style: "destructive", onPress: () => { removeFromCart.mutate( { itemId: item.id }, { onSuccess: () => { refetchCart(); }, onError: (error: any) => { Alert.alert( "Error", error.message || "Failed to remove item" ); }, } ); }, }, ] ); }} style={tw`p-1`} > )} {/* Price for 1 Hr Delivery (already in same row as slot) */} {isFlashDelivery && ( ₹{itemPrice} { Alert.alert( "Remove Item", `Remove ${product?.name} from cart?`, [ { text: "Cancel", style: "cancel" }, { text: "Remove", style: "destructive", onPress: () => { removeFromCart.mutate( { itemId: item.id }, { onSuccess: () => { refetchCart(); }, onError: (error: any) => { Alert.alert( "Error", error.message || "Failed to remove item" ); }, } ); }, }, ] ); }} style={tw`p-1`} > )} {!isAvailable && ( {productSlotInfo?.isOutOfStock ? "Out of Stock" : isFlashDelivery && !flashEligibleProductIds.has(item.skuId) ? "Not available for flash delivery. Please remove" : "No delivery slots available"} )} {/* Gray horizontal line between items (except for the last item) */} {index < cartItems.length - 1 && ( )} ); })} {/* Delivery Slot Summary */} {!isFlashDelivery && cartItems.length > 0 && ( )} )} {/* Cart Type Switcher (hidden) */} {false && cartItems.length > 0 && ( {/* First row: Text content */} {isFlashDelivery ? "1 Hr Delivery" : "Scheduled Delivery"} {isFlashDelivery ? "within 1 hour delivery • Immediate pickup" : "Choose your preferred delivery time" } {/* Second row: Navigation trigger */} { if (isFlashDelivery) { // Switch from flash to scheduled delivery router.push("/(drawer)/(tabs)/home" as any); } else { // Switch from scheduled to flash delivery router.push("/(drawer)/(tabs)/flash-delivery/(products)"); } }} activeOpacity={0.8} > {isFlashDelivery ? "Go to Scheduled Delivery" : "Go to 1 Hr Delivery"} )} {/* Coupon Selection */} {hasAvailableItems && ( Offers & Coupons { setSelectedCouponId(value ? Number(value) : null); }} placeholder={ eligibleCoupons.length === 0 ? "No coupons available" : "Select a coupon" } /> {eligibleCoupons.length === 0 && ( No coupons available for this order )} {selectedCouponId && ( setSelectedCouponId(null)} > Remove coupon )} {!isAuthenticated && ( router.push("/(drawer)/(tabs)/me")} > Log In To find offers and coupons )} {/* Link to add coupons to account */} router.push("/(drawer)/(tabs)/me/coupons?from=cart")} > Add Coupons to account )} {/* Delivery Instructions */} Delivery Instructions {/* Delivery Address */} {/* Bottom Checkout Bar - Now Static */} {hasAvailableItems && ( {/* Bill Header */} Bill Details {/* Item Total */} Item Total ₹{Math.trunc(totalPrice)} {/* Total Discount */} {totalSavings > 1 && ( Total Discount ₹{Math.trunc(totalSavings)} )} {/* Discount */} {discountAmount > 0 && ( Product Discount -₹{Math.trunc(discountAmount)} )} {/* Applied Coupon */} {selectedCoupons.length > 0 && ( Coupon Applied setCouponDialogOpen(true)}> {selectedCoupons[0].code} )} {/* Delivery Fee */} Delivery Fee {deliveryCharge === 0 && (constsData?.deliveryCharge || 0) > 0 && ( ₹{constsData?.deliveryCharge} )} {deliveryCharge === 0 ? 'Free' : `₹${deliveryCharge}`} {/* Free Delivery Nudge */} {deliveryCharge > 0 && (freeDeliveryThreshold || 0) > 0 && finalTotal < (freeDeliveryThreshold || 0) && ( Add products worth ₹{((freeDeliveryThreshold || 0) - finalTotal).toFixed(0)} for free delivery )} {/* Divider */} {/* Grand Total */} To Pay ₹{Math.trunc(finalTotalWithDelivery)} {/* Savings Banner */} {(discountAmount > 0 || deliveryCharge === 0 || totalSavings > 1) && ( You saved ₹{Math.trunc(discountAmount + totalSavings + (deliveryCharge === 0 ? (constsData?.deliveryCharge || 0) : 0))} on this order )} {/* Action Buttons */} router.push(isFlashDelivery ? "/(drawer)/(tabs)/flash-delivery" : "/(drawer)/(tabs)/home")} > Shop More { const availableItems = cartItems .filter(item => { if (productSlotsMap[item.skuId]?.isOutOfStock) return false; if (isFlashDelivery) { // Check if product supports flash delivery return flashEligibleProductIds.has(item.skuId); } return selectedSlots[item.id]; // Regular delivery requires slot selection }) .map(item => item.id); if (availableItems.length === 0) { // Determine why no items are available const outOfStockItems = cartItems.filter(item => productSlotsMap[item.skuId]?.isOutOfStock); const inStockItems = cartItems.filter(item => !productSlotsMap[item.skuId]?.isOutOfStock); let errorTitle = "Cannot Proceed"; let errorMessage = ""; if (outOfStockItems.length === cartItems.length) { // All items are out of stock errorTitle = "Items Unavailable"; errorMessage = "All items in your cart are currently out of stock. Please remove them and add available items."; } else if (isFlashDelivery) { // Check if any items are flash-eligible const flashEligibleItems = inStockItems.filter(item => flashEligibleProductIds.has(item.skuId) ); if (flashEligibleItems.length === 0) { errorTitle = "1 Hr Delivery Unavailable"; errorMessage = "None of the items in your cart are available for flash delivery. Please remove ineligible items or switch to regular delivery."; } else { errorTitle = "Some Items Not Available"; errorMessage = "Some items in your cart are not available for flash delivery. You can proceed with only the eligible items, or remove ineligible items."; } } else { // Regular delivery - check slot selection const itemsWithoutSlots = inStockItems.filter(item => !selectedSlots[item.id]); if (itemsWithoutSlots.length > 0) { errorTitle = "Delivery Slot Required"; errorMessage = `${itemsWithoutSlots.length} item(s) don't have a delivery slot. Please remove them or select a slot for each item.`; } else { errorTitle = "Cannot Proceed"; errorMessage = "Please check your cart items and try again."; } } Alert.alert(errorTitle, errorMessage); return; } // Check if there are items without slots (for regular delivery) if (!isFlashDelivery && availableItems.length < cartItems.length) { const itemsWithoutSlots = cartItems.filter(item => !selectedSlots[item.id] && !productSlotsMap[item.skuId]?.isOutOfStock); if (itemsWithoutSlots.length > 0) { Alert.alert( "Delivery Slot Required", `${itemsWithoutSlots.length} item(s) don't have a delivery slot. Please select a slot or remove the item.` ); return; } } // Group items by selected slot const itemsBySlot: Record = {}; availableItems.forEach(itemId => { const slotId = isFlashDelivery ? 0 : selectedSlots[itemId]; if (!itemsBySlot[slotId]) { itemsBySlot[slotId] = []; } itemsBySlot[slotId].push(itemId); }); // Create checkout URL with slot groupings const slotParams = Object.entries(itemsBySlot) .map(([slotId, itemIds]) => `${slotId}:${itemIds.join(',')}`) .join(';'); router.push( `${isFlashDelivery ? '/(drawer)/(tabs)/flash-delivery/checkout' : '/(drawer)/(tabs)/home/checkout'}?slots=${encodeURIComponent(slotParams)}${selectedCouponId ? `&coupons=${selectedCouponId}` : ''}&deliveryPrice=${deliveryCharge}` as any ); }} > Checkout )} {/* Coupon Details Dialog */} setCouponDialogOpen(false)} > Applied Coupons {selectedCoupons.map((coupon) => ( {coupon.code} {coupon.description} {coupon.discountType === "percentage" ? `${coupon.discountValue}% OFF` : `₹${coupon.discountValue} OFF`} {coupon.maxValue && ( Maximum discount up to ₹{coupon.maxValue} )} ))} setCouponDialogOpen(false)} > Close ); }