import React, { useState } from 'react'; import { Drawer } from 'expo-router/drawer'; import { DrawerContentComponentProps } from '@react-navigation/drawer'; import { View, ScrollView, Alert, Dimensions, RefreshControl } from 'react-native'; import { Image } from 'expo-image'; import { useRouter, usePathname, Slot } from 'expo-router'; import MaterialIcons from '@expo/vector-icons/MaterialIcons'; import { tw, theme, MyText, MyTouchableOpacity, MyFlatList, AppContainer, MiniQuantifier, SearchBar } from 'common-ui'; import { trpc } from '@/src/trpc-client'; import { useStores, useSlots } from '@/src/hooks/prominent-api-hooks'; import { useQuickDeliveryStore } from '@/src/store/quickDeliveryStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useCentralProductStore } from '@/src/store/centralProductStore'; import { useAddToCart, useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks'; import { useHideTabNav } from '@/src/hooks/useHideTabNav'; import CartIcon from '@/components/icons/CartIcon'; import ProductCard from '@/components/ProductCard'; import { useSlotStore } from '@/components/stores/slotStore'; import { useFlashTabStore } from '@/src/store/flashTabStore'; import { LinearGradient } from 'expo-linear-gradient'; import FloatingCartBar from '@/components/floating-cart-bar'; import QuickDeliveryAddressSelector from '@/components/QuickDeliveryAddressSelector'; import dayjs from 'dayjs'; const { width: screenWidth } = Dimensions.get("window"); const drawerWidth = 85; // From layout drawerStyle const itemWidth = (screenWidth - drawerWidth - 48) / 2; // Account for drawer width interface SlotLayoutProps extends SlotProductsProps { isForFlashDelivery?: boolean; } function CustomDrawerContent(baseUrl: string, drawerProps: DrawerContentComponentProps, slotIdParent?: number, storeIdParent?: number) { const router = useRouter(); const pathname = usePathname(); const { data: storesData } = useStores(); const setStoreId = useSlotStore(state => state.setStoreId); const { slotId, storeId } = useSlotStore(); // Get current pathname to determine active item const currentPath = pathname; // Check if we are on the main 'quick-delivery' page (All products) // const isAllActive = !currentPath.includes('/store/'); const isAllActive = isNaN(storeId as number); const allSlotsUrl = `${baseUrl}${slotId ? `?slotId=${slotId}` : ''}`; return ( {/* All Products Item */} { router.replace(allSlotsUrl as any); }} activeOpacity={0.8} > {isAllActive ? ( ALL ) : ( ALL )} {/* Store Items */} {storesData?.stores?.map(store => { // Check if this specific store is active const isStoreActive = storeId === store.id; // const isStoreActive = currentPath.includes(`/store/${store.id}`); return ( { setStoreId(store.id); const targetUrl = `${baseUrl}${slotId ? `?slotId=${slotId}&storeId=${store.id}` : `?storeId=${store.id}`}`; router.replace(targetUrl as any); }} activeOpacity={0.8} > {isStoreActive ? ( {store.signedImageUrl ? ( ) : ( )} {store.name.replace(/^The\s+/i, '')} {/* Active Pip/Indicator */} ) : ( {store.signedImageUrl ? ( ) : ( )} {store.name.replace(/^The\s+/i, '')} )} ); }) || ( Loading... )} ); } interface FlashTabStripProps { items: { id: number; label: string }[]; activeId: number | null; onSelect: (id: number) => void; testID: string; tabTestIDPrefix: string; } /** * Horizontally scrollable tab strip used by the 1 Hr Delivery page for both the * tag section and "Shop by Store". * * Same mechanics as the home page's TagTabStrip (plain ScrollView so Android * scrolls reliably, active tab auto-scrolled into view). It lives inside the * page's vertical ScrollView, so it scrolls away with the content. */ const FlashTabStrip = React.memo(({ items, activeId, onSelect, testID, tabTestIDPrefix, }: FlashTabStripProps) => { const scrollRef = React.useRef(null); const positions = React.useRef([]); const index = React.useMemo(() => { const idx = items.findIndex((item) => item.id === activeId); return idx < 0 ? 0 : idx; }, [items, activeId]); React.useEffect(() => { const x = positions.current[index]; if (x != null) { scrollRef.current?.scrollTo({ x: Math.max(0, x - 16), animated: true }); } }, [index]); if (items.length === 0) return null; return ( {items.map((item, i) => { const isActive = i === index; return ( { positions.current[i] = e.nativeEvent.layout.x; }} onPress={() => onSelect(item.id)} style={tw`h-12 px-3 justify-center`} activeOpacity={0.7} > {item.label} ); })} ); }); FlashTabStrip.displayName = 'FlashTabStrip'; export function SlotLayout({ slotId, storeId, baseUrl, isForFlashDelivery }: SlotLayoutProps) { const router = useRouter(); // const { slotId: paramsSlotId } = useLocalSearchParams(); const isDrawerHidden = useQuickDeliveryStore(state => state.isDrawerHidden); const setSelectedSlotId = useQuickDeliveryStore(state => state.setSelectedSlotId); const setSlotId = useSlotStore(state => state.setSlotId); const handleSlotChange = (newSlotId: number) => { setSelectedSlotId(newSlotId); setSlotId(newSlotId); router.replace(`${baseUrl}?slotId=${newSlotId}` as any); }; return ( <> {/* Flash delivery has no store rail: the tag tabs live in the products screen and this layout only renders the child route. */} {isForFlashDelivery ? ( ) : ( CustomDrawerContent(baseUrl, props, slotId, storeId)} screenOptions={{ headerShown: false, drawerType: 'permanent', drawerStyle: { width: 85, ...(isDrawerHidden && { display: 'none' }), }, headerStyle: { // width: 220, backgroundColor: 'white', }, headerShadowVisible: false, }} > )} {/* */} {/* */} ); } const formatQuantity = (quantity: number, unit: string): { value: string; display: string } => { if (unit?.toLowerCase() === 'kg' && quantity < 1) { return { value: `${Math.round(quantity * 1000)} g`, display: `${Math.round(quantity * 1000)}g` }; } return { value: `${quantity} ${unit}(s)`, display: `${quantity}${unit}` }; }; const CompactProductCard = ({ item, handleAddToCart, onPress, cartType = "regular", }: { item: any; handleAddToCart: (productId: number) => void; onPress?: () => void; cartType?: "regular" | "flash"; }) => { // Cart management for miniView const { data: cartData } = useGetCart({}, cartType); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); const updateCartItem = useUpdateCartItem({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true, }, cartType); const removeFromCart = useRemoveFromCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true, }, cartType); const cartItem = cartData?.items?.find((cartItem: any) => cartItem.skuId === item.id); const quantity = cartItem?.quantity || 0; const isOutOfStock = productSlotsMap[item.id]?.isOutOfStock; const handleQuantityChange = (newQuantity: number) => { if (newQuantity === 0 && cartItem) { removeFromCart.mutate({ itemId: cartItem.id }); } else if (newQuantity === 1 && !cartItem) { handleAddToCart(item.id); } else if (cartItem) { updateCartItem.mutate({ itemId: cartItem.id, quantity: newQuantity }); } }; return ( {isOutOfStock && ( Out of Stock )} {quantity > 0 ? ( ) : ( handleQuantityChange(1)} activeOpacity={0.8} > )} {item.name} ₹{cartType === "flash" ? (item.flashPrice ?? item.price) : item.price} {item.marketPrice && Number(item.marketPrice) > Number(item.price) && ( ₹{item.marketPrice} )} {item.productType !== 'combo' && ( Quantity: {item.unit || item.unitNotation} )} ); }; interface SlotProductsProps { slotId?: number; storeId?: number; baseUrl: string; } export function SlotProducts({ slotId:slotIdParent, storeId:storeIdParent, baseUrl, }: SlotProductsProps) { useHideTabNav('quick_delivery'); const [isLoadingDialogOpen, setIsLoadingDialogOpen] = React.useState(false); const router = useRouter(); const slotId = slotIdParent; const storeId = storeIdParent; const storeIdNum = storeId; const { data: slotsData, isLoading: slotsLoading, error: slotsError } = useSlots(); const { productsById } = useCentralProductStore(); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); // Find the specific slot from cached data const slot = slotsData?.slots?.find(s => s.id === slotId); const { addToCart = () => { } } = useAddToCart({ showSuccessAlert: false, showErrorAlert: false, refetchCart: true }, "regular") || {}; const handleAddToCart = (productId: number) => { setIsLoadingDialogOpen(true); const item = filteredProducts.find((p) => p.id === productId); const deliveryTime = slot?.deliveryTime ? dayjs(slot.deliveryTime).format('ddd, DD MMM • h:mm A') : ''; addToCart(productId, 1, slotId || 0, () => { setIsLoadingDialogOpen(false); if (item) { Alert.alert('Added to Cart', `Added ${item.name} for delivery at ${deliveryTime}`); } }); }; if (slotsLoading) { return ( Loading slot delivery... ); } if (slotsError) { return ( Oops! Failed to load slot delivery ); } if (!slot) { return ( Quick Delivery No delivery slot available. ); } // Get product details from central store using slot product IDs // Filter: 1) Must exist in productsById, 2) Must not be out of stock (from slots data) const slotProducts = slot.products ?.map(p => productsById[p.id]) ?.filter((product): product is NonNullable => product !== null && product !== undefined) ?.filter(product => !productSlotsMap[product.id]?.isOutOfStock) || []; const filteredProducts = storeIdNum ? slotProducts.filter(p => p.storeId === storeIdNum) : slotProducts; return ( ( router.push(`/(drawer)/(tabs)/home/product-detail/${item.id}`)} cartType="regular" /> )} keyExtractor={(item, index) => index.toString()} columnWrapperStyle={{ gap: 16, justifyContent: 'flex-start' }} contentContainerStyle={[tw`pb-24 px-4`, { gap: 16 }]} onRefresh={() => {}} ListEmptyComponent={ storeIdNum ? ( No products from this store in this slot. ) : null } /> ); } interface FlashDeliveryProductsProps { baseUrl: string; onProductPress?: (productId: number) => void; } // 16px page margin + two 8px gaps leaves each of the three cards this wide. const flashItemWidth = (screenWidth - 48) / 3; // Three rows per page, like the home catalog. const FLASH_PAGE_SIZE = 9; interface FlashTabItem { id: number; label: string; } /** Active tab, resolved the way the page always did: the picked id while it * still exists in this region's catalogue, otherwise the first tab. */ function resolveActiveId(items: FlashTabItem[], picked: number | null): number | null { if (picked != null && items.some((item) => item.id === picked)) return picked; return items[0]?.id ?? null; } /** * Tag strip. Reads the selection straight from the store, so a tap does not * re-render the page, and receives a memoised `items` array so its memo holds. */ const FlashTagStrip = React.memo(({ items }: { items: FlashTabItem[] }) => { const selectedTagId = useFlashTabStore((state) => state.selectedTagId); const selectTag = useFlashTabStore((state) => state.selectTag); return ( ); }); FlashTagStrip.displayName = 'FlashTagStrip'; const FlashStoreStrip = React.memo(({ items }: { items: FlashTabItem[] }) => { const selectedStoreId = useFlashTabStore((state) => state.selectedStoreId); const selectStore = useFlashTabStore((state) => state.selectStore); return ( ); }); FlashStoreStrip.displayName = 'FlashStoreStrip'; /** Search box. Owns the store subscription so typing never re-renders the page. */ const FlashSearchBar = React.memo(() => { const searchQuery = useFlashTabStore((state) => state.searchQuery); const setSearchQuery = useFlashTabStore((state) => state.setSearchQuery); return ( ); }); FlashSearchBar.displayName = 'FlashSearchBar'; interface FlashProductItemProps { item: any; onPress: (productId: number) => void; } /** One card. `onPress` is derived from the id so the parent's handler identity * is the only prop that matters. */ const FlashProductItem = React.memo(({ item, onPress }: FlashProductItemProps) => { const handlePress = React.useCallback(() => onPress(item.id), [item.id, onPress]); return ( ); }); FlashProductItem.displayName = 'FlashProductItem'; interface FlashProductGridProps { products: any[]; onProductPress: (productId: number) => void; gridTestID: string; showMoreTestID: string; } /** * One paged grid. Owns its visible count, and is keyed by the active tab so a * tab switch resets the page size on the first render instead of in an effect. * The search value lives in the store, so only the grids wake on typing. */ const FlashProductGrid = React.memo(({ products, onProductPress, gridTestID, showMoreTestID, }: FlashProductGridProps) => { const searchQuery = useFlashTabStore((state) => state.searchQuery); const trimmedQuery = searchQuery.trim().toLowerCase(); const filtered = React.useMemo(() => { if (!trimmedQuery) return products; return products.filter((product: any) => product.name?.toLowerCase().includes(trimmedQuery) ); }, [products, trimmedQuery]); const [visibleCount, setVisibleCount] = React.useState(FLASH_PAGE_SIZE); // Adjust during render, not in an effect: an effect would paint the new // results with the previous count and then reset, costing a second render. const [lastQuery, setLastQuery] = React.useState(trimmedQuery); if (lastQuery !== trimmedQuery) { setLastQuery(trimmedQuery); setVisibleCount(FLASH_PAGE_SIZE); } const visible = filtered.length > visibleCount ? filtered.slice(0, visibleCount) : filtered; if (filtered.length === 0) { return ( No 1 Hr Delivery products available. ); } return ( <> {visible.map((product: any) => ( ))} {filtered.length > visibleCount && ( setVisibleCount((count) => count + FLASH_PAGE_SIZE)} > Show More )} ); }); FlashProductGrid.displayName = 'FlashProductGrid'; interface FlashTagSectionProps { tagItems: FlashTabItem[]; tagIds: number[]; productsByTagId: Record; /** With no tags configured the section lists every flash product. */ fallbackProducts: any[]; onProductPress: (productId: number) => void; } /** Tag strip + its grid. Only this section re-renders when a tag is picked. */ const FlashTagSection = React.memo(({ tagItems, tagIds, productsByTagId, fallbackProducts, onProductPress, }: FlashTagSectionProps) => { const selectedTagId = useFlashTabStore((state) => state.selectedTagId); const tagId = selectedTagId != null && tagIds.includes(selectedTagId) ? selectedTagId : tagIds[0] ?? null; const products = tagId == null ? fallbackProducts : productsByTagId[tagId] ?? []; return ( <> ); }); FlashTagSection.displayName = 'FlashTagSection'; interface FlashStoreSectionProps { storeItems: FlashTabItem[]; storeIds: number[]; productsByStoreId: Record; onProductPress: (productId: number) => void; } /** "Shop by Store" heading, its strip and grid. Picking a store wakes only this. */ const FlashStoreSection = React.memo(({ storeItems, storeIds, productsByStoreId, onProductPress, }: FlashStoreSectionProps) => { const selectedStoreId = useFlashTabStore((state) => state.selectedStoreId); const storeId = selectedStoreId != null && storeIds.includes(selectedStoreId) ? selectedStoreId : storeIds[0] ?? null; return ( Shop by Store ); }); FlashStoreSection.displayName = 'FlashStoreSection'; export function FlashDeliveryProducts({ onProductPress }: FlashDeliveryProductsProps) { useHideTabNav('quick_delivery'); // Owned by the user's pull, not by React Query: `isFetching` is true for every // background fetch (remount-after-stale, invalidation, version bump), which // made the pull-to-refresh spinner pop up on its own. const [isRefreshing, setIsRefreshing] = useState(false); const router = useRouter(); const products = useCentralProductStore((state) => state.products); const catalogueTags = useCentralProductStore((state) => state.tags); const isProductsLoading = useCentralProductStore((state) => state.isLoading); const productsError = useCentralProductStore((state) => state.error); const refetchProducts = useCentralProductStore((state) => state.refetchProducts); const { data: storesData, refetch: refetchStores } = useStores(); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); // Single memo for the flash catalogue. Tabs, per-tab rows and per-store rows // are derived together so the screen never holds two views of the same // payload that can drift apart. Picking a tab no longer touches any of it. const { tagItems, tagIds, productsByTagId, storeItems, storeIds, productsByStoreId, flashProducts, } = React.useMemo(() => { const stores = storesData?.stores || []; const flashProducts = products.filter((product: any) => { const info = productSlotsMap[product.id]; return info?.isFlashAvailable && !info?.isOutOfStock; }); const flashProductIds = new Set(flashProducts.map((product: any) => product.id)); const flashStoreIds = new Set(flashProducts.map((product: any) => product.storeId)); // A tab only exists if it has at least one in-stock flash product; empty // tags and stores are not shown at all. const tagTabs = catalogueTags.filter((tag: any) => ((tag.productIds || []) as number[]).some((id) => flashProductIds.has(id)) ); const storeTabs = stores.filter((store: any) => flashStoreIds.has(store.id)); const productsByTagId: Record = {}; for (const tag of tagTabs) { const ids = new Set((tag.productIds || []) as number[]); productsByTagId[tag.id] = flashProducts.filter((product: any) => ids.has(product.id)); } const productsByStoreId: Record = {}; for (const store of storeTabs) { productsByStoreId[store.id] = flashProducts.filter( (product: any) => product.storeId === store.id ); } return { tagItems: tagTabs.map((tag: any) => ({ id: tag.id, label: tag.tagName })), tagIds: tagTabs.map((tag: any) => tag.id), productsByTagId, storeItems: storeTabs.map((store: any) => ({ id: store.id, label: store.name.replace(/^The\s+/i, ''), })), storeIds: storeTabs.map((store: any) => store.id), productsByStoreId, flashProducts, }; }, [products, catalogueTags, storesData, productSlotsMap]); // Stable so FlashProductItem/FlashProductGrid memos survive a re-render. const handleProductPress = React.useCallback( (productId: number) => { if (onProductPress) { onProductPress(productId); } else { router.push(`/(drawer)/(tabs)/flash-delivery/product-detail/${productId}`); } }, [onProductPress, router] ); const handleRefresh = React.useCallback(async () => { setIsRefreshing(true); try { await Promise.all([refetchProducts?.(), refetchStores()]); } finally { setIsRefreshing(false); } }, [refetchProducts, refetchStores]); // Memoised so the platform control is not rebuilt on every render. const refreshControl = React.useMemo( () => ( ), [isRefreshing, handleRefresh] ); if (isProductsLoading) { return ( Loading 1 Hr Delivery... ); } if (productsError && products.length === 0) { return ( Oops! Failed to load 1 Hr Delivery ); } return ( {/* Tag section — tabs scroll with the page, not sticky. */} {/* Shop by Store — one tab per store. */} {storeIds.length > 0 && ( )} ); }