import React, { useState, useEffect } from 'react' import type { FlashDeliveryProps } from '@packages/shared' import { useNavigate, useLocation } from '@tanstack/react-router' import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '../hooks/cart-query-hooks' import { useAllProducts } from '../hooks/prominent-api-hooks' import { useGetEssentialConsts } from '../hooks/prominent-api-hooks' import { MiniQuantifier } from 'web-components' import { ShoppingCart, ChevronRight, Clock, X, Package } from 'lucide-react' import dayjs from 'dayjs' // Smart time window formatting function const formatTimeRange = (deliveryTime: string | Date) => { 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}` } export function FloatingCartBar({ isFlashDelivery = false }: FlashDeliveryProps) { const navigate = useNavigate() const location = useLocation() const isCartPage = location.pathname === '/cart' || location.pathname === '/flash/cart' || location.pathname.startsWith('/me') const [isExpanded, setIsExpanded] = useState(false) const [quantities, setQuantities] = useState>({}) const cartType = isFlashDelivery ? 'flash' : 'regular' const { data: cartData } = useGetCart(cartType) const { data: constsData } = useGetEssentialConsts() const { data: productsData } = useAllProducts() const updateCartItem = useUpdateCartItem(cartType) const removeFromCart = useRemoveFromCart(cartType) const products = productsData?.products || [] const productsById: Record = {} products.forEach((p: any) => { productsById[p.id] = p }) const cartItems = cartData?.items || [] const itemCount = cartItems.length useEffect(() => { const initial: Record = {} cartItems.forEach((item) => { initial[item.id] = item.quantity }) setQuantities(initial) }, [cartData]) // Calculate total cart value const totalCartValue = cartItems.reduce( (sum, item) => { const product = productsById[item.skuId] const basePrice = product?.price ?? 0 const price = isFlashDelivery ? (product?.flashPrice ?? basePrice) : basePrice return sum + price * item.quantity }, 0 ) const freeDeliveryThreshold = isFlashDelivery ? constsData?.flashFreeDeliveryThreshold : constsData?.freeDeliveryThreshold const remainingForFreeDelivery = Math.max(0, freeDeliveryThreshold - totalCartValue) const cartBarColor = isFlashDelivery ? '#f81260' : 'var(--brand-600, #2563eb)' const cartBarBorderColor = isFlashDelivery ? '#e11d48' : 'var(--brand-500, #3b82f6)' const goToCart = () => { setIsExpanded(false) navigate({ to: isFlashDelivery ? '/flash/cart' : '/cart' }) } /* ---------- Desktop: slide-over panel ---------- */ const slideOver = (
{/* Header */}

Your Cart

{itemCount} {itemCount === 1 ? 'Item' : 'Items'}

{/* Progress */} {remainingForFreeDelivery > 0 && (

Free Delivery Progress

{Math.round((totalCartValue / freeDeliveryThreshold) * 100)}%

Add ₹{remainingForFreeDelivery} more for free delivery

)} {/* Items */}
{cartItems.length === 0 ? (

{isFlashDelivery ? 'No flash items yet' : 'Your cart is empty'}

{isFlashDelivery ? 'Pick something from 1 hr delivery' : 'Add fresh products to get started'}

) : ( cartItems.map((item, index) => (

{productsById[item.skuId]?.name || ''}

{productsById[item.skuId]?.unitNotation || ''}

{item.slotId && (

{formatTimeRange(item.deliveryDate || new Date())}

)}
{ if (value === 0) { removeFromCart.mutate(item.skuId) } else { setQuantities((prev) => ({ ...prev, [item.id]: value })) updateCartItem.mutate({ skuId: item.skuId, quantity: value }) } }} step={productsById[item.skuId]?.incrementStep || 1} />

₹{(() => { const product = productsById[item.skuId] const basePrice = product?.price ?? 0 const price = isFlashDelivery ? (product?.flashPrice ?? basePrice) : basePrice return price * item.quantity })()}

{index < cartItems.length - 1 &&
} )) )}
{/* Footer */}

Subtotal

₹{totalCartValue}

{remainingForFreeDelivery === 0 && itemCount > 0 && (

Free Delivery

)}
) return ( <> {/* Mobile: compact bottom bar */}
{/* Desktop: slide-over */}
setIsExpanded(false)} />
{slideOver}
) }