---
title: "Checkout Form · UI SDK — StyleX Blocks"
description: "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."
url: "https://stylexblocks.com/block/ui-sdk/checkout-form/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Checkout Form block

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.

- Behavior engine: UI SDK
- Category: [Forms](https://stylexblocks.com/blocks/forms.md)
- Built with: [Alert](https://stylexblocks.com/components/ui-sdk/alert.md), [Alert Dialog](https://stylexblocks.com/components/ui-sdk/alert-dialog.md), [Badge](https://stylexblocks.com/components/ui-sdk/badge.md), [Button](https://stylexblocks.com/components/ui-sdk/button.md), [Card](https://stylexblocks.com/components/ui-sdk/card.md), [Center](https://stylexblocks.com/components/ui-sdk/center.md), [Checkbox](https://stylexblocks.com/components/ui-sdk/checkbox.md), [Collapsible](https://stylexblocks.com/components/ui-sdk/collapsible.md), [Field](https://stylexblocks.com/components/ui-sdk/field.md), [Grid](https://stylexblocks.com/components/ui-sdk/grid.md), [Heading](https://stylexblocks.com/components/ui-sdk/heading.md), [Icon](https://stylexblocks.com/components/ui-sdk/icon.md), [Icon Button](https://stylexblocks.com/components/ui-sdk/icon-button.md), [Input](https://stylexblocks.com/components/ui-sdk/input.md), [Link](https://stylexblocks.com/components/ui-sdk/link.md), [Number Input](https://stylexblocks.com/components/ui-sdk/number-input.md), [Radio Card](https://stylexblocks.com/components/ui-sdk/radio-card.md), [Select](https://stylexblocks.com/components/ui-sdk/select.md), [Separator](https://stylexblocks.com/components/ui-sdk/separator.md), [Stack](https://stylexblocks.com/components/ui-sdk/stack.md), [Text](https://stylexblocks.com/components/ui-sdk/text.md), [Textarea](https://stylexblocks.com/components/ui-sdk/textarea.md), [Toast](https://stylexblocks.com/components/ui-sdk/toast.md), [Tooltip](https://stylexblocks.com/components/ui-sdk/tooltip.md)
- HTML page: https://stylexblocks.com/block/ui-sdk/checkout-form/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init --style ui-sdk
```

Then add the item as source you own:

```sh
npx stylexblocks add checkout-form
```

Equivalent: `npx shadcn add @stylexblocks/checkout-form`. Registry item JSON: https://stylexblocks.com/r/ui-sdk/checkout-form.json

## Usage

```tsx
import { CheckoutForm } from "#components/blocks/ui-sdk/checkout-form.tsx";

export function Example() {
  return (
    <div style={{ minHeight: "100dvh" }}>
      <CheckoutForm />
    </div>
  );
}
```

## Source

`components/blocks/ui-sdk/checkout-form.tsx`

```tsx
import * 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>
  );
}
```

Credit: Inspired by [Checkout Form](https://astryx.atmeta.com/playground?template=payment-form) from Astryx (MIT License · Copyright (c) 2026 Meta Platforms, Inc.)
