freshyo/apps/user-ui/components/cart-page.tsx
2026-11-08 13:49:17 +05:30

1748 lines
72 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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, type Product } 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 { useRegionNeo } from '@/src/hooks/useRegionNeo';
import CheckoutAddressSelector from '@/components/CheckoutAddressSelector';
import CouponBreakdownDialog from '@/src/components/CouponBreakdownDialog';
import LoginWall from '@/components/LoginWall';
import CartAddressGate from '@/components/CartAddressGate';
import { useCheckoutStore } from '@/src/store/checkoutStore';
import type { FlashDeliveryProps } from '@packages/shared';
import { computeCouponStack, computeCouponLineBreakdowns, evaluateCouponEligibility, type CartLine, type CouponLineBreakdown } 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}`;
};
/** One row of the "products this coupon applies to" list. */
type CouponTargetRow =
| {
key: string;
name: string;
unitNotation?: string;
image?: string;
}
| {
key: string;
/** Target SKU that is no longer in the region's catalog. */
unavailableSkuId: number;
};
/**
* The products a coupon is restricted to, one row per DISTINCT product name —
* the coupon targets SKUs, but several SKUs of the same product are the same
* line to a customer. A target whose SKU is not in the catalog (suspended or
* deleted SKUs are filtered out of the product store) still gets a row, so the
* count shown next to the coupon never silently shrinks — which also matches
* the backend, where a stale target simply stops matching.
*/
const buildCouponTargetRows = (
skuIds: number[],
productsById: Record<number, Product>
): CouponTargetRow[] => {
const rows: CouponTargetRow[] = [];
const seenNames = new Set<string>();
skuIds.forEach((skuId) => {
const product = productsById[skuId];
if (!product?.name) {
rows.push({ key: `sku-${skuId}`, unavailableSkuId: skuId });
return;
}
if (seenNames.has(product.name)) return;
seenNames.add(product.name);
rows.push({
key: `name-${product.name}`,
name: product.name,
unitNotation: product.unitNotation,
image: product.images?.[0],
});
});
return rows;
};
/** Inline product list for one coupon — rendered inside the coupon dropdown's
* option (the dropdown provides the bounded, scrollable container). */
function CouponTargetRows({ rows }: { rows: CouponTargetRow[] }) {
return (
<View style={tw`pt-1`}>
{rows.map((row) => (
<View
key={row.key}
style={tw`flex-row items-center px-4 py-2 border-b border-gray-100 last:border-b-0`}
>
{'unavailableSkuId' in row ? (
<>
<View style={tw`w-8 h-8 rounded-lg bg-gray-100 items-center justify-center mr-3`}>
<MaterialIcons name="inventory-2" size={16} color="#9CA3AF" />
</View>
<MyText style={tw`text-xs text-gray-500 flex-1`}>
Product unavailable · #{row.unavailableSkuId}
</MyText>
</>
) : (
<>
<Image
source={{ uri: row.image }}
style={tw`w-8 h-8 rounded-lg bg-gray-100 mr-3`}
/>
<View style={tw`flex-1`}>
<MyText style={tw`text-sm text-gray-900`} numberOfLines={2}>
{row.name}
</MyText>
{!!row.unitNotation && (
<MyText style={tw`text-xs text-gray-500 mt-0.5`}>
{row.unitNotation}
</MyText>
)}
</View>
</>
)}
</View>
))}
</View>
);
}
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<DeliverySlotGroup | null>(null);
if (groups.length === 0) return null;
return (
<View
testID="delivery-slot-summary"
style={tw`bg-white rounded-2xl shadow-sm mb-4 border border-gray-100 overflow-hidden`}
>
<View style={tw`bg-gray-50 px-4 py-3 border-b border-gray-100`}>
<MyText style={tw`text-gray-900 font-bold text-base`}>Delivery Slot</MyText>
</View>
<View style={tw`p-4`}>
{groups.map((group, index) => (
<View
key={group.slotId}
style={[
tw`flex-row items-center justify-between py-2.5`,
index > 0 ? tw`border-t border-gray-100` : {},
]}
>
<View style={tw`flex-row items-center flex-1 mr-3`}>
<MaterialIcons name="schedule" size={16} color="#6B7280" style={tw`mr-2`} />
<MyText style={tw`text-sm text-gray-700 flex-1`}>{group.label}</MyText>
</View>
<MyTouchableOpacity
testID={`delivery-slot-items-${group.slotId}`}
style={tw`flex-row items-center`}
onPress={() => setOpenGroup(group)}
activeOpacity={0.7}
>
<MyText style={tw`text-sm font-medium text-brand500`}>
{group.items.length} {group.items.length === 1 ? 'item' : 'items'}
</MyText>
<MaterialIcons name="chevron-right" size={18} color="#1570EF" />
</MyTouchableOpacity>
</View>
))}
{!!mergeSuggestion && (
<MyTouchableOpacity
testID="delivery-slot-merge"
onPress={onMerge}
activeOpacity={0.7}
style={tw`mt-3 flex-row items-center justify-between rounded-xl px-3 py-2.5 border bg-brand50 border-brand200`}
>
<View style={tw`flex-row items-center flex-1 mr-2`}>
<MaterialIcons name="merge-type" size={16} color="#1570EF" />
<MyText style={tw`text-sm font-medium text-brand700 ml-2 flex-1`}>
Deliver All items at {mergeSuggestion.label}
</MyText>
</View>
<View testID="delivery-slot-merge-apply" style={tw`p-1`}>
<MaterialIcons name="chevron-right" size={20} color="#1570EF" />
</View>
</MyTouchableOpacity>
)}
</View>
<BottomDialog open={!!openGroup} onClose={() => setOpenGroup(null)}>
<View testID="delivery-slot-group-dialog" style={tw`p-6`}>
<View style={tw`flex-row items-start justify-between mb-4`}>
<View style={tw`flex-1 mr-3`}>
<MyText style={tw`text-lg font-bold text-gray-900`}>Items</MyText>
<MyText style={tw`text-xs text-gray-500 mt-0.5`}>{openGroup?.label}</MyText>
</View>
<MyTouchableOpacity testID="delivery-slot-group-close" onPress={() => setOpenGroup(null)} style={tw`p-1`}>
<MaterialIcons name="close" size={22} color="#9CA3AF" />
</MyTouchableOpacity>
</View>
{openGroup?.items.map((item) => (
<View
key={item.id}
style={tw`flex-row items-center py-3 border-b border-gray-50`}
>
<Image
source={{ uri: item.image }}
style={tw`w-10 h-10 rounded-lg bg-gray-100 mr-3`}
/>
<View style={tw`flex-1`}>
<MyText style={tw`text-sm text-gray-900`} numberOfLines={1}>
{item.name}
</MyText>
{!!item.unitNotation && (
<MyText style={tw`text-xs text-gray-500 mt-0.5`}>
{item.unitNotation}
</MyText>
)}
</View>
<MyText style={tw`text-sm font-bold text-gray-900`}>x{item.quantity}</MyText>
</View>
))}
</View>
</BottomDialog>
</View>
);
}
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 neo = useRegionNeo();
const selectedAddressId = neo.selectedAddressId;
const regionId = neo.regionId;
// First-address gate: the region can exist (from the location) with no address yet.
const addressesQuery = trpc.user.address.getUserAddresses.useQuery(undefined, {
enabled: isAuthenticated,
});
const userNotes = useCheckoutStore((state) => state.userNotes);
const setUserNotes = useCheckoutStore((state) => state.setUserNotes);
const [quantities, setQuantities] = useState<Record<number, number>>({});
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. Slots are the browsing region's own
// (global SKUs ride along); the region is required and resolved per request, so
// a SKU from another region can never bring back that region's slots.
const { data: slotsData, refetch: refetchSlots, isLoading: isSlotsLoading } = trpc.user.cart.getCartSlots.useQuery(
{ regionId: regionId ?? 0, productIds },
{
enabled: regionId != null && 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(
{ regionId: regionId ?? 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<number>();
return new Set(
products
.filter((product) => productSlotsMap[product.id]?.isFlashAvailable)
.map((product) => product.id)
);
}, [products, productSlotsMap]);
// Cart lines (in-stock only) with their effective unit price, in the shared
// shape the coupon helpers expect. Declared before the coupon list so coupon
// targeting can be evaluated against the cart.
const cartLines = useMemo<CartLine[]>(
() =>
cartItems
.filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock)
.map((item) => {
const product = productsById[item.skuId];
const unitPrice = isFlashDelivery
? (product?.flashPrice ?? product?.price ?? 0)
: (product?.price || 0);
return {
skuId: item.skuId,
quantity: quantities[item.id] || item.quantity,
unitPrice: Number(unitPrice),
};
}),
[cartItems, productSlotsMap, productsById, isFlashDelivery, quantities]
);
// Every coupon we're allowed to surface (the API already drops expired,
// invalidated, usage-limit-exceeded and other users' personal coupons).
// Whether each one applies to THIS cart is decided locally — the shared
// resolver, the same rules the backend applies at placeOrder — so changing the
// cart never has to ask the server again. Ineligible ones are kept, flagged with
// the reason, and sorted to the end.
const eligibleCoupons = useMemo(() => {
if (!couponsRaw?.data) return [];
const isFirstOrder = couponsRaw.isFirstOrder ?? true;
const mapped = couponsRaw.data.map((coupon) => {
// Target SKUs live on the coupon row itself (empty => whole cart).
const applicableSkuIds = Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : [];
const { isEligible, reason: ineligibilityReason } = evaluateCouponEligibility(
{
regionId: coupon.regionId,
isFirstOrderOnly: coupon.isFirstOrderOnly,
minOrder: coupon.minOrder,
maxLimitForUser: coupon.maxLimitForUser,
usages: coupon.usages,
applicableSkuIds,
},
{ cartLines, regionId, isFirstOrder }
);
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,
// Raw fields so the shared coupon helpers can be used directly.
discountPercent: coupon.discountPercent,
flatDiscount: coupon.flatDiscount,
applicableSkuIds,
isEligible,
ineligibilityReason,
};
});
// Applicable coupons first, disabled ones at the end (stable within groups).
return mapped.sort((a, b) => Number(b.isEligible) - Number(a.isEligible));
}, [couponsRaw, cartLines, regionId]);
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<Record<number, number>>({});
const [selectedCouponIds, setSelectedCouponIds] = useState<number[]>([]);
const [couponDialogOpen, setCouponDialogOpen] = useState(false);
// Coupon whose per-product discount split is open (only product-specific ones
// have an "i" in the bill).
const [breakdownCouponId, setBreakdownCouponId] = useState<number | null>(null);
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]);
// Coupons currently applied, kept in the order the user selected them — the
// order matters because coupons stack sequentially.
const couponById = useMemo(
() => new Map(eligibleCoupons.map((coupon) => [coupon.id, coupon])),
[eligibleCoupons]
);
const selectedCoupons = useMemo(
() =>
selectedCouponIds
.map((id) => couponById.get(id))
.filter((coupon): coupon is NonNullable<typeof coupon> => !!coupon && coupon.isEligible),
[selectedCouponIds, couponById]
);
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);
// "Save ₹x" for an option = the MARGINAL saving of adding it to the current
// selection (coupons stack, so a coupon's worth depends on what is already on).
// A coupon that is already applied shows its own current contribution.
const dropdownData = useMemo(() => {
const base = computeCouponStack(cartLines, selectedCoupons);
const selectedIds = new Set(selectedCoupons.map((c) => c.id));
return (
eligibleCoupons?.map((coupon) => {
// The products this coupon is restricted to (empty => whole cart). One row
// per distinct product name; the same array drives the label and the list,
// so the count always matches what is rendered.
const targetRows = buildCouponTargetRows(coupon.applicableSkuIds, productsById);
const detail = targetRows.length > 0
? {
label: `Applies to ${targetRows.length} product${targetRows.length === 1 ? '' : 's'}`,
render: () => <CouponTargetRows rows={targetRows} />,
}
: undefined;
// Disabled coupons can't be applied: row 1 shows just the code (with the
// italic "Disabled" badge), row 2 the reason. No "Save" preview.
if (!coupon.isEligible) {
return {
label: coupon.code,
value: coupon.id,
disabled: true,
note: coupon.ineligibilityReason,
detail,
};
}
let save: number;
if (selectedIds.has(coupon.id)) {
save = base.perCoupon.find((entry) => entry.couponId === coupon.id)?.discount ?? 0;
} else {
const withCoupon = computeCouponStack(cartLines, [...selectedCoupons, coupon]);
save = withCoupon.discountTotal - base.discountTotal;
}
return {
label: `${coupon.code} - ${coupon.description} (Save ₹${save})`,
value: coupon.id,
disabled: false,
detail,
};
}) || []
);
}, [eligibleCoupons, cartLines, selectedCoupons, productsById]);
// The coupon dropdown is a multi-select: it toggles an id and reports the whole
// new list. An exclusive coupon still replaces every other selection (and
// nothing may be added alongside one), so the toggle is filtered here.
const handleCouponSelectionChange = (value: string | number | string[] | number[]) => {
const next = (Array.isArray(value) ? value : []).map((v) => Number(v));
setSelectedCouponIds((prev) => {
const added = next.find((id) => !prev.includes(id));
const removed = prev.find((id) => !next.includes(id));
// A deselect (or a no-op change) needs no exclusivity handling.
if (added == null || removed != null) return next;
const coupon = eligibleCoupons.find((c) => c.id === added);
const hasExclusive = prev.some(
(pid) => eligibleCoupons.find((c) => c.id === pid)?.exclusiveApply
);
// An exclusive coupon replaces every other selection.
if (coupon?.exclusiveApply || hasExclusive) return [added];
return next;
});
};
// What each applied coupon takes off, keyed by coupon id. Coupons stack in the
// order they were selected, so a later coupon only sees what the earlier ones
// left behind (this must match the backend's computeCartPricing).
const couponDiscounts = useMemo(() => {
const discounts: Record<number, number> = {};
const { perCoupon } = computeCouponStack(cartLines, selectedCoupons);
perCoupon.forEach((entry) => {
discounts[entry.couponId] = entry.discount;
});
return discounts;
}, [selectedCoupons, cartLines]);
// Sum of the per-coupon discounts, so the bill's lines always add up to it.
const discountAmount = useMemo(
() => Object.values(couponDiscounts).reduce((sum, value) => sum + value, 0),
[couponDiscounts]
);
// Where each applied coupon's discount landed, per cart line — the bill's "i"
// popup for product-specific coupons. Totals come from the same waterfall as the
// bill's own figures, so the popup's rows always add up to the coupon's line.
const couponBreakdowns = useMemo(() => {
const byId = new Map<number, CouponLineBreakdown>();
computeCouponLineBreakdowns(cartLines, selectedCoupons).forEach((entry) => {
byId.set(entry.couponId, entry);
});
return byId;
}, [cartLines, selectedCoupons]);
// Cart lines by SKU, for the popup's quantity × price line.
// The coupon whose per-product split is open, if it is still applied.
const breakdownCoupon =
breakdownCouponId != null ? couponById.get(breakdownCouponId) : undefined;
const breakdown =
breakdownCouponId != null ? couponBreakdowns.get(breakdownCouponId) : undefined;
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);
// Checkout blockers (scheduled delivery only). An in-stock item can't be
// delivered when its SKU has no slots published at all ("not in the slots
// file"), when the slot chosen for it is no longer offered for that item, or
// when that slot's freeze time has passed. Any such item disables the checkout
// button, and the reason is shown beneath it.
const slotCheck = useMemo<{ blocked: boolean; itemIds: number[]; message: string | null }>(() => {
if (isFlashDelivery) {
return { blocked: false, itemIds: [], message: null };
}
const now = dayjs();
const noSlots: number[] = []; // SKU missing from the slots file (or no slots)
const unavailable: number[] = []; // selected slot not offered for the item
const closed: number[] = []; // selected slot's freeze time passed
cartItems.forEach((item) => {
if (productSlotsMap[item.skuId]?.isOutOfStock) return;
const productSlots = slotsData?.[item.skuId];
if (!productSlots || productSlots.length === 0) {
noSlots.push(item.id);
return;
}
const slot = productSlots.find((s) => s.id === selectedSlots[item.id]);
if (!slot) {
unavailable.push(item.id);
return;
}
if (dayjs(slot.freezeTime).isBefore(now)) {
closed.push(item.id);
}
});
if (noSlots.length > 0 || unavailable.length > 0) {
return {
blocked: true,
itemIds: [...noSlots, ...unavailable],
message:
'Some items in your cart are no longer available for delivery. Please remove them to continue.',
};
}
if (closed.length > 0) {
return {
blocked: true,
itemIds: closed,
message:
'The delivery slot for some items has closed. Please pick a new slot to continue.',
};
}
return { blocked: false, itemIds: [], message: null };
}, [isFlashDelivery, cartItems, productSlotsMap, slotsData, selectedSlots]);
const isCheckoutDisabled = slotCheck.blocked;
const slotGroups = useMemo<DeliverySlotGroup[]>(() => {
if (isFlashDelivery || cartItems.length === 0) return [];
const groupMap = new Map<number, DeliverySlotGroup>();
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<DeliverySlotMergeSuggestion | null>(() => {
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<number, number> = {};
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<number, number>);
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 (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
<MyText style={tw`text-gray-500 font-medium`}>Loading...</MyText>
</View>
);
}
if (!isAuthenticated) {
return (
<LoginWall
message="Log in to view your cart and continue to checkout."
onBack={() => router.back()}
/>
);
}
if (isLoading || (isSlotsLoading && !isFlashDelivery)) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
<MyText style={tw`text-gray-500 font-medium`}>Loading cart...</MyText>
</View>
);
}
if (error) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
<MaterialIcons name="error-outline" size={48} color="#EF4444" />
<MyText style={tw`text-gray-900 text-lg font-bold mt-4`}>Oops!</MyText>
<MyText style={tw`text-gray-500 mt-2`}>Failed to load your cart</MyText>
</View>
);
}
// No delivery address yet (but a region exists from the location): ask for the
// first address before showing the cart — even when the cart is empty. The
// first saved address becomes the default.
if (addressesQuery.isLoading) {
return (
<View style={tw`flex-1 justify-center items-center bg-gray-50`}>
<MyText style={tw`text-gray-500 font-medium`}>Loading...</MyText>
</View>
);
}
// No active address for the current region. Addresses that live in another
// region do not count: the neo store never selects them across regions.
if (selectedAddressId == null) {
return (
<CartAddressGate
onDone={() => {
void addressesQuery.refetch();
}}
onBack={() => router.back()}
/>
);
}
return (
<View style={tw`flex-1 bg-gray-50`}>
{/* Fixed Cart Type Header */}
<View style={tw`bg-white px-4 py-3 border-b border-gray-100 mt-6`}>
<View style={tw`flex-row items-center`}>
<MyTouchableOpacity
testID="cart-header-back"
onPress={() => router.back()}
style={tw`p-2 -ml-2 mr-1`}
activeOpacity={0.7}
>
<MaterialIcons name="chevron-left" size={28} color="#374151" />
</MyTouchableOpacity>
<MaterialIcons
name={isFlashDelivery ? "flash-on" : "schedule"}
size={24}
color={isFlashDelivery ? "#f81260" : "#374151"}
/>
<MyText style={[
tw`text-lg font-bold ml-2`,
{ color: isFlashDelivery ? '#f81260' : '#374151' }
]}>
{isFlashDelivery ? "1 Hr Delivery Cart" : "Scheduled Delivery Cart"}
</MyText>
</View>
</View>
<AppContainer>
<ScrollView
style={tw`flex-1`}
contentContainerStyle={tw`pb-32`}
showsVerticalScrollIndicator={false}
>
{/* Cart Items */}
{cartItems.length === 0 ? (
<View style={tw`items-center justify-center py-12`}>
<View
style={tw`w-20 h-20 bg-gray-100 rounded-full items-center justify-center mb-4`}
>
<MaterialIcons name="shopping-cart" size={32} color="#9CA3AF" />
</View>
<MyText style={tw`text-lg font-bold text-gray-900`}>
Your cart is empty
</MyText>
<MyText style={tw`text-gray-500 mt-2 text-center px-8`}>
Looks like you haven&apos;t added anything to your cart yet.
</MyText>
<MyTouchableOpacity
testID="cart-start-shopping"
style={tw`mt-6 bg-brand500 px-6 py-3 rounded-xl`}
onPress={() => router.push("/(drawer)/(tabs)/home")}
>
<MyText style={tw`text-white font-bold`}>Start Shopping</MyText>
</MyTouchableOpacity>
</View>
) : (
<>
<View style={tw`bg-white rounded-2xl shadow-sm mb-4 border border-gray-100`}>
{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 (
<View key={item.id} testID={`cart-sku-${item.skuId}`}>
<View style={tw`p-4`}>
<View style={tw`flex-row items-center mb-2`}>
<MyTouchableOpacity
testID={`cart-item-image-${item.id}`}
onPress={() =>
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}
>
<Image
source={{ uri: product?.images?.[0] }}
style={tw`w-8 h-8 rounded-lg bg-gray-100 mr-3`}
/>
</MyTouchableOpacity>
<MyTouchableOpacity
testID={`cart-item-name-${item.id}`}
onPress={() =>
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`}
>
<MyText
style={tw`text-sm text-gray-900`}
numberOfLines={2}
>
{product?.name}
</MyText>
</MyTouchableOpacity>
<MyText style={tw`text-xs text-gray-500 mr-2`}>
{product?.productType !== 'combo' ? (product?.unitNotation || '') : ''}
</MyText>
<View style={tw`flex-row items-center w-32 justify-end`}>
<View style={[tw`w-12`, { width: 120 }]}>
<Quantifier
testID={`cart-item-${item.id}`}
value={quantities[item.id] || item.quantity}
setValue={(value) => {
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}
/>
</View>
</View>
</View>
{/* Delivery Slot Selection per Product - Hidden for 1 Hr Delivery */}
{!isFlashDelivery && (
<View style={tw`flex flex-row items-center justify-between mt-2`}>
<View style={tw`flex-1 mr-4`}>
<BottomDropdown
testID={`slot-dropdown-${item.id}`}
label="Select Delivery Slot"
options={productSlots}
value={selectedSlotForItem || ""}
onValueChange={(value) => {
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 (
<View style={tw`flex-row items-center py-1`}>
<MaterialIcons
name="local-shipping"
size={14}
color="#6B7280"
style={tw`mr-1`}
/>
<MyText style={tw`text-sm text-gray-900 mr-2`}>
{deliveryTimeText || (productSlots.length === 0
? "No delivery slots available"
: "Choose delivery slot")}
</MyText>
<MyTouchableOpacity
testID={`cart-item-slot-${item.id}`}
onPress={onPress}
disabled={disabled}
activeOpacity={0.7}
>
<MyText style={tw`text-sm text-brand500 font-medium`}>
Change
</MyText>
</MyTouchableOpacity>
</View>
);
}}
/>
</View>
<View style={tw`justify-end`}>
<View style={tw`flex-row items-center gap-2`}>
<MyText style={tw`text-md font-medium text-brand900`}>
₹{itemPrice}
</MyText>
<TouchableOpacity
testID={`cart-item-delete-${item.id}`}
onPress={() => {
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`}
>
<MaterialIcons
name="delete"
size={20}
color="#EF4444"
/>
</TouchableOpacity>
</View>
</View>
</View>
)}
{/* Price for 1 Hr Delivery (already in same row as slot) */}
{isFlashDelivery && (
<View style={tw`flex-row justify-end mt-2`}>
<View style={tw`flex-row items-center gap-2`}>
<MyText style={tw`text-md font-medium text-brand900`}>
₹{itemPrice}
</MyText>
<TouchableOpacity
testID={`cart-item-delete-${item.id}`}
onPress={() => {
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`}
>
<MaterialIcons
name="delete"
size={20}
color="#EF4444"
/>
</TouchableOpacity>
</View>
</View>
)}
{!isAvailable && (
<View
style={tw`bg-red-50 self-start px-2 py-1 rounded-md mt-2`}
>
<MyText style={tw`text-xs font-bold text-red-600`}>
{productSlotInfo?.isOutOfStock
? "Out of Stock"
: isFlashDelivery && !flashEligibleProductIds.has(item.skuId)
? "Not available for flash delivery. Please remove"
: "No delivery slots available"}
</MyText>
</View>
)}
</View>
{/* Gray horizontal line between items (except for the last item) */}
{index < cartItems.length - 1 && (
<View style={tw`h-px bg-gray-200 mx-4`} />
)}
</View>
);
})}
</View>
{/* Delivery Slot Summary */}
{!isFlashDelivery && cartItems.length > 0 && (
<DeliverySlotSummary
groups={slotGroups}
mergeSuggestion={mergeSuggestion}
onMerge={handleMergeSlots}
/>
)}
</>
)}
{/* Cart Type Switcher (hidden) */}
{false && cartItems.length > 0 && (
<View style={tw`bg-white rounded-2xl shadow-sm mb-4 border border-gray-100 overflow-hidden`}>
<View style={tw`p-4`}>
{/* First row: Text content */}
<View style={tw`flex-row items-center mb-3`}>
<View style={tw`w-10 h-10 rounded-full items-center justify-center mr-3 ${isFlashDelivery ? 'bg-orange-100' : 'bg-blue-100'}`}>
<MaterialIcons
name={isFlashDelivery ? "flash-on" : "schedule"}
size={20}
color={isFlashDelivery ? "#EA580C" : "#2563EB"}
/>
</View>
<View style={tw`flex-1`}>
<MyText style={tw`text-base font-bold text-gray-900`}>
{isFlashDelivery ? "1 Hr Delivery" : "Scheduled Delivery"}
</MyText>
<MyText style={tw`text-sm text-gray-500 mt-0.5`}>
{isFlashDelivery
? "within 1 hour delivery • Immediate pickup"
: "Choose your preferred delivery time"
}
</MyText>
</View>
</View>
{/* Second row: Navigation trigger */}
<MyTouchableOpacity
style={tw`bg-gray-100 px-4 py-2 rounded-lg flex-row items-center self-start`}
onPress={() => {
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}
>
<MyText style={tw`text-gray-700 font-medium mr-1`}>
{isFlashDelivery ? "Go to Scheduled Delivery" : "Go to 1 Hr Delivery"}
</MyText>
<MaterialIcons
name="arrow-forward"
size={16}
color="#374151"
/>
</MyTouchableOpacity>
</View>
</View>
)}
{/* Coupon Selection */}
{hasAvailableItems && (
<View
style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}
>
<View style={tw`flex-row items-center mb-3`}>
<View
style={tw`w-8 h-8 bg-pink-50 rounded-full items-center justify-center mr-3`}
>
<MaterialIcons name="local-offer" size={18} color="#EC4899" />
</View>
<MyText style={tw`text-base font-bold text-gray-900`}>
Offers & Coupons
</MyText>
</View>
<BottomDropdown
testID="coupon-dropdown"
label="Available Coupons"
options={dropdownData}
value={selectedCouponIds}
onValueChange={handleCouponSelectionChange}
multiple
placeholder={
eligibleCoupons.length === 0
? "No coupons available"
: "Select a coupon"
}
/>
{/* Selected coupons, each removable with the "x" on its right */}
{selectedCouponIds.length > 0 && (
<View style={tw`flex-row flex-wrap gap-2 mt-3`}>
{selectedCouponIds.map((id) => {
const coupon = eligibleCoupons.find((c) => c.id === id);
if (!coupon) return null;
return (
<View
key={id}
testID={`coupon-chip-${coupon.code}`}
style={tw`flex-row items-center bg-pink-50 border border-pink-200 rounded-full pl-3 pr-1.5 py-1`}
>
<MyText style={tw`text-xs font-semibold text-pink-700 mr-1`}>
{coupon.code}
</MyText>
<MyTouchableOpacity
testID={`coupon-chip-remove-${coupon.code}`}
onPress={() =>
setSelectedCouponIds((prev) =>
prev.filter((cid) => cid !== id)
)
}
style={tw`p-0.5`}
activeOpacity={0.7}
>
<MaterialIcons name="close" size={14} color="#BE185D" />
</MyTouchableOpacity>
</View>
);
})}
</View>
)}
{eligibleCoupons.length === 0 && (
<MyText style={tw`text-gray-400 text-xs mt-2 ml-1`}>
No coupons available for this order
</MyText>
)}
{selectedCouponIds.length > 0 && (
<MyTouchableOpacity
testID="remove-coupons"
style={tw`mt-3 self-end`}
onPress={() => setSelectedCouponIds([])}
>
<MyText style={tw`text-gray-400 text-xs font-medium`}>
Remove coupons
</MyText>
</MyTouchableOpacity>
)}
{!isAuthenticated && (
<MyTouchableOpacity
style={tw`mt-2 ml-1`}
onPress={() => router.push("/(drawer)/(tabs)/me")}
>
<MyText style={tw`text-xs`}>
<MyText style={tw`text-blue-500 underline`}>Log In</MyText>
<MyText style={tw`text-gray-400`}> To find offers and coupons</MyText>
</MyText>
</MyTouchableOpacity>
)}
{/* Link to add coupons to account */}
<MyTouchableOpacity
testID="add-coupons-to-account"
style={tw`mt-2 ml-1`}
onPress={() => router.push("/(drawer)/(tabs)/me/coupons?from=cart")}
>
<MyText style={tw`text-xs text-blue-500 underline`}>
Add Coupons to account
</MyText>
</MyTouchableOpacity>
</View>
)}
{/* Delivery Instructions */}
<View style={tw`bg-white p-5 rounded-2xl shadow-sm mb-4 border border-gray-100`}>
<MyText style={tw`text-base font-bold text-gray-900 mb-3`}>Delivery Instructions</MyText>
<MyTextInput
testID="delivery-instructions"
value={userNotes}
onChangeText={setUserNotes}
placeholder="Any special instructions for the delivery partner..."
multiline
numberOfLines={3}
/>
</View>
{/* Delivery Address */}
<CheckoutAddressSelector />
{/* Bottom Checkout Bar - Now Static */}
{hasAvailableItems && (
<View style={tw`bg-white mt-4 rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6`}>
{/* Bill Header */}
<View style={tw`bg-gray-50 px-4 py-3 border-b border-gray-100`}>
<MyText style={tw`text-gray-900 font-bold text-base`}>Bill Details</MyText>
</View>
<View style={tw`p-4`}>
{/* Item Total */}
<View style={tw`flex-row justify-between items-center mb-3`}>
<MyText style={tw`text-gray-500`}>Item Total</MyText>
<MyText style={tw`text-gray-900 font-medium`}>₹{Math.trunc(totalPrice)}</MyText>
</View>
{/* Products discount (market-price savings) */}
{totalSavings > 1 && (
<View style={tw`flex-row justify-between items-center mb-3`}>
<MyText style={tw`text-gray-500`}>Products discount</MyText>
<MyText style={tw`text-green-600 font-medium`}>₹{Math.trunc(totalSavings)}</MyText>
</View>
)}
{/* Coupon discounts: every applied coupon and what it takes off */}
{selectedCoupons.map((coupon) => (
<View
key={coupon.id}
style={tw`flex-row justify-between items-center mb-3`}
>
<View style={tw`flex-row items-center flex-1 mr-2`}>
<MyTouchableOpacity
testID={`coupon-bill-${coupon.id}`}
style={tw`flex-row items-center`}
onPress={() => setCouponDialogOpen(true)}
activeOpacity={0.7}
>
<MaterialIcons name="local-offer" size={14} color="#EC4899" style={tw`mr-1.5`} />
<MyText style={tw`text-pink-600 font-medium`}>
{coupon.code}
</MyText>
</MyTouchableOpacity>
{/* Product-specific coupon: how much came off each product. A
sibling of the row above, so it cannot open the applied-
coupons dialog by accident. */}
{coupon.applicableSkuIds.length > 0 && (
<MyTouchableOpacity
testID={`coupon-breakdown-${coupon.id}`}
onPress={() => setBreakdownCouponId(coupon.id)}
style={tw`p-1 ml-0.5`}
activeOpacity={0.7}
>
<MaterialIcons name="info-outline" size={14} color="#EC4899" />
</MyTouchableOpacity>
)}
</View>
<MyText style={tw`text-green-600 font-medium`}>
-₹{Math.trunc(couponDiscounts[coupon.id] || 0)}
</MyText>
</View>
))}
{/* Delivery Fee */}
<View style={tw`flex-row justify-between items-center mb-3`}>
<View style={tw`flex-row items-center`}>
<MyText style={tw`text-gray-500`}>Delivery Fee</MyText>
<MaterialIcons name="info-outline" size={14} color="#9CA3AF" style={tw`ml-1`} />
</View>
<View style={tw`flex-row items-center`}>
{deliveryCharge === 0 && (constsData?.deliveryCharge || 0) > 0 && (
<MyText style={tw`text-gray-400 line-through mr-2 text-xs`}>
₹{constsData?.deliveryCharge}
</MyText>
)}
<MyText style={tw`${deliveryCharge === 0 ? 'text-green-600' : 'text-gray-900'} font-medium`}>
{deliveryCharge === 0 ? 'Free' : `₹${deliveryCharge}`}
</MyText>
</View>
</View>
{/* Free Delivery Nudge */}
{deliveryCharge > 0 && (freeDeliveryThreshold || 0) > 0 && finalTotal < (freeDeliveryThreshold || 0) && (
<View style={tw`bg-blue-50 p-2.5 rounded-lg mb-3 flex-row items-center`}>
<MaterialIcons name="shopping-bag" size={16} color="#2563EB" style={tw`mr-2`} />
<MyText style={tw`text-blue-700 text-xs font-medium flex-1`}>
Add products worth ₹{((freeDeliveryThreshold || 0) - finalTotal).toFixed(0)} for free delivery
</MyText>
</View>
)}
{/* Divider */}
<View style={tw`h-px bg-gray-100 my-2`} />
{/* Grand Total */}
<View style={tw`flex-row justify-between items-center mt-2`}>
<MyText style={tw`text-lg font-bold text-gray-900`}>To Pay</MyText>
<MyText testID="cart-to-pay" style={tw`text-xl font-bold text-gray-900`}>₹{Math.trunc(finalTotalWithDelivery)}</MyText>
</View>
{/* Savings Banner */}
{(discountAmount > 0 || deliveryCharge === 0 || totalSavings > 1) && (
<View style={tw`bg-green-50 rounded-lg p-2 mt-4 flex-row justify-center items-center`}>
<MaterialIcons name="stars" size={16} color="#059669" style={tw`mr-1.5`} />
<MyText style={tw`text-green-700 text-xs font-bold`}>
You saved ₹{Math.trunc(discountAmount + totalSavings + (deliveryCharge === 0 ? (constsData?.deliveryCharge || 0) : 0))} on this order
</MyText>
</View>
)}
</View>
{/* Action Buttons */}
<View style={tw`p-4 border-t border-gray-100 bg-gray-50`}>
<View style={tw`flex-row gap-3`}>
<MyTouchableOpacity
testID="shop-more-button"
style={tw`flex-1 bg-white border border-gray-200 py-3.5 rounded-xl items-center shadow-sm`}
onPress={() => router.push(isFlashDelivery ? "/(drawer)/(tabs)/flash-delivery" : "/(drawer)/(tabs)/home")}
>
<MyText style={tw`text-gray-700 font-bold`}>Shop More</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity
testID="checkout-button"
disabled={isCheckoutDisabled}
style={tw`flex-1 ${isCheckoutDisabled ? 'bg-gray-300' : 'bg-brand500'} py-3.5 rounded-xl items-center flex-row justify-center ${isCheckoutDisabled ? '' : 'shadow-md'}`}
onPress={() => {
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<number, number[]> = {};
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)}${selectedCouponIds.length ? `&coupons=${selectedCouponIds.join(',')}` : ''}&deliveryPrice=${deliveryCharge}` as any
);
}}
>
<MyText style={tw`text-white font-bold mr-1`}>Checkout</MyText>
<MaterialIcons name="arrow-forward" size={18} color="white" />
</MyTouchableOpacity>
</View>
{slotCheck.blocked && (
<View style={tw`mt-3 bg-red-50 border border-red-100 rounded-lg p-2.5 flex-row items-center`}>
<MaterialIcons name="error-outline" size={16} color="#DC2626" style={tw`mr-2`} />
<MyText style={tw`text-red-600 text-xs font-medium flex-1`}>
{slotCheck.message}
</MyText>
</View>
)}
</View>
</View>
)}
</ScrollView>
</AppContainer>
{/* Per-product discount split of one applied coupon (the bill's "i") */}
<CouponBreakdownDialog
coupon={breakdownCoupon ? { id: breakdownCoupon.id, code: breakdownCoupon.code } : null}
breakdown={breakdown ?? null}
cartLines={cartLines}
onClose={() => setBreakdownCouponId(null)}
/>
{/* Coupon Details Dialog */}
<BottomDialog
open={couponDialogOpen}
onClose={() => setCouponDialogOpen(false)}
>
<View testID="coupon-details-dialog" style={tw`p-6`}>
<View style={tw`flex-row items-center mb-6`}>
<View
style={tw`w-10 h-10 bg-pink-50 rounded-full items-center justify-center mr-3`}
>
<MaterialIcons name="local-offer" size={20} color="#EC4899" />
</View>
<MyText style={tw`text-xl font-bold text-gray-900`}>
Applied Coupons
</MyText>
</View>
{selectedCoupons.map((coupon) => (
<View
key={coupon.id}
style={tw`mb-4 p-4 bg-white border border-gray-100 rounded-xl shadow-sm`}
>
<View style={tw`flex-row justify-between items-start`}>
<View>
<MyText style={tw`font-bold text-gray-900 text-lg`}>
{coupon.code}
</MyText>
<MyText style={tw`text-sm text-gray-500 mt-1`}>
{coupon.description}
</MyText>
</View>
<View style={tw`bg-green-50 px-2 py-1 rounded`}>
<MyText style={tw`text-xs font-bold text-green-700`}>
{coupon.discountType === "percentage"
? `${coupon.discountValue}% OFF`
: `₹${coupon.discountValue} OFF`}
</MyText>
</View>
</View>
{coupon.maxValue && (
<MyText style={tw`text-xs text-gray-400 mt-2`}>
Maximum discount up to ₹{coupon.maxValue}
</MyText>
)}
</View>
))}
<MyTouchableOpacity
testID="coupon-details-close"
style={tw`mt-4 bg-gray-900 py-3.5 rounded-xl items-center`}
onPress={() => setCouponDialogOpen(false)}
>
<MyText style={tw`text-white font-bold`}>Close</MyText>
</MyTouchableOpacity>
</View>
</BottomDialog>
</View>
);
}