import { createFileRoute, useNavigate } from '@tanstack/react-router' import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react' import { MiniQuantifier } from 'web-components' import { useAllProducts, useStores } from '../hooks/prominent-api-hooks' import { useCentralProductStore } from '../lib/stores/central-product-store' import { useCentralSlotStore } from '../lib/stores/central-slot-store' import { useFlashTabStore } from '../lib/stores/flash-tab-store' import { useAddToCart, useGetCart, useUpdateCartItem, useRemoveFromCart } from '../hooks/cart-query-hooks' import { usePopulateCentralStores } from '../hooks/usePopulateCentralStores' import { usePopulateCentralProductStore } from '../hooks/usePopulateCentralProductStore' import { AppLayout } from '../components/AppLayout' import { Zap, ShoppingCart } from 'lucide-react' import type { CompactProductCardProps } from '@packages/shared' export const Route = createFileRoute('/flash')({ component: FlashDeliveryPage, }) // Three rows of three at a time, like the home catalog. const PAGE_SIZE = 9 const GRID_CLASS = 'grid grid-cols-3 gap-3 sm:gap-4 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5' const STRIP_CLASS = 'scrollbar-hide -mx-4 mb-5 flex gap-1 overflow-x-auto px-4 md:mx-0 md:px-0' interface TabItem { 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: TabItem[], picked: number | null): number | null { if (picked != null && items.some((item) => item.id === picked)) return picked return items[0]?.id ?? null } /** * Tag tabs. Reads the selection from the store, so a tap re-renders only this * strip and the tag grid — mirroring the native FlashTagStrip/TagScene split. */ const FlashTagStrip = memo(({ items }: { items: TabItem[] }) => { const selectedTagId = useFlashTabStore((state) => state.selectedTagId) const selectTag = useFlashTabStore((state) => state.selectTag) const scrollRef = useRef(null) const positions = useRef([]) const activeId = resolveActiveId(items, selectedTagId) const index = Math.max( 0, items.findIndex((item) => item.id === activeId) ) useEffect(() => { const x = positions.current[index] if (x != null) { scrollRef.current?.scrollTo({ left: Math.max(0, x - 16), behavior: 'smooth' }) } }, [index]) if (items.length === 0) return null return (
{items.map((item, i) => { const active = item.id === activeId return ( ) })}
) }) FlashTagStrip.displayName = 'FlashTagStrip' const FlashStoreStrip = memo(({ items }: { items: TabItem[] }) => { const selectedStoreId = useFlashTabStore((state) => state.selectedStoreId) const selectStore = useFlashTabStore((state) => state.selectStore) const activeId = resolveActiveId(items, selectedStoreId) if (items.length === 0) return null return (
{items.map((item) => { const active = item.id === activeId return ( ) })}
) }) FlashStoreStrip.displayName = 'FlashStoreStrip' /** One card. Navigation is derived from the id so the parent handler identity * is the only prop that can invalidate the memo. */ const FlashProductItem = memo( ({ item, onAddToCart }: { item: any; onAddToCart: (productId: number) => void }) => { const navigate = useNavigate() const handlePress = useCallback(() => { navigate({ to: '/flash/product/$id', params: { id: String(item.id) } }) }, [navigate, item.id]) return ( ) } ) FlashProductItem.displayName = 'FlashProductItem' interface FlashProductGridProps { products: any[] onAddToCart: (productId: number) => void } /** * 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. */ const FlashProductGrid = memo(({ products, onAddToCart }: FlashProductGridProps) => { const [visibleCount, setVisibleCount] = useState(PAGE_SIZE) const visible = products.length > visibleCount ? products.slice(0, visibleCount) : products if (products.length === 0) { return (

No flash delivery products available.

) } return ( <>
{visible.map((product: any) => ( ))}
{products.length > visibleCount && (
)} ) }) FlashProductGrid.displayName = 'FlashProductGrid' interface FlashTagSectionProps { tagItems: TabItem[] tagIds: number[] productsByTagId: Record /** With no tags configured the section lists every flash product. */ fallbackProducts: any[] onAddToCart: (productId: number) => void } const FlashTagSection = memo( ({ tagItems, tagIds, productsByTagId, fallbackProducts, onAddToCart, }: 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] ?? [] const label = tagItems.find((item) => item.id === tagId)?.label ?? 'All Products' return ( <>

{label}

{products.length} items

) } ) FlashTagSection.displayName = 'FlashTagSection' interface FlashStoreSectionProps { storeItems: TabItem[] storeIds: number[] productsByStoreId: Record onAddToCart: (productId: number) => void } const FlashStoreSection = memo( ({ storeItems, storeIds, productsByStoreId, onAddToCart }: FlashStoreSectionProps) => { const selectedStoreId = useFlashTabStore((state) => state.selectedStoreId) const storeId = selectedStoreId != null && storeIds.includes(selectedStoreId) ? selectedStoreId : storeIds[0] ?? null const products = productsByStoreId[storeId ?? -1] ?? [] return (

Shop by Store

{products.length} items

) } ) FlashStoreSection.displayName = 'FlashStoreSection' function FlashDeliveryPage() { // Populate central stores so flash-eligible products resolve on direct load usePopulateCentralStores() usePopulateCentralProductStore() const { data: productsData } = useAllProducts() const { data: storesData } = useStores() const { productsById } = useCentralProductStore() const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap) const addToCart = useAddToCart('flash') const { data: cartData } = useGetCart('flash') // Single memo for the flash catalogue: tabs and per-tab rows are derived // together so the page never holds two views of the same payload. Picking a // tab no longer touches any of it. const { tagItems, tagIds, productsByTagId, storeItems, storeIds, productsByStoreId, allFlashProducts, } = useMemo(() => { const tags = productsData?.tags || [] const stores = storesData?.stores || [] const allFlashProducts = Object.values(productsById).filter( (product: any) => product && productSlotsMap[product.id]?.isFlashAvailable && !productSlotsMap[product.id]?.isOutOfStock ) const flashProductIds = new Set(allFlashProducts.map((p: any) => p.id)) const flashStoreIds = new Set(allFlashProducts.map((p: any) => p.storeId)) // A tab only exists when it has at least one in-stock flash product. const tagTabs = tags.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] = allFlashProducts.filter((product: any) => ids.has(product.id) ) } const productsByStoreId: Record = {} for (const store of storeTabs) { productsByStoreId[store.id] = allFlashProducts.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, allFlashProducts, } }, [productsData, storesData, productsById, productSlotsMap]) // Stable so FlashProductItem memos survive a section re-render. const handleAddToCart = useCallback( (productId: number) => { const item = allFlashProducts.find((p: any) => p.id === productId) addToCart.mutate( { skuId: productId, quantity: 1, storeId: item?.storeId ?? 0 }, { onSuccess: () => { alert(`Added ${item?.name || 'item'} for 1 Hr Delivery`) }, } ) }, [addToCart, allFlashProducts] ) return (
{/* Page header */}

Express Counter

Delivery within 1 hour

{/* Info Banner */}

Get these products delivered within 1 hour! Only available for select items.

{/* Tag tabs — same model as the home page tabs */} {storeIds.length > 0 && ( )}
) } // Memoised: identical to the native ProductCard change — an unmemoised card // re-runs its cart hooks for every sibling whenever its section re-renders. const CompactProductCard = memo(function CompactProductCard({ item, handleAddToCart, onPress, }: CompactProductCardProps) { const { data: cartData } = useGetCart('flash'); const productSlotsMap = useCentralSlotStore((state) => state.productSlotsMap); const updateCartItem = useUpdateCartItem('flash'); const removeFromCart = useRemoveFromCart('flash'); 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(cartItem.id); } else if (newQuantity === 1 && !cartItem) { handleAddToCart(item.id); } else if (cartItem) { updateCartItem.mutate({ skuId: cartItem.skuId, quantity: newQuantity }); } }; const price = item.flashPrice ?? item.price return (
{item.name} {isOutOfStock && (

Out of Stock

)}
{quantity > 0 ? ( ) : (
{ e.stopPropagation(); handleQuantityChange(1); }} >
)}

{item.name}

₹{price}

{item.marketPrice && Number(item.marketPrice) > Number(item.price) && (

₹{item.marketPrice}

)}

{item.unitNotation || item.unit}

); })