All blocks
Checkout Form
Two-column storefront checkout with express wallets, shipping and billing address fields, selectable delivery cards, auto-formatted card entry with network detection, promo code discounts, gift notes, inline validation, and a sticky collapsible order summary.
Built withAlertAlert DialogBadgeButtonCardCenterCheckboxCollapsibleFieldGridHeadingIconIcon ButtonInputLinkNumber InputRadio CardSelectSeparatorStackTextTextareaToastTooltip
Kuro Roastery & KilnEncrypted checkout
Checkout
Small-batch coffee roasted in Portland and hand-thrown stoneware. Every transaction is protected with 256-bit SSL encryption.
Install
1npx stylexblocks add checkout-formSource
components/blocks/ui-sdk/checkout-form.tsx
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057import * as stylex from "@stylexjs/stylex";import { useCallback, useId, useMemo, useState } from "react";import { Alert } from "#components/ui/ui-sdk/alert.tsx";import { AlertDialog } from "#components/ui/ui-sdk/alert-dialog.tsx";import { Badge } from "#components/ui/ui-sdk/badge.tsx";import { Button } from "#components/ui/ui-sdk/button.tsx";import { Card } from "#components/ui/ui-sdk/card.tsx";import { Square } from "#components/ui/ui-sdk/center.tsx";import { Checkbox } from "#components/ui/ui-sdk/checkbox.tsx";import { Collapsible } from "#components/ui/ui-sdk/collapsible.tsx";import { Field } from "#components/ui/ui-sdk/field.tsx";import { Grid } from "#components/ui/ui-sdk/grid.tsx";import { Heading } from "#components/ui/ui-sdk/heading.tsx";import { Icon } from "#components/ui/ui-sdk/icon.tsx";import { IconButton } from "#components/ui/ui-sdk/icon-button.tsx";import { Input } from "#components/ui/ui-sdk/input.tsx";import { Link } from "#components/ui/ui-sdk/link.tsx";import { NumberInput } from "#components/ui/ui-sdk/number-input.tsx";import { RadioCard } from "#components/ui/ui-sdk/radio-card.tsx";import { Select } from "#components/ui/ui-sdk/select.tsx";import { Separator } from "#components/ui/ui-sdk/separator.tsx";import { HStack, VStack } from "#components/ui/ui-sdk/stack.tsx";import { Text } from "#components/ui/ui-sdk/text.tsx";import { Textarea } from "#components/ui/ui-sdk/textarea.tsx";import { Toast, Toaster } from "#components/ui/ui-sdk/toast.tsx";import { Tooltip } from "#components/ui/ui-sdk/tooltip.tsx";import { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";import { semanticRadii } from "@stylexblocks/ui/semantic-tokens/radii.stylex.ts";import { accentPalette, bluePalette, emeraldPalette, greenPalette, redPalette,} from "@stylexblocks/ui/themes/palettes.ts";import { fontSizes } from "@stylexblocks/ui/tokens/font-sizes.stylex.ts";import { fontWeights } from "@stylexblocks/ui/tokens/font-weights.stylex.ts";import { fonts } from "@stylexblocks/ui/tokens/fonts.stylex.ts";import { sizes } from "@stylexblocks/ui/tokens/sizes.stylex.ts";import { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";import type { StyleOverrideProps } from "#lib/recipe-props.ts";
// ── Types ─────────────────────────────────────────────────────────────────────
export type CheckoutArtworkKind = "carafe" | "coffee" | "cups";
export interface CheckoutItem { id: string; sku: string; name: string; variant: string; price: number; qty: number; badge?: string; artwork: CheckoutArtworkKind;}
export type DeliveryMethodId = "standard" | "express" | "pickup";
export interface CheckoutOrderPayload { orderNumber: string; email: string; deliveryMethod: DeliveryMethodId; promoCode: string | null; items: CheckoutItem[]; subtotal: number; discount: number; shipping: number; tax: number; total: number;}
export interface CheckoutFormProps extends StyleOverrideProps { /** Storefront eyebrow label displayed above the checkout heading. */ brandName?: string; /** Primary page heading. */ title?: string; /** Supporting subtitle beneath the heading. */ description?: string; /** Initial cart items rendered in the order summary. */ initialItems?: CheckoutItem[]; /** Order subtotal threshold that unlocks complimentary standard shipping. */ freeShippingThreshold?: number; /** Fractional tax rate applied to the post-discount subtotal (e.g. 0.0825). */ taxRate?: number; /** Called after client-side validation succeeds on Place Order. */ onPlaceOrder?: (payload: CheckoutOrderPayload) => void; /** Called when the user clicks Continue Shopping. */ onContinueShopping?: () => void; /** Called when the user clicks Sign In. */ onSignIn?: () => void;}
// ── Demo Data & Constants ─────────────────────────────────────────────────────
const DEFAULT_CHECKOUT_ITEMS: CheckoutItem[] = [ { id: "carafe", sku: "KRN-014", name: "Kuro Pour-Over Carafe", variant: "Matte obsidian stoneware · 600 ml", price: 68, qty: 1, artwork: "carafe", }, { id: "guji", sku: "KRN-042", name: "Single-Origin Ethiopia Guji (500g)", variant: "Washed heirloom · Bergamot & jasmine · Whole bean", price: 29.5, qty: 2, badge: "Small Lot", artwork: "coffee", }, { id: "cups", sku: "KRN-029", name: "Stoneware Tasting Cup Set", variant: "Hand-thrown oatmeal glaze · Pair of 6 oz cups", price: 54, qty: 1, artwork: "cups", },];
const DELIVERY_OPTIONS: Array<{ id: DeliveryMethodId; label: string; description: string; price: number;}> = [ { id: "standard", label: "Standard Ground (3–5 business days)", description: "Carbon-neutral parcel via USPS Priority Mail", price: 6.5, }, { id: "express", label: "Roast Express (1–2 business days)", description: "Packed within 24 hours of roasting with insulated sleeve", price: 14, }, { id: "pickup", label: "Roastery Counter Pickup (Ready in 2 hours)", description: "Portland Kiln & Tasting Bar · 418 SE Alder St", price: 0, },];
const PROMO_CODES: Record<string, { discountRate: number; label: string }> = { ROAST15: { discountRate: 0.15, label: "15% off roastery order" },};
const EXPIRY_MONTHS = Array.from({ length: 12 }, (_, idx) => { const val = String(idx + 1).padStart(2, "0"); return { value: val, label: val };});
const EXPIRY_YEARS = Array.from({ length: 10 }, (_, idx) => { const val = String(2026 + idx); return { value: val, label: val };});
const US_STATES = [ "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming",].map((name) => ({ value: name, label: name }));
// ── Formatting & Detection Helpers ────────────────────────────────────────────
const formatCurrency = (amount: number) => `$${amount.toFixed(2)}`;
type CardNetwork = "visa" | "mastercard" | "amex" | null;
function detectCardNetwork(raw: string): CardNetwork { const digits = raw.replace(/\D/g, ""); if (digits.startsWith("4")) return "visa"; if (/^3[47]/.test(digits)) return "amex"; if (/^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)/.test(digits)) return "mastercard"; return null;}
function formatCardNumber(raw: string): string { const digits = raw.replace(/\D/g, ""); const isAmex = /^3[47]/.test(digits); if (isAmex) { const trimmed = digits.slice(0, 15); const parts = [trimmed.slice(0, 4), trimmed.slice(4, 10), trimmed.slice(10, 15)].filter( Boolean, ); return parts.join(" "); } const trimmed = digits.slice(0, 16); return trimmed.replace(/(.{4})(?=.)/g, "$1 ");}
function formatCvc(raw: string, network: CardNetwork): string { const limit = network === "amex" ? 4 : 3; return raw.replace(/\D/g, "").slice(0, limit);}
function isValidEmail(value: string): boolean { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());}
// ── Styles ────────────────────────────────────────────────────────────────────
const styles = stylex.create({ root: { backgroundColor: semanticColors.bg, color: semanticColors.fg, fontFamily: fonts.body, minHeight: "100%", width: "100%", paddingBlock: { default: spacing._10, "@media (max-width: 640px)": spacing._6, }, paddingInline: { default: spacing._6, "@media (max-width: 640px)": spacing._4, }, }, container: { marginInline: "auto", maxWidth: "70rem", width: "100%", }, headingReset: { marginBlock: 0, }, pageSubtitle: { maxWidth: "60ch", }, columns: { gap: { default: spacing._8, "@media (max-width: 900px)": spacing._6, }, gridTemplateColumns: { default: "minmax(0, 1.32fr) minmax(0, 1fr)", "@media (max-width: 900px)": "minmax(0, 1fr)", }, }, summaryColumn: { minWidth: 0, order: { default: 0, "@media (max-width: 900px)": -1, }, position: { default: "sticky", "@media (max-width: 900px)": "static", }, top: spacing._6, }, section: { gap: spacing._3_5, }, accountRow: { backgroundColor: semanticColors.bgPanel, borderColor: semanticColors.border, borderRadius: semanticRadii.panel, borderStyle: "solid", borderWidth: "1px", paddingBlock: spacing._3_5, paddingInline: spacing._4, }, grid2: { gridTemplateColumns: { default: "repeat(2, minmax(0, 1fr))", "@media (max-width: 560px)": "minmax(0, 1fr)", }, }, grid3: { gridTemplateColumns: { default: "repeat(3, minmax(0, 1fr))", "@media (max-width: 560px)": "minmax(0, 1fr)", }, }, tooltipButton: { color: { default: semanticColors.fgMuted, ":hover": semanticColors.fg, }, height: sizes._5, minWidth: sizes._5, width: sizes._5, }, deliveryList: { gap: spacing._2_5, }, deliveryPrice: { marginInlineStart: "auto", whiteSpace: "nowrap", }, expressGrid: { gridTemplateColumns: { default: "repeat(2, minmax(0, 1fr))", "@media (max-width: 480px)": "minmax(0, 1fr)", }, }, flexOne: { flexBasis: 0, flexGrow: 1, flexShrink: 1, }, mutedColor: { color: semanticColors.fgMuted, }, billingFields: { paddingTop: spacing._1, }, trustBar: { color: semanticColors.fgMuted, paddingBlock: spacing._1, }, fullWidth: { width: "100%", }, policyLinks: { fontSize: fontSizes.xs, }, summaryCardBody: { gap: spacing._4, }, summaryTrigger: { alignItems: "center", appearance: "none", backgroundColor: "transparent", borderStyle: "none", borderWidth: 0, color: semanticColors.fg, cursor: "pointer", display: "flex", fontFamily: "inherit", gap: spacing._2, justifyContent: "space-between", paddingBlock: 0, paddingInline: 0, textAlign: "start", width: "100%", }, chevron: { transitionProperty: "transform", transitionDuration: "180ms", }, chevronOpen: { transform: "rotate(180deg)", }, summaryPanelInner: { paddingTop: spacing._4, }, thumbnailFrame: { borderColor: semanticColors.border, borderRadius: semanticRadii.control, borderStyle: "solid", borderWidth: "1px", height: "4.25rem", overflow: "hidden", width: "4.25rem", }, thumbnailImage: { display: "block", height: "100%", objectFit: "cover", width: "100%", }, nowrap: { whiteSpace: "nowrap", }, itemControlsRow: { paddingTop: spacing._1_5, }, qtyStepper: { width: "5.25rem", }, textActionBtn: { appearance: "none", backgroundColor: "transparent", borderStyle: "none", borderWidth: 0, color: { default: semanticColors.fgMuted, ":hover": semanticColors.fg, }, cursor: "pointer", fontFamily: "inherit", fontSize: fontSizes.xs, fontWeight: fontWeights.medium, paddingBlock: 0, paddingInline: 0, textDecoration: { default: "none", ":hover": "underline", }, }, emptyBagBox: { backgroundColor: semanticColors.bgMuted, borderRadius: semanticRadii.control, paddingBlock: spacing._6, paddingInline: spacing._4, textAlign: "center", }, orderBannerActions: { paddingTop: spacing._1_5, }, giftTextarea: { minHeight: "5.5rem", resize: "vertical", },});
// ── Product Thumbnails ────────────────────────────────────────────────────────
const THUMBNAIL_SRC: Record<CheckoutArtworkKind, string> = { carafe: "/images/blocks/checkout-form/carafe.webp", coffee: "/images/blocks/checkout-form/coffee.webp", cups: "/images/blocks/checkout-form/cups.webp",};
function ProductThumbnail({ kind }: { kind: CheckoutArtworkKind }) { return ( <img src={THUMBNAIL_SRC[kind]} alt="" width={68} height={68} loading="lazy" decoding="async" {...stylex.props(styles.thumbnailImage)} /> );}
// ── Inline SVG Icons ──────────────────────────────────────────────────────────
function LockIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <rect x="4" y="9" width="12" height="8" rx="2" /> <path d="M7 9V6.5a3 3 0 0 1 6 0V9" /> </Icon> );}
function ShieldCheckIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <path d="M10 2.5 16.5 5v4.8c0 3.7-2.6 6.8-6.5 7.7-3.9-.9-6.5-4-6.5-7.7V5L10 2.5Z" /> <path d="m7.3 10.2 1.8 1.8 3.6-3.8" /> </Icon> );}
function CheckCircleIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <circle cx="10" cy="10" r="7.5" /> <path d="m6.8 10.2 2.1 2.1 4.3-4.5" /> </Icon> );}
function TruckIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <path d="M2.5 5h9v8.5h-9z" /> <path d="M11.5 7.5h3.4l2.6 2.8v3.2h-6" /> <circle cx="6" cy="14.5" r="1.6" /> <circle cx="14.5" cy="14.5" r="1.6" /> </Icon> );}
function CreditCardIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <rect x="2.5" y="4.5" width="15" height="11" rx="2" /> <path d="M2.5 8.5h15" /> <path d="M5.5 12h3.5" /> </Icon> );}
function WalletIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <path d="M3 6.5A2 2 0 0 1 5 4.5h10a2 2 0 0 1 2 2v7.5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7.5Z" /> <path d="M13 10.5h4" /> <circle cx="13.5" cy="10.5" r="0.8" fill="currentColor" stroke="none" /> </Icon> );}
function DevicePayIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <rect x="5.5" y="2.5" width="9" height="15" rx="2" /> <path d="M9 14.5h2" /> </Icon> );}
function InfoCircleIcon() { return ( <Icon size="xs" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <circle cx="8" cy="8" r="6.25" /> <path d="M8 7.5V11" /> <path d="M8 5.2v.1" /> </Icon> );}
function ChevronDownIcon({ open }: { open: boolean }) { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" style={[styles.chevron, open && styles.chevronOpen]} > <path d="m5.5 7.5 4.5 5 4.5-5" /> </Icon> );}
function TrashIcon() { return ( <Icon size="sm" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" > <path d="M4 6h12" /> <path d="M7.5 6V4.5a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1V6" /> <path d="M6 6l.8 9.5a1.5 1.5 0 0 0 1.5 1.5h3.4a1.5 1.5 0 0 0 1.5-1.5L14 6" /> </Icon> );}
// ── Component ─────────────────────────────────────────────────────────────────
/** * CheckoutForm — two-column storefront checkout experience with express pay, * contact & shipping fields, selectable delivery cards, auto-formatted payment * card inputs with network detection, promo code discount (`ROAST15`), gift * note options, inline field validation, and a sticky interactive order summary. */export function CheckoutForm({ brandName = "Kuro Roastery & Kiln", title = "Checkout", description = "Small-batch coffee roasted in Portland and hand-thrown stoneware. Every transaction is protected with 256-bit SSL encryption.", initialItems = DEFAULT_CHECKOUT_ITEMS, freeShippingThreshold = 200, taxRate = 0.0825, onPlaceOrder, onContinueShopping, onSignIn, palette, style,}: CheckoutFormProps) { const idPrefix = useId(); const queue = useMemo(() => Toast.createToaster(), []);
// Cart & summary state const [items, setItems] = useState<CheckoutItem[]>(initialItems); const [summaryOpen, setSummaryOpen] = useState(true); const [pendingRemoval, setPendingRemoval] = useState<CheckoutItem | null>(null);
// Contact & shipping const [email, setEmail] = useState(""); const [emailOffers, setEmailOffers] = useState(true); const [firstName, setFirstName] = useState(""); const [lastName, setLastName] = useState(""); const [address, setAddress] = useState(""); const [city, setCity] = useState(""); const [zip, setZip] = useState(""); const [usState, setUsState] = useState(""); const [phone, setPhone] = useState(""); const [saveInfo, setSaveInfo] = useState(false);
// Delivery const [deliveryMethod, setDeliveryMethod] = useState<DeliveryMethodId>("standard");
// Payment const [cardNumber, setCardNumber] = useState(""); const [expMonth, setExpMonth] = useState(""); const [expYear, setExpYear] = useState(""); const [cvc, setCvc] = useState(""); const [cardName, setCardName] = useState(""); const [billingMatchesShipping, setBillingMatchesShipping] = useState(true); const [billingAddress, setBillingAddress] = useState(""); const [billingCity, setBillingCity] = useState(""); const [billingZip, setBillingZip] = useState(""); const [billingState, setBillingState] = useState("");
// Promo & gift const [promoInput, setPromoInput] = useState(""); const [appliedPromo, setAppliedPromo] = useState<string | null>(null); const [promoError, setPromoError] = useState<string | null>(null); const [addGiftMessage, setAddGiftMessage] = useState(false); const [giftTo, setGiftTo] = useState(""); const [giftFrom, setGiftFrom] = useState(""); const [giftMessage, setGiftMessage] = useState("");
// Submission const [submitted, setSubmitted] = useState(false); const [placedOrderNumber, setPlacedOrderNumber] = useState<string | null>(null);
const cardNetwork = useMemo(() => detectCardNetwork(cardNumber), [cardNumber]);
// Derived totals const itemCount = useMemo(() => items.reduce((sum, item) => sum + item.qty, 0), [items]); const subtotal = useMemo( () => items.reduce((sum, item) => sum + item.price * item.qty, 0), [items], ); const promoMeta = appliedPromo ? PROMO_CODES[appliedPromo] : undefined; const discount = promoMeta ? subtotal * promoMeta.discountRate : 0; const discountedSubtotal = Math.max(0, subtotal - discount); const qualifiesForFreeStandard = discountedSubtotal >= freeShippingThreshold && items.length > 0; const amountToFreeShipping = Math.max(0, freeShippingThreshold - discountedSubtotal);
const shippingCost = useMemo(() => { if (items.length === 0) return 0; if (deliveryMethod === "pickup") return 0; if (deliveryMethod === "standard") { return qualifiesForFreeStandard ? 0 : 6.5; } return 14; }, [deliveryMethod, items.length, qualifiesForFreeStandard]);
const taxAmount = items.length === 0 ? 0 : discountedSubtotal * taxRate; const grandTotal = discountedSubtotal + shippingCost + taxAmount;
// Validation const cardDigits = cardNumber.replace(/\D/g, ""); const requiredCvcLen = cardNetwork === "amex" ? 4 : 3;
const problems = { email: !email.trim() ? "Enter an email address for your receipt" : !isValidEmail(email) ? "Enter a valid email address" : undefined, firstName: !firstName.trim() ? "Enter a first name" : undefined, lastName: !lastName.trim() ? "Enter a last name" : undefined, address: !address.trim() ? "Enter a street address" : undefined, city: !city.trim() ? "Enter a city" : undefined, zip: !zip.trim() ? "Enter a ZIP code" : !/^\d{5}(-\d{4})?$/.test(zip.trim()) ? "Use a 5-digit ZIP code" : undefined, usState: !usState ? "Select a state" : undefined, phone: !phone.trim() ? "Enter a phone number for delivery updates" : undefined, cardNumber: !cardDigits ? "Enter a card number" : cardDigits.length < (cardNetwork === "amex" ? 15 : 16) ? "Card number looks incomplete" : undefined, expMonth: !expMonth ? "Select month" : undefined, expYear: !expYear ? "Select year" : undefined, cvc: !cvc.trim() ? "Enter security code" : cvc.trim().length < requiredCvcLen ? `Enter ${requiredCvcLen} digits` : undefined, cardName: !cardName.trim() ? "Enter the name on the card" : undefined, billingAddress: !billingMatchesShipping && !billingAddress.trim() ? "Enter a billing street address" : undefined, billingCity: !billingMatchesShipping && !billingCity.trim() ? "Enter a billing city" : undefined, billingZip: !billingMatchesShipping && !billingZip.trim() ? "Enter a billing ZIP code" : undefined, billingState: !billingMatchesShipping && !billingState ? "Select a billing state" : undefined, };
const errors: Partial<typeof problems> = submitted ? problems : {}; const errorCount = Object.values(problems).filter(Boolean).length;
// Handlers const handleQuantityChange = useCallback((id: string, nextValue: number | null) => { if (nextValue == null || !Number.isFinite(nextValue)) return; const clamped = Math.min(10, Math.max(1, Math.round(nextValue))); setItems((prev) => prev.map((item) => (item.id === id ? { ...item, qty: clamped } : item))); }, []);
const handleConfirmRemove = useCallback(() => { if (!pendingRemoval) return; const removed = pendingRemoval; setItems((prev) => prev.filter((item) => item.id !== removed.id)); setPendingRemoval(null); queue.info(`Removed ${removed.name}`, { description: "Your order summary totals have been updated.", }); }, [pendingRemoval, queue]);
const handleRestoreItems = useCallback(() => { setItems(initialItems); queue.info("Roastery bag restored", { description: `${initialItems.length} demo items added back to your order.`, }); }, [initialItems, queue]);
const handleApplyPromo = useCallback(() => { const normalized = promoInput.trim().toUpperCase(); if (!normalized) { setPromoError("Enter a promo code such as ROAST15"); return; } const found = PROMO_CODES[normalized]; if (!found) { setPromoError(`"${normalized}" is not active. Try ROAST15 for 15% off.`); return; } setAppliedPromo(normalized); setPromoError(null); setPromoInput(""); queue.success(`Promo code ${normalized} applied`, { description: found.label, }); }, [promoInput, queue]);
const handleRemovePromo = useCallback(() => { const previous = appliedPromo; setAppliedPromo(null); setPromoError(null); if (previous) { queue.info(`Removed promo code ${previous}`); } }, [appliedPromo, queue]);
const handleSignIn = useCallback(() => { onSignIn?.(); queue.info("Roastery member sign-in", { description: "Connect your auth flow here to prefill saved addresses and cards.", }); }, [onSignIn, queue]);
const handleExpressPay = useCallback( (provider: string) => { queue.info(`${provider} express checkout`, { description: `Total ready to authorize: ${formatCurrency(grandTotal)}.`, }); }, [grandTotal, queue], );
const handleContinueShopping = useCallback(() => { onContinueShopping?.(); queue.info("Returning to Kuro Roastery catalog", { description: "Your bag stays saved while you keep browsing.", }); }, [onContinueShopping, queue]);
const handleSubmit = useCallback( (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); setSubmitted(true);
if (items.length === 0) { queue.error("Your bag is empty", { description: "Restore the demo items before placing an order.", }); return; }
if (errorCount > 0) { queue.error(`Please fix ${errorCount} highlighted ${errorCount === 1 ? "field" : "fields"}`, { description: "Review your contact, shipping, and payment details.", }); return; }
const orderNumber = `KR-${String(84900 + itemCount * 7)}`; const payload: CheckoutOrderPayload = { orderNumber, email: email.trim(), deliveryMethod, promoCode: appliedPromo, items, subtotal, discount, shipping: shippingCost, tax: taxAmount, total: grandTotal, };
setPlacedOrderNumber(orderNumber); onPlaceOrder?.(payload); queue.success(`Order ${orderNumber} confirmed`, { description: `Receipt sent to ${email.trim()} · Total ${formatCurrency(grandTotal)}.`, }); }, [ appliedPromo, deliveryMethod, discount, email, errorCount, grandTotal, itemCount, items, onPlaceOrder, queue, shippingCost, subtotal, taxAmount, ], );
const handleResetDemo = useCallback(() => { setPlacedOrderNumber(null); setSubmitted(false); setItems(initialItems); setAppliedPromo(null); setPromoInput(""); setPromoError(null); queue.info("Checkout reset", { description: "Ready for another test order.", }); }, [initialItems, queue]);
return ( <div {...stylex.props(palette, styles.root, style)}> <VStack gap="6" style={styles.container}> {/* Page Header */} <VStack render={<header />} gap="4"> <VStack gap="2"> <HStack wrap="wrap" gap="2"> <Badge variant="subtle" size="sm"> {brandName} </Badge> <Badge variant="outline" size="sm"> <LockIcon /> Encrypted checkout </Badge> </HStack> <Heading render={<h1 />} size="3xl" style={styles.headingReset}> {title} </Heading> <Text variant="muted" size="md" style={styles.pageSubtitle}> {description} </Text> </VStack> <Separator decorative /> </VStack>
{/* Order confirmation banner after valid submission */} {placedOrderNumber ? ( <Alert.Root role="status" status="success" variant="subtle" size="md" palette={emeraldPalette} > <Alert.Indicator> <CheckCircleIcon /> </Alert.Indicator> <Alert.Content> <Alert.Title>Order {placedOrderNumber} is confirmed</Alert.Title> <Alert.Description> We sent a roast schedule and receipt to {email.trim()} for{" "} {formatCurrency(grandTotal)}. </Alert.Description> <HStack wrap="wrap" gap="2" style={styles.orderBannerActions}> <Button variant="surface" size="xs" onClick={handleResetDemo}> Start a new order </Button> </HStack> </Alert.Content> </Alert.Root> ) : null}
{/* Validation summary alert after invalid submit */} {submitted && errorCount > 0 ? ( <Alert.Root role="alert" status="error" variant="subtle" size="md" palette={redPalette}> <Alert.Indicator> <InfoCircleIcon /> </Alert.Indicator> <Alert.Content> <Alert.Title> {errorCount} {errorCount === 1 ? "field needs" : "fields need"} attention </Alert.Title> <Alert.Description> Complete the highlighted sections below to finish placing your order. </Alert.Description> </Alert.Content> </Alert.Root> ) : null}
{/* Two-column checkout layout */} <Grid align="start" style={styles.columns}> {/* Left column: Form */} <VStack render={<form onSubmit={handleSubmit} noValidate />} gap="8"> {/* Member Sign-In Prompt */} <HStack wrap="wrap" justify="between" gap="3" style={styles.accountRow}> <VStack gap="0.5"> <Text size="sm" weight="semibold"> Have a Roastery account? </Text> <Text variant="caption"> Sign in to apply bean rewards and autofill your saved shipping address. </Text> </VStack> <Button type="button" variant="surface" size="sm" onClick={handleSignIn}> Sign in </Button> </HStack>
{/* Contact Information */} <VStack render={<section aria-labelledby={`${idPrefix}-contact`} />} style={styles.section}> <VStack gap="1"> <Heading id={`${idPrefix}-contact`} size="lg" style={styles.headingReset}> Contact Information </Heading> </VStack>
<Field.Root required invalid={Boolean(errors.email)}> <Field.Label> Email address <Field.RequiredIndicator /> </Field.Label> <Input type="email" size="lg" autoComplete="email" placeholder="claire@roaststudio.co" value={email} onValueChange={setEmail} /> {errors.email ? <Field.Error match>{errors.email}</Field.Error> : null} </Field.Root>
<Checkbox.Root size="sm" palette={accentPalette}> <Checkbox.Control checked={emailOffers} onCheckedChange={(next) => setEmailOffers(next === true)} /> <Checkbox.Label> Email me seasonal micro-lot drops and pour-over brew guides </Checkbox.Label> </Checkbox.Root> </VStack>
{/* Shipping Information */} <VStack render={<section aria-labelledby={`${idPrefix}-shipping`} />} style={styles.section}> <VStack gap="1"> <Heading id={`${idPrefix}-shipping`} size="lg" style={styles.headingReset}> Shipping Address </Heading> </VStack>
<Grid columns="2" gap="3" style={styles.grid2}> <Field.Root required invalid={Boolean(errors.firstName)}> <Field.Label> First name <Field.RequiredIndicator /> </Field.Label> <Input size="lg" autoComplete="given-name" placeholder="Claire" value={firstName} onValueChange={setFirstName} /> {errors.firstName ? <Field.Error match>{errors.firstName}</Field.Error> : null} </Field.Root>
<Field.Root required invalid={Boolean(errors.lastName)}> <Field.Label> Last name <Field.RequiredIndicator /> </Field.Label> <Input size="lg" autoComplete="family-name" placeholder="Takahashi" value={lastName} onValueChange={setLastName} /> {errors.lastName ? <Field.Error match>{errors.lastName}</Field.Error> : null} </Field.Root> </Grid>
<Field.Root required invalid={Boolean(errors.address)}> <Field.Label> Street address <Field.RequiredIndicator /> </Field.Label> <Input size="lg" autoComplete="street-address" placeholder="742 NW Flanders St, Apt 4B" value={address} onValueChange={setAddress} /> {errors.address ? <Field.Error match>{errors.address}</Field.Error> : null} </Field.Root>
<Grid columns="2" gap="3" style={styles.grid2}> <Field.Root required invalid={Boolean(errors.city)}> <Field.Label> City <Field.RequiredIndicator /> </Field.Label> <Input size="lg" autoComplete="address-level2" placeholder="Portland" value={city} onValueChange={setCity} /> {errors.city ? <Field.Error match>{errors.city}</Field.Error> : null} </Field.Root>
<Field.Root required invalid={Boolean(errors.zip)}> <Field.Label> ZIP code <Field.RequiredIndicator /> </Field.Label> <Input size="lg" inputMode="numeric" autoComplete="postal-code" placeholder="97209" value={zip} onValueChange={setZip} /> {errors.zip ? <Field.Error match>{errors.zip}</Field.Error> : null} </Field.Root> </Grid>
<Field.Root required invalid={Boolean(errors.usState)}> <Field.Label> State <Field.RequiredIndicator /> </Field.Label> <Select.Root items={US_STATES} size="lg" value={usState || null} onValueChange={(next) => setUsState(next ?? "")} style={styles.fullWidth} > <Select.Control> <Select.Trigger> <Select.Value placeholder="Select state" /> </Select.Trigger> <Select.IndicatorGroup> <Select.Icon /> </Select.IndicatorGroup> </Select.Control> <Select.Content> {US_STATES.map((st) => ( <Select.Item key={st.value} value={st.value}> <Select.ItemText>{st.label}</Select.ItemText> <Select.ItemIndicator /> </Select.Item> ))} </Select.Content> </Select.Root> {errors.usState ? <Field.Error match>{errors.usState}</Field.Error> : null} </Field.Root>
<Field.Root required invalid={Boolean(errors.phone)}> <Field.Label> <HStack render={<span />} gap="1.5"> Phone number <Field.RequiredIndicator /> <Tooltip.Root variant="inverted" delay={150} closeDelay={80}> <Tooltip.Trigger render={ <IconButton type="button" variant="ghost" size="2xs" shape="rounded" aria-label="Why we ask for your phone number" style={styles.tooltipButton} /> } > <InfoCircleIcon /> </Tooltip.Trigger> <Tooltip.Content sideOffset={8}> <Tooltip.Arrow /> Used only for carrier delivery alerts and fragile stoneware drop-off notes. </Tooltip.Content> </Tooltip.Root> </HStack> </Field.Label> <Input type="tel" size="lg" autoComplete="tel" placeholder="+1 (503) 555-0194" value={phone} onValueChange={setPhone} /> {errors.phone ? <Field.Error match>{errors.phone}</Field.Error> : null} </Field.Root>
<Checkbox.Root size="sm" palette={accentPalette}> <Checkbox.Control checked={saveInfo} onCheckedChange={(next) => setSaveInfo(next === true)} /> <Checkbox.Label>Save my shipping details for faster checkout</Checkbox.Label> </Checkbox.Root> </VStack>
{/* Delivery Method */} <VStack render={<section aria-labelledby={`${idPrefix}-delivery`} />} style={styles.section}> <VStack gap="1"> <Heading id={`${idPrefix}-delivery`} size="lg" style={styles.headingReset}> Delivery Method </Heading> <Text variant="muted" size="sm"> Coffee is roasted to order every Monday and Thursday; stoneware ships double-boxed. </Text> </VStack>
<RadioCard.Root value={deliveryMethod} onValueChange={(next) => { if (next === "standard" || next === "express" || next === "pickup") { setDeliveryMethod(next); } }} variant="outline" size="md" palette={accentPalette} aria-label="Delivery method" style={styles.deliveryList} > {DELIVERY_OPTIONS.map((option) => { const isFree = option.price === 0 || (option.id === "standard" && qualifiesForFreeStandard); const displayPrice = isFree ? "Free" : formatCurrency(option.price); return ( <RadioCard.Item key={option.id} value={option.id}> <RadioCard.ItemControl> <HStack render={<span />} gap="3" style={styles.fullWidth}> <RadioCard.ItemIndicator /> <RadioCard.ItemContent> <RadioCard.ItemText>{option.label}</RadioCard.ItemText> <RadioCard.ItemDescription> {option.description} </RadioCard.ItemDescription> </RadioCard.ItemContent> <Text render={<span />} size="sm" weight="semibold" tabular="true" tone={isFree ? "success" : "default"} style={styles.deliveryPrice} > {displayPrice} </Text> </HStack> </RadioCard.ItemControl> </RadioCard.Item> ); })} </RadioCard.Root> </VStack>
{/* Payment Method */} <VStack render={<section aria-labelledby={`${idPrefix}-payment`} />} style={styles.section}> <VStack gap="1"> <Heading id={`${idPrefix}-payment`} size="lg" style={styles.headingReset}> Payment Method </Heading> <Text variant="muted" size="sm"> Express wallets or card payment. Card numbers are tokenized before submission. </Text> </VStack>
{/* Express Checkout Buttons */} <Grid columns="2" gap="3" style={styles.expressGrid}> <Button type="button" variant="surface" size="lg" onClick={() => handleExpressPay("Apple Pay")} > <DevicePayIcon /> Apple Pay </Button> <Button type="button" variant="surface" size="lg" onClick={() => handleExpressPay("Shop Pay")} > <WalletIcon /> Shop Pay </Button> </Grid>
{/* OR Divider */} <HStack gap="3"> <div {...stylex.props(styles.flexOne)}> <Separator decorative /> </div> <Text render={<span />} variant="overline" weight="medium"> or pay by card </Text> <div {...stylex.props(styles.flexOne)}> <Separator decorative /> </div> </HStack>
{/* Accepted Card Networks */} <HStack wrap="wrap" gap="1.5" style={styles.mutedColor}> <CreditCardIcon /> <Badge variant={cardNetwork === "visa" ? "solid" : "outline"} size="sm" palette={cardNetwork === "visa" ? accentPalette : undefined} > Visa </Badge> <Badge variant={cardNetwork === "mastercard" ? "solid" : "outline"} size="sm" palette={cardNetwork === "mastercard" ? accentPalette : undefined} > Mastercard </Badge> <Badge variant={cardNetwork === "amex" ? "solid" : "outline"} size="sm" palette={cardNetwork === "amex" ? accentPalette : undefined} > Amex </Badge> </HStack>
{/* Card Fields */} <Field.Root required invalid={Boolean(errors.cardNumber)}> <Field.Label> Card number <Field.RequiredIndicator /> </Field.Label> <Input size="lg" inputMode="numeric" autoComplete="cc-number" placeholder="4242 4242 4242 4242" value={cardNumber} onValueChange={(next) => setCardNumber(formatCardNumber(next))} /> {errors.cardNumber ? <Field.Error match>{errors.cardNumber}</Field.Error> : null} </Field.Root>
<Grid columns="3" gap="3" style={styles.grid3}> <Field.Root required invalid={Boolean(errors.expMonth)}> <Field.Label> Exp. month <Field.RequiredIndicator /> </Field.Label> <Select.Root items={EXPIRY_MONTHS} size="lg" value={expMonth || null} onValueChange={(next) => setExpMonth(next ?? "")} style={styles.fullWidth} > <Select.Control> <Select.Trigger> <Select.Value placeholder="MM" /> </Select.Trigger> <Select.IndicatorGroup> <Select.Icon /> </Select.IndicatorGroup> </Select.Control> <Select.Content> {EXPIRY_MONTHS.map((m) => ( <Select.Item key={m.value} value={m.value}> <Select.ItemText>{m.label}</Select.ItemText> <Select.ItemIndicator /> </Select.Item> ))} </Select.Content> </Select.Root> {errors.expMonth ? <Field.Error match>{errors.expMonth}</Field.Error> : null} </Field.Root>
<Field.Root required invalid={Boolean(errors.expYear)}> <Field.Label> Exp. year <Field.RequiredIndicator /> </Field.Label> <Select.Root items={EXPIRY_YEARS} size="lg" value={expYear || null} onValueChange={(next) => setExpYear(next ?? "")} style={styles.fullWidth} > <Select.Control> <Select.Trigger> <Select.Value placeholder="YYYY" /> </Select.Trigger> <Select.IndicatorGroup> <Select.Icon /> </Select.IndicatorGroup> </Select.Control> <Select.Content> {EXPIRY_YEARS.map((y) => ( <Select.Item key={y.value} value={y.value}> <Select.ItemText>{y.label}</Select.ItemText> <Select.ItemIndicator /> </Select.Item> ))} </Select.Content> </Select.Root> {errors.expYear ? <Field.Error match>{errors.expYear}</Field.Error> : null} </Field.Root>
<Field.Root required invalid={Boolean(errors.cvc)}> <Field.Label> <HStack render={<span />} gap="1.5"> CVC <Field.RequiredIndicator /> <Tooltip.Root variant="inverted" delay={150} closeDelay={80}> <Tooltip.Trigger render={ <IconButton type="button" variant="ghost" size="2xs" shape="rounded" aria-label="What is a card security code?" style={styles.tooltipButton} /> } > <InfoCircleIcon /> </Tooltip.Trigger> <Tooltip.Content sideOffset={8}> <Tooltip.Arrow /> 3-digit code on the back of Visa/Mastercard, or 4 digits on the front of American Express. </Tooltip.Content> </Tooltip.Root> </HStack> </Field.Label> <Input size="lg" inputMode="numeric" autoComplete="cc-csc" placeholder={cardNetwork === "amex" ? "1234" : "123"} value={cvc} onValueChange={(next) => setCvc(formatCvc(next, cardNetwork))} /> {errors.cvc ? <Field.Error match>{errors.cvc}</Field.Error> : null} </Field.Root> </Grid>
<Field.Root required invalid={Boolean(errors.cardName)}> <Field.Label> Name on card <Field.RequiredIndicator /> </Field.Label> <Input size="lg" autoComplete="cc-name" placeholder="Claire Takahashi" value={cardName} onValueChange={setCardName} /> {errors.cardName ? <Field.Error match>{errors.cardName}</Field.Error> : null} </Field.Root>
<Checkbox.Root size="sm" palette={accentPalette}> <Checkbox.Control checked={billingMatchesShipping} onCheckedChange={(next) => setBillingMatchesShipping(next === true)} /> <Checkbox.Label>Use shipping address as billing address</Checkbox.Label> </Checkbox.Root>
{!billingMatchesShipping ? ( <VStack gap="3" style={styles.billingFields}> <Field.Root required invalid={Boolean(errors.billingAddress)}> <Field.Label> Billing street address <Field.RequiredIndicator /> </Field.Label> <Input size="lg" placeholder="418 SE Alder St" value={billingAddress} onValueChange={setBillingAddress} /> {errors.billingAddress ? ( <Field.Error match>{errors.billingAddress}</Field.Error> ) : null} </Field.Root>
<Grid columns="2" gap="3" style={styles.grid2}> <Field.Root required invalid={Boolean(errors.billingCity)}> <Field.Label> Billing city <Field.RequiredIndicator /> </Field.Label> <Input size="lg" placeholder="Portland" value={billingCity} onValueChange={setBillingCity} /> {errors.billingCity ? ( <Field.Error match>{errors.billingCity}</Field.Error> ) : null} </Field.Root>
<Field.Root required invalid={Boolean(errors.billingZip)}> <Field.Label> Billing ZIP code <Field.RequiredIndicator /> </Field.Label> <Input size="lg" inputMode="numeric" placeholder="97214" value={billingZip} onValueChange={setBillingZip} /> {errors.billingZip ? ( <Field.Error match>{errors.billingZip}</Field.Error> ) : null} </Field.Root> </Grid>
<Field.Root required invalid={Boolean(errors.billingState)}> <Field.Label> Billing state <Field.RequiredIndicator /> </Field.Label> <Select.Root items={US_STATES} size="lg" value={billingState || null} onValueChange={(next) => setBillingState(next ?? "")} style={styles.fullWidth} > <Select.Control> <Select.Trigger> <Select.Value placeholder="Select state" /> </Select.Trigger> <Select.IndicatorGroup> <Select.Icon /> </Select.IndicatorGroup> </Select.Control> <Select.Content> {US_STATES.map((st) => ( <Select.Item key={st.value} value={st.value}> <Select.ItemText>{st.label}</Select.ItemText> <Select.ItemIndicator /> </Select.Item> ))} </Select.Content> </Select.Root> {errors.billingState ? ( <Field.Error match>{errors.billingState}</Field.Error> ) : null} </Field.Root> </VStack> ) : null} </VStack>
{/* Promo Code */} <VStack render={<section aria-labelledby={`${idPrefix}-promo`} />} style={styles.section}> <VStack gap="1"> <Heading id={`${idPrefix}-promo`} size="lg" style={styles.headingReset}> Promo Code </Heading> <Text variant="muted" size="sm"> Try <strong>ROAST15</strong> for 15% off your roastery and ceramics order. </Text> </VStack>
{appliedPromo ? ( <HStack wrap="wrap" justify="between" gap="2"> <Badge variant="subtle" size="md" palette={greenPalette}> <CheckCircleIcon /> {appliedPromo} · 15% off applied </Badge> <Button type="button" variant="ghost" size="sm" onClick={handleRemovePromo}> Remove code </Button> </HStack> ) : ( <HStack align="start" gap="2"> <div {...stylex.props(styles.flexOne)}> <Field.Root invalid={Boolean(promoError)}> <Input size="lg" aria-label="Promo code" placeholder="Enter promo code (e.g. ROAST15)" value={promoInput} onValueChange={(next) => { setPromoInput(next); if (promoError) setPromoError(null); }} /> {promoError ? <Field.Error match>{promoError}</Field.Error> : null} </Field.Root> </div> <Button type="button" variant="surface" size="lg" onClick={handleApplyPromo}> Apply </Button> </HStack> )} </VStack>
{/* Gift Options */} <VStack render={<section aria-labelledby={`${idPrefix}-gift`} />} style={styles.section}> <VStack gap="1"> <Heading id={`${idPrefix}-gift`} size="lg" style={styles.headingReset}> Gift Options </Heading> </VStack>
<Checkbox.Root size="sm" palette={accentPalette}> <Checkbox.Control checked={addGiftMessage} onCheckedChange={(next) => setAddGiftMessage(next === true)} /> <Checkbox.Label>Include a handwritten letterpress tasting card</Checkbox.Label> </Checkbox.Root>
{addGiftMessage ? ( <VStack gap="3"> <Grid columns="2" gap="3" style={styles.grid2}> <Field.Root> <Field.Label>To</Field.Label> <Input size="lg" placeholder="Recipient name" value={giftTo} onValueChange={setGiftTo} /> </Field.Root> <Field.Root> <Field.Label>From</Field.Label> <Input size="lg" placeholder="Your name" value={giftFrom} onValueChange={setGiftFrom} /> </Field.Root> </Grid> <Field.Root> <Field.Label>Note</Field.Label> <Textarea size="lg" rows={3} placeholder="Enjoy your morning pour-over ritual…" value={giftMessage} onValueChange={setGiftMessage} style={styles.giftTextarea} /> </Field.Root> </VStack> ) : null} </VStack>
{/* Trust bar + CTAs + Policy links */} <VStack render={<section aria-label="Order submission" />} style={styles.section}> <HStack wrap="wrap" justify="center" gap="4" style={styles.trustBar}> <HStack render={<span />} gap="1.5"> <ShieldCheckIcon /> <Text render={<span />} variant="caption"> Secure payment </Text> </HStack> <HStack render={<span />} gap="1.5"> <LockIcon /> <Text render={<span />} variant="caption"> 256-bit SSL </Text> </HStack> <HStack render={<span />} gap="1.5"> <CheckCircleIcon /> <Text render={<span />} variant="caption"> 30-day ceramic returns </Text> </HStack> </HStack>
<VStack gap="2.5"> <Button type="submit" variant="solid" size="lg" palette={accentPalette} disabled={items.length === 0} style={styles.fullWidth} > Place Order · {formatCurrency(grandTotal)} </Button> <Button type="button" variant="surface" size="lg" onClick={handleContinueShopping} style={styles.fullWidth} > Continue Shopping </Button> </VStack>
<Separator decorative />
<HStack render={<nav aria-label="Store policies" />} wrap="wrap" justify="center" gap="4" style={styles.policyLinks} > {["Refund policy", "Privacy policy", "Terms of service", "Shipping & roasts"].map( (policy) => ( <Link key={policy} href={`#${policy.toLowerCase().replace(/[^a-z]+/g, "-")}`} onClick={(event) => { event.preventDefault(); queue.info(policy, { description: "Link this policy to your storefront legal page.", }); }} > {policy} </Link> ), )} </HStack> </VStack> </VStack>
{/* Right column: Sticky Order Summary */} <aside aria-label="Order summary" {...stylex.props(styles.summaryColumn)}> <Card.Root variant="outline" size="lg"> <Card.Body style={styles.summaryCardBody}> <Collapsible.Root open={summaryOpen} onOpenChange={setSummaryOpen}> <Collapsible.Trigger render={<button type="button" {...stylex.props(styles.summaryTrigger)} />} > <HStack render={<span />} gap="2"> <Heading render={<span />} size="lg" style={styles.headingReset}> Order Summary </Heading> <Badge variant="subtle" size="sm"> {itemCount} {itemCount === 1 ? "item" : "items"} </Badge> </HStack> <HStack render={<span />} gap="2" style={styles.mutedColor}> <Text render={<span />} size="md" weight="semibold" tabular="true"> {formatCurrency(grandTotal)} </Text> <ChevronDownIcon open={summaryOpen} /> </HStack> </Collapsible.Trigger>
<Collapsible.Panel> <VStack gap="4" style={styles.summaryPanelInner}> {/* Cart Line Items */} {items.length === 0 ? ( <VStack align="center" gap="2.5" style={styles.emptyBagBox}> <Text size="sm" weight="medium"> Your roastery bag is empty. </Text> <Button type="button" variant="surface" size="sm" onClick={handleRestoreItems} > Restore demo items </Button> </VStack> ) : ( items.map((item) => ( <VStack key={item.id} gap="4"> <HStack align="start" style={styles.section}> <Square style={styles.thumbnailFrame}> <ProductThumbnail kind={item.artwork} /> </Square>
<VStack gap="1" style={styles.flexOne}> <HStack align="start" justify="between" gap="2"> <HStack wrap="wrap" gap="1.5"> <Text render={<span />} size="sm" weight="semibold"> {item.name} </Text> {item.badge ? ( <Badge variant="subtle" size="xs" palette={emeraldPalette}> {item.badge} </Badge> ) : null} </HStack> <Text render={<span />} size="sm" weight="semibold" tabular="true" style={styles.nowrap} > {formatCurrency(item.price * item.qty)} </Text> </HStack>
<Text variant="caption">{item.variant}</Text> <Text render={<span />} variant="mono" size="2xs" tone="subtle"> SKU {item.sku} · {formatCurrency(item.price)} ea </Text>
<HStack wrap="wrap" gap="3" style={styles.itemControlsRow}> <NumberInput.Root size="sm" min={1} max={10} step={1} value={item.qty} onValueChange={(next) => handleQuantityChange(item.id, next)} style={styles.qtyStepper} > <NumberInput.Group> <NumberInput.Input aria-label={`Quantity for ${item.name}`} /> <NumberInput.Control /> </NumberInput.Group> </NumberInput.Root>
<HStack gap="3"> <button type="button" onClick={() => setPendingRemoval(item)} {...stylex.props(styles.textActionBtn)} > Remove </button> <button type="button" onClick={() => queue.info(`Saved ${item.name}`, { description: "Added to your saved tasting shelf.", }) } {...stylex.props(styles.textActionBtn)} > Save for later </button> </HStack> </HStack> </VStack> </HStack> <Separator decorative /> </VStack> )) )}
{/* Order Totals */} <VStack gap="2.5"> <HStack justify="between" gap="2"> <Text render={<span />} size="sm" tone="muted"> Subtotal </Text> <Text render={<span />} size="sm" tabular="true"> {formatCurrency(subtotal)} </Text> </HStack>
{appliedPromo && discount > 0 ? ( <HStack justify="between" gap="2"> <Text render={<span />} size="sm" tone="muted"> Promo ({appliedPromo} · 15%) </Text> <Text render={<span />} size="sm" tone="success" weight="medium" tabular="true" > −{formatCurrency(discount)} </Text> </HStack> ) : null}
<HStack justify="between" gap="2"> <Text render={<span />} size="sm" tone="muted"> {deliveryMethod === "pickup" ? "Roastery pickup" : deliveryMethod === "express" ? "Roast Express shipping" : "Standard shipping"} </Text> <Text render={<span />} size="sm" tone={shippingCost === 0 && items.length > 0 ? "success" : "default"} weight={shippingCost === 0 && items.length > 0 ? "medium" : "inherit"} tabular="true" > {items.length === 0 ? formatCurrency(0) : shippingCost === 0 ? "Free" : formatCurrency(shippingCost)} </Text> </HStack>
<HStack justify="between" gap="2"> <Text render={<span />} size="sm" tone="muted"> Estimated tax </Text> <Text render={<span />} size="sm" tabular="true"> {formatCurrency(taxAmount)} </Text> </HStack> </VStack>
<Separator decorative />
<HStack align="baseline" justify="between" gap="2"> <Text render={<span />} size="md" weight="semibold"> Total </Text> <Text render={<span />} size="xl" weight="semibold" tabular="true"> {formatCurrency(grandTotal)} </Text> </HStack>
{/* Free Shipping Threshold Banner */} <Alert.Root status={qualifiesForFreeStandard ? "success" : "info"} variant="subtle" size="sm" palette={qualifiesForFreeStandard ? emeraldPalette : bluePalette} > <Alert.Indicator> <TruckIcon /> </Alert.Indicator> <Alert.Content> <Alert.Title> {qualifiesForFreeStandard ? "Complimentary standard shipping unlocked" : `Add ${formatCurrency(amountToFreeShipping)} for free standard shipping`} </Alert.Title> <Alert.Description> {qualifiesForFreeStandard ? `Orders over ${formatCurrency(freeShippingThreshold)} ship standard ground on us.` : `Free standard ground shipping on orders of ${formatCurrency(freeShippingThreshold)} or more.`} </Alert.Description> </Alert.Content> </Alert.Root> </VStack> </Collapsible.Panel> </Collapsible.Root> </Card.Body> </Card.Root> </aside> </Grid> </VStack>
{/* Item Removal Confirmation Dialog */} <AlertDialog.Root open={Boolean(pendingRemoval)} onOpenChange={(open) => { if (!open) setPendingRemoval(null); }} size="sm" > <AlertDialog.Backdrop /> <AlertDialog.Content> <AlertDialog.Header> <AlertDialog.Icon palette={redPalette}> <TrashIcon /> </AlertDialog.Icon> <AlertDialog.Title> Remove {pendingRemoval?.name ?? "item"} from your bag? </AlertDialog.Title> </AlertDialog.Header> <AlertDialog.Body> <AlertDialog.Description> This removes the item from your current order summary. You can restore the demo bag at any time if your cart becomes empty. </AlertDialog.Description> </AlertDialog.Body> <AlertDialog.Footer> <AlertDialog.Cancel render={<Button variant="surface" size="sm" />}> Keep item </AlertDialog.Cancel> <Button variant="solid" size="sm" palette={redPalette} onClick={handleConfirmRemove} > Remove item </Button> </AlertDialog.Footer> </AlertDialog.Content> </AlertDialog.Root>
<Toaster toaster={queue} /> </div> );}
Inspired by the Checkout Form template from Astryx (MIT License · Copyright (c) 2026 Meta Platforms, Inc.).