---
title: "Dialog Wizard · UI SDK — StyleX Blocks"
description: "Three-step scheduled backup policy wizard inside a modal Dialog over a live Arbor Cloud workspace. Features a pinned title and compact stepper header, scrollable per-step validation for target cluster, region, cadence, retention, replication, and KMS encryption, a pinned Back/Continue/Create footer, and live host table updates with toast confirmation."
url: "https://stylexblocks.com/block/ui-sdk/form-wizard-dialog/"
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/"
---

# Dialog Wizard block

Three-step scheduled backup policy wizard inside a modal Dialog over a live Arbor Cloud workspace. Features a pinned title and compact stepper header, scrollable per-step validation for target cluster, region, cadence, retention, replication, and KMS encryption, a pinned Back/Continue/Create footer, and live host table updates with toast 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), [Data List](https://stylexblocks.com/components/ui-sdk/data-list.md), [Dialog](https://stylexblocks.com/components/ui-sdk/dialog.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), [Segment Group](https://stylexblocks.com/components/ui-sdk/segment-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), [Status](https://stylexblocks.com/components/ui-sdk/status.md), [Steps](https://stylexblocks.com/components/ui-sdk/steps.md), [Switch](https://stylexblocks.com/components/ui-sdk/switch.md), [Table](https://stylexblocks.com/components/ui-sdk/table.md), [Text](https://stylexblocks.com/components/ui-sdk/text.md), [Toast](https://stylexblocks.com/components/ui-sdk/toast.md)
- HTML page: https://stylexblocks.com/block/ui-sdk/form-wizard-dialog/

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

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

## Usage

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

export function Example() {
  return (
    <div style={{ minHeight: "48rem" }}>
      <FormWizardDialog />
    </div>
  );
}
```

## Source

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

```tsx
import * as stylex from "@stylexjs/stylex";
import {
  useCallback,
  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 { DataList } from "#components/ui/ui-sdk/data-list.tsx";
import { Dialog } from "#components/ui/ui-sdk/dialog.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 { IconButton } from "#components/ui/ui-sdk/icon-button.tsx";
import { Icon } from "#components/ui/ui-sdk/icon.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 { SegmentGroup } from "#components/ui/ui-sdk/segment-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 { Status } from "#components/ui/ui-sdk/status.tsx";
import { Steps } from "#components/ui/ui-sdk/steps.tsx";
import { Switch } from "#components/ui/ui-sdk/switch.tsx";
import { Table } from "#components/ui/ui-sdk/table.tsx";
import { Text } from "#components/ui/ui-sdk/text.tsx";
import { Toast, Toaster } from "#components/ui/ui-sdk/toast.tsx";
import { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";
import { semanticRadii } from "@stylexblocks/ui/semantic-tokens/radii.stylex.ts";
import {
  accentPalette,
  amberPalette,
  greenPalette,
  redPalette,
} from "@stylexblocks/ui/themes/palettes.ts";
import { fontSizes } from "@stylexblocks/ui/tokens/font-sizes.stylex.ts";
import { fontWeights } from "@stylexblocks/ui/tokens/font-weights.stylex.ts";
import { fonts } from "@stylexblocks/ui/tokens/fonts.stylex.ts";
import { lineHeights } from "@stylexblocks/ui/tokens/line-heights.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 ArborBrandIcon() {
  return (
    <Icon
      size="sm"
      viewBox="0 0 20 20"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.7"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M10 3.25 4.25 11h11.5L10 3.25Z" />
      <path d="M10 11v5.75" />
      <path d="M6.75 16.75h6.5" />
    </Icon>
  );
}

function PlusIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      aria-hidden="true"
    >
      <path d="M8 3.25v9.5" />
      <path d="M3.25 8h9.5" />
    </Icon>
  );
}

function CloseIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      aria-hidden="true"
    >
      <path d="m4 4 8 8" />
      <path d="m12 4-8 8" />
    </Icon>
  );
}

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="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.7"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <circle cx="8" cy="8" r="5.75" />
      <path d="M8 5.25v3" />
      <path d="M8 10.75v.1" />
    </Icon>
  );
}

function ShieldCheckIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.7"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M8 2.25 13 4.2v3.6c0 3.1-2.1 5.2-5 6-2.9-.8-5-2.9-5-6V4.2L8 2.25Z" />
      <path d="m5.8 8.1 1.5 1.5 3-3.1" />
    </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>
  );
}

function GlobeIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <circle cx="8" cy="8" r="5.75" />
      <path d="M2.5 8h11" />
      <path d="M8 2.25c1.6 1.55 2.4 3.55 2.4 5.75S9.6 12.2 8 13.75C6.4 12.2 5.6 10.2 5.6 8S6.4 3.8 8 2.25Z" />
    </Icon>
  );
}

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

export type VaultRegionId = "us-east-va" | "us-west-or" | "eu-central-fr" | "ap-south-sg";
export type BackupCadence = "hourly" | "daily" | "weekly";
export type EncryptionKeyId = "arbor-managed" | "customer-cmk" | "dedicated-hsm";
export type BackupPolicyStatus = "active" | "paused";

export interface BackupPolicy {
  id: string;
  name: string;
  clusterId: string;
  clusterLabel: string;
  volumeGb: number;
  regionId: VaultRegionId;
  cadence: BackupCadence;
  retentionDays: number;
  crossRegionReplication: boolean;
  encryptionKeyId: EncryptionKeyId;
  notifyChannel: string;
  monthlyCost: number;
  status: BackupPolicyStatus;
  lastSnapshot: string;
  isNew?: boolean;
}

export interface FormWizardDialogProps extends StyleOverrideProps {
  /** Dialog heading for the backup policy wizard. */
  title?: string;
  /** Workspace brand label shown in the host workspace header. */
  workspaceName?: string;
  /** Optional initial backup policies shown in the host workspace table. */
  initialPolicies?: readonly BackupPolicy[];
  /**
   * Keeps the dialog and backdrop contained inside the block stage so embedded
   * previews never cover or lock the surrounding page. Set `false` for a full
   * browser top-layer modal in standalone apps.
   */
  inline?: boolean;
  /** Controls whether the dialog starts open. Defaults to `inline`. */
  defaultOpen?: boolean;
  /** Invoked when the user finishes the wizard and adds a policy. */
  onCreatePolicy?: (policy: BackupPolicy) => void;
}

interface StepDefinition {
  id: string;
  label: string;
}

const STEPS: readonly StepDefinition[] = [
  { id: "target", label: "Target & region" },
  { id: "cadence", label: "Cadence & retention" },
  { id: "review", label: "Review & confirm" },
];

interface ClusterOption {
  value: string;
  label: string;
  engine: string;
  volumeGb: number;
}

const CLUSTERS: readonly ClusterOption[] = [
  {
    value: "arbor-pg-orders",
    label: "arbor-pg-orders — PostgreSQL 16 (1.2 TB)",
    engine: "PostgreSQL 16",
    volumeGb: 1200,
  },
  {
    value: "arbor-pg-ledger",
    label: "arbor-pg-ledger — PostgreSQL 16 (2.4 TB)",
    engine: "PostgreSQL 16",
    volumeGb: 2400,
  },
  {
    value: "arbor-ch-events",
    label: "arbor-ch-events — ClickHouse (4.6 TB)",
    engine: "ClickHouse",
    volumeGb: 4600,
  },
  {
    value: "arbor-kv-sessions",
    label: "arbor-kv-sessions — Valkey (360 GB)",
    engine: "Valkey",
    volumeGb: 360,
  },
];

interface VaultRegionOption {
  id: VaultRegionId;
  label: string;
  shortCode: string;
  note: string;
  ratePerGb: number;
  drPair: string;
}

const VAULT_REGIONS: readonly VaultRegionOption[] = [
  {
    id: "us-east-va",
    label: "US East (Virginia)",
    shortCode: "us-east-va",
    note: "Low latency · $0.023/GB",
    ratePerGb: 0.023,
    drPair: "US West (Oregon)",
  },
  {
    id: "us-west-or",
    label: "US West (Oregon)",
    shortCode: "us-west-or",
    note: "Hydro-backed · $0.023/GB",
    ratePerGb: 0.023,
    drPair: "US East (Virginia)",
  },
  {
    id: "eu-central-fr",
    label: "EU Central (Frankfurt)",
    shortCode: "eu-central-fr",
    note: "GDPR sovereign · $0.026/GB",
    ratePerGb: 0.026,
    drPair: "EU West (Dublin)",
  },
  {
    id: "ap-south-sg",
    label: "Asia Pacific (Singapore)",
    shortCode: "ap-south-sg",
    note: "APAC primary · $0.027/GB",
    ratePerGb: 0.027,
    drPair: "Asia Pacific (Tokyo)",
  },
];

interface EncryptionKeyOption {
  value: EncryptionKeyId;
  label: string;
  shortLabel: string;
  monthlySurcharge: number;
}

const ENCRYPTION_KEYS: readonly EncryptionKeyOption[] = [
  {
    value: "arbor-managed",
    label: "Arbor Managed Key (AES-256-GCM)",
    shortLabel: "Arbor Managed",
    monthlySurcharge: 0,
  },
  {
    value: "customer-cmk",
    label: "Customer KMS · arn:arbor:kms:prod-01",
    shortLabel: "Customer KMS",
    monthlySurcharge: 8,
  },
  {
    value: "dedicated-hsm",
    label: "Dedicated HSM Vault (FIPS 140-3)",
    shortLabel: "FIPS HSM",
    monthlySurcharge: 35,
  },
];

const INITIAL_POLICIES: readonly BackupPolicy[] = [
  {
    id: "pol-ledger-01",
    name: "prod-ledger-hourly",
    clusterId: "arbor-pg-ledger",
    clusterLabel: "PostgreSQL 16 · 2.4 TB",
    volumeGb: 2400,
    regionId: "us-east-va",
    cadence: "hourly",
    retentionDays: 14,
    crossRegionReplication: true,
    encryptionKeyId: "customer-cmk",
    notifyChannel: "#fin-infra-alerts",
    monthlyCost: 112,
    status: "active",
    lastSnapshot: "14m ago",
  },
  {
    id: "pol-events-02",
    name: "telemetry-warehouse-daily",
    clusterId: "arbor-ch-events",
    clusterLabel: "ClickHouse · 4.6 TB",
    volumeGb: 4600,
    regionId: "eu-central-fr",
    cadence: "daily",
    retentionDays: 30,
    crossRegionReplication: false,
    encryptionKeyId: "arbor-managed",
    notifyChannel: "#data-ops",
    monthlyCost: 148,
    status: "active",
    lastSnapshot: "3h ago",
  },
  {
    id: "pol-sessions-03",
    name: "identity-sessions-weekly",
    clusterId: "arbor-kv-sessions",
    clusterLabel: "Valkey · 360 GB",
    volumeGb: 360,
    regionId: "us-west-or",
    cadence: "weekly",
    retentionDays: 90,
    crossRegionReplication: true,
    encryptionKeyId: "dedicated-hsm",
    notifyChannel: "#security-ops",
    monthlyCost: 56,
    status: "paused",
    lastSnapshot: "4d ago",
  },
];

type ValidatableFieldKey = "policyName" | "retentionDays" | "notifyChannel";

const POLICY_NAME_PATTERN = /^[a-z0-9][a-z0-9-_]{2,47}$/;
const CHANNEL_PATTERN = /^(#[a-z0-9][a-z0-9-_]{1,38}|https:\/\/[^\s]+)$/i;

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

const CADENCE_LABELS: Record<BackupCadence, string> = {
  hourly: "Hourly",
  daily: "Daily",
  weekly: "Weekly",
};

function formatVolume(gb: number): string {
  if (gb >= 1000) {
    return `${(gb / 1000).toFixed(1)} TB`;
  }
  return `${gb} GB`;
}

function estimateSnapshotCount(cadence: BackupCadence, retentionDays: number): number {
  const safeDays = Math.max(1, Math.round(retentionDays || 1));
  if (cadence === "hourly") return safeDays * 24;
  if (cadence === "daily") return safeDays;
  return Math.max(1, Math.ceil(safeDays / 7));
}

function estimateMonthlyStorageCost(params: {
  volumeGb: number;
  ratePerGb: number;
  cadence: BackupCadence;
  retentionDays: number;
  crossRegionReplication: boolean;
  encryptionSurcharge: number;
}): {
  baseCost: number;
  replicationCost: number;
  encryptionCost: number;
  total: number;
} {
  const safeDays = Math.max(1, Math.min(365, params.retentionDays || 1));
  // Incremental snapshots add a modest delta overhead relative to retention & cadence.
  const cadenceFactor =
    params.cadence === "hourly" ? 1.45 : params.cadence === "daily" ? 1.15 : 0.85;
  const retentionMultiplier = 1 + Math.min(safeDays, 365) / 180;
  const baseCost = Math.max(
    6,
    Math.round(params.volumeGb * params.ratePerGb * cadenceFactor * retentionMultiplier * 0.42),
  );
  const replicationCost = params.crossRegionReplication ? Math.round(baseCost * 0.35) : 0;
  const encryptionCost = params.encryptionSurcharge;
  return {
    baseCost,
    replicationCost,
    encryptionCost,
    total: baseCost + replicationCost + encryptionCost,
  };
}

function formatBlockedSummary(count: number): string {
  return count === 1 ? "1 field needs attention" : `${count} fields need attention`;
}

// ── Styles (StyleX longhand properties + named @container queries) ───────────

const NARROW = "@container form-wizard-dialog (max-width: 780px)";
const COMPACT = "@container form-wizard-dialog (max-width: 580px)";

const styles = stylex.create({
  stage: {
    backgroundColor: semanticColors.bg,
    color: semanticColors.fg,
    containerName: "form-wizard-dialog",
    containerType: "inline-size",
    fontFamily: fonts.body,
    minHeight: "48rem",
    overflowX: "hidden",
    overflowY: "hidden",
    position: "relative",
    width: "100%",
  },
  hostShell: {
    flexGrow: 1,
    marginInline: "auto",
    maxWidth: "66rem",
    paddingBlock: spacing._6,
    paddingInline: {
      default: spacing._6,
      [COMPACT]: spacing._4,
    },
    width: "100%",
  },
  hostHeader: {
    alignItems: {
      default: "center",
      [COMPACT]: "flex-start",
    },
    display: "flex",
    flexDirection: {
      default: "row",
      [COMPACT]: "column",
    },
    gap: spacing._4,
    justifyContent: "space-between",
    width: "100%",
  },
  headingReset: {
    marginBlock: 0,
  },
  fullWidth: {
    width: "100%",
  },
  flexGrow: {
    flexGrow: 1,
  },
  nowrap: {
    whiteSpace: "nowrap",
  },
  breakWord: {
    wordBreak: "break-word",
  },
  mutedColor: {
    color: semanticColors.fgMuted,
  },
  subtleColor: {
    color: semanticColors.fgSubtle,
  },
  errorColor: {
    color: semanticColors.fgError,
  },
  kpiGrid: {
    gridTemplateColumns: {
      default: "repeat(3, minmax(0, 1fr))",
      [NARROW]: "repeat(2, minmax(0, 1fr))",
      [COMPACT]: "minmax(0, 1fr)",
    },
    width: "100%",
  },
  kpiCardBody: {
    display: "flex",
    flexDirection: "column",
    gap: spacing._1_5,
  },
  tableCardHeader: {
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
  },
  tableCardBody: {
    paddingBlock: 0,
    paddingInline: 0,
  },
  tableScroll: {
    overflowX: "auto",
    width: "100%",
  },
  tableCellPadded: {
    paddingBlock: spacing._3,
    paddingInline: spacing._4,
    verticalAlign: "middle",
  },
  tableHeaderPadded: {
    color: semanticColors.fgMuted,
    fontSize: fontSizes.xs,
    fontWeight: fontWeights.medium,
    lineHeight: lineHeights.xs,
    paddingBlock: spacing._2_5,
    paddingInline: spacing._4,
    whiteSpace: "nowrap",
  },
  policyPrimaryCell: {
    minWidth: "11rem",
  },
  regionStack: {
    minWidth: "8.5rem",
  },
  // ── Dialog surface chrome (positioning & backdrop containment handled by Dialog `contained`) ──
  dialogContent: {
    borderColor: semanticColors.border,
    borderStyle: "solid",
    borderWidth: "1px",
    maxWidth: "38.5rem",
    overflowX: "hidden",
    overflowY: "hidden",
    width: "calc(100% - 2rem)",
  },
  modalMaxHeight: {
    maxHeight: "min(41rem, calc(100dvh - 3rem))",
  },
  dialogHeader: {
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    display: "flex",
    flexBasis: "auto",
    flexDirection: "column",
    flexGrow: 0,
    flexShrink: 0,
    gap: spacing._3_5,
    paddingBottom: spacing._4,
    paddingInline: {
      default: spacing._6,
      [COMPACT]: spacing._4,
    },
    paddingTop: spacing._5,
  },
  dialogHeaderTop: {
    paddingInlineEnd: spacing._8,
    width: "100%",
  },
  dialogSubtitle: {
    color: semanticColors.fgMuted,
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
    marginBlock: 0,
  },
  stepItemLast: {
    flexBasis: "auto",
    flexGrow: 0,
    flexShrink: 0,
  },
  stepIndicatorError: {
    backgroundColor: semanticColors.bgError,
    borderColor: semanticColors.borderError,
    borderStyle: "solid",
    borderWidth: "2px",
    color: semanticColors.fgError,
  },
  stepTitleCompact: {
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
    whiteSpace: "nowrap",
  },
  stepTitleMuted: {
    color: semanticColors.fgMuted,
    display: {
      default: "inline",
      [COMPACT]: "none",
    },
  },
  dialogBody: {
    display: "flex",
    flexDirection: "column",
    flexGrow: 1,
    gap: spacing._4,
    overflowX: "hidden",
    overflowY: "auto",
    paddingBlock: spacing._5,
    paddingInline: {
      default: spacing._6,
      [COMPACT]: spacing._4,
    },
  },
  twoColRow: {
    gap: spacing._3_5,
    gridTemplateColumns: {
      default: "repeat(2, minmax(0, 1fr))",
      [COMPACT]: "minmax(0, 1fr)",
    },
    width: "100%",
  },
  regionGrid: {
    display: "grid",
    gap: spacing._2_5,
    gridTemplateColumns: {
      default: "repeat(2, minmax(0, 1fr))",
      [COMPACT]: "minmax(0, 1fr)",
    },
    width: "100%",
  },
  regionCardItem: {
    height: "100%",
  },
  regionCardControl: {
    alignItems: "flex-start",
    height: "100%",
    paddingBlock: spacing._2_5,
    paddingInline: spacing._3,
    width: "100%",
  },
  regionCardContent: {
    gap: spacing._0_5,
    minWidth: 0,
    width: "100%",
  },
  regionCardLabel: {
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
  },
  regionCardNote: {
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
  },
  segmentRoot: {
    display: "flex",
    width: "100%",
  },
  segmentItem: {
    flexBasis: 0,
    flexGrow: 1,
    justifyContent: "center",
  },
  switchCard: {
    backgroundColor: semanticColors.bgSubtle,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._3,
    paddingInline: spacing._3_5,
    width: "100%",
  },
  switchRow: {
    alignItems: "center",
    display: "flex",
    gap: spacing._4,
    justifyContent: "space-between",
    width: "100%",
  },
  estimateBar: {
    backgroundColor: semanticColors.bgMuted,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._3,
    paddingInline: spacing._3_5,
  },
  reviewCardBody: {
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
  },
  reviewLabel: {
    flexShrink: 0,
    minWidth: {
      default: "8.75rem",
      [COMPACT]: "6.75rem",
    },
  },
  dialogFooter: {
    alignItems: "center",
    borderTopColor: semanticColors.border,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
    display: "flex",
    flexBasis: "auto",
    flexGrow: 0,
    flexShrink: 0,
    flexWrap: "wrap",
    gap: spacing._3,
    justifyContent: "space-between",
    paddingBlock: spacing._3_5,
    paddingInline: {
      default: spacing._6,
      [COMPACT]: spacing._4,
    },
  },
});

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

/**
 * FormWizardDialog — compact three-step backup policy wizard housed inside a
 * modal Dialog over a live Arbor Cloud host workspace. Step navigation stays
 * pinned to the dialog header and footer while step fields scroll inside the
 * dialog body; completing the flow closes the modal, updates the live table
 * underneath, and fires a toast confirmation.
 */
export function FormWizardDialog({
  title = "New backup policy",
  workspaceName = "Arbor Cloud",
  initialPolicies = INITIAL_POLICIES,
  inline = true,
  defaultOpen,
  onCreatePolicy,
  palette,
  style,
}: FormWizardDialogProps) {
  const queue = useMemo(() => Toast.createToaster(), []);
  const regionLabelId = useId();
  const cadenceLabelId = useId();

  const [stageEl, setStageEl] = useState<HTMLDivElement | null>(null);
  const attachStage = useCallback((node: HTMLDivElement | null) => {
    setStageEl(node);
  }, []);

  // Host workspace state
  const [policies, setPolicies] = useState<BackupPolicy[]>(() => [...initialPolicies]);

  // Modal & wizard draft state
  const [isOpen, setIsOpen] = useState<boolean>(defaultOpen ?? inline);
  const [step, setStep] = useState(0);
  const [attempted, setAttempted] = useState<ReadonlySet<number>>(() => new Set());

  // Step 0 — Target & region
  const [policyName, setPolicyName] = useState("prod-orders-nightly");
  const [clusterId, setClusterId] = useState(CLUSTERS[0].value);
  const [regionId, setRegionId] = useState<VaultRegionId>("us-east-va");

  // Step 1 — Cadence & retention
  const [cadence, setCadence] = useState<BackupCadence>("daily");
  const [retentionDays, setRetentionDays] = useState<number>(30);
  const [crossRegionReplication, setCrossRegionReplication] = useState<boolean>(true);
  const [encryptionKeyId, setEncryptionKeyId] = useState<EncryptionKeyId>("customer-cmk");

  // Step 2 — Review & optional notification channel
  const [notifyChannel, setNotifyChannel] = useState("#infra-backups");

  // Field refs for invalid focus management
  const policyNameRef = useRef<HTMLInputElement>(null);
  const retentionRef = useRef<HTMLInputElement>(null);
  const notifyChannelRef = useRef<HTMLInputElement>(null);

  const resetDraft = useCallback(() => {
    setStep(0);
    setAttempted(new Set());
    setPolicyName("");
    setClusterId(CLUSTERS[0].value);
    setRegionId("us-east-va");
    setCadence("daily");
    setRetentionDays(30);
    setCrossRegionReplication(true);
    setEncryptionKeyId("customer-cmk");
    setNotifyChannel("#infra-backups");
  }, []);

  const handleOpenChange = useCallback(
    (nextOpen: boolean) => {
      setIsOpen(nextOpen);
      if (!nextOpen) {
        resetDraft();
      }
    },
    [resetDraft],
  );

  // Derived selections & cost math
  const selectedCluster = useMemo(
    () => CLUSTERS.find((item) => item.value === clusterId) ?? CLUSTERS[0],
    [clusterId],
  );
  const selectedRegion = useMemo(
    () => VAULT_REGIONS.find((item) => item.id === regionId) ?? VAULT_REGIONS[0],
    [regionId],
  );
  const selectedEncryption = useMemo(
    () =>
      ENCRYPTION_KEYS.find((item) => item.value === encryptionKeyId) ?? ENCRYPTION_KEYS[0],
    [encryptionKeyId],
  );

  const retainedSnapshots = useMemo(
    () => estimateSnapshotCount(cadence, retentionDays),
    [cadence, retentionDays],
  );

  const costEstimate = useMemo(
    () =>
      estimateMonthlyStorageCost({
        volumeGb: selectedCluster.volumeGb,
        ratePerGb: selectedRegion.ratePerGb,
        cadence,
        retentionDays,
        crossRegionReplication,
        encryptionSurcharge: selectedEncryption.monthlySurcharge,
      }),
    [
      selectedCluster.volumeGb,
      selectedRegion.ratePerGb,
      cadence,
      retentionDays,
      crossRegionReplication,
      selectedEncryption.monthlySurcharge,
    ],
  );

  // Host workspace KPI aggregates
  const hostStats = useMemo(() => {
    const activeCount = policies.filter((item) => item.status === "active").length;
    const pausedCount = policies.length - activeCount;
    const totalVolumeGb = policies.reduce((sum, item) => sum + item.volumeGb, 0);
    const totalMonthlySpend = policies.reduce((sum, item) => sum + item.monthlyCost, 0);
    const replicatedCount = policies.filter((item) => item.crossRegionReplication).length;
    return {
      activeCount,
      pausedCount,
      totalVolumeGb,
      totalMonthlySpend,
      replicatedCount,
    };
  }, [policies]);

  // Per-step validation
  const errorsByStep = useMemo<Array<Partial<Record<ValidatableFieldKey, string>>>>(() => {
    const normalizedName = policyName.trim().toLowerCase();
    const step0: Partial<Record<ValidatableFieldKey, string>> = {};

    if (!normalizedName) {
      step0.policyName = "Enter a policy name (e.g. prod-orders-nightly).";
    } else if (!POLICY_NAME_PATTERN.test(normalizedName)) {
      step0.policyName =
        "Use 3–48 lowercase letters, numbers, hyphens, or underscores.";
    } else if (policies.some((item) => item.name.toLowerCase() === normalizedName)) {
      step0.policyName = `"${normalizedName}" already exists in this workspace.`;
    }

    const step1: Partial<Record<ValidatableFieldKey, string>> = {};
    const maxDays = cadence === "hourly" ? 90 : 365;
    if (!Number.isFinite(retentionDays) || retentionDays < 7) {
      step1.retentionDays = "Retention must be at least 7 days for point-in-time recovery.";
    } else if (retentionDays > maxDays) {
      step1.retentionDays =
        cadence === "hourly"
          ? "Hourly policies support up to 90 days of retention."
          : "Retention cannot exceed 365 days.";
    }

    const step2: Partial<Record<ValidatableFieldKey, string>> = {};
    const trimmedChannel = notifyChannel.trim();
    if (trimmedChannel.length > 0 && !CHANNEL_PATTERN.test(trimmedChannel)) {
      step2.notifyChannel =
        "Enter a #channel name or an https:// webhook URL, or leave blank.";
    }

    return [step0, step1, step2];
  }, [policyName, policies, cadence, retentionDays, notifyChannel]);

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

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

  const focusField = useCallback((fieldKey: ValidatableFieldKey) => {
    const targets: Record<ValidatableFieldKey, HTMLElement | null> = {
      policyName: policyNameRef.current,
      retentionDays: retentionRef.current,
      notifyChannel: notifyChannelRef.current,
    };
    targets[fieldKey]?.focus();
  }, []);

  const handleNext = () => {
    setAttempted((prev) => {
      if (prev.has(step)) return prev;
      const next = new Set(prev);
      next.add(step);
      return next;
    });

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

    if (!isLastStep) {
      setStep((current) => Math.min(STEPS.length - 1, current + 1));
      return;
    }

    const normalizedName = policyName.trim().toLowerCase();
    const createdPolicy: BackupPolicy = {
      id: `pol-${Date.now().toString(36)}`,
      name: normalizedName,
      clusterId: selectedCluster.value,
      clusterLabel: `${selectedCluster.engine} · ${formatVolume(selectedCluster.volumeGb)}`,
      volumeGb: selectedCluster.volumeGb,
      regionId,
      cadence,
      retentionDays: Math.round(retentionDays),
      crossRegionReplication,
      encryptionKeyId,
      notifyChannel: notifyChannel.trim() || "None",
      monthlyCost: costEstimate.total,
      status: "active",
      lastSnapshot: "Scheduled",
      isNew: true,
    };

    setPolicies((prev) => [createdPolicy, ...prev]);
    onCreatePolicy?.(createdPolicy);
    handleOpenChange(false);
    queue.success("Backup policy created", {
      description: `${createdPolicy.name} (${CADENCE_LABELS[createdPolicy.cadence]} · ${createdPolicy.retentionDays}d) added to ${workspaceName}.`,
    });
  };

  const handleTogglePolicyStatus = (policyId: string) => {
    setPolicies((prev) =>
      prev.map((item) => {
        if (item.id !== policyId) return item;
        const nextStatus: BackupPolicyStatus =
          item.status === "active" ? "paused" : "active";
        queue.info(
          nextStatus === "active" ? "Policy resumed" : "Policy paused",
          {
            description:
              nextStatus === "active"
                ? `${item.name} will resume on its next ${item.cadence} window.`
                : `${item.name} is paused. Existing snapshots remain intact.`,
          },
        );
        return { ...item, status: nextStatus };
      }),
    );
  };

  return (
    <VStack
      ref={attachStage}
      gap="0"
      palette={palette}
      style={[styles.stage, style]}
    >
      <Dialog.Root
        size="md"
        placement="center"
        scrollBehavior="inside"
        open={isOpen}
        onOpenChange={handleOpenChange}
        closeOnOutsidePress={false}
        contained={inline}
        container={inline ? stageEl : undefined}
      >
        {/* Live host workspace surface visible behind the dialog */}
        <VStack gap="6" style={styles.hostShell}>
          <header {...stylex.props(styles.hostHeader)}>
            <VStack gap="1">
              <HStack render={<span />} gap="1.5" style={styles.mutedColor}>
                <ArborBrandIcon />
                <Text render={<span />} size="xs" tone="muted" weight="medium">
                  {workspaceName} · Data Protection
                </Text>
              </HStack>
              <HStack wrap="wrap" gap="2.5">
                <Heading render={<h1 />} size="xl" style={styles.headingReset}>
                  Backup policies
                </Heading>
                <Badge variant="subtle" size="sm" palette={accentPalette}>
                  {policies.length} {policies.length === 1 ? "policy" : "policies"}
                </Badge>
              </HStack>
              <Text variant="muted" size="sm">
                Automate encrypted cluster snapshots, retention windows, and cross-region
                vault replication.
              </Text>
            </VStack>

            <Dialog.Trigger
              render={
                <Button variant="solid" size="sm" palette={accentPalette} />
              }
            >
              <PlusIcon />
              New backup policy
            </Dialog.Trigger>
          </header>

          {/* Summary KPI strip */}
          <Grid columns="3" gap="4" style={styles.kpiGrid}>
            <Card.Root variant="outline" size="md">
              <Card.Body style={styles.kpiCardBody}>
                <Text render={<span />} size="xs" tone="muted" weight="medium">
                  Active schedules
                </Text>
                <Text
                  render={<span />}
                  size="2xl"
                  weight="semibold"
                  tabular="true"
                >
                  {hostStats.activeCount} / {policies.length}
                </Text>
                <HStack render={<span />} gap="1.5" style={styles.subtleColor}>
                  <Status.Root
                    size="sm"
                    palette={hostStats.pausedCount === 0 ? greenPalette : amberPalette}
                  >
                    <Status.Indicator />
                    <Text render={<span />} size="xs" tone="subtle">
                      {hostStats.pausedCount === 0
                        ? "All schedules running"
                        : `${hostStats.pausedCount} paused`}
                    </Text>
                  </Status.Root>
                </HStack>
              </Card.Body>
            </Card.Root>

            <Card.Root variant="outline" size="md">
              <Card.Body style={styles.kpiCardBody}>
                <Text render={<span />} size="xs" tone="muted" weight="medium">
                  Protected cluster data
                </Text>
                <Text
                  render={<span />}
                  size="2xl"
                  weight="semibold"
                  tabular="true"
                >
                  {formatVolume(hostStats.totalVolumeGb)}
                </Text>
                <HStack render={<span />} gap="1.5" style={styles.subtleColor}>
                  <GlobeIcon />
                  <Text render={<span />} size="xs" tone="subtle">
                    {hostStats.replicatedCount} with cross-region DR
                  </Text>
                </HStack>
              </Card.Body>
            </Card.Root>

            <Card.Root variant="outline" size="md">
              <Card.Body style={styles.kpiCardBody}>
                <Text render={<span />} size="xs" tone="muted" weight="medium">
                  Estimated vault spend
                </Text>
                <Text
                  render={<span />}
                  size="2xl"
                  weight="semibold"
                  tabular="true"
                >
                  ${hostStats.totalMonthlySpend.toLocaleString("en-US")}/mo
                </Text>
                <Text render={<span />} size="xs" tone="subtle">
                  Incremental compressed snapshots
                </Text>
              </Card.Body>
            </Card.Root>
          </Grid>

          {/* Live policies table */}
          <Card.Root variant="outline" size="md">
            <HStack
              justify="between"
              wrap="wrap"
              gap="3"
              style={styles.tableCardHeader}
            >
              <VStack gap="0.5">
                <Heading render={<h2 />} size="sm" style={styles.headingReset}>
                  Scheduled backup policies
                </Heading>
                <Text variant="muted" size="xs">
                  Snapshots execute asynchronously without write locks. New policies appear
                  here immediately after confirmation.
                </Text>
              </VStack>
              <Badge variant="surface" size="sm" palette={greenPalette}>
                Zero-downtime snapshots
              </Badge>
            </HStack>
            <Card.Body style={styles.tableCardBody}>
              <div {...stylex.props(styles.tableScroll)}>
                <Table.Root variant="line" size="md">
                  <Table.Header>
                    <Table.Row>
                      <Table.ColumnHeader style={styles.tableHeaderPadded}>
                        Policy &amp; cluster
                      </Table.ColumnHeader>
                      <Table.ColumnHeader style={styles.tableHeaderPadded}>
                        Vault region
                      </Table.ColumnHeader>
                      <Table.ColumnHeader style={styles.tableHeaderPadded}>
                        Cadence &amp; retention
                      </Table.ColumnHeader>
                      <Table.ColumnHeader style={styles.tableHeaderPadded}>
                        Encryption
                      </Table.ColumnHeader>
                      <Table.ColumnHeader style={styles.tableHeaderPadded}>
                        Est. cost
                      </Table.ColumnHeader>
                      <Table.ColumnHeader style={styles.tableHeaderPadded}>
                        Status
                      </Table.ColumnHeader>
                    </Table.Row>
                  </Table.Header>
                  <Table.Body>
                    {policies.map((policy) => {
                      const regionInfo =
                        VAULT_REGIONS.find((r) => r.id === policy.regionId) ??
                        VAULT_REGIONS[0];
                      const keyInfo =
                        ENCRYPTION_KEYS.find((k) => k.value === policy.encryptionKeyId) ??
                        ENCRYPTION_KEYS[0];
                      return (
                        <Table.Row key={policy.id}>
                          <Table.Cell style={styles.tableCellPadded}>
                            <VStack gap="0.5" style={styles.policyPrimaryCell}>
                              <HStack render={<span />} wrap="wrap" gap="2">
                                <Text
                                  render={<span />}
                                  variant="mono"
                                  size="xs"
                                  weight="semibold"
                                >
                                  {policy.name}
                                </Text>
                                {policy.isNew ? (
                                  <Badge
                                    variant="subtle"
                                    size="xs"
                                    palette={greenPalette}
                                  >
                                    New
                                  </Badge>
                                ) : null}
                              </HStack>
                              <Text render={<span />} size="xs" tone="muted">
                                {policy.clusterId} · {policy.clusterLabel}
                              </Text>
                            </VStack>
                          </Table.Cell>
                          <Table.Cell style={styles.tableCellPadded}>
                            <VStack gap="1" style={styles.regionStack}>
                              <Text render={<span />} size="xs">
                                {regionInfo.label}
                              </Text>
                              {policy.crossRegionReplication ? (
                                <HStack
                                  render={<span />}
                                  gap="1"
                                  style={styles.mutedColor}
                                >
                                  <GlobeIcon />
                                  <Text render={<span />} size="xs" tone="muted">
                                    DR → {regionInfo.drPair}
                                  </Text>
                                </HStack>
                              ) : (
                                <Text render={<span />} size="xs" tone="muted">
                                  Single-region vault
                                </Text>
                              )}
                            </VStack>
                          </Table.Cell>
                          <Table.Cell style={styles.tableCellPadded}>
                            <VStack gap="0.5" style={styles.nowrap}>
                              <Text
                                render={<span />}
                                variant="mono"
                                size="xs"
                                tabular="true"
                              >
                                {CADENCE_LABELS[policy.cadence]} · {policy.retentionDays}d
                              </Text>
                              <Text render={<span />} size="xs" tone="muted">
                                Last run: {policy.lastSnapshot}
                              </Text>
                            </VStack>
                          </Table.Cell>
                          <Table.Cell style={styles.tableCellPadded}>
                            <Badge variant="outline" size="sm">
                              {keyInfo.shortLabel}
                            </Badge>
                          </Table.Cell>
                          <Table.Cell style={styles.tableCellPadded}>
                            <Text
                              render={<span />}
                              size="sm"
                              weight="medium"
                              tabular="true"
                              style={styles.nowrap}
                            >
                              ${policy.monthlyCost}/mo
                            </Text>
                          </Table.Cell>
                          <Table.Cell style={styles.tableCellPadded}>
                            <HStack
                              justify="between"
                              gap="3"
                              style={styles.fullWidth}
                            >
                              <Status.Root
                                size="sm"
                                palette={
                                  policy.status === "active"
                                    ? greenPalette
                                    : amberPalette
                                }
                              >
                                <Status.Indicator />
                                <span>
                                  {policy.status === "active" ? "Active" : "Paused"}
                                </span>
                              </Status.Root>
                              <Button
                                variant="ghost"
                                size="xs"
                                onClick={() => handleTogglePolicyStatus(policy.id)}
                              >
                                {policy.status === "active" ? "Pause" : "Resume"}
                              </Button>
                            </HStack>
                          </Table.Cell>
                        </Table.Row>
                      );
                    })}
                  </Table.Body>
                </Table.Root>
              </div>
            </Card.Body>
          </Card.Root>
        </VStack>

        {/* Backdrop stays strictly inside the stage when contained */}
        {!inline || stageEl ? <Dialog.Backdrop /> : null}

        {/* Compact 3-step Wizard Dialog */}
        <Dialog.Content
          style={[styles.dialogContent, !inline && styles.modalMaxHeight]}
        >
          {/* Pinned Header + Compact Non-Interactive Stepper */}
          <Dialog.Header style={styles.dialogHeader}>
            <HStack
              align="start"
              justify="between"
              gap="3"
              style={styles.dialogHeaderTop}
            >
              <VStack gap="0.5">
                <Dialog.Title>{title}</Dialog.Title>
                <Dialog.Description style={styles.dialogSubtitle}>
                  Configure snapshot targeting, retention, and vault encryption without
                  leaving {workspaceName}.
                </Dialog.Description>
              </VStack>
              <Dialog.Close
                render={
                  <IconButton
                    variant="ghost"
                    size="xs"
                    aria-label="Close wizard"
                  />
                }
              >
                <CloseIcon />
              </Dialog.Close>
            </HStack>

            <Steps.Root
              count={STEPS.length}
              step={step}
              size="xs"
              orientation="horizontal"
              palette={accentPalette}
              aria-label="Backup policy setup 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}
                    >
                      <HStack gap="2">
                        <Steps.Indicator
                          palette={hasError ? redPalette : undefined}
                          style={hasError ? styles.stepIndicatorError : undefined}
                        >
                          {hasError ? (
                            <AlertCircleIcon />
                          ) : isComplete ? (
                            <CheckIcon />
                          ) : (
                            index + 1
                          )}
                        </Steps.Indicator>
                        <Steps.Title
                          style={[
                            styles.stepTitleCompact,
                            index !== step && styles.stepTitleMuted,
                          ]}
                        >
                          {definition.label}
                        </Steps.Title>
                      </HStack>
                      <Steps.Separator />
                    </Steps.Item>
                  );
                })}
              </Steps.List>
            </Steps.Root>
          </Dialog.Header>

          {/* Scrollable Step Body */}
          <Dialog.Body style={styles.dialogBody}>
            {step === 0 ? (
              <VStack gap="4" style={styles.fullWidth}>
                <Field.Root
                  required
                  invalid={Boolean(currentErrors.policyName)}
                >
                  <Field.Label>
                    Policy name
                    <Field.RequiredIndicator />
                  </Field.Label>
                  <Input
                    ref={policyNameRef}
                    size="sm"
                    value={policyName}
                    onValueChange={(nextValue) =>
                      setPolicyName(nextValue.toLowerCase())
                    }
                    placeholder="prod-orders-nightly"
                    autoCapitalize="none"
                    autoCorrect="off"
                    spellCheck={false}
                    aria-invalid={currentErrors.policyName ? true : undefined}
                  />
                  {currentErrors.policyName ? (
                    <Field.Error match={true}>{currentErrors.policyName}</Field.Error>
                  ) : (
                    <Field.Description>
                      Unique slug used in audit trails and automated restore targets.
                    </Field.Description>
                  )}
                </Field.Root>

                <Select.Root
                  size="sm"
                  items={CLUSTERS}
                  value={clusterId}
                  onValueChange={(nextCluster) => {
                    if (nextCluster) {
                      setClusterId(nextCluster);
                    }
                  }}
                  placeholder="Select target cluster"
                  palette={accentPalette}
                >
                  <Select.Label>Target cluster</Select.Label>
                  <Select.Control>
                    <Select.Trigger>
                      <Select.Value />
                    </Select.Trigger>
                    <Select.IndicatorGroup>
                      <Select.Icon />
                    </Select.IndicatorGroup>
                  </Select.Control>
                  <Select.Content>
                    {CLUSTERS.map((cluster) => (
                      <Select.Item key={cluster.value} value={cluster.value}>
                        <Select.ItemText>{cluster.label}</Select.ItemText>
                        <Select.ItemIndicator />
                      </Select.Item>
                    ))}
                  </Select.Content>
                </Select.Root>

                <Field.Root>
                  <Field.Label id={regionLabelId}>Primary vault region</Field.Label>
                  <RadioCard.Root
                    value={regionId}
                    onValueChange={(nextRegion) => {
                      if (
                        nextRegion === "us-east-va" ||
                        nextRegion === "us-west-or" ||
                        nextRegion === "eu-central-fr" ||
                        nextRegion === "ap-south-sg"
                      ) {
                        setRegionId(nextRegion);
                      }
                    }}
                    variant="outline"
                    size="sm"
                    palette={accentPalette}
                    aria-labelledby={regionLabelId}
                    style={styles.regionGrid}
                  >
                    {VAULT_REGIONS.map((region) => (
                      <RadioCard.Item
                        key={region.id}
                        value={region.id}
                        style={styles.regionCardItem}
                      >
                        <RadioCard.ItemControl style={styles.regionCardControl}>
                          <RadioCard.ItemContent style={styles.regionCardContent}>
                            <HStack
                              justify="between"
                              gap="2"
                              style={styles.fullWidth}
                            >
                              <RadioCard.ItemText style={styles.regionCardLabel}>
                                {region.label}
                              </RadioCard.ItemText>
                              <RadioCard.ItemIndicator />
                            </HStack>
                            <RadioCard.ItemDescription style={styles.regionCardNote}>
                              {region.note}
                            </RadioCard.ItemDescription>
                          </RadioCard.ItemContent>
                        </RadioCard.ItemControl>
                      </RadioCard.Item>
                    ))}
                  </RadioCard.Root>
                </Field.Root>
              </VStack>
            ) : null}

            {step === 1 ? (
              <VStack gap="4" style={styles.fullWidth}>
                <Field.Root>
                  <Field.Label id={cadenceLabelId}>Snapshot cadence</Field.Label>
                  <SegmentGroup.Root
                    size="sm"
                    value={cadence}
                    onValueChange={(nextCadence) => {
                      if (
                        nextCadence === "hourly" ||
                        nextCadence === "daily" ||
                        nextCadence === "weekly"
                      ) {
                        setCadence(nextCadence);
                      }
                    }}
                    aria-labelledby={cadenceLabelId}
                    style={styles.segmentRoot}
                  >
                    <SegmentGroup.Item value="hourly" style={styles.segmentItem}>
                      Hourly
                    </SegmentGroup.Item>
                    <SegmentGroup.Item value="daily" style={styles.segmentItem}>
                      Daily
                    </SegmentGroup.Item>
                    <SegmentGroup.Item value="weekly" style={styles.segmentItem}>
                      Weekly
                    </SegmentGroup.Item>
                  </SegmentGroup.Root>
                </Field.Root>

                <Grid columns="2" gap="4" style={styles.twoColRow}>
                  <Field.Root
                    required
                    invalid={Boolean(currentErrors.retentionDays)}
                  >
                    <Field.Label>
                      Retention (days)
                      <Field.RequiredIndicator />
                    </Field.Label>
                    <NumberInput.Root
                      size="sm"
                      value={retentionDays}
                      onValueChange={(nextDays) => setRetentionDays(nextDays ?? 0)}
                      min={1}
                      max={365}
                      step={1}
                      palette={accentPalette}
                    >
                      <NumberInput.Group>
                        <NumberInput.Input
                          ref={retentionRef}
                          aria-label="Retention days"
                          aria-invalid={currentErrors.retentionDays ? true : undefined}
                        />
                        <NumberInput.Control />
                      </NumberInput.Group>
                    </NumberInput.Root>
                    {currentErrors.retentionDays ? (
                      <Field.Error match={true}>
                        {currentErrors.retentionDays}
                      </Field.Error>
                    ) : (
                      <Field.Description>
                        Retains ~{retainedSnapshots.toLocaleString("en-US")}{" "}
                        {retainedSnapshots === 1 ? "snapshot" : "snapshots"} (min 7d).
                      </Field.Description>
                    )}
                  </Field.Root>

                  <Select.Root
                    size="sm"
                    items={ENCRYPTION_KEYS}
                    value={encryptionKeyId}
                    onValueChange={(nextKey) => {
                      if (
                        nextKey === "arbor-managed" ||
                        nextKey === "customer-cmk" ||
                        nextKey === "dedicated-hsm"
                      ) {
                        setEncryptionKeyId(nextKey);
                      }
                    }}
                    placeholder="Select encryption key"
                    palette={accentPalette}
                  >
                    <Select.Label>Encryption key</Select.Label>
                    <Select.Control>
                      <Select.Trigger>
                        <Select.Value />
                      </Select.Trigger>
                      <Select.IndicatorGroup>
                        <Select.Icon />
                      </Select.IndicatorGroup>
                    </Select.Control>
                    <Select.Content>
                      {ENCRYPTION_KEYS.map((key) => (
                        <Select.Item key={key.value} value={key.value}>
                          <Select.ItemText>{key.label}</Select.ItemText>
                          <Select.ItemIndicator />
                        </Select.Item>
                      ))}
                    </Select.Content>
                  </Select.Root>
                </Grid>

                <div {...stylex.props(styles.switchCard)}>
                  <Switch.Root
                    variant="solid"
                    size="sm"
                    palette={accentPalette}
                    style={styles.switchRow}
                  >
                    <VStack
                      render={<span />}
                      gap="0.5"
                      style={styles.flexGrow}
                    >
                      <Text render={<span />} size="sm" weight="medium">
                        Cross-region DR replication
                      </Text>
                      <Text render={<span />} size="xs" tone="muted">
                        Asynchronously mirror encrypted snapshots to{" "}
                        {selectedRegion.drPair} (+35% vault storage).
                      </Text>
                    </VStack>
                    <Switch.Control
                      checked={crossRegionReplication}
                      onCheckedChange={setCrossRegionReplication}
                    />
                  </Switch.Root>
                </div>

                {crossRegionReplication ? (
                  <Alert.Root
                    status="info"
                    variant="subtle"
                    size="sm"
                    palette={accentPalette}
                  >
                    <Alert.Indicator>
                      <GlobeIcon />
                    </Alert.Indicator>
                    <Alert.Content>
                      <Alert.Title>
                        Paired DR vault: {selectedRegion.drPair}
                      </Alert.Title>
                      <Alert.Description>
                        Target RPO under 15 minutes after each snapshot completes.
                      </Alert.Description>
                    </Alert.Content>
                  </Alert.Root>
                ) : null}

                <HStack
                  justify="between"
                  wrap="wrap"
                  gap="3"
                  style={styles.estimateBar}
                >
                  <VStack gap="0.5">
                    <Text render={<span />} size="xs" weight="medium">
                      Estimated monthly vault storage
                    </Text>
                    <Text
                      render={<span />}
                      size="xs"
                      tone="muted"
                      tabular="true"
                    >
                      {formatVolume(selectedCluster.volumeGb)} ·{" "}
                      {CADENCE_LABELS[cadence]} · {selectedEncryption.shortLabel}
                    </Text>
                  </VStack>
                  <Text
                    render={<span />}
                    size="xl"
                    weight="semibold"
                    tabular="true"
                  >
                    ${costEstimate.total}
                    <Text
                      render={<span />}
                      size="xs"
                      tone="muted"
                      weight="normal"
                    >
                      /mo
                    </Text>
                  </Text>
                </HStack>
              </VStack>
            ) : null}

            {step === 2 ? (
              <VStack gap="4" style={styles.fullWidth}>
                <Card.Root variant="outline" size="sm">
                  <Card.Body style={styles.reviewCardBody}>
                    <DataList.Root orientation="horizontal" variant="subtle" size="sm">
                      <DataList.Item>
                        <DataList.ItemLabel style={styles.reviewLabel}>
                          Policy name
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          <Text
                            render={<span />}
                            variant="mono"
                            size="xs"
                            style={styles.breakWord}
                          >
                            {policyName.trim().toLowerCase() || "—"}
                          </Text>
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item>
                        <DataList.ItemLabel style={styles.reviewLabel}>
                          Target cluster
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {selectedCluster.value} ({selectedCluster.engine} ·{" "}
                          {formatVolume(selectedCluster.volumeGb)})
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item>
                        <DataList.ItemLabel style={styles.reviewLabel}>
                          Primary vault
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {selectedRegion.label}
                          {crossRegionReplication
                            ? ` → DR ${selectedRegion.drPair}`
                            : " (single region)"}
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item>
                        <DataList.ItemLabel style={styles.reviewLabel}>
                          Schedule &amp; retention
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {CADENCE_LABELS[cadence]} · {Math.round(retentionDays)} days (
                          {retainedSnapshots.toLocaleString("en-US")} snapshots)
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item>
                        <DataList.ItemLabel style={styles.reviewLabel}>
                          Encryption
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {selectedEncryption.label}
                        </DataList.ItemValue>
                      </DataList.Item>
                    </DataList.Root>
                  </Card.Body>
                </Card.Root>

                <HStack
                  justify="between"
                  wrap="wrap"
                  gap="3"
                  style={styles.estimateBar}
                >
                  <VStack gap="0.5">
                    <Text render={<span />} size="xs" weight="medium">
                      Estimated monthly storage cost
                    </Text>
                    <Text
                      render={<span />}
                      size="xs"
                      tone="muted"
                      tabular="true"
                    >
                      ${costEstimate.baseCost} primary vault
                      {costEstimate.replicationCost > 0
                        ? ` + $${costEstimate.replicationCost} DR mirror`
                        : ""}
                      {costEstimate.encryptionCost > 0
                        ? ` + $${costEstimate.encryptionCost} key vault`
                        : ""}
                    </Text>
                  </VStack>
                  <Text
                    render={<span />}
                    size="xl"
                    weight="semibold"
                    tabular="true"
                  >
                    ${costEstimate.total}
                    <Text
                      render={<span />}
                      size="xs"
                      tone="muted"
                      weight="normal"
                    >
                      /mo
                    </Text>
                  </Text>
                </HStack>

                <Separator decorative />

                <Field.Root invalid={Boolean(currentErrors.notifyChannel)}>
                  <Field.Label>
                    Failure alert channel
                    <Text
                      render={<span />}
                      size="xs"
                      tone="subtle"
                      weight="normal"
                    >
                      Optional
                    </Text>
                  </Field.Label>
                  <Input
                    ref={notifyChannelRef}
                    size="sm"
                    value={notifyChannel}
                    onValueChange={setNotifyChannel}
                    placeholder="#infra-backups or https://hooks.arbor.cloud/..."
                    aria-invalid={currentErrors.notifyChannel ? true : undefined}
                  />
                  {currentErrors.notifyChannel ? (
                    <Field.Error match={true}>
                      {currentErrors.notifyChannel}
                    </Field.Error>
                  ) : (
                    <Field.Description>
                      Only notifies on missed snapshot windows or checksum mismatches.
                    </Field.Description>
                  )}
                </Field.Root>

                <Alert.Root
                  status="success"
                  variant="subtle"
                  size="sm"
                  palette={greenPalette}
                >
                  <Alert.Indicator>
                    <ShieldCheckIcon />
                  </Alert.Indicator>
                  <Alert.Content>
                    <Alert.Title>Ready to schedule</Alert.Title>
                    <Alert.Description>
                      The first incremental snapshot will queue on the next{" "}
                      {cadence} window with zero impact on active reads or writes.
                    </Alert.Description>
                  </Alert.Content>
                </Alert.Root>
              </VStack>
            ) : null}
          </Dialog.Body>

          {/* Pinned Footer with Back, compact error summary, and Continue / Create */}
          <Dialog.Footer style={styles.dialogFooter}>
            <Button
              type="button"
              variant="surface"
              size="sm"
              disabled={step === 0}
              onClick={() => setStep((current) => Math.max(0, current - 1))}
            >
              <ArrowLeftIcon />
              Back
            </Button>

            <HStack justify="end" wrap="wrap" gap="3">
              {currentErrorCount > 0 ? (
                <HStack
                  render={<span role="status" />}
                  gap="1.5"
                  style={styles.errorColor}
                >
                  <AlertCircleIcon />
                  <Text
                    render={<span />}
                    size="xs"
                    weight="medium"
                    tone="error"
                  >
                    {formatBlockedSummary(currentErrorCount)}
                  </Text>
                </HStack>
              ) : null}

              <Button
                type="button"
                variant="solid"
                size="sm"
                palette={accentPalette}
                onClick={handleNext}
              >
                {isLastStep ? (
                  <>
                    <ShieldCheckIcon />
                    Create policy
                  </>
                ) : (
                  <>
                    Continue
                    <ArrowRightIcon />
                  </>
                )}
              </Button>
            </HStack>
          </Dialog.Footer>
        </Dialog.Content>
      </Dialog.Root>

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

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