---
title: "Checkout Wizard · UI SDK — StyleX Blocks"
description: "Four-step two-column checkout flow with live cart quantities and promo codes, country-aware shipping validation, delivery method selection, payment review, sticky order summary, and local order confirmation."
url: "https://stylexblocks.com/block/ui-sdk/checkout-wizard/"
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 Wizard block

Four-step two-column checkout flow with live cart quantities and promo codes, country-aware shipping validation, delivery method selection, payment review, sticky order summary, and local order confirmation.

- Behavior engine: UI SDK
- Category: [Forms](https://stylexblocks.com/blocks/forms.md)
- Built with: [Alert](https://stylexblocks.com/components/ui-sdk/alert.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), [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), [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), [Steps](https://stylexblocks.com/components/ui-sdk/steps.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-wizard/

## 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-wizard
```

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

## Usage

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

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

## Source

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

```tsx
import * as stylex from "@stylexjs/stylex";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Alert } from "#components/ui/ui-sdk/alert.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 { 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 { 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, Stack, VStack } from "#components/ui/ui-sdk/stack.tsx";
import { Steps } from "#components/ui/ui-sdk/steps.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,
  greenPalette,
  redPalette,
} from "@stylexblocks/ui/themes/palettes.ts";
import { fonts } from "@stylexblocks/ui/tokens/fonts.stylex.ts";
import { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";
import type { StyleOverrideProps } from "#lib/recipe-props.ts";

// ── Inline SVG icons (zero external icon packages) ───────────────────────────

function CartIcon() {
  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="8" cy="16.25" r="1.25" />
      <circle cx="15" cy="16.25" r="1.25" />
      <path d="M2.5 3.5h2.2l1.6 8.2a1 1 0 0 0 1 .8h7.9a1 1 0 0 0 .97-.76l1.33-5.24H5.4" />
    </Icon>
  );
}

function LocationIcon() {
  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 17.2s5.25-4.35 5.25-8.45a5.25 5.25 0 1 0-10.5 0C4.75 12.85 10 17.2 10 17.2Z" />
      <circle cx="10" cy="8.75" r="1.85" />
    </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 5.25h9.25v8.5H2.5z" />
      <path d="M11.75 8h3.3l2.2 2.45v3.3h-5.5V8Z" />
      <circle cx="5.75" cy="14.5" r="1.5" />
      <circle cx="14.75" cy="14.5" r="1.5" />
    </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.25" y="4.5" width="15.5" height="11" rx="2" />
      <path d="M2.25 8.25h15.5" />
      <path d="M5.5 12.25h3.5" />
    </Icon>
  );
}

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="1.75" />
      <path d="M6.75 9V6.5a3.25 3.25 0 0 1 6.5 0V9" />
    </Icon>
  );
}

function AlertCircleIcon() {
  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.25" />
      <path d="M10 6.75v3.75" />
      <path d="M10 13.5v.1" />
    </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.25" />
      <path d="m7 10.2 2 2 4-4.4" />
    </Icon>
  );
}

function InfoCircleIcon() {
  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.25" />
      <path d="M10 9.25v4" />
      <path d="M10 6.5v.1" />
    </Icon>
  );
}

function ChevronDownIcon({ rotated }: { rotated?: 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={rotated ? styles.chevronOpen : styles.chevronClosed}
    >
      <path d="m5.5 7.75 4.5 4.5 4.5-4.5" />
    </Icon>
  );
}

// ── Data & validation rules ───────────────────────────────────────────────────

export interface CheckoutItem {
  id: string;
  name: string;
  variant: string;
  price: number;
  qty: number;
  thumbnailSrc: string;
  isLimited?: boolean;
}

export interface CheckoutOrderSummary {
  orderNumber: string;
  items: CheckoutItem[];
  subtotal: number;
  discount: number;
  shipping: number;
  tax: number;
  total: number;
  email: string;
  deliveryMethod: string;
}

const DEFAULT_CART_ITEMS: CheckoutItem[] = [
  {
    id: "fieldmic",
    name: "FieldMic Condenser USB-C",
    variant: "Cardioid capsule · Brushed aluminum",
    price: 148,
    qty: 1,
    thumbnailSrc: "/images/blocks/checkout-wizard/fieldmic.webp",
    isLimited: false,
  },
  {
    id: "desk-arm",
    name: "Anodized Desk Arm",
    variant: "Low-profile clamp · Matte graphite",
    price: 92,
    qty: 1,
    thumbnailSrc: "/images/blocks/checkout-wizard/desk-arm.webp",
    isLimited: false,
  },
  {
    id: "monitor-pads",
    name: "Acoustic Monitor Pads",
    variant: "High-density isolation · Pair (5° tilt)",
    price: 54,
    qty: 2,
    thumbnailSrc: "/images/blocks/checkout-wizard/monitor-pads.webp",
    isLimited: true,
  },
];

const STEPS = [
  { label: "Cart", icon: CartIcon },
  { label: "Shipping", icon: LocationIcon },
  { label: "Delivery", icon: TruckIcon },
  { label: "Payment", icon: CreditCardIcon },
] as const;

const COUNTRIES = [
  { value: "us", label: "United States" },
  { value: "ca", label: "Canada" },
  { value: "uk", label: "United Kingdom" },
];

const US_STATES = [
  "California",
  "Colorado",
  "Illinois",
  "Massachusetts",
  "New York",
  "Oregon",
  "Texas",
  "Washington",
];

const US_STATE_ITEMS = US_STATES.map((st) => ({ value: st, label: st }));

const DELIVERY_OPTIONS = [
  {
    value: "standard",
    label: "Standard ground",
    window: "3–7 business days",
    price: 6.95,
  },
  {
    value: "expedited",
    label: "Expedited air",
    window: "1–2 business days",
    price: 14.95,
  },
  {
    value: "overnight",
    label: "Overnight priority",
    window: "Next business day by 5pm (US only)",
    price: 28.95,
  },
] as const;

const PROMOS: Record<string, { label: string; rate: number }> = {
  STUDIO10: { label: "STUDIO10 · 10% off", rate: 0.1 },
  DESK20: { label: "DESK20 · 20% off", rate: 0.2 },
};

const TAX_RATE = 0.08;
const FREE_SHIPPING_THRESHOLD = 380;
const NARROW_HOST_WIDTH = 860;
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;

const POSTAL_CODE_RULES: Record<
  string,
  { label: string; placeholder: string; pattern: RegExp; error: string }
> = {
  us: {
    label: "ZIP code",
    placeholder: "94110",
    pattern: /^\d{5}(?:-\d{4})?$/,
    error: "Enter a 5-digit ZIP code, with an optional 4-digit suffix.",
  },
  ca: {
    label: "Postal code",
    placeholder: "V6B 1A1",
    pattern: /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ -]?\d[ABCEGHJ-NPRSTV-Z]\d$/i,
    error: "Enter a Canadian postal code, for example V6B 1A1.",
  },
  uk: {
    label: "Postcode",
    placeholder: "EC1V 9BP",
    pattern: /^(?:GIR\s?0AA|[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2})$/i,
    error: "Enter a UK postcode, for example EC1V 9BP.",
  },
};

const money = (amount: number) => `$${amount.toFixed(2)}`;

const blockedMessage = (count: number) =>
  count === 1
    ? "One problem above needs fixing first."
    : `${count} problems above need fixing first.`;

// ── Styles ────────────────────────────────────────────────────────────────────

const styles = stylex.create({
  root: {
    backgroundColor: semanticColors.bg,
    color: semanticColors.fg,
    fontFamily: fonts.body,
    minHeight: "100%",
    paddingBlock: spacing._6,
    paddingInline: spacing._6,
    width: "100%",
  },
  container: {
    marginInline: "auto",
    maxWidth: "62.5rem",
    width: "100%",
  },
  headingReset: {
    marginBlock: 0,
  },
  mutedColor: {
    color: semanticColors.fgMuted,
  },
  fullWidth: {
    width: "100%",
  },
  flexGrow: {
    flexGrow: 1,
  },
  noShrink: {
    flexShrink: 0,
  },
  nowrap: {
    whiteSpace: "nowrap",
  },
  formColumn: {
    flexBasis: 0,
    flexGrow: 1,
    flexShrink: 1,
    width: "100%",
  },
  summaryColumnSticky: {
    alignSelf: "flex-start",
    flexShrink: 0,
    maxWidth: "100%",
    position: "sticky",
    top: spacing._6,
    width: "22.5rem",
  },
  summaryCardBody: {
    gap: spacing._4,
  },
  summaryTrigger: {
    alignItems: "center",
    appearance: "none",
    backgroundColor: "transparent",
    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%",
  },
  summaryPanelBody: {
    paddingTop: spacing._4,
  },
  topPadding1: {
    paddingTop: spacing._1,
  },
  stepItemLast: {
    flexBasis: "auto",
    flexGrow: 0,
    flexShrink: 0,
  },
  stepIndicatorError: {
    backgroundColor: semanticColors.bgError,
    borderColor: semanticColors.borderError,
    borderStyle: "solid",
    borderWidth: "2px",
    color: semanticColors.fgError,
  },
  stepTitleHidden: {
    display: "none",
  },
  stepSection: {
    outline: "none",
  },
  thumbnail: {
    backgroundColor: semanticColors.bgMuted,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panelSm,
    borderStyle: "solid",
    borderWidth: "1px",
    display: "block",
    flexShrink: 0,
    height: "4rem",
    objectFit: "cover",
    width: "4rem",
  },
  thumbnailSm: {
    backgroundColor: semanticColors.bgMuted,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panelSm,
    borderStyle: "solid",
    borderWidth: "1px",
    display: "block",
    flexShrink: 0,
    height: "3rem",
    objectFit: "cover",
    width: "3rem",
  },
  qtyInputRoot: {
    width: "5.75rem",
  },
  emptyCartBox: {
    backgroundColor: semanticColors.bgMuted,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "dashed",
    borderWidth: "1px",
    paddingBlock: spacing._5,
    paddingInline: spacing._5,
  },
  promoInputWrap: {
    flexBasis: 0,
    flexGrow: 1,
    minWidth: 0,
  },
  successColor: {
    color: semanticColors.fgSuccess,
  },
  warningColor: {
    color: semanticColors.fgWarning,
  },
  errorColor: {
    color: semanticColors.fgError,
  },
  radioListStack: {
    display: "flex",
    flexDirection: "column",
    gap: spacing._2_5,
    width: "100%",
  },
  radioItemControl: {
    alignItems: "center",
    justifyContent: "space-between",
    width: "100%",
  },
  inputWithLeadingIcon: {
    position: "relative",
    width: "100%",
  },
  leadingIconSlot: {
    alignItems: "center",
    color: semanticColors.fgMuted,
    display: "inline-flex",
    insetBlock: 0,
    insetInlineStart: spacing._3,
    pointerEvents: "none",
    position: "absolute",
    zIndex: 1,
  },
  cardNumberInput: {
    paddingInlineStart: spacing._9,
  },
  shortField: {
    width: "8.75rem",
  },
  helpTrigger: {
    color: semanticColors.fgMuted,
    height: "1.125rem",
    minWidth: "1.125rem",
    width: "1.125rem",
  },
  reviewBox: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
  },
  continueButton: {
    flexBasis: 0,
    flexGrow: 1,
    width: "100%",
  },
  confirmationDetails: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._4,
    paddingInline: spacing._4,
  },
  chevronClosed: {
    transform: "rotate(0deg)",
    transitionDuration: "160ms",
    transitionProperty: "transform",
  },
  chevronOpen: {
    transform: "rotate(180deg)",
    transitionDuration: "160ms",
    transitionProperty: "transform",
  },
});

export interface CheckoutWizardProps extends StyleOverrideProps {
  /** Initial cart line items. Defaults to the modular studio hardware demo order. */
  items?: CheckoutItem[];
  /** Zero-based starting step index (0 = Cart, 1 = Shipping, 2 = Delivery, 3 = Payment). */
  initialStep?: number;
  /** Called when the final payment step passes validation and completes locally. */
  onOrderComplete?: (order: CheckoutOrderSummary) => void;
}

/**
 * CheckoutWizard — stepped two-column checkout flow with a sticky derived
 * order summary, per-step validation with focus forwarding, responsive narrow
 * host collapsible summary, and local order confirmation state.
 */
export function CheckoutWizard({
  items: initialItems = DEFAULT_CART_ITEMS,
  initialStep = 0,
  onOrderComplete,
  palette,
  style,
}: CheckoutWizardProps) {
  const queue = useMemo(() => Toast.createToaster(), []);

  // Measure the host container directly rather than the viewport so embedded
  // previews switch cleanly to the stacked narrow layout.
  const hostRef = useRef<HTMLElement | null>(null);
  const [isNarrow, setIsNarrow] = useState(false);

  const attachHost = useCallback((element: HTMLElement | null) => {
    hostRef.current = element;
    if (element && element.clientWidth > 0) {
      setIsNarrow(element.clientWidth <= NARROW_HOST_WIDTH);
    }
  }, []);

  useEffect(() => {
    const host = hostRef.current;
    if (!host || typeof ResizeObserver === "undefined") {
      return;
    }

    const observer = new ResizeObserver((entries) => {
      const width = entries[0]?.contentRect.width ?? host.clientWidth;
      if (width > 0) {
        setIsNarrow(width <= NARROW_HOST_WIDTH);
      }
    });
    observer.observe(host);
    return () => observer.disconnect();
  }, []);

  const [step, setStep] = useState(() =>
    Math.min(Math.max(initialStep, 0), STEPS.length - 1),
  );
  const [attempted, setAttempted] = useState<ReadonlySet<number>>(() => new Set());
  const [isComplete, setIsComplete] = useState(false);
  const [summaryOpen, setSummaryOpen] = useState(false);
  const [orderNumber, setOrderNumber] = useState("SB-4821");

  const [quantities, setQuantities] = useState<Record<string, number>>(() =>
    Object.fromEntries(initialItems.map((item) => [item.id, item.qty])),
  );
  const [promoInput, setPromoInput] = useState("");
  const [promoWasChecked, setPromoWasChecked] = useState(false);
  const [appliedPromo, setAppliedPromo] = useState<string | null>(null);

  const [email, setEmail] = useState("");
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [address, setAddress] = useState("");
  const [apartment, setApartment] = useState("");
  const [city, setCity] = useState("");
  const [state, setState] = useState("");
  const [postalCode, setPostalCode] = useState("");
  const [country, setCountry] = useState("us");

  const [delivery, setDelivery] = useState("standard");
  const [deliveryNote, setDeliveryNote] = useState("");
  const [isGift, setIsGift] = useState(false);

  const [cardNumber, setCardNumber] = useState("");
  const [cardName, setCardName] = useState("");
  const [expiry, setExpiry] = useState("");
  const [cvc, setCvc] = useState("");
  const [billingMatches, setBillingMatches] = useState(true);

  // ── Derived summary figures ─────────────────────────────────────────────────

  const items = useMemo(
    () =>
      initialItems
        .map((item) => ({
          ...item,
          qty: quantities[item.id] ?? item.qty,
        }))
        .filter((item) => item.qty > 0),
    [initialItems, quantities],
  );

  const subtotal = items.reduce((sum, item) => sum + item.price * item.qty, 0);
  const promo = appliedPromo ? PROMOS[appliedPromo] : undefined;
  const discount = promo ? subtotal * promo.rate : 0;
  const deliveryOption =
    DELIVERY_OPTIONS.find((option) => option.value === delivery) ?? DELIVERY_OPTIONS[0];
  const shipping =
    items.length === 0
      ? 0
      : subtotal - discount >= FREE_SHIPPING_THRESHOLD && delivery === "standard"
        ? 0
        : deliveryOption.price;
  const tax = (subtotal - discount) * TAX_RATE;
  const total = subtotal - discount + shipping + tax;
  const itemCount = items.reduce((sum, item) => sum + item.qty, 0);

  const postalRule = POSTAL_CODE_RULES[country] ?? POSTAL_CODE_RULES.us;
  const countryLabel =
    COUNTRIES.find((entry) => entry.value === country)?.label ?? "United States";

  // ── Per-step validation ─────────────────────────────────────────────────────

  const errorsByStep = useMemo<Array<Record<string, string>>>(() => {
    const cartErrors: Record<string, string> = {};
    if (items.length === 0) {
      cartErrors.items = "Your cart is empty. Restore items to continue.";
    }

    const shippingErrors: Record<string, string> = {};
    if (!EMAIL_PATTERN.test(email.trim())) {
      shippingErrors.email = "Enter an email address for order updates.";
    }
    if (!firstName.trim()) {
      shippingErrors.firstName = "Required";
    }
    if (!lastName.trim()) {
      shippingErrors.lastName = "Required";
    }
    if (!address.trim()) {
      shippingErrors.address = "Required";
    }
    if (!city.trim()) {
      shippingErrors.city = "Required";
    }
    if (country === "us" && !state) {
      shippingErrors.state = "Required";
    }
    if (!postalRule.pattern.test(postalCode.trim())) {
      shippingErrors.postalCode = postalRule.error;
    }

    const deliveryErrors: Record<string, string> = {};
    if (delivery === "overnight" && country !== "us") {
      deliveryErrors.delivery = "Overnight delivery is only available in the United States.";
    }

    const paymentErrors: Record<string, string> = {};
    if (cardNumber.replace(/[\s-]/g, "").length < 15) {
      paymentErrors.cardNumber = "Enter the full card number.";
    }
    if (!cardName.trim()) {
      paymentErrors.cardName = "Enter the name printed on the card.";
    }
    if (!/^(0[1-9]|1[0-2])\s?\/\s?\d{2}$/.test(expiry.trim())) {
      paymentErrors.expiry = "Use MM/YY.";
    }
    if (!/^\d{3,4}$/.test(cvc.trim())) {
      paymentErrors.cvc = "3 or 4 digits.";
    }

    return [cartErrors, shippingErrors, deliveryErrors, paymentErrors];
  }, [
    items.length,
    email,
    firstName,
    lastName,
    address,
    city,
    state,
    postalCode,
    country,
    postalRule,
    delivery,
    cardNumber,
    cardName,
    expiry,
    cvc,
  ]);

  const shownErrors = (index: number) =>
    attempted.has(index) ? errorsByStep[index] : {};
  const currentErrors = shownErrors(step);
  const currentErrorCount = Object.keys(currentErrors).length;
  const isLastStep = step === STEPS.length - 1;

  // Forward focus to the first invalid control after a blocked step advance.
  const stepContentRef = useRef<HTMLDivElement | null>(null);
  const pendingFocusStepRef = useRef<number | null>(null);

  useEffect(() => {
    if (pendingFocusStepRef.current !== step) {
      return;
    }
    pendingFocusStepRef.current = null;

    const root = stepContentRef.current;
    if (!root) {
      return;
    }
    const invalid = root.matches('[aria-invalid="true"], [data-invalid]')
      ? root
      : root.querySelector<HTMLElement>('[aria-invalid="true"], [data-invalid]');
    const focusableSelector =
      'input:not(:disabled), button:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';
    const focusTarget = invalid?.matches(focusableSelector)
      ? invalid
      : invalid?.querySelector<HTMLElement>(focusableSelector);
    focusTarget?.focus();
  }, [attempted, step]);

  const markAttempted = useCallback((indices: ReadonlyArray<number>) => {
    setAttempted((previous) => {
      const next = new Set(previous);
      for (const index of indices) {
        next.add(index);
      }
      return next;
    });
  }, []);

  const goNext = () => {
    markAttempted([step]);
    if (Object.keys(errorsByStep[step]).length > 0) {
      pendingFocusStepRef.current = step;
      return;
    }
    if (isLastStep) {
      const nextOrderNumber = `SB-${4800 + ((itemCount * 37 + Math.round(total)) % 900)}`;
      setOrderNumber(nextOrderNumber);
      setIsComplete(true);
      onOrderComplete?.({
        orderNumber: nextOrderNumber,
        items,
        subtotal,
        discount,
        shipping,
        tax,
        total,
        email: email.trim(),
        deliveryMethod: deliveryOption.label,
      });
      queue.success("Order confirmed", {
        description: `Reference ${nextOrderNumber} recorded locally for ${money(total)}.`,
      });
      return;
    }
    setStep((current) => current + 1);
  };

  const goTo = (index: number) => {
    if (index <= step) {
      setStep(index);
      return;
    }

    const checked: number[] = [];
    let firstInvalid: number | null = null;
    for (let candidate = step; candidate < index; candidate += 1) {
      checked.push(candidate);
      if (Object.keys(errorsByStep[candidate]).length > 0) {
        firstInvalid = candidate;
        break;
      }
    }
    markAttempted(checked);

    if (firstInvalid != null) {
      pendingFocusStepRef.current = firstInvalid;
      setStep(firstInvalid);
      return;
    }
    setStep(index);
  };

  const handlePromoInputChange = (value: string) => {
    setPromoInput(value);
    setPromoWasChecked(false);
    setAppliedPromo(null);
  };

  const applyPromo = () => {
    const code = promoInput.trim().toUpperCase();
    setPromoWasChecked(code.length > 0);
    if (PROMOS[code]) {
      setAppliedPromo(code);
      queue.success("Promo code applied", {
        description: PROMOS[code].label,
      });
    } else {
      setAppliedPromo(null);
    }
  };

  const restoreDefaultItems = () => {
    setQuantities(Object.fromEntries(initialItems.map((item) => [item.id, item.qty])));
  };

  const resetCheckout = () => {
    setIsComplete(false);
    setStep(0);
    setAttempted(new Set());
    restoreDefaultItems();
    setPromoInput("");
    setPromoWasChecked(false);
    setAppliedPromo(null);
    setCardNumber("");
    setCardName("");
    setExpiry("");
    setCvc("");
    setBillingMatches(true);
  };

  // ── Shared Order Summary ────────────────────────────────────────────────────

  const formattedAddress = [
    address.trim(),
    apartment.trim(),
    [city.trim(), country === "us" ? state : "", postalCode.trim()]
      .filter(Boolean)
      .join(", "),
    countryLabel,
  ]
    .filter(Boolean)
    .join(" · ");

  const freeShippingRemaining = Math.max(
    0,
    FREE_SHIPPING_THRESHOLD - (subtotal - discount),
  );

  const totalsRows = (
    <VStack gap="2">
      <HStack justify="between" gap="2">
        <Text render={<span />} size="sm" tone="muted">
          Subtotal
        </Text>
        <Text render={<span />} size="sm" tabular="true">
          {money(subtotal)}
        </Text>
      </HStack>
      {promo ? (
        <HStack justify="between" gap="2">
          <Text render={<span />} size="sm" tone="muted">
            {promo.label}
          </Text>
          <Text render={<span />} size="sm" tone="success" weight="medium" tabular="true">
            −{money(discount)}
          </Text>
        </HStack>
      ) : null}
      <HStack justify="between" gap="2">
        <Text render={<span />} size="sm" tone="muted">
          {deliveryOption.label}
        </Text>
        <Text render={<span />} size="sm" tabular="true">
          {shipping === 0 ? "Free" : money(shipping)}
        </Text>
      </HStack>
      <HStack justify="between" gap="2">
        <Text render={<span />} size="sm" tone="muted">
          Estimated tax
        </Text>
        <Text render={<span />} size="sm" tabular="true">
          {money(tax)}
        </Text>
      </HStack>
      <Separator />
      <HStack justify="between" gap="2" style={styles.topPadding1}>
        <Text render={<span />} size="lg" weight="semibold">
          Total
        </Text>
        <Text render={<span />} size="lg" weight="semibold" tabular="true">
          {money(total)}
        </Text>
      </HStack>
    </VStack>
  );

  const summaryBody = (
    <VStack gap="4">
      {items.length > 0 ? (
        <VStack gap="3">
          {items.map((item) => (
            <HStack key={item.id} align="start" gap="3">
              <img
                src={item.thumbnailSrc}
                alt={item.name}
                {...stylex.props(styles.thumbnailSm)}
              />
              <VStack gap="0.5" style={styles.flexGrow}>
                <HStack align="start" justify="between" gap="2">
                  <Text render={<span />} size="sm" weight="medium">
                    {item.name}
                  </Text>
                  <Text
                    render={<span />}
                    size="sm"
                    weight="semibold"
                    tabular="true"
                    style={styles.nowrap}
                  >
                    {money(item.price * item.qty)}
                  </Text>
                </HStack>
                <Text render={<span />} variant="caption">
                  {item.variant} · Qty {item.qty}
                </Text>
              </VStack>
            </HStack>
          ))}
        </VStack>
      ) : (
        <Text variant="muted" size="sm">
          No hardware selected yet.
        </Text>
      )}
      <Separator />
      {totalsRows}
      {items.length > 0 && freeShippingRemaining > 0 ? (
        <Alert.Root status="info" variant="subtle" size="sm" palette={bluePalette}>
          <Alert.Indicator>
            <TruckIcon />
          </Alert.Indicator>
          <Alert.Content>
            <Alert.Title>
              {money(freeShippingRemaining)} away from free standard shipping
            </Alert.Title>
          </Alert.Content>
        </Alert.Root>
      ) : null}
    </VStack>
  );

  const summaryCard = (
    <Card.Root variant="outline" size="lg">
      <Card.Body style={styles.summaryCardBody}>
        {isNarrow ? (
          <Collapsible.Root open={summaryOpen} onOpenChange={setSummaryOpen}>
            <Collapsible.Trigger
              render={<button type="button" {...stylex.props(styles.summaryTrigger)} />}
            >
              <Text render={<span />} size="md" weight="medium">
                Order summary
              </Text>
              <HStack render={<span />} gap="2">
                <Text render={<span />} size="md" weight="medium" tabular="true">
                  {money(total)}
                </Text>
                <ChevronDownIcon rotated={summaryOpen} />
              </HStack>
            </Collapsible.Trigger>
            <Collapsible.Panel>
              <div {...stylex.props(styles.summaryPanelBody)}>{summaryBody}</div>
            </Collapsible.Panel>
          </Collapsible.Root>
        ) : (
          <>
            <HStack justify="between" gap="2">
              <Text render={<h2 />} size="md" weight="semibold">
                Order summary
              </Text>
              <Badge variant="subtle" size="sm">
                {itemCount} {itemCount === 1 ? "item" : "items"}
              </Badge>
            </HStack>
            {summaryBody}
          </>
        )}
      </Card.Body>
    </Card.Root>
  );

  // ── Progress stepper ────────────────────────────────────────────────────────

  const progress = (
    <Steps.Root
      count={STEPS.length}
      step={step}
      onStepChange={({ step: next }) => goTo(next)}
      size="sm"
      orientation="horizontal"
      palette={accentPalette}
      aria-label="Checkout progress"
    >
      <Steps.List>
        {STEPS.map(({ label, icon: StepIcon }, index) => {
          const hasError = Object.keys(shownErrors(index)).length > 0;
          const isLast = index === STEPS.length - 1;
          return (
            <Steps.Item
              key={label}
              index={index}
              style={isLast ? styles.stepItemLast : undefined}
            >
              <Steps.Trigger aria-label={label}>
                <Steps.Indicator
                  palette={hasError ? redPalette : undefined}
                  style={hasError ? styles.stepIndicatorError : undefined}
                >
                  {hasError ? <AlertCircleIcon /> : <StepIcon />}
                </Steps.Indicator>
                <Steps.Title
                  style={isNarrow && index !== step ? styles.stepTitleHidden : undefined}
                >
                  {label}
                </Steps.Title>
              </Steps.Trigger>
              <Steps.Separator />
            </Steps.Item>
          );
        })}
      </Steps.List>
    </Steps.Root>
  );

  // ── Step actions ────────────────────────────────────────────────────────────

  const actions = (
    <VStack gap="3" style={styles.topPadding1}>
      {currentErrorCount > 0 ? (
        <HStack role="status" aria-live="polite" gap="1.5" style={styles.errorColor}>
          <AlertCircleIcon />
          <Text render={<span />} size="xs" weight="medium" tone="error">
            {blockedMessage(currentErrorCount)}
          </Text>
        </HStack>
      ) : null}
      <HStack gap="3" style={styles.fullWidth}>
        <Button
          variant="surface"
          onClick={() => {
            if (step === 0) {
              queue.info("Returning to hardware catalog", {
                description: "Your studio cart stays saved while you browse.",
              });
              return;
            }
            setStep((current) => Math.max(0, current - 1));
          }}
        >
          {step === 0 ? "Continue shopping" : "Back"}
        </Button>
        <Button
          variant="solid"
          palette={accentPalette}
          style={styles.continueButton}
          onClick={goNext}
        >
          {isLastStep ? `Pay ${money(total)}` : "Continue"}
        </Button>
      </HStack>
    </VStack>
  );

  // ── Render ──────────────────────────────────────────────────────────────────

  return (
    <VStack gap="0" palette={palette} style={[styles.root, style]}>
      <VStack render={<main ref={attachHost} />} gap="6" style={styles.container}>
        <HStack render={<header />} wrap="wrap" justify="between" gap="3">
          <Heading render={<h1 />} size="2xl" style={styles.headingReset}>
            Checkout
          </Heading>
          <HStack render={<span />} gap="1.5" style={styles.mutedColor}>
            <LockIcon />
            <Text render={<span />} variant="caption">
              Secure checkout
            </Text>
          </HStack>
        </HStack>

        <Stack
          direction={isNarrow ? "column" : "row"}
          align={isNarrow ? "stretch" : "start"}
          gap={isNarrow ? "6" : "8"}
          style={styles.fullWidth}
        >
          {isNarrow ? <div {...stylex.props(styles.fullWidth)}>{summaryCard}</div> : null}

          <VStack gap="6" style={isNarrow ? styles.fullWidth : styles.formColumn}>
            {isComplete ? (
              <VStack render={<section aria-label="Order confirmation" />} gap="5">
                <Alert.Root
                  status="success"
                  variant="subtle"
                  size="md"
                  palette={greenPalette}
                >
                  <Alert.Indicator>
                    <CheckCircleIcon />
                  </Alert.Indicator>
                  <Alert.Content>
                    <Alert.Title>Order {orderNumber} confirmed</Alert.Title>
                    <Alert.Description>
                      This local example completed an order for {money(total)}. No
                      payment was sent.
                    </Alert.Description>
                  </Alert.Content>
                </Alert.Root>

                <VStack gap="1">
                  <Heading render={<h2 />} size="xl" style={styles.headingReset}>
                    Thanks for your order
                  </Heading>
                  <Text variant="muted" size="sm">
                    The confirmation is stored in local component state so you can
                    inspect the complete checkout outcome or start again.
                  </Text>
                </VStack>

                <VStack gap="3" style={styles.confirmationDetails}>
                  <VStack gap="0.5">
                    <Text render={<span />} variant="caption">
                      Confirmation sent to
                    </Text>
                    <Text render={<span />} size="sm">
                      {email.trim() || "studio@example.com"}
                    </Text>
                  </VStack>
                  <Separator />
                  <VStack gap="0.5">
                    <Text render={<span />} variant="caption">
                      Shipping destination
                    </Text>
                    <Text render={<span />} size="sm">
                      {`${firstName.trim()} ${lastName.trim()}`.trim()}
                      {formattedAddress ? ` · ${formattedAddress}` : ""}
                    </Text>
                  </VStack>
                  <Separator />
                  <VStack gap="0.5">
                    <Text render={<span />} variant="caption">
                      Delivery speed
                    </Text>
                    <Text render={<span />} size="sm">
                      {deliveryOption.label} ({deliveryOption.window})
                    </Text>
                  </VStack>
                </VStack>

                <div>
                  <Button variant="surface" onClick={resetCheckout}>
                    Start a new order
                  </Button>
                </div>
              </VStack>
            ) : (
              progress
            )}

            {/* Step 0: Cart */}
            {!isComplete && step === 0 ? (
              <VStack
                ref={stepContentRef}
                gap="5"
                aria-invalid={currentErrors.items ? true : undefined}
                tabIndex={-1}
                style={styles.stepSection}
              >
                <VStack gap="1">
                  <Heading render={<h2 />} size="xl" style={styles.headingReset}>
                    Review your cart
                  </Heading>
                  <Text variant="muted" size="sm">
                    Adjust quantities or apply a studio promo code before entering
                    shipping details.
                  </Text>
                </VStack>

                {items.length > 0 ? (
                  <VStack gap="4">
                    {items.map((item) => (
                      <VStack key={item.id} gap="4">
                        <HStack align="start" gap="4">
                          <img
                            src={item.thumbnailSrc}
                            alt={item.name}
                            {...stylex.props(styles.thumbnail)}
                          />
                          <VStack gap="1.5" style={styles.flexGrow}>
                            <HStack align="start" justify="between" gap="2">
                              <HStack wrap="wrap" gap="2">
                                <Text render={<span />} size="sm" weight="medium">
                                  {item.name}
                                </Text>
                                {item.isLimited ? (
                                  <Badge
                                    variant="subtle"
                                    size="sm"
                                    palette={greenPalette}
                                  >
                                    Limited run
                                  </Badge>
                                ) : null}
                              </HStack>
                              <Text
                                render={<span />}
                                size="sm"
                                weight="semibold"
                                tabular="true"
                                style={styles.nowrap}
                              >
                                {money(item.price * item.qty)}
                              </Text>
                            </HStack>
                            <Text render={<span />} variant="caption">
                              {item.variant} · {money(item.price)} each
                            </Text>
                            <HStack gap="2" style={styles.topPadding1}>
                              <NumberInput.Root
                                value={item.qty}
                                onValueChange={(nextValue) =>
                                  setQuantities((prev) => ({
                                    ...prev,
                                    [item.id]: nextValue ?? 0,
                                  }))
                                }
                                min={0}
                                max={10}
                                step={1}
                                palette={accentPalette}
                                style={styles.qtyInputRoot}
                              >
                                <NumberInput.Group>
                                  <NumberInput.Input
                                    aria-label={`Quantity of ${item.name}`}
                                  />
                                  <NumberInput.Control />
                                </NumberInput.Group>
                              </NumberInput.Root>
                              <Button
                                variant="ghost"
                                onClick={() =>
                                  setQuantities((prev) => ({
                                    ...prev,
                                    [item.id]: 0,
                                  }))
                                }
                              >
                                Remove
                              </Button>
                            </HStack>
                          </VStack>
                        </HStack>
                        <Separator />
                      </VStack>
                    ))}
                  </VStack>
                ) : (
                  <VStack align="start" gap="3" style={styles.emptyCartBox}>
                    <Text variant="muted" size="sm">
                      {currentErrors.items ??
                        "Your cart has no hardware items right now."}
                    </Text>
                    <Button variant="surface" onClick={restoreDefaultItems}>
                      Restore sample items
                    </Button>
                  </VStack>
                )}

                <Field.Root>
                  <Field.Label>
                    Promo code
                    <Text render={<span />} size="xs" tone="subtle" weight="normal">
                      Optional
                    </Text>
                  </Field.Label>
                  <HStack gap="2" style={styles.fullWidth}>
                    <div {...stylex.props(styles.promoInputWrap)}>
                      <Input
                        value={promoInput}
                        onValueChange={handlePromoInputChange}
                        placeholder="STUDIO10"
                        onKeyDown={(event) => {
                          if (event.key === "Enter") {
                            event.preventDefault();
                            applyPromo();
                          }
                        }}
                      />
                    </div>
                    <Button variant="surface" onClick={applyPromo}>
                      Apply
                    </Button>
                  </HStack>
                  {appliedPromo && promo ? (
                    <HStack render={<span />} gap="1.5" style={styles.successColor}>
                      <CheckCircleIcon />
                      <Text render={<span />} size="xs" weight="medium" tone="success">
                        {promo.label} applied.
                      </Text>
                    </HStack>
                  ) : promoInput.trim() && promoWasChecked ? (
                    <HStack render={<span />} gap="1.5" style={styles.warningColor}>
                      <AlertCircleIcon />
                      <Text render={<span />} size="xs" weight="medium" tone="warning">
                        That promo code is not valid. Try STUDIO10 or DESK20.
                      </Text>
                    </HStack>
                  ) : promoInput.trim() ? (
                    <HStack render={<span />} gap="1.5" style={styles.warningColor}>
                      <InfoCircleIcon />
                      <Text render={<span />} size="xs" weight="medium" tone="warning">
                        Press Apply to check this code.
                      </Text>
                    </HStack>
                  ) : (
                    <Field.Description>
                      Try STUDIO10 (10% off) or DESK20 (20% off).
                    </Field.Description>
                  )}
                </Field.Root>
              </VStack>
            ) : null}

            {/* Step 1: Shipping */}
            {!isComplete && step === 1 ? (
              <VStack ref={stepContentRef} gap="5" style={styles.stepSection}>
                <VStack gap="1">
                  <Heading render={<h2 />} size="xl" style={styles.headingReset}>
                    Where should it go?
                  </Heading>
                  <Text variant="muted" size="sm">
                    Delivery options and tax are calculated from this address.
                  </Text>
                </VStack>

                <VStack gap="4">
                  <Field.Root required invalid={Boolean(currentErrors.email)}>
                    <Field.Label>
                      Email
                      <Field.RequiredIndicator />
                    </Field.Label>
                    <Input
                      type="email"
                      autoComplete="email"
                      value={email}
                      onValueChange={setEmail}
                      placeholder="studio@example.com"
                      aria-invalid={currentErrors.email ? true : undefined}
                    />
                    <Field.Description>
                      Order confirmation and tracking go here.
                    </Field.Description>
                    {currentErrors.email ? (
                      <Field.Error match={true}>{currentErrors.email}</Field.Error>
                    ) : null}
                  </Field.Root>

                  <Grid columns={isNarrow ? "1" : "2"} gap="4" style={styles.fullWidth}>
                    <Field.Root required invalid={Boolean(currentErrors.firstName)}>
                      <Field.Label>
                        First name
                        <Field.RequiredIndicator />
                      </Field.Label>
                      <Input
                        autoComplete="given-name"
                        value={firstName}
                        onValueChange={setFirstName}
                        aria-invalid={currentErrors.firstName ? true : undefined}
                      />
                      {currentErrors.firstName ? (
                        <Field.Error match={true}>{currentErrors.firstName}</Field.Error>
                      ) : null}
                    </Field.Root>

                    <Field.Root required invalid={Boolean(currentErrors.lastName)}>
                      <Field.Label>
                        Last name
                        <Field.RequiredIndicator />
                      </Field.Label>
                      <Input
                        autoComplete="family-name"
                        value={lastName}
                        onValueChange={setLastName}
                        aria-invalid={currentErrors.lastName ? true : undefined}
                      />
                      {currentErrors.lastName ? (
                        <Field.Error match={true}>{currentErrors.lastName}</Field.Error>
                      ) : null}
                    </Field.Root>
                  </Grid>

                  <Select.Root
                    items={COUNTRIES}
                    value={country}
                    onValueChange={(nextCountry) => {
                      if (nextCountry) {
                        setCountry(nextCountry);
                      }
                    }}
                    placeholder="Select country"
                    palette={accentPalette}
                  >
                    <Select.Label>Country</Select.Label>
                    <Select.Control>
                      <Select.Trigger>
                        <Select.Value />
                      </Select.Trigger>
                      <Select.IndicatorGroup>
                        <Select.Icon />
                      </Select.IndicatorGroup>
                    </Select.Control>
                    <Select.Content>
                      {COUNTRIES.map((option) => (
                        <Select.Item key={option.value} value={option.value}>
                          <Select.ItemText>{option.label}</Select.ItemText>
                          <Select.ItemIndicator />
                        </Select.Item>
                      ))}
                    </Select.Content>
                  </Select.Root>

                  <Field.Root required invalid={Boolean(currentErrors.address)}>
                    <Field.Label>
                      Street address
                      <Field.RequiredIndicator />
                    </Field.Label>
                    <Input
                      autoComplete="street-address"
                      value={address}
                      onValueChange={setAddress}
                      placeholder="742 Valencia Street"
                      aria-invalid={currentErrors.address ? true : undefined}
                    />
                    {currentErrors.address ? (
                      <Field.Error match={true}>{currentErrors.address}</Field.Error>
                    ) : null}
                  </Field.Root>

                  <Field.Root>
                    <Field.Label>
                      Apartment, suite, etc.
                      <Text render={<span />} size="xs" tone="subtle" weight="normal">
                        Optional
                      </Text>
                    </Field.Label>
                    <Input
                      autoComplete="address-line2"
                      value={apartment}
                      onValueChange={setApartment}
                      placeholder="Suite 4B"
                    />
                  </Field.Root>

                  <Grid
                    columns={isNarrow ? "1" : country === "us" ? "3" : "2"}
                    gap="4"
                    style={styles.fullWidth}
                  >
                    <Field.Root required invalid={Boolean(currentErrors.city)}>
                      <Field.Label>
                        City
                        <Field.RequiredIndicator />
                      </Field.Label>
                      <Input
                        autoComplete="address-level2"
                        value={city}
                        onValueChange={setCity}
                        aria-invalid={currentErrors.city ? true : undefined}
                      />
                      {currentErrors.city ? (
                        <Field.Error match={true}>{currentErrors.city}</Field.Error>
                      ) : null}
                    </Field.Root>

                    {country === "us" ? (
                      <Field.Root required invalid={Boolean(currentErrors.state)}>
                        <Select.Root
                          items={US_STATE_ITEMS}
                          value={state || null}
                          onValueChange={(nextState) => setState(nextState ?? "")}
                          placeholder="Select state"
                          palette={accentPalette}
                        >
                          <Select.Label>State</Select.Label>
                          <Select.Control>
                            <Select.Trigger
                              aria-invalid={currentErrors.state ? true : undefined}
                            >
                              <Select.Value />
                            </Select.Trigger>
                            <Select.IndicatorGroup>
                              <Select.Icon />
                            </Select.IndicatorGroup>
                          </Select.Control>
                          <Select.Content>
                            {US_STATE_ITEMS.map((option) => (
                              <Select.Item key={option.value} value={option.value}>
                                <Select.ItemText>{option.label}</Select.ItemText>
                                <Select.ItemIndicator />
                              </Select.Item>
                            ))}
                          </Select.Content>
                        </Select.Root>
                        {currentErrors.state ? (
                          <Field.Error match={true}>{currentErrors.state}</Field.Error>
                        ) : null}
                      </Field.Root>
                    ) : null}

                    <Field.Root required invalid={Boolean(currentErrors.postalCode)}>
                      <Field.Label>
                        {postalRule.label}
                        <Field.RequiredIndicator />
                      </Field.Label>
                      <Input
                        autoComplete="postal-code"
                        value={postalCode}
                        onValueChange={setPostalCode}
                        placeholder={postalRule.placeholder}
                        aria-invalid={currentErrors.postalCode ? true : undefined}
                      />
                      {currentErrors.postalCode ? (
                        <Field.Error match={true}>
                          {currentErrors.postalCode}
                        </Field.Error>
                      ) : null}
                    </Field.Root>
                  </Grid>
                </VStack>
              </VStack>
            ) : null}

            {/* Step 2: Delivery */}
            {!isComplete && step === 2 ? (
              <VStack ref={stepContentRef} gap="5" style={styles.stepSection}>
                <VStack gap="1">
                  <Heading render={<h2 />} size="xl" style={styles.headingReset}>
                    How fast do you need it?
                  </Heading>
                  <Text variant="muted" size="sm">
                    Estimates run from the day the order ships, usually 1–2 business
                    days after you place it.
                  </Text>
                </VStack>

                <VStack gap="4">
                  <Field.Root invalid={Boolean(currentErrors.delivery)}>
                    <Field.Label>Delivery method</Field.Label>
                    <RadioCard.Root
                      value={delivery}
                      onValueChange={(nextDelivery) => {
                        if (nextDelivery) {
                          setDelivery(nextDelivery);
                        }
                      }}
                      variant="outline"
                      size="md"
                      palette={accentPalette}
                      aria-label="Delivery method"
                      aria-invalid={currentErrors.delivery ? true : undefined}
                      style={styles.radioListStack}
                    >
                      {DELIVERY_OPTIONS.map((option) => {
                        const isFree =
                          option.value === "standard" &&
                          subtotal - discount >= FREE_SHIPPING_THRESHOLD;
                        return (
                          <RadioCard.Item key={option.value} value={option.value}>
                            <RadioCard.ItemControl style={styles.radioItemControl}>
                              <RadioCard.ItemContent>
                                <RadioCard.ItemText>{option.label}</RadioCard.ItemText>
                                <RadioCard.ItemDescription>
                                  {option.window}
                                </RadioCard.ItemDescription>
                              </RadioCard.ItemContent>
                              <HStack render={<span />} gap="3" style={styles.noShrink}>
                                <Text
                                  render={<span />}
                                  size="sm"
                                  weight="medium"
                                  tabular="true"
                                  style={styles.nowrap}
                                >
                                  {isFree ? "Free" : money(option.price)}
                                </Text>
                                <RadioCard.ItemIndicator />
                              </HStack>
                            </RadioCard.ItemControl>
                          </RadioCard.Item>
                        );
                      })}
                    </RadioCard.Root>
                    {currentErrors.delivery ? (
                      <Field.Error match={true}>{currentErrors.delivery}</Field.Error>
                    ) : null}
                  </Field.Root>

                  <Separator />

                  <Checkbox.Root palette={accentPalette}>
                    <Checkbox.Control
                      checked={isGift}
                      onCheckedChange={(checked) => setIsGift(checked === true)}
                    />
                    <Checkbox.Label>This is a gift</Checkbox.Label>
                  </Checkbox.Root>

                  <Field.Root>
                    <Field.Label>
                      {isGift ? "Gift message" : "Delivery instructions"}
                      <Text render={<span />} size="xs" tone="subtle" weight="normal">
                        Optional
                      </Text>
                    </Field.Label>
                    <Textarea
                      rows={3}
                      maxLength={240}
                      value={deliveryNote}
                      onValueChange={setDeliveryNote}
                      placeholder={
                        isGift
                          ? "Enjoy the new desk setup — happy recording."
                          : "Ring the studio buzzer at the side entrance."
                      }
                    />
                    <Field.Description>
                      {isGift
                        ? "Printed on an enclosure card. Prices are omitted from the packing slip."
                        : "Shared with the courier where supported."}
                    </Field.Description>
                  </Field.Root>
                </VStack>
              </VStack>
            ) : null}

            {/* Step 3: Payment & Review */}
            {!isComplete && step === 3 ? (
              <VStack ref={stepContentRef} gap="5" style={styles.stepSection}>
                <VStack gap="1">
                  <Heading render={<h2 />} size="xl" style={styles.headingReset}>
                    Payment & review
                  </Heading>
                  <Text variant="muted" size="sm">
                    This block validates payment details and completes locally. No card
                    is charged.
                  </Text>
                </VStack>

                <VStack gap="3" style={styles.reviewBox}>
                  <HStack justify="between" gap="3">
                    <VStack gap="0.5">
                      <Text render={<span />} variant="caption">
                        Ship to
                      </Text>
                      <Text render={<span />} size="sm">
                        {formattedAddress || "Shipping address not entered"}
                      </Text>
                    </VStack>
                    <Button variant="ghost" onClick={() => setStep(1)}>
                      Edit
                    </Button>
                  </HStack>
                  <Separator />
                  <HStack justify="between" gap="3">
                    <VStack gap="0.5">
                      <Text render={<span />} variant="caption">
                        Delivery
                      </Text>
                      <Text render={<span />} size="sm">
                        {deliveryOption.label} · {deliveryOption.window}
                      </Text>
                    </VStack>
                    <Button variant="ghost" onClick={() => setStep(2)}>
                      Edit
                    </Button>
                  </HStack>
                </VStack>

                <VStack gap="4">
                  <Field.Root required invalid={Boolean(currentErrors.cardNumber)}>
                    <Field.Label>
                      Card number
                      <Field.RequiredIndicator />
                    </Field.Label>
                    <div {...stylex.props(styles.inputWithLeadingIcon)}>
                      <span {...stylex.props(styles.leadingIconSlot)}>
                        <LockIcon />
                      </span>
                      <Input
                        inputMode="numeric"
                        autoComplete="cc-number"
                        value={cardNumber}
                        onValueChange={setCardNumber}
                        placeholder="4242 4242 4242 4242"
                        aria-invalid={currentErrors.cardNumber ? true : undefined}
                        style={styles.cardNumberInput}
                      />
                    </div>
                    {currentErrors.cardNumber ? (
                      <Field.Error match={true}>{currentErrors.cardNumber}</Field.Error>
                    ) : null}
                  </Field.Root>

                  <Field.Root required invalid={Boolean(currentErrors.cardName)}>
                    <Field.Label>
                      Name on card
                      <Field.RequiredIndicator />
                    </Field.Label>
                    <Input
                      autoComplete="cc-name"
                      value={cardName}
                      onValueChange={setCardName}
                      placeholder="Jordan Ellis"
                      aria-invalid={currentErrors.cardName ? true : undefined}
                    />
                    {currentErrors.cardName ? (
                      <Field.Error match={true}>{currentErrors.cardName}</Field.Error>
                    ) : null}
                  </Field.Root>

                  {/* Fixed-width short fields stay sized to their expected values */}
                  <HStack align="start" wrap="wrap" gap="4">
                    <Field.Root
                      required
                      invalid={Boolean(currentErrors.expiry)}
                      style={styles.shortField}
                    >
                      <Field.Label>
                        Expiry
                        <Field.RequiredIndicator />
                      </Field.Label>
                      <Input
                        inputMode="numeric"
                        autoComplete="cc-exp"
                        value={expiry}
                        onValueChange={setExpiry}
                        placeholder="MM/YY"
                        aria-invalid={currentErrors.expiry ? true : undefined}
                      />
                      {currentErrors.expiry ? (
                        <Field.Error match={true}>{currentErrors.expiry}</Field.Error>
                      ) : null}
                    </Field.Root>

                    <Field.Root
                      required
                      invalid={Boolean(currentErrors.cvc)}
                      style={styles.shortField}
                    >
                      <Field.Label>
                        <HStack render={<span />} gap="1.5">
                          <span>CVC</span>
                          <Field.RequiredIndicator />
                          <Tooltip.Root variant="inverted">
                            <Tooltip.Trigger
                              render={
                                <IconButton
                                  type="button"
                                  variant="ghost"
                                  size="2xs"
                                  shape="rounded"
                                  aria-label="About card security code"
                                  style={styles.helpTrigger}
                                />
                              }
                            >
                              <InfoCircleIcon />
                            </Tooltip.Trigger>
                            <Tooltip.Content side="top" sideOffset={6}>
                              Three digits on the back of the card, or four on the front
                              for American Express.
                              <Tooltip.Arrow />
                            </Tooltip.Content>
                          </Tooltip.Root>
                        </HStack>
                      </Field.Label>
                      <Input
                        inputMode="numeric"
                        autoComplete="cc-csc"
                        value={cvc}
                        onValueChange={setCvc}
                        placeholder="123"
                        aria-invalid={currentErrors.cvc ? true : undefined}
                      />
                      {currentErrors.cvc ? (
                        <Field.Error match={true}>{currentErrors.cvc}</Field.Error>
                      ) : null}
                    </Field.Root>
                  </HStack>

                  <Separator />

                  <Checkbox.Root palette={accentPalette}>
                    <Checkbox.Control
                      checked={billingMatches}
                      onCheckedChange={(checked) =>
                        setBillingMatches(checked === true)
                      }
                    />
                    <Checkbox.Label>
                      Billing address matches the shipping address
                    </Checkbox.Label>
                  </Checkbox.Root>

                  {!billingMatches ? (
                    <Alert.Root
                      status="info"
                      variant="subtle"
                      size="sm"
                      palette={bluePalette}
                    >
                      <Alert.Indicator>
                        <InfoCircleIcon />
                      </Alert.Indicator>
                      <Alert.Content>
                        <Alert.Title>Connect a billing-address step</Alert.Title>
                        <Alert.Description>
                          This local example does not collect a separate billing address
                          or transmit card data. Mount your payment provider&apos;s
                          elements here in production.
                        </Alert.Description>
                      </Alert.Content>
                    </Alert.Root>
                  ) : null}
                </VStack>
              </VStack>
            ) : null}

            {!isComplete ? actions : null}
          </VStack>

          {!isNarrow ? (
            <aside
              aria-label="Order summary"
              {...stylex.props(styles.summaryColumnSticky)}
            >
              {summaryCard}
            </aside>
          ) : null}
        </Stack>
      </VStack>

      <Toaster toaster={queue} />
    </VStack>
  );
}
```

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