---
title: "Form Wizard · UI SDK — StyleX Blocks"
description: "Four-step cloud workspace onboarding wizard with a pinned horizontal stepper, per-step validation on advance, plan tier radio cards, live monthly cost estimate, optional skippable team setup, editable review cards, and local launch confirmation."
url: "https://stylexblocks.com/block/ui-sdk/form-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/"
---

# Form Wizard block

Four-step cloud workspace onboarding wizard with a pinned horizontal stepper, per-step validation on advance, plan tier radio cards, live monthly cost estimate, optional skippable team setup, editable review cards, and local launch confirmation.

- Behavior engine: UI SDK
- Category: [Onboarding](https://stylexblocks.com/blocks/onboarding.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), [Checkbox Group](https://stylexblocks.com/components/ui-sdk/checkbox-group.md), [Data List](https://stylexblocks.com/components/ui-sdk/data-list.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), [Input](https://stylexblocks.com/components/ui-sdk/input.md), [Input Addon](https://stylexblocks.com/components/ui-sdk/input-addon.md), [Number Input](https://stylexblocks.com/components/ui-sdk/number-input.md), [Radio Card](https://stylexblocks.com/components/ui-sdk/radio-card.md), [Radio Group](https://stylexblocks.com/components/ui-sdk/radio-group.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), [Switch](https://stylexblocks.com/components/ui-sdk/switch.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)
- HTML page: https://stylexblocks.com/block/ui-sdk/form-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 form-wizard
```

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

## Usage

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

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

## Source

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

```tsx
import * as stylex from "@stylexjs/stylex";
import { useCallback, useEffect, useId, 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 { CheckboxGroup } from "#components/ui/ui-sdk/checkbox-group.tsx";
import { DataList } from "#components/ui/ui-sdk/data-list.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 { InputGroup } from "#components/ui/ui-sdk/input-addon.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 { RadioGroup } from "#components/ui/ui-sdk/radio-group.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 { Steps } from "#components/ui/ui-sdk/steps.tsx";
import { Switch } from "#components/ui/ui-sdk/switch.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 { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";
import {
  accentPalette,
  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 CheckIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="m3.5 8.5 3 3 6-6.5" />
    </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 RocketIcon() {
  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="M11.5 13.5 6.5 8.5c1.5-3 4.7-5 8.75-5.25-.25 4.05-2.25 7.25-5.25 8.75Z" />
      <path d="M6.5 8.5 3.75 9.75l2 2" />
      <path d="M11.5 13.5 10.25 16.25l-2-2" />
      <circle cx="12.25" cy="7.75" r="1.25" />
    </Icon>
  );
}

function ArrowLeftIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M12.5 8h-9" />
      <path d="M7.25 4.25 3.5 8l3.75 3.75" />
    </Icon>
  );
}

function ArrowRightIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M3.5 8h9" />
      <path d="M8.75 4.25 12.5 8l-3.75 3.75" />
    </Icon>
  );
}

// ── Types & domain configuration ─────────────────────────────────────────────

export type PlanTierId = "developer" | "team" | "scale";
export type InviteRoleId = "maintainer" | "developer" | "observer";
export type SecurityAddonId = "saml" | "siem" | "kms";

export interface FormWizardValues {
  organizationName: string;
  workspaceSlug: string;
  projectName: string;
  projectSummary: string;
  region: string;
  runtime: string;
  planId: PlanTierId;
  seats: number;
  inviteEmails: string;
  inviteRole: InviteRoleId;
  securityAddons: SecurityAddonId[];
  requireMfa: boolean;
  sendInvitesNow: boolean;
  welcomeNote: string;
  acceptedTerms: boolean;
}

export interface FormWizardCompletionPayload {
  workspaceId: string;
  workspaceUrl: string;
  monthlyTotal: number;
  invitedCount: number;
  values: FormWizardValues;
}

export interface FormWizardProps extends StyleOverrideProps {
  /** Primary page heading shown in the pinned header. */
  title?: string;
  /** Hostname prefix used for workspace URLs. */
  workspaceDomain?: string;
  /** Optional initial values overriding the default onboarding preset. */
  initialValues?: Partial<FormWizardValues>;
  /** Called once all steps validate and the user launches the workspace. */
  onLaunch?: (payload: FormWizardCompletionPayload) => void;
  /** Called when the user activates the Cancel action in the header. */
  onCancel?: () => void;
}

interface StepDefinition {
  id: string;
  label: string;
  isOptional?: boolean;
}

const STEPS: readonly StepDefinition[] = [
  { id: "organization", label: "Organization" },
  { id: "infrastructure", label: "Infrastructure" },
  { id: "team", label: "Team & security", isOptional: true },
  { id: "review", label: "Review" },
];

const REGIONS = [
  { value: "us-east-iad", label: "US East — Ashburn (iad1)" },
  { value: "us-west-pdx", label: "US West — Portland (pdx1)" },
  { value: "eu-central-fra", label: "EU Central — Frankfurt (fra1)" },
  { value: "ap-northeast-hnd", label: "Asia Pacific — Tokyo (hnd1)" },
] as const;

const RUNTIMES = [
  { value: "node-22", label: "Node.js 22 LTS (Containers)" },
  { value: "bun-1", label: "Bun 1.x (Edge & Workers)" },
  { value: "python-313", label: "Python 3.13 (Async & ML)" },
  { value: "go-124", label: "Go 1.24 (Static Binary)" },
] as const;

const PLANS: ReadonlyArray<{
  id: PlanTierId;
  label: string;
  pricePerSeat: number;
  seatLimit: number;
  description: string;
  highlight: string;
  recommended?: boolean;
}> = [
  {
    id: "developer",
    label: "Developer",
    pricePerSeat: 0,
    seatLimit: 3,
    description: "Personal projects, 2 environments, and community forums.",
    highlight: "Up to 3 seats · 100 GB egress",
  },
  {
    id: "team",
    label: "Team",
    pricePerSeat: 29,
    seatLimit: 100,
    description: "Preview branches, zero-downtime rollouts, and email support.",
    highlight: "Up to 100 seats · 2 TB egress",
    recommended: true,
  },
  {
    id: "scale",
    label: "Scale",
    pricePerSeat: 64,
    seatLimit: 1000,
    description: "Private VPC peering, 99.99% SLA, and 24/7 incident response.",
    highlight: "Up to 1,000 seats · Custom quotas",
  },
];

const INVITE_ROLES: ReadonlyArray<{
  value: InviteRoleId;
  label: string;
  description: string;
}> = [
  {
    value: "maintainer",
    label: "Maintainer",
    description: "Deploy services, manage environments, and configure billing.",
  },
  {
    value: "developer",
    label: "Developer",
    description: "Push builds, inspect logs, and manage preview branches.",
  },
  {
    value: "observer",
    label: "Observer",
    description: "Read-only access to deployments, metrics, and audit trails.",
  },
];

const SECURITY_ADDONS: ReadonlyArray<{
  id: SecurityAddonId;
  label: string;
  pricePerSeat: number;
  description: string;
}> = [
  {
    id: "saml",
    label: "SAML SSO & SCIM",
    pricePerSeat: 4,
    description: "Enforce identity provider sign-in via Okta, Entra ID, or Google.",
  },
  {
    id: "siem",
    label: "SIEM audit streaming",
    pricePerSeat: 3,
    description: "Stream deployment and access logs to Datadog, Splunk, or S3.",
  },
  {
    id: "kms",
    label: "Dedicated secrets KMS",
    pricePerSeat: 5,
    description: "Customer-managed encryption keys with automatic 90-day rotation.",
  },
];

const DEFAULT_VALUES: FormWizardValues = {
  organizationName: "Meridian Labs",
  workspaceSlug: "meridian-labs",
  projectName: "Core API Gateway",
  projectSummary: "Edge-routed TypeScript APIs and background job workers.",
  region: "us-east-iad",
  runtime: "bun-1",
  planId: "team",
  seats: 6,
  inviteEmails:
    "nina.patel@meridianlabs.io\ndavid.chen@meridianlabs.io\nclaire.moreau@meridianlabs.io",
  inviteRole: "developer",
  securityAddons: ["siem"],
  requireMfa: true,
  sendInvitesNow: true,
  welcomeNote: "",
  acceptedTerms: false,
};

const RESERVED_SLUGS = new Set([
  "admin",
  "api",
  "billing",
  "console",
  "harbor",
  "status",
  "support",
]);

const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
const SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
const NARROW_HOST_WIDTH = 640;

type ValidatableFieldKey =
  | "organizationName"
  | "workspaceSlug"
  | "projectName"
  | "seats"
  | "inviteEmails"
  | "acceptedTerms";

// ── Helpers ───────────────────────────────────────────────────────────────────

const money = (amount: number) =>
  amount === 0 ? "$0" : `$${amount.toLocaleString("en-US")}`;

function slugify(value: string): string {
  return value
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

function parseEmails(raw: string): string[] {
  return raw
    .split(/[\n,]/)
    .map((entry) => entry.trim())
    .filter(Boolean);
}

function buildWorkspaceId(slug: string): string {
  let hash = 0;
  for (let i = 0; i < slug.length; i += 1) {
    hash = (hash * 31 + slug.charCodeAt(i)) % 46656;
  }
  const suffix = hash.toString(36).padStart(4, "0").slice(-4);
  const prefix = (slug.replace(/[^a-z0-9]/g, "").slice(0, 3) || "hbr").toLowerCase();
  return `ws_${prefix}_${suffix}`;
}

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

const styles = stylex.create({
  root: {
    backgroundColor: semanticColors.bg,
    color: semanticColors.fg,
    fontFamily: fonts.body,
    minHeight: "100%",
    width: "100%",
  },
  header: {
    backgroundColor: semanticColors.bg,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    position: "sticky",
    top: 0,
    width: "100%",
    zIndex: 10,
  },
  headerInner: {
    marginInline: "auto",
    maxWidth: "46rem",
    paddingBlock: spacing._5,
    paddingInline: spacing._6,
    width: "100%",
  },
  headerInnerNarrow: {
    paddingBlock: spacing._4,
    paddingInline: spacing._4,
  },
  headingReset: {
    marginBlock: 0,
  },
  stepItemLast: {
    flexBasis: "auto",
    flexGrow: 0,
    flexShrink: 0,
  },
  stepIndicatorError: {
    backgroundColor: semanticColors.bgError,
    borderColor: semanticColors.borderError,
    borderStyle: "solid",
    borderWidth: "2px",
    color: semanticColors.fgError,
  },
  stepTitleHidden: {
    display: "none",
  },
  main: {
    flexGrow: 1,
    width: "100%",
  },
  mainInner: {
    marginInline: "auto",
    maxWidth: "46rem",
    paddingBlock: spacing._8,
    paddingInline: spacing._6,
    width: "100%",
  },
  mainInnerNarrow: {
    paddingBlock: spacing._6,
    paddingInline: spacing._4,
  },
  fullWidth: {
    width: "100%",
  },
  flexGrow: {
    flexGrow: 1,
  },
  marginTopAuto: {
    marginTop: "auto",
  },
  nowrap: {
    whiteSpace: "nowrap",
  },
  breakWord: {
    wordBreak: "break-word",
  },
  statusGood: {
    color: semanticColors.fgSuccess,
  },
  planGridWide: {
    display: "grid",
    gap: spacing._3,
    gridTemplateColumns: "repeat(3, minmax(0, 1fr))",
    width: "100%",
  },
  planGridNarrow: {
    display: "flex",
    flexDirection: "column",
    gap: spacing._3,
    width: "100%",
  },
  planCardItem: {
    height: "100%",
  },
  planCardControl: {
    alignItems: "flex-start",
    height: "100%",
    width: "100%",
  },
  planCardContent: {
    gap: spacing._2,
    height: "100%",
    width: "100%",
  },
  seatsInputRoot: {
    maxWidth: "12rem",
  },
  estimateCard: {
    backgroundColor: semanticColors.bgMuted,
  },
  optionItemRow: {
    alignItems: "flex-start",
    display: "flex",
    gap: spacing._2_5,
  },
  optionControlOffset: {
    marginTop: spacing._0_5,
  },
  switchRow: {
    alignItems: "center",
    display: "flex",
    gap: spacing._4,
    justifyContent: "space-between",
    width: "100%",
  },
  issuesList: {
    marginTop: spacing._1_5,
  },
  issueActionWrap: {
    marginTop: spacing._2,
  },
  reviewCardHeader: {
    alignItems: "center",
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    display: "flex",
    flexDirection: "row",
    gap: spacing._3,
    justifyContent: "space-between",
    paddingBlock: spacing._3,
    paddingInline: spacing._4,
  },
  reviewCardBody: {
    paddingBlock: spacing._4,
    paddingInline: spacing._4,
  },
  reviewDataLabel: {
    flexShrink: 0,
    minWidth: "10.5rem",
  },
  reviewDataLabelNarrow: {
    minWidth: 0,
  },
  termsRow: {
    alignItems: "flex-start",
    width: "100%",
  },
  footer: {
    backgroundColor: semanticColors.bg,
    borderTopColor: semanticColors.border,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
    bottom: 0,
    marginTop: "auto",
    position: "sticky",
    width: "100%",
    zIndex: 10,
  },
  footerInner: {
    marginInline: "auto",
    maxWidth: "46rem",
    paddingBlock: spacing._4,
    paddingInline: spacing._6,
    width: "100%",
  },
  footerInnerNarrow: {
    paddingInline: spacing._4,
  },
  footerLeftZone: {
    flexBasis: 0,
    flexGrow: 1,
    minWidth: "4.5rem",
  },
  footerRightZone: {
    flexBasis: 0,
    flexGrow: 1,
    minWidth: "fit-content",
  },
});

// ── Component ─────────────────────────────────────────────────────────────────

/**
 * FormWizard — four-step workspace and cloud project onboarding wizard with a
 * pinned header stepper, per-step validation on advance, optional skippable
 * team step, live monthly cost readout, editable review summary, and local
 * launch confirmation state.
 */
export function FormWizard({
  title = "Create workspace",
  workspaceDomain = "harbor.cloud",
  initialValues,
  onLaunch,
  onCancel,
  palette,
  style,
}: FormWizardProps) {
  const mergedInitial = useMemo<FormWizardValues>(
    () => ({
      ...DEFAULT_VALUES,
      ...initialValues,
      securityAddons: initialValues?.securityAddons
        ? [...initialValues.securityAddons]
        : [...DEFAULT_VALUES.securityAddons],
    }),
    [initialValues],
  );

  const queue = useMemo(() => Toast.createToaster(), []);
  const slugInputId = useId();
  const planGroupLabelId = useId();
  const roleGroupLabelId = useId();
  const addonsGroupLabelId = useId();

  // Responsive container measurement so narrow previews collapse gracefully.
  const [isNarrow, setIsNarrow] = useState(false);
  const hostObserverRef = useRef<ResizeObserver | null>(null);
  const attachHost = useCallback((node: HTMLDivElement | null) => {
    hostObserverRef.current?.disconnect();
    hostObserverRef.current = null;
    if (!node) return;
    setIsNarrow(node.getBoundingClientRect().width < NARROW_HOST_WIDTH);
    if (typeof ResizeObserver === "undefined") return;
    const observer = new ResizeObserver((entries) => {
      const width = entries[0]?.contentRect.width;
      if (typeof width === "number") {
        setIsNarrow(width < NARROW_HOST_WIDTH);
      }
    });
    observer.observe(node);
    hostObserverRef.current = observer;
  }, []);

  // Wizard flow state
  const [step, setStep] = useState(0);
  const [attempted, setAttempted] = useState<ReadonlySet<number>>(() => new Set());
  const [isLaunched, setIsLaunched] = useState(false);
  const [launchedWorkspaceId, setLaunchedWorkspaceId] = useState<string | null>(null);
  const [slugTouched, setSlugTouched] = useState(
    Boolean(initialValues?.workspaceSlug),
  );

  // Form field state
  const [organizationName, setOrganizationName] = useState(
    mergedInitial.organizationName,
  );
  const [workspaceSlug, setWorkspaceSlug] = useState(mergedInitial.workspaceSlug);
  const [projectName, setProjectName] = useState(mergedInitial.projectName);
  const [projectSummary, setProjectSummary] = useState(mergedInitial.projectSummary);

  const [region, setRegion] = useState(mergedInitial.region);
  const [runtime, setRuntime] = useState(mergedInitial.runtime);
  const [planId, setPlanId] = useState<PlanTierId>(mergedInitial.planId);
  const [seats, setSeats] = useState(mergedInitial.seats);

  const [inviteEmails, setInviteEmails] = useState(mergedInitial.inviteEmails);
  const [inviteRole, setInviteRole] = useState<InviteRoleId>(mergedInitial.inviteRole);
  const [securityAddons, setSecurityAddons] = useState<SecurityAddonId[]>(
    mergedInitial.securityAddons,
  );
  const [requireMfa, setRequireMfa] = useState(mergedInitial.requireMfa);
  const [sendInvitesNow, setSendInvitesNow] = useState(mergedInitial.sendInvitesNow);
  const [welcomeNote, setWelcomeNote] = useState(mergedInitial.welcomeNote);

  const [acceptedTerms, setAcceptedTerms] = useState(mergedInitial.acceptedTerms);

  // Focus targets for every validated field, keyed by the same names errorsByStep uses.
  const organizationNameRef = useRef<HTMLInputElement>(null);
  const workspaceSlugRef = useRef<HTMLInputElement>(null);
  const projectNameRef = useRef<HTMLInputElement>(null);
  const seatsRef = useRef<HTMLInputElement>(null);
  const inviteEmailsRef = useRef<HTMLTextAreaElement>(null);
  const acceptedTermsRef = useRef<HTMLButtonElement>(null);
  const pendingFocusFieldRef = useRef<ValidatableFieldKey | null>(null);

  const focusField = useCallback((fieldKey: ValidatableFieldKey) => {
    const targetMap: Record<ValidatableFieldKey, HTMLElement | null> = {
      organizationName: organizationNameRef.current,
      workspaceSlug: workspaceSlugRef.current,
      projectName: projectNameRef.current,
      seats: seatsRef.current,
      inviteEmails: inviteEmailsRef.current,
      acceptedTerms: acceptedTermsRef.current,
    };
    const element = targetMap[fieldKey];
    if (element) {
      element.focus();
      element.scrollIntoView({ block: "center", behavior: "smooth" });
    }
  }, []);

  // Derived data & pricing
  const emails = useMemo(() => parseEmails(inviteEmails), [inviteEmails]);
  const invalidEmails = useMemo(
    () => emails.filter((address) => !EMAIL_PATTERN.test(address)),
    [emails],
  );
  const selectedPlan = useMemo(
    () => PLANS.find((tier) => tier.id === planId) ?? PLANS[1],
    [planId],
  );
  const selectedRegion = useMemo(
    () => REGIONS.find((item) => item.value === region) ?? REGIONS[0],
    [region],
  );
  const selectedRuntime = useMemo(
    () => RUNTIMES.find((item) => item.value === runtime) ?? RUNTIMES[0],
    [runtime],
  );
  const selectedRole = useMemo(
    () => INVITE_ROLES.find((item) => item.value === inviteRole) ?? INVITE_ROLES[1],
    [inviteRole],
  );
  const selectedAddonObjects = useMemo(
    () => SECURITY_ADDONS.filter((addon) => securityAddons.includes(addon.id)),
    [securityAddons],
  );
  const addonCostPerSeat = useMemo(
    () => selectedAddonObjects.reduce((sum, addon) => sum + addon.pricePerSeat, 0),
    [selectedAddonObjects],
  );
  const effectiveSeats = Number.isFinite(seats) && seats > 0 ? seats : 0;
  const monthlyTotal = (selectedPlan.pricePerSeat + addonCostPerSeat) * effectiveSeats;

  // Single source of truth for per-step validation rules.
  const errorsByStep = useMemo<
    Array<Partial<Record<ValidatableFieldKey, string>>>
  >(() => {
    const normalizedSlug = workspaceSlug.trim();

    const step0: Partial<Record<ValidatableFieldKey, string>> = {};
    if (!organizationName.trim()) {
      step0.organizationName = "Enter an organization name.";
    }
    if (!normalizedSlug) {
      step0.workspaceSlug = "Enter a workspace URL slug.";
    } else if (!SLUG_PATTERN.test(normalizedSlug)) {
      step0.workspaceSlug =
        "Use lowercase letters, numbers, and hyphens, starting and ending with a letter or number.";
    } else if (RESERVED_SLUGS.has(normalizedSlug)) {
      step0.workspaceSlug = `${workspaceDomain}/${normalizedSlug} is reserved or already taken.`;
    }
    if (!projectName.trim()) {
      step0.projectName = "Enter an initial project name.";
    }

    const step1: Partial<Record<ValidatableFieldKey, string>> = {};
    if (!Number.isFinite(seats) || seats < 1) {
      step1.seats = "A workspace requires at least 1 seat.";
    } else if (seats > selectedPlan.seatLimit) {
      step1.seats = `${selectedPlan.label} supports up to ${selectedPlan.seatLimit} seats. Choose a larger tier or reduce seats.`;
    } else if (seats < emails.length + 1) {
      step1.seats = `You are inviting ${emails.length} ${
        emails.length === 1 ? "teammate" : "teammates"
      } plus yourself, so you need at least ${emails.length + 1} seats.`;
    }

    const step2: Partial<Record<ValidatableFieldKey, string>> = {};
    if (invalidEmails.length > 0) {
      step2.inviteEmails = `Invalid email address: ${invalidEmails.join(", ")}`;
    }

    const step3: Partial<Record<ValidatableFieldKey, string>> = {};
    if (!acceptedTerms) {
      step3.acceptedTerms = "Accept the Cloud Services Agreement to launch.";
    }

    return [step0, step1, step2, step3];
  }, [
    organizationName,
    workspaceSlug,
    workspaceDomain,
    projectName,
    seats,
    selectedPlan.seatLimit,
    selectedPlan.label,
    emails.length,
    invalidEmails,
    acceptedTerms,
  ]);

  const shownErrors = useCallback(
    (index: number) => (attempted.has(index) ? errorsByStep[index] : {}),
    [attempted, errorsByStep],
  );

  const currentErrors = shownErrors(step);
  const isLastStep = step === STEPS.length - 1;

  // Earlier steps with unresolved validation errors — surfaced on Review so
  // nothing hides behind another panel before Launch.
  const outstandingSteps = useMemo(
    () =>
      STEPS.map((definition, index) => ({
        ...definition,
        index,
        issues: Object.values(errorsByStep[index]).filter(
          (message): message is string => Boolean(message),
        ),
      })).filter((entry) => entry.index !== step && entry.issues.length > 0),
    [errorsByStep, step],
  );

  // Apply deferred focus after step transitions render the target field.
  useEffect(() => {
    const fieldKey = pendingFocusFieldRef.current;
    if (!fieldKey) return;
    pendingFocusFieldRef.current = null;
    focusField(fieldKey);
  }, [step, focusField]);

  const markAttempted = useCallback((index: number) => {
    setAttempted((prev) => {
      if (prev.has(index)) return prev;
      const next = new Set(prev);
      next.add(index);
      return next;
    });
  }, []);

  const handleOrganizationChange = (nextValue: string) => {
    setOrganizationName(nextValue);
    if (!slugTouched) {
      setWorkspaceSlug(slugify(nextValue));
    }
  };

  const handleSlugChange = (nextValue: string) => {
    setSlugTouched(true);
    setWorkspaceSlug(nextValue.toLowerCase());
  };

  const goToStep = (nextIndex: number) => {
    if (isLaunched) return;
    if (nextIndex > step) {
      markAttempted(step);
    }
    setStep(nextIndex);
  };

  const goNext = () => {
    markAttempted(step);

    const stepErrorKeys = Object.keys(
      errorsByStep[step],
    ) as ValidatableFieldKey[];
    if (stepErrorKeys.length > 0) {
      focusField(stepErrorKeys[0]);
      return;
    }

    if (isLastStep) {
      const firstBrokenStep = errorsByStep.findIndex(
        (stepErrors) => Object.keys(stepErrors).length > 0,
      );
      if (firstBrokenStep !== -1) {
        const brokenKeys = Object.keys(
          errorsByStep[firstBrokenStep],
        ) as ValidatableFieldKey[];
        markAttempted(firstBrokenStep);
        pendingFocusFieldRef.current = brokenKeys[0] ?? null;
        setStep(firstBrokenStep);
        return;
      }

      const normalizedSlug = workspaceSlug.trim();
      const workspaceId = buildWorkspaceId(normalizedSlug);
      const workspaceUrl = `https://${workspaceDomain}/${normalizedSlug}`;
      const payload: FormWizardCompletionPayload = {
        workspaceId,
        workspaceUrl,
        monthlyTotal,
        invitedCount: emails.length,
        values: {
          organizationName: organizationName.trim(),
          workspaceSlug: normalizedSlug,
          projectName: projectName.trim(),
          projectSummary: projectSummary.trim(),
          region,
          runtime,
          planId,
          seats,
          inviteEmails,
          inviteRole,
          securityAddons,
          requireMfa,
          sendInvitesNow,
          welcomeNote: welcomeNote.trim(),
          acceptedTerms,
        },
      };

      setLaunchedWorkspaceId(workspaceId);
      setIsLaunched(true);
      onLaunch?.(payload);
      queue.success("Workspace launched", {
        description: `${organizationName.trim()} is ready at ${workspaceDomain}/${normalizedSlug}.`,
      });
      return;
    }

    setStep((current) => Math.min(STEPS.length - 1, current + 1));
  };

  // Skip declines the optional Team step outright: clear any partial input and
  // advance without leaving hidden validation errors behind.
  const goSkip = () => {
    setInviteEmails("");
    setWelcomeNote("");
    setStep((current) => Math.min(STEPS.length - 1, current + 1));
  };

  const handleCancel = () => {
    onCancel?.();
    queue.info("Onboarding cancelled", {
      description: "No workspace was provisioned. Draft state remains local.",
    });
  };

  const handleResetWizard = () => {
    setIsLaunched(false);
    setLaunchedWorkspaceId(null);
    setStep(0);
    setAttempted(new Set());
    setSlugTouched(Boolean(initialValues?.workspaceSlug));
    setOrganizationName(mergedInitial.organizationName);
    setWorkspaceSlug(mergedInitial.workspaceSlug);
    setProjectName(mergedInitial.projectName);
    setProjectSummary(mergedInitial.projectSummary);
    setRegion(mergedInitial.region);
    setRuntime(mergedInitial.runtime);
    setPlanId(mergedInitial.planId);
    setSeats(mergedInitial.seats);
    setInviteEmails(mergedInitial.inviteEmails);
    setInviteRole(mergedInitial.inviteRole);
    setSecurityAddons([...mergedInitial.securityAddons]);
    setRequireMfa(mergedInitial.requireMfa);
    setSendInvitesNow(mergedInitial.sendInvitesNow);
    setWelcomeNote(mergedInitial.welcomeNote);
    setAcceptedTerms(false);
  };

  const normalizedSlug = workspaceSlug.trim();
  const slugIsValid =
    normalizedSlug.length > 0 &&
    SLUG_PATTERN.test(normalizedSlug) &&
    !RESERVED_SLUGS.has(normalizedSlug);

  return (
    <VStack
      ref={attachHost}
      gap="0"
      palette={palette}
      style={[styles.root, style]}
    >
      {/* Pinned header + horizontal stepper */}
      <header {...stylex.props(styles.header)}>
        <VStack
          gap={isNarrow ? "3" : "4"}
          style={[styles.headerInner, isNarrow && styles.headerInnerNarrow]}
        >
          <HStack justify="between" wrap="wrap" gap="3">
            <HStack wrap="wrap" gap="2.5">
              <Heading render={<h1 />} size="2xl" style={styles.headingReset}>
                {isLaunched ? "Workspace ready" : title}
              </Heading>
              <Badge
                variant="subtle"
                size="sm"
                palette={isLaunched ? greenPalette : accentPalette}
              >
                {isLaunched ? "Provisioned" : workspaceDomain}
              </Badge>
            </HStack>
            {!isLaunched ? (
              <Button variant="ghost" size="sm" onClick={handleCancel}>
                Cancel
              </Button>
            ) : null}
          </HStack>

          {!isLaunched ? (
            <Steps.Root
              count={STEPS.length}
              step={step}
              onStepChange={({ step: next }) => goToStep(next)}
              size="sm"
              orientation="horizontal"
              palette={accentPalette}
              aria-label="Workspace onboarding progress"
            >
              <Steps.List>
                {STEPS.map((definition, index) => {
                  const hasError = Object.keys(shownErrors(index)).length > 0;
                  const isComplete = index < step && !hasError;
                  const isLast = index === STEPS.length - 1;
                  return (
                    <Steps.Item
                      key={definition.id}
                      index={index}
                      style={isLast ? styles.stepItemLast : undefined}
                    >
                      <Steps.Trigger aria-label={definition.label}>
                        <Steps.Indicator
                          palette={hasError ? redPalette : undefined}
                          style={hasError ? styles.stepIndicatorError : undefined}
                        >
                          {hasError ? (
                            <AlertCircleIcon />
                          ) : isComplete ? (
                            <CheckIcon />
                          ) : (
                            index + 1
                          )}
                        </Steps.Indicator>
                        <Steps.Title
                          style={
                            isNarrow && index !== step
                              ? styles.stepTitleHidden
                              : undefined
                          }
                        >
                          <HStack render={<span />} align="baseline" gap="1">
                            <span>{definition.label}</span>
                            {definition.isOptional && !isNarrow ? (
                              <Text
                                render={<span />}
                                size="xs"
                                tone="subtle"
                                weight="normal"
                              >
                                (Optional)
                              </Text>
                            ) : null}
                          </HStack>
                        </Steps.Title>
                      </Steps.Trigger>
                      <Steps.Separator />
                    </Steps.Item>
                  );
                })}
              </Steps.List>
            </Steps.Root>
          ) : null}
        </VStack>
      </header>

      {/* Active step panel (or launch confirmation) */}
      <VStack render={<main />} gap="0" style={styles.main}>
        <VStack
          gap="6"
          style={[styles.mainInner, isNarrow && styles.mainInnerNarrow]}
        >
          {isLaunched ? (
            <VStack
              render={<section aria-label="Workspace launch confirmation" />}
              gap="6"
            >
              <Alert.Root
                status="success"
                variant="subtle"
                size="md"
                palette={greenPalette}
              >
                <Alert.Indicator>
                  <CheckCircleIcon />
                </Alert.Indicator>
                <Alert.Content>
                  <Alert.Title>
                    {organizationName.trim()} provisioned in {selectedRegion.label}
                  </Alert.Title>
                  <Alert.Description>
                    Initial project &ldquo;{projectName.trim()}&rdquo; is initialized
                    on {selectedRuntime.label}. This demo records launch state locally
                    without billing or external network calls.
                  </Alert.Description>
                </Alert.Content>
              </Alert.Root>

              <VStack gap="1.5">
                <Heading render={<h2 />} size="xl" style={styles.headingReset}>
                  Your cloud workspace is live
                </Heading>
                <Text variant="muted" size="sm">
                  Review the provisioned workspace details below, jump into the
                  dashboard, or start a fresh onboarding run.
                </Text>
              </VStack>

              <Card.Root variant="outline" size="md">
                <Card.Body style={styles.reviewCardBody}>
                  <DataList.Root
                    orientation={isNarrow ? "vertical" : "horizontal"}
                    variant="subtle"
                    size="md"
                  >
                    <DataList.Item>
                      <DataList.ItemLabel
                        style={
                          isNarrow
                            ? styles.reviewDataLabelNarrow
                            : styles.reviewDataLabel
                        }
                      >
                        Workspace ID
                      </DataList.ItemLabel>
                      <DataList.ItemValue>
                        <Text
                          render={<span />}
                          variant="mono"
                          size="xs"
                          style={styles.breakWord}
                        >
                          {launchedWorkspaceId}
                        </Text>
                      </DataList.ItemValue>
                    </DataList.Item>
                    <DataList.Item>
                      <DataList.ItemLabel
                        style={
                          isNarrow
                            ? styles.reviewDataLabelNarrow
                            : styles.reviewDataLabel
                        }
                      >
                        Workspace URL
                      </DataList.ItemLabel>
                      <DataList.ItemValue>
                        <Text
                          render={<span />}
                          variant="mono"
                          size="xs"
                          style={styles.breakWord}
                        >
                          https://{workspaceDomain}/{normalizedSlug}
                        </Text>
                      </DataList.ItemValue>
                    </DataList.Item>
                    <DataList.Item>
                      <DataList.ItemLabel
                        style={
                          isNarrow
                            ? styles.reviewDataLabelNarrow
                            : styles.reviewDataLabel
                        }
                      >
                        Initial project
                      </DataList.ItemLabel>
                      <DataList.ItemValue>{projectName.trim()}</DataList.ItemValue>
                    </DataList.Item>
                    <DataList.Item>
                      <DataList.ItemLabel
                        style={
                          isNarrow
                            ? styles.reviewDataLabelNarrow
                            : styles.reviewDataLabel
                        }
                      >
                        Region &amp; runtime
                      </DataList.ItemLabel>
                      <DataList.ItemValue>
                        {selectedRegion.label} · {selectedRuntime.label}
                      </DataList.ItemValue>
                    </DataList.Item>
                    <DataList.Item>
                      <DataList.ItemLabel
                        style={
                          isNarrow
                            ? styles.reviewDataLabelNarrow
                            : styles.reviewDataLabel
                        }
                      >
                        Plan &amp; capacity
                      </DataList.ItemLabel>
                      <DataList.ItemValue>
                        {selectedPlan.label} · {seats}{" "}
                        {seats === 1 ? "seat" : "seats"} ({money(monthlyTotal)}/mo)
                      </DataList.ItemValue>
                    </DataList.Item>
                    <DataList.Item>
                      <DataList.ItemLabel
                        style={
                          isNarrow
                            ? styles.reviewDataLabelNarrow
                            : styles.reviewDataLabel
                        }
                      >
                        Team &amp; security
                      </DataList.ItemLabel>
                      <DataList.ItemValue>
                        {emails.length === 0
                          ? "Owner only"
                          : `${emails.length} ${
                              emails.length === 1 ? "invite" : "invites"
                            } (${selectedRole.label}${
                              sendInvitesNow ? ", queued now" : ", draft"
                            })`}
                        {requireMfa ? " · Passkey / 2FA enforced" : ""}
                      </DataList.ItemValue>
                    </DataList.Item>
                  </DataList.Root>
                </Card.Body>
              </Card.Root>

              <HStack wrap="wrap" gap="3">
                <Button
                  variant="solid"
                  palette={accentPalette}
                  onClick={() =>
                    queue.info("Opening workspace dashboard", {
                      description: `Routing to https://${workspaceDomain}/${normalizedSlug}`,
                    })
                  }
                >
                  <RocketIcon />
                  Open workspace dashboard
                </Button>
                <Button variant="surface" onClick={handleResetWizard}>
                  Create another workspace
                </Button>
              </HStack>
            </VStack>
          ) : null}

          {/* Step 0 — Organization & workspace slug */}
          {!isLaunched && step === 0 ? (
            <VStack
              render={<section aria-label="Organization details" />}
              gap="6"
            >
              <VStack gap="1.5">
                <Heading render={<h2 />} size="xl" style={styles.headingReset}>
                  Organization &amp; workspace identity
                </Heading>
                <Text variant="muted" size="sm">
                  Name your organization, claim a workspace URL, and create your
                  first cloud project.
                </Text>
              </VStack>

              <VStack gap="5" style={styles.fullWidth}>
                <Field.Root
                  required
                  invalid={Boolean(currentErrors.organizationName)}
                >
                  <Field.Label>
                    Organization name
                    <Field.RequiredIndicator />
                  </Field.Label>
                  <Input
                    ref={organizationNameRef}
                    value={organizationName}
                    onValueChange={handleOrganizationChange}
                    placeholder="Meridian Labs"
                    aria-invalid={
                      currentErrors.organizationName ? true : undefined
                    }
                  />
                  {currentErrors.organizationName ? (
                    <Field.Error match={true}>
                      {currentErrors.organizationName}
                    </Field.Error>
                  ) : null}
                </Field.Root>

                <Field.Root
                  required
                  invalid={Boolean(currentErrors.workspaceSlug)}
                >
                  <Field.Label htmlFor={slugInputId}>
                    Workspace URL
                    <Field.RequiredIndicator />
                  </Field.Label>
                  <InputGroup.Root variant="outline" size="md">
                    <InputGroup.Addon>{workspaceDomain}/</InputGroup.Addon>
                    <InputGroup.Input
                      id={slugInputId}
                      ref={workspaceSlugRef}
                      value={workspaceSlug}
                      onChange={(event) =>
                        handleSlugChange(event.currentTarget.value)
                      }
                      placeholder="meridian-labs"
                      autoCapitalize="none"
                      autoCorrect="off"
                      spellCheck={false}
                      aria-invalid={
                        currentErrors.workspaceSlug ? "true" : undefined
                      }
                    />
                  </InputGroup.Root>
                  {currentErrors.workspaceSlug ? (
                    <Field.Error match={true}>
                      {currentErrors.workspaceSlug}
                    </Field.Error>
                  ) : slugIsValid ? (
                    <HStack
                      render={<span />}
                      gap="1.5"
                      style={styles.statusGood}
                    >
                      <CheckCircleIcon />
                      <Text
                        render={<span />}
                        size="xs"
                        weight="medium"
                        tone="success"
                      >
                        {workspaceDomain}/{normalizedSlug} is available.
                      </Text>
                    </HStack>
                  ) : (
                    <Field.Description>
                      Lowercase letters, numbers, and hyphens only. Reserved slugs
                      like &ldquo;api&rdquo; or &ldquo;admin&rdquo; are unavailable.
                    </Field.Description>
                  )}
                </Field.Root>

                <Separator decorative />

                <Field.Root
                  required
                  invalid={Boolean(currentErrors.projectName)}
                >
                  <Field.Label>
                    Initial project name
                    <Field.RequiredIndicator />
                  </Field.Label>
                  <Input
                    ref={projectNameRef}
                    value={projectName}
                    onValueChange={setProjectName}
                    placeholder="Core API Gateway"
                    aria-invalid={currentErrors.projectName ? true : undefined}
                  />
                  <Field.Description>
                    Creates your first repository link, deployment pipeline, and
                    environment variables store.
                  </Field.Description>
                  {currentErrors.projectName ? (
                    <Field.Error match={true}>
                      {currentErrors.projectName}
                    </Field.Error>
                  ) : null}
                </Field.Root>

                <Field.Root>
                  <Field.Label>
                    Workload summary
                    <Text
                      render={<span />}
                      size="xs"
                      tone="subtle"
                      weight="normal"
                    >
                      Optional
                    </Text>
                  </Field.Label>
                  <Textarea
                    rows={2}
                    maxLength={220}
                    value={projectSummary}
                    onValueChange={setProjectSummary}
                    placeholder="Describe the services or apps running in this project."
                  />
                </Field.Root>
              </VStack>
            </VStack>
          ) : null}

          {/* Step 1 — Region, runtime & plan tier */}
          {!isLaunched && step === 1 ? (
            <VStack
              render={<section aria-label="Infrastructure and plan" />}
              gap="6"
            >
              <VStack gap="1.5">
                <Heading render={<h2 />} size="xl" style={styles.headingReset}>
                  Region, runtime &amp; plan tier
                </Heading>
                <Text variant="muted" size="sm">
                  Select where encrypted project data lives, your default build
                  runtime, and monthly seat capacity.
                </Text>
              </VStack>

              <VStack gap="5" style={styles.fullWidth}>
                <Grid
                  columns={isNarrow ? "1" : "2"}
                  gap="4"
                  style={styles.fullWidth}
                >
                  <Select.Root
                    items={REGIONS}
                    value={region}
                    onValueChange={(nextRegion) => {
                      if (nextRegion) {
                        setRegion(nextRegion);
                      }
                    }}
                    placeholder="Select region"
                    palette={accentPalette}
                  >
                    <Select.Label>Primary compute region</Select.Label>
                    <Select.Control>
                      <Select.Trigger>
                        <Select.Value />
                      </Select.Trigger>
                      <Select.IndicatorGroup>
                        <Select.Icon />
                      </Select.IndicatorGroup>
                    </Select.Control>
                    <Select.Content>
                      {REGIONS.map((option) => (
                        <Select.Item key={option.value} value={option.value}>
                          <Select.ItemText>{option.label}</Select.ItemText>
                          <Select.ItemIndicator />
                        </Select.Item>
                      ))}
                    </Select.Content>
                  </Select.Root>

                  <Select.Root
                    items={RUNTIMES}
                    value={runtime}
                    onValueChange={(nextRuntime) => {
                      if (nextRuntime) {
                        setRuntime(nextRuntime);
                      }
                    }}
                    placeholder="Select runtime"
                    palette={accentPalette}
                  >
                    <Select.Label>Default runtime</Select.Label>
                    <Select.Control>
                      <Select.Trigger>
                        <Select.Value />
                      </Select.Trigger>
                      <Select.IndicatorGroup>
                        <Select.Icon />
                      </Select.IndicatorGroup>
                    </Select.Control>
                    <Select.Content>
                      {RUNTIMES.map((option) => (
                        <Select.Item key={option.value} value={option.value}>
                          <Select.ItemText>{option.label}</Select.ItemText>
                          <Select.ItemIndicator />
                        </Select.Item>
                      ))}
                    </Select.Content>
                  </Select.Root>
                </Grid>

                <Field.Root>
                  <Field.Label id={planGroupLabelId}>Plan tier</Field.Label>
                  <RadioCard.Root
                    value={planId}
                    onValueChange={(nextPlan) => {
                      if (
                        nextPlan === "developer" ||
                        nextPlan === "team" ||
                        nextPlan === "scale"
                      ) {
                        setPlanId(nextPlan);
                      }
                    }}
                    variant="outline"
                    size="md"
                    palette={accentPalette}
                    aria-labelledby={planGroupLabelId}
                    style={isNarrow ? styles.planGridNarrow : styles.planGridWide}
                  >
                    {PLANS.map((tier) => (
                      <RadioCard.Item
                        key={tier.id}
                        value={tier.id}
                        style={styles.planCardItem}
                      >
                        <RadioCard.ItemControl style={styles.planCardControl}>
                          <RadioCard.ItemContent style={styles.planCardContent}>
                            <HStack
                              justify="between"
                              gap="2"
                              style={styles.fullWidth}
                            >
                              <HStack wrap="wrap" gap="1.5">
                                <RadioCard.ItemText>
                                  {tier.label}
                                </RadioCard.ItemText>
                                {tier.recommended ? (
                                  <Badge
                                    variant="subtle"
                                    size="xs"
                                    palette={greenPalette}
                                  >
                                    Recommended
                                  </Badge>
                                ) : null}
                              </HStack>
                              <RadioCard.ItemIndicator />
                            </HStack>
                            <Text
                              render={<span />}
                              size="xl"
                              weight="semibold"
                              tabular="true"
                            >
                              {tier.pricePerSeat === 0
                                ? "Free"
                                : `${money(tier.pricePerSeat)}/seat`}
                            </Text>
                            <RadioCard.ItemDescription>
                              {tier.description}
                            </RadioCard.ItemDescription>
                            <Text
                              render={<span />}
                              size="xs"
                              tone="subtle"
                              style={styles.marginTopAuto}
                            >
                              {tier.highlight}
                            </Text>
                          </RadioCard.ItemContent>
                        </RadioCard.ItemControl>
                      </RadioCard.Item>
                    ))}
                  </RadioCard.Root>
                </Field.Root>

                <Field.Root required invalid={Boolean(currentErrors.seats)}>
                  <Field.Label>
                    Workspace seats
                    <Field.RequiredIndicator />
                  </Field.Label>
                  <NumberInput.Root
                    value={seats}
                    onValueChange={(nextSeats) => setSeats(nextSeats ?? 0)}
                    min={1}
                    max={selectedPlan.seatLimit}
                    step={1}
                    palette={accentPalette}
                    style={styles.seatsInputRoot}
                  >
                    <NumberInput.Group>
                      <NumberInput.Input
                        ref={seatsRef}
                        aria-label="Workspace seats"
                        aria-invalid={currentErrors.seats ? true : undefined}
                      />
                      <NumberInput.Control />
                    </NumberInput.Group>
                  </NumberInput.Root>
                  <Field.Description>
                    Includes you as owner. {selectedPlan.label} allows up to{" "}
                    {selectedPlan.seatLimit.toLocaleString("en-US")} seats.
                  </Field.Description>
                  {currentErrors.seats ? (
                    <Field.Error match={true}>{currentErrors.seats}</Field.Error>
                  ) : null}
                </Field.Root>
              </VStack>

              {/* Readout card intentionally outside the form inputs */}
              <Card.Root variant="outline" size="md" style={styles.estimateCard}>
                <Card.Body>
                  <HStack justify="between" wrap="wrap" gap="4">
                    <VStack gap="0.5">
                      <Text render={<span />} size="sm" weight="medium">
                        Estimated monthly total
                      </Text>
                      <Text
                        render={<span />}
                        size="xs"
                        tone="muted"
                        tabular="true"
                      >
                        {effectiveSeats}{" "}
                        {effectiveSeats === 1 ? "seat" : "seats"} ×{" "}
                        {money(selectedPlan.pricePerSeat + addonCostPerSeat)}
                        {addonCostPerSeat > 0
                          ? ` (${money(selectedPlan.pricePerSeat)} plan + ${money(addonCostPerSeat)} security add-ons)`
                          : ` (${selectedPlan.label} tier)`}
                      </Text>
                    </VStack>
                    <Text
                      render={<span />}
                      size="2xl"
                      weight="semibold"
                      tabular="true"
                    >
                      {money(monthlyTotal)}
                      <Text
                        render={<span />}
                        size="sm"
                        tone="muted"
                        weight="normal"
                      >
                        /mo
                      </Text>
                    </Text>
                  </HStack>
                </Card.Body>
              </Card.Root>
            </VStack>
          ) : null}

          {/* Step 2 — Team invites & security defaults (optional) */}
          {!isLaunched && step === 2 ? (
            <VStack
              render={<section aria-label="Team invites and security defaults" />}
              gap="6"
            >
              <VStack gap="1.5">
                <Heading render={<h2 />} size="xl" style={styles.headingReset}>
                  Team invites &amp; security defaults
                </Heading>
                <Text variant="muted" size="sm">
                  Invite teammates and configure compliance controls now, or skip
                  this step and finish setup from workspace settings later.
                </Text>
              </VStack>

              <VStack gap="5" style={styles.fullWidth}>
                <Field.Root invalid={Boolean(currentErrors.inviteEmails)}>
                  <Field.Label>
                    Teammate email addresses
                    <Text
                      render={<span />}
                      size="xs"
                      tone="subtle"
                      weight="normal"
                    >
                      Optional
                    </Text>
                  </Field.Label>
                  <Textarea
                    ref={inviteEmailsRef}
                    rows={4}
                    value={inviteEmails}
                    onValueChange={setInviteEmails}
                    placeholder={"alex@meridianlabs.io\nsamira@meridianlabs.io"}
                    aria-invalid={currentErrors.inviteEmails ? true : undefined}
                  />
                  {currentErrors.inviteEmails ? (
                    <Field.Error match={true}>
                      {currentErrors.inviteEmails}
                    </Field.Error>
                  ) : emails.length > 0 && invalidEmails.length === 0 ? (
                    <HStack
                      render={<span />}
                      gap="1.5"
                      style={styles.statusGood}
                    >
                      <CheckCircleIcon />
                      <Text
                        render={<span />}
                        size="xs"
                        weight="medium"
                        tone="success"
                      >
                        {emails.length}{" "}
                        {emails.length === 1 ? "teammate" : "teammates"} ready to
                        invite.
                      </Text>
                    </HStack>
                  ) : (
                    <Field.Description>
                      Enter one email per line or separate addresses with commas.
                    </Field.Description>
                  )}
                </Field.Root>

                <Field.Root>
                  <Field.Label id={roleGroupLabelId}>
                    Default role for invitees
                  </Field.Label>
                  <RadioGroup.Root
                    value={inviteRole}
                    onValueChange={setInviteRole}
                    variant="solid"
                    size="md"
                    palette={accentPalette}
                    aria-labelledby={roleGroupLabelId}
                  >
                    {INVITE_ROLES.map((option) => (
                      <RadioGroup.Item
                        key={option.value}
                        style={styles.optionItemRow}
                      >
                        <RadioGroup.ItemControl
                          value={option.value}
                          style={styles.optionControlOffset}
                        />
                        <VStack render={<span />} gap="0.5">
                          <RadioGroup.ItemText>{option.label}</RadioGroup.ItemText>
                          <Text
                            render={<span />}
                            size="xs"
                            tone="muted"
                            weight="normal"
                          >
                            {option.description}
                          </Text>
                        </VStack>
                      </RadioGroup.Item>
                    ))}
                  </RadioGroup.Root>
                </Field.Root>

                <Separator decorative />

                <Field.Root>
                  <Field.Label id={addonsGroupLabelId}>
                    Security &amp; compliance add-ons
                  </Field.Label>
                  <CheckboxGroup.Root
                    value={securityAddons}
                    onValueChange={(nextAddons) =>
                      setSecurityAddons(nextAddons as SecurityAddonId[])
                    }
                    variant="solid"
                    size="md"
                    orientation="vertical"
                    palette={accentPalette}
                    aria-labelledby={addonsGroupLabelId}
                  >
                    {SECURITY_ADDONS.map((addon) => (
                      <CheckboxGroup.Item
                        key={addon.id}
                        style={styles.optionItemRow}
                      >
                        <CheckboxGroup.ItemControl
                          value={addon.id}
                          style={styles.optionControlOffset}
                        />
                        <VStack render={<span />} gap="0.5">
                          <HStack render={<span />} wrap="wrap" gap="2">
                            <CheckboxGroup.ItemLabel>
                              {addon.label}
                            </CheckboxGroup.ItemLabel>
                            <Text
                              render={<span />}
                              size="xs"
                              tone="muted"
                              weight="medium"
                              tabular="true"
                            >
                              +{money(addon.pricePerSeat)}/seat
                            </Text>
                          </HStack>
                          <Text
                            render={<span />}
                            size="xs"
                            tone="muted"
                            weight="normal"
                          >
                            {addon.description}
                          </Text>
                        </VStack>
                      </CheckboxGroup.Item>
                    ))}
                  </CheckboxGroup.Root>
                </Field.Root>

                <Separator decorative />

                <VStack gap="4" style={styles.fullWidth}>
                  <Switch.Root
                    variant="solid"
                    size="md"
                    palette={accentPalette}
                    style={styles.switchRow}
                  >
                    <VStack
                      render={<span />}
                      gap="0.5"
                      style={styles.flexGrow}
                    >
                      <Text render={<span />} size="sm" weight="medium">
                        Require hardware passkeys or 2FA
                      </Text>
                      <Text render={<span />} size="xs" tone="muted">
                        Prompt every member to enroll a WebAuthn passkey or TOTP
                        app on first sign-in.
                      </Text>
                    </VStack>
                    <Switch.Control
                      checked={requireMfa}
                      onCheckedChange={setRequireMfa}
                    />
                  </Switch.Root>

                  <Switch.Root
                    variant="solid"
                    size="md"
                    palette={accentPalette}
                    style={styles.switchRow}
                  >
                    <VStack
                      render={<span />}
                      gap="0.5"
                      style={styles.flexGrow}
                    >
                      <Text render={<span />} size="sm" weight="medium">
                        Send invite emails immediately on launch
                      </Text>
                      <Text render={<span />} size="xs" tone="muted">
                        Turn off to save invites as drafts until your first
                        environment is deployed.
                      </Text>
                    </VStack>
                    <Switch.Control
                      checked={sendInvitesNow}
                      onCheckedChange={setSendInvitesNow}
                    />
                  </Switch.Root>
                </VStack>

                {sendInvitesNow ? (
                  <Field.Root>
                    <Field.Label>
                      Welcome note
                      <Text
                        render={<span />}
                        size="xs"
                        tone="subtle"
                        weight="normal"
                      >
                        Optional
                      </Text>
                    </Field.Label>
                    <Textarea
                      rows={2}
                      maxLength={240}
                      value={welcomeNote}
                      onValueChange={setWelcomeNote}
                      placeholder="Welcome to our Harbor Cloud workspace — staging deploys live here."
                    />
                  </Field.Root>
                ) : null}
              </VStack>
            </VStack>
          ) : null}

          {/* Step 3 — Review & launch */}
          {!isLaunched && step === 3 ? (
            <VStack
              render={<section aria-label="Review and launch workspace" />}
              gap="6"
            >
              <VStack gap="1.5">
                <Heading render={<h2 />} size="xl" style={styles.headingReset}>
                  Review &amp; launch
                </Heading>
                <Text variant="muted" size="sm">
                  Nothing is provisioned until you launch. Use Edit on any card or
                  click a step above to adjust settings.
                </Text>
              </VStack>

              {outstandingSteps.length > 0 ? (
                <Alert.Root
                  status="error"
                  variant="subtle"
                  size="md"
                  palette={redPalette}
                >
                  <Alert.Indicator>
                    <AlertCircleIcon />
                  </Alert.Indicator>
                  <Alert.Content>
                    <Alert.Title>
                      {outstandingSteps.length}{" "}
                      {outstandingSteps.length === 1
                        ? "step needs"
                        : "steps need"}{" "}
                      attention before launch
                    </Alert.Title>
                    <VStack gap="2" style={styles.issuesList}>
                      {outstandingSteps.map((entry) => (
                        <Text key={entry.id} size="xs">
                          <Text render={<span />} size="xs" weight="semibold">
                            {entry.label}:
                          </Text>{" "}
                          {entry.issues.join(" ")}
                        </Text>
                      ))}
                      <HStack
                        wrap="wrap"
                        gap="2"
                        style={styles.issueActionWrap}
                      >
                        <Button
                          variant="surface"
                          size="xs"
                          onClick={() => {
                            const target = outstandingSteps[0];
                            markAttempted(target.index);
                            const [firstKey] = Object.keys(
                              errorsByStep[target.index],
                            ) as ValidatableFieldKey[];
                            pendingFocusFieldRef.current = firstKey ?? null;
                            setStep(target.index);
                          }}
                        >
                          Fix {outstandingSteps[0].label}
                        </Button>
                      </HStack>
                    </VStack>
                  </Alert.Content>
                </Alert.Root>
              ) : null}

              <VStack gap="4" style={styles.fullWidth}>
                {/* Section 1: Organization */}
                <Card.Root variant="outline" size="md">
                  <Card.Header style={styles.reviewCardHeader}>
                    <HStack gap="2">
                      <Card.Title>Organization</Card.Title>
                      {Object.keys(errorsByStep[0]).length > 0 ? (
                        <Badge variant="subtle" size="xs" palette={redPalette}>
                          Needs attention
                        </Badge>
                      ) : null}
                    </HStack>
                    <Button variant="ghost" size="xs" onClick={() => goToStep(0)}>
                      Edit
                    </Button>
                  </Card.Header>
                  <Card.Body style={styles.reviewCardBody}>
                    <DataList.Root
                      orientation={isNarrow ? "vertical" : "horizontal"}
                      variant="subtle"
                      size="md"
                    >
                      <DataList.Item>
                        <DataList.ItemLabel
                          style={
                            isNarrow
                              ? styles.reviewDataLabelNarrow
                              : styles.reviewDataLabel
                          }
                        >
                          Organization name
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {organizationName.trim() || "—"}
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item>
                        <DataList.ItemLabel
                          style={
                            isNarrow
                              ? styles.reviewDataLabelNarrow
                              : styles.reviewDataLabel
                          }
                        >
                          Workspace URL
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          <Text
                            render={<span />}
                            variant="mono"
                            size="xs"
                            style={styles.breakWord}
                          >
                            {workspaceDomain}/{normalizedSlug || "—"}
                          </Text>
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item>
                        <DataList.ItemLabel
                          style={
                            isNarrow
                              ? styles.reviewDataLabelNarrow
                              : styles.reviewDataLabel
                          }
                        >
                          Initial project
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {projectName.trim() || "—"}
                        </DataList.ItemValue>
                      </DataList.Item>
                      {projectSummary.trim() ? (
                        <DataList.Item>
                          <DataList.ItemLabel
                            style={
                              isNarrow
                                ? styles.reviewDataLabelNarrow
                                : styles.reviewDataLabel
                            }
                          >
                            Workload summary
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            {projectSummary.trim()}
                          </DataList.ItemValue>
                        </DataList.Item>
                      ) : null}
                    </DataList.Root>
                  </Card.Body>
                </Card.Root>

                {/* Section 2: Infrastructure & Plan */}
                <Card.Root variant="outline" size="md">
                  <Card.Header style={styles.reviewCardHeader}>
                    <HStack gap="2">
                      <Card.Title>Infrastructure &amp; plan</Card.Title>
                      {Object.keys(errorsByStep[1]).length > 0 ? (
                        <Badge variant="subtle" size="xs" palette={redPalette}>
                          Needs attention
                        </Badge>
                      ) : null}
                    </HStack>
                    <Button variant="ghost" size="xs" onClick={() => goToStep(1)}>
                      Edit
                    </Button>
                  </Card.Header>
                  <Card.Body style={styles.reviewCardBody}>
                    <DataList.Root
                      orientation={isNarrow ? "vertical" : "horizontal"}
                      variant="subtle"
                      size="md"
                    >
                      <DataList.Item>
                        <DataList.ItemLabel
                          style={
                            isNarrow
                              ? styles.reviewDataLabelNarrow
                              : styles.reviewDataLabel
                          }
                        >
                          Primary region
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {selectedRegion.label}
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item>
                        <DataList.ItemLabel
                          style={
                            isNarrow
                              ? styles.reviewDataLabelNarrow
                              : styles.reviewDataLabel
                          }
                        >
                          Default runtime
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {selectedRuntime.label}
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item>
                        <DataList.ItemLabel
                          style={
                            isNarrow
                              ? styles.reviewDataLabelNarrow
                              : styles.reviewDataLabel
                          }
                        >
                          Plan tier
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {selectedPlan.pricePerSeat === 0
                            ? `${selectedPlan.label} (Free)`
                            : `${selectedPlan.label} · ${money(selectedPlan.pricePerSeat)}/seat`}
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item>
                        <DataList.ItemLabel
                          style={
                            isNarrow
                              ? styles.reviewDataLabelNarrow
                              : styles.reviewDataLabel
                          }
                        >
                          Estimated monthly
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {money(monthlyTotal)}/mo · {effectiveSeats}{" "}
                          {effectiveSeats === 1 ? "seat" : "seats"}
                        </DataList.ItemValue>
                      </DataList.Item>
                    </DataList.Root>
                  </Card.Body>
                </Card.Root>

                {/* Section 3: Team & Security */}
                <Card.Root variant="outline" size="md">
                  <Card.Header style={styles.reviewCardHeader}>
                    <HStack gap="2">
                      <Card.Title>Team &amp; security</Card.Title>
                      {Object.keys(errorsByStep[2]).length > 0 ? (
                        <Badge variant="subtle" size="xs" palette={redPalette}>
                          Needs attention
                        </Badge>
                      ) : null}
                    </HStack>
                    <Button variant="ghost" size="xs" onClick={() => goToStep(2)}>
                      Edit
                    </Button>
                  </Card.Header>
                  <Card.Body style={styles.reviewCardBody}>
                    <DataList.Root
                      orientation={isNarrow ? "vertical" : "horizontal"}
                      variant="subtle"
                      size="md"
                    >
                      <DataList.Item>
                        <DataList.ItemLabel
                          style={
                            isNarrow
                              ? styles.reviewDataLabelNarrow
                              : styles.reviewDataLabel
                          }
                        >
                          Invitations
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {emails.length === 0
                            ? "None (invite teammates later)"
                            : `${emails.length} ${
                                emails.length === 1 ? "person" : "people"
                              } as ${selectedRole.label}${
                                sendInvitesNow ? "" : " (saved as drafts)"
                              }`}
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item>
                        <DataList.ItemLabel
                          style={
                            isNarrow
                              ? styles.reviewDataLabelNarrow
                              : styles.reviewDataLabel
                          }
                        >
                          Security add-ons
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {selectedAddonObjects.length === 0
                            ? "None"
                            : selectedAddonObjects
                                .map((addon) => addon.label)
                                .join(", ")}
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item>
                        <DataList.ItemLabel
                          style={
                            isNarrow
                              ? styles.reviewDataLabelNarrow
                              : styles.reviewDataLabel
                          }
                        >
                          Authentication policy
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {requireMfa
                            ? "Hardware passkeys or 2FA required"
                            : "Standard email & password allowed"}
                        </DataList.ItemValue>
                      </DataList.Item>
                    </DataList.Root>
                  </Card.Body>
                </Card.Root>
              </VStack>

              <Separator decorative />

              <Field.Root
                required
                invalid={Boolean(currentErrors.acceptedTerms)}
              >
                <Checkbox.Root
                  size="md"
                  palette={accentPalette}
                  style={styles.termsRow}
                >
                  <Checkbox.Control
                    ref={acceptedTermsRef}
                    checked={acceptedTerms}
                    onCheckedChange={(next) => setAcceptedTerms(next === true)}
                    aria-invalid={currentErrors.acceptedTerms ? true : undefined}
                    style={styles.optionControlOffset}
                  />
                  <VStack render={<span />} gap="0.5">
                    <Checkbox.Label>
                      I agree to the Cloud Services Agreement and Data Processing
                      Addendum
                    </Checkbox.Label>
                    <Text
                      render={<span />}
                      size="xs"
                      tone="muted"
                      weight="normal"
                    >
                      Billing starts after the 14-day workspace evaluation period.
                      You can downgrade or cancel at any time.
                    </Text>
                  </VStack>
                </Checkbox.Root>
                {currentErrors.acceptedTerms ? (
                  <Field.Error match={true}>
                    {currentErrors.acceptedTerms}
                  </Field.Error>
                ) : null}
              </Field.Root>
            </VStack>
          ) : null}
        </VStack>
      </VStack>

      {/* Pinned footer bar with Skip, centered counter, Back, and Next / Launch */}
      {!isLaunched ? (
        <footer {...stylex.props(styles.footer)}>
          <HStack
            justify="between"
            wrap="wrap"
            gap="3"
            style={[styles.footerInner, isNarrow && styles.footerInnerNarrow]}
          >
            <HStack justify="start" style={styles.footerLeftZone}>
              {STEPS[step].isOptional ? (
                <Button variant="ghost" onClick={goSkip}>
                  Skip
                </Button>
              ) : null}
            </HStack>

            <Text
              render={<span />}
              size="xs"
              tone="muted"
              align="center"
              tabular="true"
              style={styles.nowrap}
            >
              Step {step + 1} of {STEPS.length}
            </Text>

            <HStack justify="end" gap="2.5" style={styles.footerRightZone}>
              <Button
                variant="surface"
                disabled={step === 0}
                onClick={() => setStep((current) => Math.max(0, current - 1))}
              >
                <ArrowLeftIcon />
                Back
              </Button>
              <Button
                variant="solid"
                palette={accentPalette}
                onClick={goNext}
              >
                {isLastStep ? (
                  <>
                    <RocketIcon />
                    Launch workspace
                  </>
                ) : (
                  <>
                    Next
                    <ArrowRightIcon />
                  </>
                )}
              </Button>
            </HStack>
          </HStack>
        </footer>
      ) : null}

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

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