"use client"
import * as React from "react"
import { ArrowRight, ShoppingBag, Truck } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
Heading,
nextHeadingLevel,
type HeadingLevel,
} from "@/components/hazine/heading"
import { useControllableState } from "@/hooks/use-controllable-state"
import {
CartPageSummaryRailLine,
CartPageSummaryRailRemovedLine,
cartLinkClass,
type CartLine,
} from "./cart-page-summary-rail.line"
import {
CartPageSummaryRailPromo,
type CartPromo,
} from "./cart-page-summary-rail.promo"
export type { CartLine, CartPromo }
export interface CartShipping {
cost: number
/** Subtotal after discount from which shipping is free. */
freeFrom?: number
}
export interface CartDelivery {
/** ISO dates, for example "2026-03-12". */
earliest: string
latest: string
method: string
}
export interface CartPageSummaryRailProps
extends Omit<React.ComponentProps<"section">, "title"> {
title?: string
headingLevel?: HeadingLevel
lines?: CartLine[]
defaultLines?: CartLine[]
onLinesChange?: (lines: CartLine[]) => void
/** Codes the cart accepts. A submitted code outside this list shows as invalid. */
promos?: CartPromo[]
/** The applied code, or null for none. */
promoCode?: string | null
defaultPromoCode?: string | null
onPromoCodeChange?: (code: string | null) => void
shipping?: CartShipping
delivery?: CartDelivery
currency?: string
locale?: string
checkoutHref?: string
continueHref?: string
}
const DEFAULT_LINES: CartLine[] = [
{
id: "linen-overshirt",
name: "Linen Overshirt",
variant: "Sand, size M",
href: "/products/linen-overshirt",
unitPrice: 89,
quantity: 1,
maxQuantity: 5,
},
{
id: "merino-crew-socks",
name: "Merino Crew Socks",
variant: "Charcoal, pack of 2",
href: "/products/merino-crew-socks",
unitPrice: 14,
quantity: 2,
maxQuantity: 10,
},
{
id: "canvas-day-pack",
name: "Canvas Day Pack",
variant: "Olive, 18 L",
href: "/products/canvas-day-pack",
unitPrice: 64,
quantity: 1,
maxQuantity: 3,
},
]
const DEFAULT_PROMOS: CartPromo[] = [
{ code: "WELCOME10", label: "10% off items", percentOff: 10 },
{ code: "PACK15", label: "€15 off your order", amountOff: 15 },
]
const DEFAULT_SHIPPING: CartShipping = { cost: 6.5, freeFrom: 200 }
const DEFAULT_DELIVERY: CartDelivery = {
earliest: "2026-03-12",
latest: "2026-03-14",
method: "Tracked parcel from Rotterdam",
}
const EMPTY_TARGET = "empty-state"
const MINUS = "−"
const headingFocus =
"rounded-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-foreground"
function countItems(count: number) {
return count === 1 ? "1 item" : `${count} items`
}
function toCents(amount: number) {
return Math.round(amount * 100) / 100
}
function LedgerRow({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="flex items-baseline justify-between gap-4 py-2">
<dt className="min-w-0 text-muted-foreground wrap-break-word">{label}</dt>
<dd className="whitespace-nowrap tabular-nums">{children}</dd>
</div>
)
}
export function CartPageSummaryRail({
title = "Your cart",
headingLevel = 2,
lines: linesProp,
defaultLines = DEFAULT_LINES,
onLinesChange,
promos = DEFAULT_PROMOS,
promoCode: promoCodeProp,
defaultPromoCode = null,
onPromoCodeChange,
shipping = DEFAULT_SHIPPING,
delivery = DEFAULT_DELIVERY,
currency = "EUR",
locale = "en-US",
checkoutHref = "/checkout",
continueHref = "/",
className,
...props
}: CartPageSummaryRailProps) {
const titleId = React.useId()
const subLevel = nextHeadingLevel(headingLevel)
const [lines, setLines] = useControllableState({
value: linesProp,
defaultValue: defaultLines,
onChange: onLinesChange,
})
const [promoCode, setPromoCode] = useControllableState<string | null>({
value: promoCodeProp,
defaultValue: defaultPromoCode,
onChange: onPromoCodeChange,
})
const promo = promos.find((entry) => entry.code === promoCode)
const [announcement, setAnnouncement] = React.useState("")
const [removed, setRemoved] = React.useState<{ line: CartLine; index: number } | null>(null)
const lineNodes = React.useRef(new Map<string, HTMLLIElement>())
const emptyHeading = React.useRef<HTMLHeadingElement>(null)
const pendingFocus = React.useRef<string | null>(null)
// After a removal or an undo, focus lands on the line that took the place,
// or on the empty state heading when nothing is left.
React.useEffect(() => {
const target = pendingFocus.current
if (target === null) return
pendingFocus.current = null
const node = target === EMPTY_TARGET ? emptyHeading.current : lineNodes.current.get(target)
node?.focus()
}, [lines])
const itemCount = lines.reduce((sum, line) => sum + line.quantity, 0)
const subtotal = toCents(lines.reduce((sum, line) => sum + line.unitPrice * line.quantity, 0))
const promoValue = promo?.percentOff === undefined ? (promo?.amountOff ?? 0) : (subtotal * promo.percentOff) / 100
const discount = toCents(Math.min(subtotal, Math.max(0, promoValue)))
const discounted = toCents(subtotal - discount)
const freeFrom = shipping.freeFrom
const shippingCost = freeFrom !== undefined && discounted >= freeFrom ? 0 : shipping.cost
const total = toCents(discounted + shippingCost)
const toFreeShipping = freeFrom === undefined ? 0 : toCents(Math.max(0, freeFrom - discounted))
// The undo offer ends when the line is back, whoever put it there.
const undoable = removed && !lines.some((line) => line.id === removed.line.id) ? removed : null
// Decimals drop only when every figure shown is whole, so one column never
// mixes "89" with "6.50".
const allWhole = [shipping.cost, discount, toFreeShipping, ...lines.map((line) => line.unitPrice)].every(Number.isInteger)
const money = new Intl.NumberFormat(locale, {
style: "currency",
currency,
minimumFractionDigits: allWhole ? 0 : 2,
maximumFractionDigits: allWhole ? 0 : 2,
})
const formatMoney = (amount: number) => money.format(amount)
const day = new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", timeZone: "UTC" })
function setQuantity(line: CartLine, quantity: number) {
const atLimit = line.maxQuantity !== undefined && quantity >= line.maxQuantity
setAnnouncement(`${line.name}, quantity ${quantity}${atLimit ? ", the limit per order" : ""}.`)
setLines((current) => current.map((entry) => (entry.id === line.id ? { ...entry, quantity } : entry)))
}
function removeLine(line: CartLine) {
const index = lines.findIndex((entry) => entry.id === line.id)
if (index === -1) return
const next = lines.filter((entry) => entry.id !== line.id)
pendingFocus.current = next.length === 0 ? EMPTY_TARGET : next[Math.min(index, next.length - 1)].id
setRemoved({ line, index })
setAnnouncement(`${line.name} removed from cart. Undo is available.`)
setLines(next)
}
function undoRemoval() {
if (!undoable) return
pendingFocus.current = undoable.line.id
setAnnouncement(`${undoable.line.name} is back in your cart.`)
setLines([...lines.slice(0, undoable.index), undoable.line, ...lines.slice(undoable.index)])
setRemoved(null)
}
const removedRow = undoable && (
<CartPageSummaryRailRemovedLine name={undoable.line.name} onUndo={undoRemoval} />
)
const checkoutIcon = <ArrowRight aria-hidden="true" className="rtl:rotate-180" />
return (
<section
data-slot="cart-page-summary-rail"
aria-labelledby={titleId}
className={cn("@container bg-background py-12 text-foreground", className)}
{...props}
>
<div className="mx-auto w-full max-w-6xl px-4 @3xl:px-6">
<Heading
level={headingLevel}
id={titleId}
className="text-2xl font-semibold tracking-tight text-balance @3xl:text-4xl"
>
{title}
</Heading>
{lines.length > 0 && (
<p className="mt-4 text-base text-muted-foreground">
<span className="font-medium text-foreground tabular-nums">
{countItems(itemCount)} in your cart.
</span>{" "}
Review quantities here. Address and payment come next.
</p>
)}
{/* One region for every computed change, so a change is spoken once. */}
<p role="status" className="sr-only">
{announcement}
{lines.length > 0 && ` Total ${money.format(total)} for ${countItems(itemCount)}.`}
</p>
{lines.length === 0 ? (
<div className="mt-10 flex flex-col items-center rounded-xl border border-dashed border-border px-6 py-16 text-center">
<span
aria-hidden="true"
className="flex size-9 items-center justify-center rounded-md border border-border bg-background"
>
<ShoppingBag className="size-5" strokeWidth={1.5} />
</span>
<Heading
ref={emptyHeading}
tabIndex={-1}
level={subLevel}
className={cn("mt-4 text-lg font-semibold", headingFocus)}
>
Your cart is empty
</Heading>
<p className="mt-1 max-w-[40ch] text-sm text-muted-foreground wrap-break-word">
{undoable && (
<span className="font-medium text-foreground">
{undoable.line.name} removed.{" "}
</span>
)}
Items you add are listed here with their price and delivery estimate.
</p>
<div className="mt-6 flex flex-wrap justify-center gap-2">
{undoable && (
<Button
type="button"
aria-label={`Undo removal of ${undoable.line.name}`}
onClick={undoRemoval}
>
Undo removal
</Button>
)}
<Button asChild variant="outline">
<a href={continueHref}>Continue shopping</a>
</Button>
</div>
</div>
) : (
// overflow-clip rounds the frame without making it a scroll
// container, so the rail and the bar can stick to the page.
<div className="mt-10 grid overflow-clip rounded-xl border border-border @3xl:grid-cols-3">
<div className="@container/lines flex flex-col @3xl:col-span-2">
<ul className="divide-y divide-border">
{lines.map((line, index) => (
<React.Fragment key={line.id}>
{undoable?.index === index && removedRow}
<CartPageSummaryRailLine
ref={(node) => {
if (node) lineNodes.current.set(line.id, node)
else lineNodes.current.delete(line.id)
}}
line={line}
formatMoney={formatMoney}
onQuantityChange={(quantity) => setQuantity(line, quantity)}
onRemove={() => removeLine(line)}
/>
</React.Fragment>
))}
{undoable && undoable.index >= lines.length && removedRow}
</ul>
<p className="mt-auto border-t border-border px-4 py-3 text-sm font-medium @lg/lines:px-6">
<a href={continueHref} className={cartLinkClass}>Continue shopping</a>
</p>
</div>
<div className="border-t border-border bg-muted/50 @3xl:border-s @3xl:border-t-0">
{/* Capped at the viewport height, so checkout stays reachable
when the pinned rail is taller than the window. */}
<div
data-slot="cart-page-summary-rail-rail"
className="@3xl:sticky @3xl:top-0 @3xl:max-h-dvh @3xl:overflow-y-auto"
>
<div className="p-4 @3xl:p-6">
<Heading level={subLevel} className="text-lg font-semibold">
Order summary
</Heading>
<p className="mt-4 flex items-start gap-2 text-sm">
<Truck aria-hidden="true" className="mt-0.5 size-4 shrink-0" />
<span>
<span className="font-medium">
Arrives <time dateTime={delivery.earliest}>{day.format(new Date(delivery.earliest))}</time>
{delivery.latest !== delivery.earliest && (
<>
{" to "}
<time dateTime={delivery.latest}>{day.format(new Date(delivery.latest))}</time>
</>
)}
</span>
<span className="mt-0.5 block text-muted-foreground">
{delivery.method}.
{toFreeShipping > 0 && (
<>
{" Add "}
<span className="font-medium text-foreground tabular-nums">
{money.format(toFreeShipping)}
</span>
{" for free shipping."}
</>
)}
</span>
</span>
</p>
</div>
<CartPageSummaryRailPromo
promos={promos}
code={promoCode}
onCodeChange={setPromoCode}
onAnnounce={setAnnouncement}
className="border-t border-border p-4 @3xl:p-6"
/>
<dl className="divide-y divide-border border-t border-border p-4 text-sm @3xl:px-6">
<LedgerRow label={`Subtotal, ${countItems(itemCount)}`}>
{money.format(subtotal)}
</LedgerRow>
{promo && (
<LedgerRow label={`Discount, ${promo.code}`}>
{MINUS}
{money.format(discount)}
</LedgerRow>
)}
<LedgerRow label="Shipping">
{shippingCost === 0 ? "Free" : money.format(shippingCost)}
</LedgerRow>
</dl>
<div className="border-t border-border p-4 @3xl:p-6">
<div className="hidden @3xl:block">
<p className="text-sm text-muted-foreground">Total</p>
<p className="mt-1 text-2xl font-semibold tracking-tight tabular-nums">
{money.format(total)}
</p>
<p className="mt-1 text-xs text-muted-foreground tabular-nums">
{money.format(subtotal)} items
{promo && ` ${MINUS} ${money.format(discount)} discount`}
{shippingCost === 0 ? " + free shipping" : ` + ${money.format(shippingCost)} shipping`}
</p>
<Button asChild size="lg" className="mt-6 h-11 w-full">
<a href={checkoutHref}>
Check out {countItems(itemCount)}
{checkoutIcon}
</a>
</Button>
</div>
<p className="text-center text-xs text-muted-foreground @3xl:mt-3">
Prices include VAT. Free returns within 30 days.
</p>
</div>
</div>
</div>
{/* Under 48rem the total and the checkout action leave the rail
and stay in view at the bottom edge. */}
<div
data-slot="cart-page-summary-rail-bar"
className="sticky bottom-0 flex items-center justify-between gap-4 border-t border-border bg-background px-4 py-3 @3xl:hidden"
>
<p className="min-w-0">
<span className="block text-xs text-muted-foreground tabular-nums">
Total, {countItems(itemCount)}
</span>
<span className="block text-lg font-semibold tracking-tight tabular-nums">
{money.format(total)}
</span>
</p>
<Button asChild size="lg" className="h-11 w-36 shrink-0">
<a href={checkoutHref}>
Check out
{checkoutIcon}
</a>
</Button>
</div>
</div>
)}
</div>
</section>
)
}