'use client'; import { useEffect, useRef, useState } from 'react'; import { AlertTriangle, Loader2, ShoppingBag, X } from 'lucide-react'; import { formatPrice } from 'brainerce'; import { Link } from '@/core/lib/navigation'; import { useCartPage } from '@/core/hooks/use-cart-page'; import { useCart, useStoreInfo } from '@/core/providers/store-provider'; import { CartItem } from '@/ui/cart/cart-item'; import { CartUpgradeBanner } from '@/ui/cart/cart-upgrade-banner'; import { CartBundleOfferCard } from '@/ui/cart/cart-bundle-offer'; import { CartSummary } from '@/ui/cart/cart-summary'; import { CouponInput } from '@/ui/cart/coupon-input'; import { CartNudges } from '@/ui/cart/cart-nudges'; import { FreeShippingBar } from '@/ui/cart/free-shipping-bar'; import { ReservationCountdown } from '@/ui/cart/reservation-countdown'; import { CartRecommendationSection } from '@/ui/product/recommendation-section'; import { Button } from '@/components/ui/button'; import { Checkbox } from '@/components/ui/checkbox'; import { Card } from '@/components/ui/card'; import { Separator } from '@/components/ui/separator'; import { Skeleton } from '@/components/ui/skeleton'; import { getErrorCode } from '@/core/lib/add-to-cart-error'; import { useCurrency } from '@/core/lib/use-currency'; import { useTranslations } from '@/core/lib/translations'; import { cn } from '@/core/lib/utils'; /** * Which `cart.*` sentence a failed cart write gets. Two refusals are permanent * (a retry cannot clear them) and get their own sentence; everything else is * the generic "your cart is back the way it was". */ function mutationErrorKey(error: Error): 'notEnoughStock' | 'itemUnavailable' | 'updateFailed' { const code = getErrorCode(error); if (code === 'INSUFFICIENT_STOCK') return 'notEnoughStock'; if (code === 'PRODUCT_UNAVAILABLE') return 'itemUnavailable'; return 'updateFailed'; } export function CartView() { const t = useTranslations('cart'); const tp = useTranslations('productDetail'); const { storeInfo } = useStoreInfo(); const tc = useTranslations('common'); const tr = useTranslations('reservation'); const currency = useCurrency(); const { cart, refreshCart, itemCount, cartRecs, upgrades, bundles, reservationExpired, selectedItemIds, selectedItems, toggleItemSelected, allSelected, setAllSelected, checkoutHref, canProceedToCheckout, onReservationExpired, proceedToCheckout, proceedingToCheckout, } = useCartPage(); // Cart STATE. `status` is what decides what to draw: `cart === null` means // "loading" and "could not load" alike, and neither is an empty cart. const { status, hintCount, isSyncing, totalsStale, totals, mutationError, dismissMutationError, retry, } = useCart(); // The in-page checkout button is far down the page on a phone; the sticky bar // below stands in for it until the real one scrolls into view. const summaryCtaRef = useRef(null); const [summaryCtaInView, setSummaryCtaInView] = useState(false); useEffect(() => { const el = summaryCtaRef.current; if (!el || typeof IntersectionObserver === 'undefined') return; const observer = new IntersectionObserver( ([entry]) => setSummaryCtaInView(entry.isIntersecting), { rootMargin: '0px 0px -96px 0px' } ); observer.observe(el); return () => observer.disconnect(); }, [status]); // 1. No answer yet: a skeleton the size of the cart we remember, never a // spinner and never the empty state. if (status === 'loading') { const rows = hintCount > 0 ? Math.min(hintCount, 4) : 2; return (
); } // 2. The load FAILED. This is not an empty cart, so it does not look like one, // and it carries the way out. if (status === 'error') { return (
); } // 3. The server said the cart has no lines. if (status === 'empty' || !cart) { return (
); } // 4. Ready. (`cart.items` can be empty here for a moment: the last line was // removed optimistically and the server has not confirmed it yet. The cart // stays on screen until it does, and the checkout button below is closed.) // `canProceedToCheckout` is closed while the cart is not ready, while a change // is still on its way to the server, while the reservation is expired and while // a TICKED line is unavailable. The line under the button says which. const canCheckoutNow = canProceedToCheckout && cart.items.length > 0; const hardReason = selectedItems.some((item) => item.isAvailable === false) ? t('unavailableItemsHint') : reservationExpired ? tr('expiredHint') : cart.items.length === 0 ? t('emptyTitle') : selectedItems.length === 0 ? t('selectItemsHint') : null; // Muted "waiting" while a click is holding for the cart's last writes, or the // button is closed only because a change is still pending; a hard reason (red) // otherwise. const checkoutNote = proceedingToCheckout ? { text: t('checkoutWaiting'), blocked: false } : canCheckoutNow ? null : hardReason ? { text: hardReason, blocked: true } : totalsStale ? { text: t('checkoutWaiting'), blocked: false } : null; // "Proceed to checkout" is a real link, so a modified click (new tab) and // right-click still work. A plain click waits until the cart writes the // shopper just made have reached the server, THEN navigates (`proceedToCheckout` // does both): checkout reads the cart from the server, and a tap on + a moment // ago must be in it. A failed write stays on the cart, rolled back, with the // alert above. function handleCheckoutClick(event: React.MouseEvent) { if ( event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey ) { return; } event.preventDefault(); void proceedToCheckout(); } const renderCheckoutAction = (className: string) => canCheckoutNow ? ( ) : ( ); return (

{t('title')} ({itemCount} {itemCount === 1 ? tc('item') : tc('items')})

{/* Subtle, and never blocking: the cart stays fully usable while this shows. Always mounted so a screen reader hears it appear. The row keeps its height whether or not it shows anything: an indicator that adds a line when it appears pushes the quantity buttons down mid-tap, and the next tap of a quick burst lands above the button. */}
{isSyncing ? ( <>
{/* A cart write that failed and was rolled back. Dismissible; it also clears itself on the next successful write. */} {mutationError && (

{t(mutationErrorKey(mutationError))}

)} {/* Reservation countdown. onExpire refreshes the cart and closes the checkout gate below. Passing it is what makes expiry mean anything. */} {cart.reservation?.hasReservation && ( )}
{/* Cart Items */}
{/* Nudges */} {cart.nudges && cart.nudges.length > 0 && ( )} {/* Select-all. Partial checkout: only the ticked lines are sent to createCheckout, and whatever stays unticked is still in the cart (and still for sale) after payment. */}
setAllSelected(checked === true)} />
{/* Cart items */}
{cart.items.map((item) => (
toggleItemSelected(item.id)} aria-label={item.product.name} />
{upgrades?.upgrades?.[item.productId] && ( )}
))}
{/* Bundle offers */} {bundles?.bundles && bundles.bundles.length > 0 && (

{t('bundleOffers')}

{bundles.bundles.map((offer) => ( ))}
)} {/* Coupon input */}
{/* Summary sidebar */}
{/* Totals are the last CONFIRMED ones from the server (this page never computes prices). While a change is still on its way they are dimmed, not hidden. */}
{/* Totals are for the WHOLE cart. A partial selection is priced authoritatively on the checkout page, which is the only place the server has scoped the discounts and tax to the subset. */} {totalsStale && {t('totalsUpdating')}}
{/* Shown once the shopper unticks anything. At zero selected this is what explains the disabled button below — a count, so it needs no copy of its own. */} {!allSelected && (

{selectedItems.length} {selectedItems.length === 1 ? tc('item') : tc('items')}

)} {/* Proceed to checkout. When the gate is closed this must be a real disabled control, never a styled-down link: an anchor ignores `disabled` and would still navigate. The reason sits beside it, and the same line says "waiting" while the click is holding for the cart's last writes. */}
{renderCheckoutAction('mt-6 w-full rounded px-6 text-sm')}

{checkoutNote?.text ?? null}

{tc('continueShopping')}
{/* Manual recommendations (the merchant's own list) */} {cartRecs?.recommendations && cartRecs.recommendations.length > 0 && ( )} {/* Automatic suggestions from purchase history: ONE group, its own rail AFTER the manual one, never merged into it. Never contains a product already in the cart. */} {cartRecs?.automaticRecommendations && cartRecs.automaticRecommendations.items.length > 0 && (cartRecs.automaticRecommendations.kind !== 'bought_together' || storeInfo?.upsell?.frequentlyBoughtTogetherEnabled) && ( )} {/* Phone checkout bar. In normal flow at the END of the page, so it can never sit on top of the footer; `sticky` keeps it at the bottom of the screen while the items scroll. It stands down (still taking up its space, so nothing jumps) while the in-page button is on screen. The bottom padding keeps it clear of the home indicator. */}

{tc('total')}

{formatPrice(totals.total, { currency }) as string}

{renderCheckoutAction('flex-shrink-0 rounded px-6 text-sm')}
); }