"use client"
import * as React from "react"
import {
ArrowRight,
Check,
LoaderCircle,
ShoppingBag,
X,
} from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
Sheet,
SheetClose,
SheetContent,
SheetDescription,
SheetTitle,
SheetTrigger,
} from "@/components/ui/sheet"
import {
Heading,
nextHeadingLevel,
type HeadingLevel,
} from "@/components/hazine/heading"
import { useControllableState } from "@/hooks/use-controllable-state"
import {
MiniCartSideDrawerLine,
focusRing,
tileClass,
zonePadding,
type CartLine,
} from "./mini-cart-side-drawer.line"
export type { CartLine }
/** Props spread to the wrapper around the cart button. The panel is portalled. */
export interface MiniCartSideDrawerProps extends Omit<
React.ComponentProps<"div">,
"title"
> {
title?: string
headingLevel?: HeadingLevel
open?: boolean
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
lines?: CartLine[]
defaultLines?: CartLine[]
onLinesChange?: (lines: CartLine[]) => void
/** Subtotal from which shipping is free. Pass 0 to hide the meter. */
freeShippingFrom?: number
/** Replaces the lines with skeleton rows and holds the checkout action. */
loading?: boolean
/** Edge the panel slides in from. Pass "left" in right-to-left layouts. */
side?: "right" | "left"
currency?: string
locale?: string
checkoutHref?: string
cartHref?: string
}
const DEFAULT_LINES: CartLine[] = [
{
id: "stoneware-pour-over-set",
name: "Stoneware Pour-Over Set",
variant: "Speckled white, 2 cups",
href: "/products/stoneware-pour-over-set",
unitPrice: 48,
quantity: 1,
maxQuantity: 4,
},
{
id: "guji-filter-roast",
name: "Guji Filter Roast",
variant: "Whole bean, 250 g",
href: "/products/guji-filter-roast",
unitPrice: 13.5,
quantity: 2,
maxQuantity: 12,
},
{
id: "gooseneck-kettle",
name: "Gooseneck Kettle",
variant: "Matte black, 0.9 L",
href: "/products/gooseneck-kettle",
unitPrice: 64,
quantity: 1,
maxQuantity: 2,
},
]
const DEFAULT_FREE_SHIPPING_FROM = 150
const EMPTY_TARGET = "empty-state"
const SKELETON_ROWS = ["first", "second", "third"]
const skeletonClass = "rounded-md bg-muted motion-safe:animate-pulse"
function countItems(count: number) {
return count === 1 ? "1 item" : `${count} items`
}
function ShippingMeter({
subtotal,
target,
money,
}: {
subtotal: number
target: number
money: Intl.NumberFormat
}) {
const textId = React.useId()
const remaining = Math.max(0, target - subtotal)
return (
<>
<div
role="meter"
aria-labelledby={textId}
aria-valuemin={0}
aria-valuemax={target}
aria-valuenow={Math.min(subtotal, target)}
aria-valuetext={`${money.format(subtotal)} of ${money.format(target)}`}
className="h-1.5 overflow-hidden rounded-full bg-muted"
>
<div
className="h-full rounded-full bg-primary"
style={{ inlineSize: `${Math.min(100, (subtotal / target) * 100)}%` }}
/>
</div>
<p id={textId} className="mt-2 text-sm text-muted-foreground">
{remaining > 0 ? (
<>
<span className="font-medium text-foreground tabular-nums">
{money.format(remaining)}
</span>{" "}
to go for free shipping
</>
) : (
<span className="inline-flex items-center gap-1.5 font-medium text-success">
<Check aria-hidden="true" className="size-3.5" />
Free shipping unlocked
</span>
)}
</p>
</>
)
}
export function MiniCartSideDrawer({
title = "Your cart",
headingLevel = 2,
open: openProp,
defaultOpen = false,
onOpenChange,
lines: linesProp,
defaultLines = DEFAULT_LINES,
onLinesChange,
freeShippingFrom = DEFAULT_FREE_SHIPPING_FROM,
loading = false,
side = "right",
currency = "EUR",
locale = "en-US",
checkoutHref = "/checkout",
cartHref = "/cart",
className,
...props
}: MiniCartSideDrawerProps) {
const [open, setOpen] = useControllableState({
value: openProp,
defaultValue: defaultOpen,
onChange: onOpenChange,
})
const [lines, setLines] = useControllableState({
value: linesProp,
defaultValue: defaultLines,
onChange: onLinesChange,
})
const [announcement, setAnnouncement] = React.useState("")
const lineNodes = React.useRef(new Map<string, HTMLLIElement>())
const emptyHeading = React.useRef<HTMLHeadingElement>(null)
const pendingFocus = React.useRef<string | null>(null)
// After a removal, focus lands on the line that took its place, or on the
// empty state heading when nothing is left. It never falls out of the panel.
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 = lines.reduce(
(sum, line) => sum + line.unitPrice * line.quantity,
0
)
const empty = lines.length === 0 && !loading
// Decimals are dropped only when every figure in the panel is whole, so one
// column never mixes "48" with "13.50".
const allWhole = [freeShippingFrom, ...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,
})
function setQuantity(id: string, quantity: number) {
setLines((current) =>
current.map((line) => (line.id === id ? { ...line, quantity } : line))
)
}
function removeLine(id: string) {
const index = lines.findIndex((line) => line.id === id)
if (index === -1) return
const next = lines.filter((line) => line.id !== id)
pendingFocus.current =
next.length === 0 ? EMPTY_TARGET : next[Math.min(index, next.length - 1)].id
setAnnouncement(`${lines[index].name} removed from cart.`)
setLines(next)
}
return (
<div
data-slot="mini-cart-side-drawer"
className={cn("inline-flex", className)}
{...props}
>
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button type="button" variant="outline">
<ShoppingBag aria-hidden="true" />
Cart
{itemCount > 0 && (
<span
aria-hidden="true"
className="flex h-5 min-w-5 items-center justify-center rounded-full bg-primary px-1.5 text-xs font-medium text-primary-foreground tabular-nums"
>
{itemCount}
</span>
)}
<span className="sr-only">
, {itemCount === 0 ? "empty" : countItems(itemCount)}
</span>
</Button>
</SheetTrigger>
<SheetContent
side={side}
showCloseButton={false}
aria-modal="true"
className="gap-0 data-[side=left]:w-full data-[side=right]:w-full"
>
<div
data-slot="mini-cart-side-drawer-panel"
className="@container flex min-h-0 flex-1 flex-col"
>
<div className={cn("flex items-start justify-between gap-4 py-4", zonePadding)}>
<div className="min-w-0">
<SheetTitle asChild className="text-lg font-semibold">
<Heading level={headingLevel}>{title}</Heading>
</SheetTitle>
<SheetDescription className="mt-0.5">
{empty && "Nothing added yet."}
{loading && "Updating your cart."}
{!empty && !loading && (
<>
<span className="font-medium text-foreground tabular-nums">
{countItems(itemCount)}.
</span>{" "}
Dispatched from Utrecht within 2 working days.
</>
)}
</SheetDescription>
</div>
<SheetClose asChild>
<Button type="button" variant="ghost" size="icon" aria-label="Close cart">
<X aria-hidden="true" />
</Button>
</SheetClose>
</div>
<p role="status" className="sr-only">
{announcement}
</p>
{freeShippingFrom > 0 && !empty && (
<div className={cn("border-t border-border py-3", zonePadding)}>
{loading ? (
<div aria-hidden="true">
<span className={cn("block h-1.5", skeletonClass)} />
<span className={cn("mt-2 block h-5 w-40", skeletonClass)} />
</div>
) : (
<ShippingMeter subtotal={subtotal} target={freeShippingFrom} money={money} />
)}
</div>
)}
{empty ? (
<div className="flex flex-1 flex-col items-center justify-center border-t border-border px-6 py-12 text-center">
<span aria-hidden="true" className={tileClass}>
<ShoppingBag className="size-5" strokeWidth={1.5} />
</span>
<Heading
ref={emptyHeading}
tabIndex={-1}
level={nextHeadingLevel(headingLevel)}
className={cn("mt-4 rounded-sm text-sm font-semibold", focusRing)}
>
Your cart is empty
</Heading>
<p className="mt-1 max-w-[40ch] text-sm text-muted-foreground">
Items you add are listed here with their quantity and price.
</p>
<SheetClose asChild>
<Button type="button" variant="outline" className="mt-6">
Continue shopping
</Button>
</SheetClose>
</div>
) : (
// A native scroller: the scroll-area primitive pins its content to
// left-to-right unless the host adds a direction provider.
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain border-t border-border">
<ul aria-busy={loading} className="divide-y divide-border">
{loading
? SKELETON_ROWS.map((row) => (
<li
key={row}
aria-hidden="true"
className={cn("flex gap-3 py-4", zonePadding)}
>
<span className={cn("size-9 shrink-0", skeletonClass)} />
<span className="flex flex-1 flex-col gap-2">
<span className={cn("h-4 w-3/4", skeletonClass)} />
<span className={cn("h-4 w-1/2", skeletonClass)} />
<span className={cn("mt-1 h-8 w-24", skeletonClass)} />
</span>
</li>
))
: lines.map((line) => (
<MiniCartSideDrawerLine
key={line.id}
ref={(node) => {
if (node) lineNodes.current.set(line.id, node)
else lineNodes.current.delete(line.id)
}}
line={line}
money={money}
onQuantityChange={(quantity) => setQuantity(line.id, quantity)}
onRemove={() => removeLine(line.id)}
/>
))}
</ul>
</div>
)}
{!empty && (
<div className={cn("border-t border-border bg-muted/50 py-4", zonePadding)}>
<div role="status" className="flex items-baseline justify-between gap-4">
<p className="text-sm text-muted-foreground">
{loading ? "Subtotal" : `Subtotal, ${countItems(itemCount)}`}
</p>
{loading ? (
<span aria-hidden="true" className={cn("h-8 w-24", skeletonClass)} />
) : (
<p className="text-2xl font-semibold tracking-tight whitespace-nowrap tabular-nums">
{money.format(subtotal)}
</p>
)}
</div>
<div className="mt-4 flex flex-col gap-2">
{loading ? (
<Button type="button" size="lg" disabled aria-busy="true" className="h-11 w-full">
<LoaderCircle aria-hidden="true" className="motion-safe:animate-spin" />
Updating cart
</Button>
) : (
<Button asChild size="lg" className="h-11 w-full">
<a href={checkoutHref}>
Check out {countItems(itemCount)}
<ArrowRight aria-hidden="true" className="rtl:rotate-180" />
</a>
</Button>
)}
<Button asChild variant="outline" className="w-full">
<a href={cartHref}>View cart</a>
</Button>
</div>
<p className="mt-3 text-center text-xs text-muted-foreground">
Shipping and taxes are calculated at checkout.
</p>
</div>
)}
</div>
</SheetContent>
</Sheet>
</div>
)
}