---
title: "Vertical Wizard · UI SDK — StyleX Blocks"
description: "Five-step enterprise SSO and workspace provisioning wizard with a persistent vertical stepper rail, live per-step statuses and summary subtitles, overall progress indicator, draft save tracking, conditional protocol and SIEM fields, broken-step validation flagging, container-responsive top bar collapse, and grouped review and confirmation screens."
url: "https://stylexblocks.com/block/ui-sdk/form-wizard-vertical/"
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/"
---

# Vertical Wizard block

Five-step enterprise SSO and workspace provisioning wizard with a persistent vertical stepper rail, live per-step statuses and summary subtitles, overall progress indicator, draft save tracking, conditional protocol and SIEM fields, broken-step validation flagging, container-responsive top bar collapse, and grouped review and confirmation screens.

- 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), [Center](https://stylexblocks.com/components/ui-sdk/center.md), [Checkbox](https://stylexblocks.com/components/ui-sdk/checkbox.md), [Checkbox Card](https://stylexblocks.com/components/ui-sdk/checkbox-card.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), [Fieldset](https://stylexblocks.com/components/ui-sdk/fieldset.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), [Progress](https://stylexblocks.com/components/ui-sdk/progress.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), [Switch](https://stylexblocks.com/components/ui-sdk/switch.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-vertical/

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

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

## Usage

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

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

## Source

`components/blocks/ui-sdk/form-wizard-vertical.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 { Circle, Square } from "#components/ui/ui-sdk/center.tsx";
import { CheckboxCard } from "#components/ui/ui-sdk/checkbox-card.tsx";
import { CheckboxGroup } from "#components/ui/ui-sdk/checkbox-group.tsx";
import { Checkbox } from "#components/ui/ui-sdk/checkbox.tsx";
import { DataList } from "#components/ui/ui-sdk/data-list.tsx";
import { Field } from "#components/ui/ui-sdk/field.tsx";
import { Fieldset } from "#components/ui/ui-sdk/fieldset.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 { Progress } from "#components/ui/ui-sdk/progress.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 { Switch } from "#components/ui/ui-sdk/switch.tsx";
import { Text } from "#components/ui/ui-sdk/text.tsx";
import { Toast, Toaster } from "#components/ui/ui-sdk/toast.tsx";
import type { StyleOverrideProps } from "#lib/recipe-props.ts";
import { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";
import { semanticRadii } from "@stylexblocks/ui/semantic-tokens/radii.stylex.ts";
import { semanticShadows } from "@stylexblocks/ui/semantic-tokens/shadows.stylex.ts";
import {
  accentPalette,
  amberPalette,
  grayPalette,
  greenPalette,
  redPalette,
} from "@stylexblocks/ui/themes/palettes.ts";
import { durations } from "@stylexblocks/ui/tokens/durations.stylex.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 { radii } from "@stylexblocks/ui/tokens/radii.stylex.ts";
import { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";

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

function ShieldEmblemIcon() {
  return (
    <Icon
      size="sm"
      viewBox="0 0 20 20"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M10 2.25 3.75 4.75v4.75c0 4 2.7 6.8 6.25 8.25 3.55-1.45 6.25-4.25 6.25-8.25V4.75L10 2.25Z" />
      <path d="m7.5 10.1 1.75 1.8 3.5-3.9" />
    </Icon>
  );
}

function CheckIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="2.1"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="m3.5 8.4 3 3 6-6.6" />
    </Icon>
  );
}

function AlertTriangleIcon() {
  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="M8 2.25 14 13H2L8 2.25Z" />
      <path d="M8 6.25v3" />
      <path d="M8 11.25v.1" />
    </Icon>
  );
}

function AlertCircleIcon() {
  return (
    <Icon
      size="sm"
      viewBox="0 0 20 20"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.65"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <circle cx="10" cy="10" r="7.5" />
      <path d="M10 6.5v4" />
      <path d="M10 13.5v.1" />
    </Icon>
  );
}

function CheckCircleIcon() {
  return (
    <Icon
      size="sm"
      viewBox="0 0 20 20"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.65"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <circle cx="10" cy="10" r="7.5" />
      <path d="m7 10.2 2 2 4-4.4" />
    </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 SaveDraftIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.6"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M3 2.5h8.25L13.5 4.75V13.5h-11V2.5H3Z" />
      <path d="M5.25 2.5v3.5h5V2.5" />
      <path d="M5 13.5v-4h6v4" />
    </Icon>
  );
}

function DownloadIcon() {
  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.5v7.5" />
      <path d="m5 7.25 3 3 3-3" />
      <path d="M2.75 12.75h10.5" />
    </Icon>
  );
}

function LockIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.6"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <rect x="3.25" y="7.25" width="9.5" height="6.5" rx="1.5" />
      <path d="M5.5 7.25V5.25a2.5 2.5 0 0 1 5 0v2" />
    </Icon>
  );
}

function EditPencilIcon() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.6"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="m10.9 2.9 2.2 2.2-7.1 7.1-2.8.6.6-2.8 7.1-7.1Z" />
    </Icon>
  );
}

// ── Domain types & configuration ─────────────────────────────────────────────

export type ResidencyRegionId = "eu-central" | "us-east" | "ca-central";
export type SsoProtocolId = "saml" | "oidc" | "scim-saml";
export type IdpVendorId = "okta" | "entra" | "google" | "ping" | "onelogin" | "custom";
export type WorkspaceRoleId = "viewer" | "analyst" | "operator" | "admin";
export type GroupRuleId =
  | "sec-admins"
  | "soc-responders"
  | "compliance-auditors"
  | "eng-readonly";
export type SiemDestinationId =
  | "datadog"
  | "splunk"
  | "sentinel"
  | "chronicle"
  | "s3"
  | "none";
export type AlertChannelId = "email" | "slack" | "pagerduty" | "webhook";
export type LogRetentionId = "90d" | "1y" | "3y" | "7y";

export interface FormWizardVerticalValues {
  organizationName: string;
  workspaceSlug: string;
  residencyRegion: ResidencyRegionId;
  primaryAdminEmail: string;
  protocol: SsoProtocolId;
  idpVendor: IdpVendorId;
  entityOrDiscoveryUrl: string;
  oidcClientId: string;
  scimEndpointUrl: string;
  autoDeprovision: boolean;
  enforceSso: boolean;
  breakGlassEmail: string;
  defaultRole: WorkspaceRoleId;
  groupRules: GroupRuleId[];
  sessionTimeoutMinutes: number;
  requireHardwareMfa: boolean;
  allowPlatformPasskeys: boolean;
  siemDestination: SiemDestinationId;
  siemEndpointUrl: string;
  alertChannels: AlertChannelId[];
  alertEndpointUrl: string;
  logRetention: LogRetentionId;
  confirmedProvisioning: boolean;
}

export interface FormWizardVerticalProvisionPayload {
  tenantId: string;
  portalUrl: string;
  callbackUrl: string;
  provisionedAt: string;
  values: FormWizardVerticalValues;
}

export interface FormWizardVerticalProps extends StyleOverrideProps {
  /** Primary title displayed in the sticky top bar. */
  title?: string;
  /** Product suite badge shown beside the title. */
  suiteName?: string;
  /** Hostname prefix used for workspace URLs and SSO callback endpoints. */
  portalDomain?: string;
  /** Optional initial values overriding the default Boreal Security Suite preset. */
  initialValues?: Partial<FormWizardVerticalValues>;
  /** Initial active step index (defaults to 1 so Step 1 displays completed state on load). */
  initialStep?: number;
  /** Called when the user saves a draft snapshot. */
  onSaveDraft?: (values: FormWizardVerticalValues) => void;
  /** Called once all steps validate and the workspace is provisioned. */
  onProvision?: (payload: FormWizardVerticalProvisionPayload) => void;
}

type StepStatusKind = "completed" | "in-progress" | "needs-attention" | "upcoming";

interface StepMeta {
  id: string;
  label: string;
  shortLabel: string;
  description: string;
}

const STEPS: readonly StepMeta[] = [
  {
    id: "identity",
    label: "Workspace Identity",
    shortLabel: "Identity",
    description: "Name the tenant, lock its data residency region, and assign the primary security admin.",
  },
  {
    id: "idp",
    label: "Identity Provider",
    shortLabel: "IdP",
    description: "Choose your federation protocol, bind your IdP metadata, and set SSO enforcement rules.",
  },
  {
    id: "access",
    label: "Access & Role Mapping",
    shortLabel: "Access",
    description: "Map directory groups to workspace roles, set session timeouts, and enforce hardware MFA.",
  },
  {
    id: "audit",
    label: "Audit & Notifications",
    shortLabel: "Audit",
    description: "Stream security events to your SIEM, pick alert channels, and lock immutable log retention.",
  },
  {
    id: "review",
    label: "Review & Provision",
    shortLabel: "Review",
    description: "Verify every security control, resolve any flagged sections, and provision the tenant.",
  },
];

const RESIDENCY_REGIONS: ReadonlyArray<{
  id: ResidencyRegionId;
  label: string;
  shortLabel: string;
  datacenter: string;
  compliance: string;
  description: string;
  recommended?: boolean;
}> = [
  {
    id: "eu-central",
    label: "EU Central (Frankfurt)",
    shortLabel: "EU Central",
    datacenter: "fra-sec-01",
    compliance: "GDPR · ISO 27018",
    description: "Sovereign EU encryption keys with zero cross-border telemetry egress.",
    recommended: true,
  },
  {
    id: "us-east",
    label: "US East (Virginia)",
    shortLabel: "US East",
    datacenter: "iad-sec-02",
    compliance: "SOC 2 Type II · HIPAA",
    description: "Low-latency North American control plane with dual-AZ HSM vaults.",
  },
  {
    id: "ca-central",
    label: "Canada Central (Montréal)",
    shortLabel: "CA Central",
    datacenter: "yul-sec-01",
    compliance: "PIPEDA · Sovereign KMS",
    description: "Dedicated Canadian residency zone with customer-held root keys.",
  },
];

const PROTOCOLS: ReadonlyArray<{
  value: SsoProtocolId;
  label: string;
}> = [
  { value: "saml", label: "SAML 2.0" },
  { value: "oidc", label: "OIDC" },
  { value: "scim-saml", label: "SCIM + SAML" },
];

const IDP_VENDORS: ReadonlyArray<{ value: IdpVendorId; label: string }> = [
  { value: "okta", label: "Okta Workforce Identity" },
  { value: "entra", label: "Microsoft Entra ID" },
  { value: "google", label: "Google Workspace" },
  { value: "ping", label: "PingFederate Enterprise" },
  { value: "onelogin", label: "OneLogin Identity" },
  { value: "custom", label: "Custom Identity Provider" },
];

const DEFAULT_ROLES: ReadonlyArray<{ value: WorkspaceRoleId; label: string }> = [
  { value: "viewer", label: "Security Viewer — Read-only posture & reports" },
  { value: "analyst", label: "SOC Analyst — Alert triage & telemetry queries" },
  { value: "operator", label: "Platform Operator — Policies, integrations & vaults" },
  { value: "admin", label: "Workspace Admin — Full security & tenant control" },
];

const GROUP_ROLE_RULES: ReadonlyArray<{
  id: GroupRuleId;
  groupName: string;
  mappedRole: string;
  description: string;
}> = [
  {
    id: "sec-admins",
    groupName: "boreal-admins",
    mappedRole: "Workspace Admin",
    description: "Policy administration, IdP certificate rotation, and break-glass vault control.",
  },
  {
    id: "soc-responders",
    groupName: "soc-tier2",
    mappedRole: "SOC Analyst",
    description: "Incident investigation, rule suppression, and signed forensic evidence export.",
  },
  {
    id: "compliance-auditors",
    groupName: "grc-audit",
    mappedRole: "Compliance Auditor",
    description: "Read-only access to immutable audit trails and automated SOC 2 evidence bundles.",
  },
  {
    id: "eng-readonly",
    groupName: "platform-eng",
    mappedRole: "Security Viewer",
    description: "Inspect vulnerability posture and secret-scanning findings for owned services.",
  },
];

const SIEM_DESTINATIONS: ReadonlyArray<{
  value: SiemDestinationId;
  label: string;
  endpointPlaceholder: string;
}> = [
  {
    value: "datadog",
    label: "Datadog Security SIEM",
    endpointPlaceholder: "https://http-intake.logs.datadoghq.eu/api/v2/logs",
  },
  {
    value: "splunk",
    label: "Splunk Cloud HEC",
    endpointPlaceholder: "https://http-inputs-kestrel.splunkcloud.com:443/services/collector",
  },
  {
    value: "sentinel",
    label: "Microsoft Sentinel",
    endpointPlaceholder: "https://kestrel-dce.westeurope-1.ingest.monitor.azure.com",
  },
  {
    value: "chronicle",
    label: "Google SecOps (Chronicle)",
    endpointPlaceholder: "https://europe-malachiteingestion-pa.googleapis.com/v2/unstructuredlogentries",
  },
  {
    value: "s3",
    label: "Sovereign S3 Bucket (Parquet)",
    endpointPlaceholder: "https://s3.eu-central-1.amazonaws.com/kestrel-boreal-audit",
  },
  {
    value: "none",
    label: "Built-in Boreal Audit Vault only",
    endpointPlaceholder: "",
  },
];

const ALERT_CHANNELS: ReadonlyArray<{
  id: AlertChannelId;
  label: string;
  description: string;
}> = [
  {
    id: "email",
    label: "Primary & SecOps email digest",
    description: "Immediate critical alerts plus daily 08:00 UTC security summary.",
  },
  {
    id: "slack",
    label: "Slack #secops-alerts channel",
    description: "Interactive incident cards with one-click session revocation.",
  },
  {
    id: "pagerduty",
    label: "PagerDuty high-severity escalation",
    description: "Pages on-call responder for break-glass sign-ins and policy tampering.",
  },
  {
    id: "webhook",
    label: "Signed JSON webhook (HMAC-SHA256)",
    description: "Deliver real-time event payloads to custom SOAR or ticketing pipelines.",
  },
];

const LOG_RETENTION_OPTIONS: ReadonlyArray<{
  value: LogRetentionId;
  label: string;
  complianceNote: string;
}> = [
  {
    value: "90d",
    label: "90 days",
    complianceNote: "Standard operational window for incident response.",
  },
  {
    value: "1y",
    label: "1 year",
    complianceNote: "Covers annual SOC 2 Type II and ISO 27001 audit cycles.",
  },
  {
    value: "3y",
    label: "3 years",
    complianceNote: "Recommended for regulated fintech and enterprise telemetry.",
  },
  {
    value: "7y",
    label: "7 years (WORM)",
    complianceNote: "Write-once-read-many archival aligned with DORA, MiFID II, and HIPAA.",
  },
];

const DEFAULT_VALUES: FormWizardVerticalValues = {
  organizationName: "Kestrel Financial Holdings",
  workspaceSlug: "kestrel-financial",
  residencyRegion: "eu-central",
  primaryAdminEmail: "elena.lindholm@kestrelfin.example",
  protocol: "scim-saml",
  idpVendor: "okta",
  entityOrDiscoveryUrl: "https://kestrel.okta.com/app/exk92a8b1c3d/sso/saml/metadata",
  oidcClientId: "0oa8f3k2m9p4q7r1s5t6",
  scimEndpointUrl: "https://kestrel.okta.com/scim/v2",
  autoDeprovision: true,
  enforceSso: true,
  breakGlassEmail: "secops-breakglass@kestrelfin.example",
  defaultRole: "analyst",
  groupRules: ["sec-admins", "soc-responders", "compliance-auditors"],
  sessionTimeoutMinutes: 60,
  requireHardwareMfa: true,
  allowPlatformPasskeys: true,
  siemDestination: "datadog",
  siemEndpointUrl: "https://http-intake.logs.datadoghq.eu/api/v2/logs",
  alertChannels: ["email", "slack"],
  alertEndpointUrl: "https://hooks.slack.example/services/T04KESTREL/B09SECOPS",
  logRetention: "3y",
  confirmedProvisioning: false,
};

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

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

type ValidatableFieldKey =
  | "organizationName"
  | "workspaceSlug"
  | "primaryAdminEmail"
  | "entityOrDiscoveryUrl"
  | "oidcClientId"
  | "scimEndpointUrl"
  | "breakGlassEmail"
  | "groupRules"
  | "sessionTimeoutMinutes"
  | "siemEndpointUrl"
  | "alertChannels"
  | "alertEndpointUrl"
  | "confirmedProvisioning";

// ── Container queries ────────────────────────────────────────────────────────

const COLLAPSE_RAIL = "@container form-wizard-vertical (max-width: 860px)";
const COMPACT = "@container form-wizard-vertical (max-width: 560px)";

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

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

function buildTenantId(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, 4) || "brsl").toLowerCase();
  return `brs_${prefix}_${suffix}`;
}

function formatClock(date: Date): string {
  return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}

function statusLabelFor(status: StepStatusKind): string {
  switch (status) {
    case "completed":
      return "Completed";
    case "in-progress":
      return "In Progress";
    case "needs-attention":
      return "Needs Attention";
    case "upcoming":
      return "Upcoming";
  }
}

function statusPaletteFor(status: StepStatusKind) {
  switch (status) {
    case "completed":
      return greenPalette;
    case "in-progress":
      return accentPalette;
    case "needs-attention":
      return redPalette;
    case "upcoming":
      return grayPalette;
  }
}

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

const styles = stylex.create({
  root: {
    backgroundColor: semanticColors.bg,
    color: semanticColors.fg,
    containerName: "form-wizard-vertical",
    containerType: "inline-size",
    fontFamily: fonts.body,
    minHeight: "100%",
    width: "100%",
  },

  // ── Shared layout helpers ──
  headingReset: {
    marginBlock: 0,
  },
  fullWidth: {
    width: "100%",
  },
  flexGrow: {
    flexGrow: 1,
  },
  nowrap: {
    whiteSpace: "nowrap",
  },
  breakWord: {
    wordBreak: "break-word",
  },
  breakAll: {
    wordBreak: "break-all",
  },
  mutedColor: {
    color: semanticColors.fgMuted,
  },
  successColor: {
    color: semanticColors.fgSuccess,
  },
  listReset: {
    marginBlock: 0,
    paddingBlock: 0,
    paddingInline: 0,
  },

  // ── Sticky top header ──
  header: {
    backgroundColor: semanticColors.bg,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    position: "sticky",
    top: 0,
    width: "100%",
    zIndex: 20,
  },
  headerInner: {
    paddingBlock: {
      default: spacing._3_5,
      [COMPACT]: spacing._3,
    },
    paddingInline: {
      default: spacing._6,
      [COMPACT]: spacing._4,
    },
    width: "100%",
  },
  brandEmblem: {
    backgroundColor: semanticColors.accentSubtle,
    borderColor: semanticColors.accentBorder,
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.accentFg,
  },

  // ── Compact mobile/narrow top step selector ──
  compactBar: {
    display: {
      default: "none",
      [COLLAPSE_RAIL]: "flex",
    },
    flexDirection: "column",
    gap: spacing._2_5,
    paddingTop: spacing._1,
  },
  compactStepChips: {
    display: "flex",
    flexWrap: "nowrap",
    gap: spacing._1_5,
    marginBlock: 0,
    overflowX: "auto",
    paddingBlock: spacing._0_5,
    paddingInline: 0,
    scrollbarWidth: "none",
  },
  compactChipItem: {
    flexShrink: 0,
    listStyleType: "none",
  },
  compactChipButton: {
    alignItems: "center",
    backgroundColor: {
      default: semanticColors.bgSurface,
      ":hover": semanticColors.bgSubtle,
    },
    borderColor: semanticColors.border,
    borderRadius: radii.full,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.fgMuted,
    cursor: {
      default: "pointer",
      ":disabled": "not-allowed",
    },
    display: "inline-flex",
    fontFamily: fonts.body,
    fontSize: fontSizes.xs,
    fontWeight: fontWeights.medium,
    gap: spacing._1_5,
    lineHeight: lineHeights.xs,
    opacity: {
      default: 1,
      ":disabled": 0.5,
    },
    outlineColor: {
      default: null,
      ":focus-visible": semanticColors.accentFocusRing,
    },
    outlineOffset: {
      default: null,
      ":focus-visible": "2px",
    },
    outlineStyle: {
      default: null,
      ":focus-visible": "solid",
    },
    outlineWidth: {
      default: null,
      ":focus-visible": "2px",
    },
    paddingBlock: spacing._1,
    paddingInline: spacing._2_5,
    whiteSpace: "nowrap",
  },
  compactChipActive: {
    backgroundColor: semanticColors.accentSubtle,
    borderColor: semanticColors.accentBorder,
    color: semanticColors.accentFg,
  },
  compactChipError: {
    backgroundColor: semanticColors.bgError,
    borderColor: semanticColors.borderError,
    color: semanticColors.fgError,
  },
  compactChipDone: {
    borderColor: semanticColors.borderSuccess,
    color: semanticColors.fg,
  },

  // ── Two-column workspace layout ──
  workspaceGrid: {
    flexGrow: 1,
    gridTemplateColumns: {
      default: "19.5rem minmax(0, 1fr)",
      [COLLAPSE_RAIL]: "minmax(0, 1fr)",
    },
    minHeight: 0,
    width: "100%",
  },

  // ── Persistent left navigation rail ──
  rail: {
    backgroundColor: semanticColors.bgMuted,
    borderInlineEndColor: semanticColors.border,
    borderInlineEndStyle: "solid",
    borderInlineEndWidth: "1px",
    display: {
      default: "flex",
      [COLLAPSE_RAIL]: "none",
    },
    flexDirection: "column",
    gap: spacing._5,
    paddingBlock: spacing._6,
    paddingInline: spacing._5,
  },
  railStickyInner: {
    position: "sticky",
    top: "5.25rem",
  },

  // ── Vertical stepper list inside rail ──
  railStepLi: {
    listStyleType: "none",
    position: "relative",
  },
  railStepButton: {
    alignItems: "flex-start",
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.bgSubtle,
    },
    borderColor: "transparent",
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.fg,
    cursor: {
      default: "pointer",
      ":disabled": "not-allowed",
    },
    display: "flex",
    fontFamily: fonts.body,
    gap: spacing._3,
    opacity: {
      default: 1,
      ":disabled": 0.56,
    },
    outlineColor: {
      default: null,
      ":focus-visible": semanticColors.accentFocusRing,
    },
    outlineOffset: {
      default: null,
      ":focus-visible": "2px",
    },
    outlineStyle: {
      default: null,
      ":focus-visible": "solid",
    },
    outlineWidth: {
      default: null,
      ":focus-visible": "2px",
    },
    paddingBlock: spacing._2_5,
    paddingInline: spacing._2_5,
    textAlign: "start",
    transitionDuration: durations.fast,
    transitionProperty: "background-color, border-color, box-shadow",
    width: "100%",
  },
  railStepButtonActive: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.borderEmphasized,
    boxShadow: semanticShadows.xs,
  },
  railStepButtonError: {
    backgroundColor: {
      default: semanticColors.bgError,
      ":hover": semanticColors.bgError,
    },
    borderColor: semanticColors.borderError,
  },
  railTimelineCol: {
    alignSelf: "stretch",
    flexShrink: 0,
    width: spacing._7,
  },
  railIndicatorCircle: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.borderEmphasized,
    borderStyle: "solid",
    borderWidth: "1.5px",
    color: semanticColors.fgMuted,
    fontSize: fontSizes.xs,
    fontVariantNumeric: "tabular-nums",
    fontWeight: fontWeights.semibold,
    height: spacing._7,
    width: spacing._7,
  },
  railIndicatorActive: {
    backgroundColor: semanticColors.accentSolid,
    borderColor: semanticColors.accentSolid,
    color: semanticColors.accentContrast,
  },
  railIndicatorCompleted: {
    backgroundColor: semanticColors.greenSolid,
    borderColor: semanticColors.greenSolid,
    color: semanticColors.greenContrast,
  },
  railIndicatorError: {
    backgroundColor: semanticColors.redSolid,
    borderColor: semanticColors.redSolid,
    color: semanticColors.redContrast,
  },
  railConnector: {
    backgroundColor: semanticColors.border,
    flexGrow: 1,
    marginTop: spacing._1_5,
    minHeight: spacing._3,
    width: "2px",
  },
  railConnectorCompleted: {
    backgroundColor: semanticColors.greenBorder,
  },
  railConnectorError: {
    backgroundColor: semanticColors.borderError,
  },
  railStepCopy: {
    flexGrow: 1,
    paddingTop: spacing._0_5,
  },
  railStepStatusRow: {
    marginTop: spacing._0_5,
  },

  // ── Rail posture / draft box ──
  railFooterBox: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._3,
    paddingInline: spacing._3_5,
  },

  // ── Right-hand main form column ──
  mainInner: {
    flexGrow: 1,
    marginInline: "auto",
    maxWidth: "46rem",
    paddingBlock: {
      default: spacing._8,
      [COMPACT]: spacing._5,
    },
    paddingInline: {
      default: spacing._8,
      [COLLAPSE_RAIL]: spacing._6,
      [COMPACT]: spacing._4,
    },
    width: "100%",
  },

  // ── Form grids & controls ──
  twoColGrid: {
    gridTemplateColumns: {
      default: "repeat(2, minmax(0, 1fr))",
      [COMPACT]: "minmax(0, 1fr)",
    },
    width: "100%",
  },
  threeColGrid: {
    display: "grid",
    gap: spacing._3,
    gridTemplateColumns: {
      default: "repeat(3, minmax(0, 1fr))",
      [COMPACT]: "minmax(0, 1fr)",
    },
    width: "100%",
  },
  cardGridTwo: {
    gridTemplateColumns: {
      default: "repeat(2, minmax(0, 1fr))",
      [COMPACT]: "minmax(0, 1fr)",
    },
    width: "100%",
  },
  cardItemStretch: {
    height: "100%",
  },
  cardControlTop: {
    alignItems: "flex-start",
    height: "100%",
    width: "100%",
  },
  cardContentStack: {
    gap: spacing._1_5,
    height: "100%",
    width: "100%",
  },
  cardMetaRow: {
    marginTop: "auto",
    paddingTop: spacing._1,
  },
  monoCodeInline: {
    backgroundColor: semanticColors.bgMuted,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.controlSm,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.fg,
    fontFamily: fonts.mono,
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
    paddingBlock: spacing._0_5,
    paddingInline: spacing._1_5,
  },
  callbackBox: {
    backgroundColor: semanticColors.bgMuted,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._3,
    paddingInline: spacing._3_5,
  },
  segmentWrap: {
    maxWidth: "100%",
    overflowX: "auto",
  },
  timeoutInputRoot: {
    maxWidth: "11rem",
  },
  switchCard: {
    backgroundColor: semanticColors.bgSurface,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    gap: spacing._3_5,
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
  },
  switchRow: {
    alignItems: "center",
    display: "flex",
    gap: spacing._4,
    justifyContent: "space-between",
    width: "100%",
  },
  conditionalIndent: {
    borderInlineStartColor: semanticColors.accentBorder,
    borderInlineStartStyle: "solid",
    borderInlineStartWidth: "2px",
    paddingInlineStart: spacing._4,
  },
  checkboxRow: {
    alignItems: "flex-start",
    display: "flex",
    gap: spacing._2_5,
  },
  checkboxControlOffset: {
    marginTop: spacing._0_5,
  },

  // ── Review & confirmation ──
  issuesList: {
    marginTop: spacing._1_5,
  },
  issueButtonsRow: {
    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,
  },
  reviewDataItem: {
    alignItems: {
      default: "baseline",
      [COMPACT]: "flex-start",
    },
    flexDirection: {
      default: "row",
      [COMPACT]: "column",
    },
    gap: {
      default: spacing._4,
      [COMPACT]: spacing._0_5,
    },
  },
  reviewDataLabel: {
    flexShrink: 0,
    minWidth: {
      default: "11.5rem",
      [COMPACT]: 0,
    },
  },

  // ── Sticky bottom action bar ──
  footer: {
    backgroundColor: semanticColors.bg,
    borderTopColor: semanticColors.border,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
    bottom: 0,
    marginTop: "auto",
    position: "sticky",
    width: "100%",
    zIndex: 20,
  },
  footerInner: {
    paddingBlock: spacing._3_5,
    paddingInline: {
      default: spacing._6,
      [COMPACT]: spacing._4,
    },
    width: "100%",
  },
});

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

/**
 * FormWizardVertical — five-step enterprise SSO & workspace provisioning wizard
 * with a persistent left-hand vertical stepper rail, live step statuses,
 * overall completion progress bar, draft save indicator, conditional fields
 * driven by earlier choices, per-step validation with broken-step flagging,
 * container-responsive collapse, and a grouped review & confirmation screen.
 */
export function FormWizardVertical({
  title = "Enterprise SSO & Workspace Provisioning",
  suiteName = "Boreal Security Suite",
  portalDomain = "boreal.security",
  initialValues,
  initialStep = 1,
  onSaveDraft,
  onProvision,
  palette,
  style,
}: FormWizardVerticalProps) {
  const mergedInitial = useMemo<FormWizardVerticalValues>(
    () => ({
      ...DEFAULT_VALUES,
      ...initialValues,
      groupRules: initialValues?.groupRules
        ? [...initialValues.groupRules]
        : [...DEFAULT_VALUES.groupRules],
      alertChannels: initialValues?.alertChannels
        ? [...initialValues.alertChannels]
        : [...DEFAULT_VALUES.alertChannels],
    }),
    [initialValues],
  );

  const clampedInitialStep = Math.max(0, Math.min(STEPS.length - 1, initialStep));

  const queue = useMemo(() => Toast.createToaster(), []);
  const slugInputId = useId();
  const residencyGroupLabelId = useId();
  const protocolGroupLabelId = useId();
  const retentionGroupLabelId = useId();

  // Flow & navigation state (starts mid-stride on step 2 with step 1 completed)
  const [step, setStep] = useState<number>(clampedInitialStep);
  const [visited, setVisited] = useState<ReadonlySet<number>>(() => {
    const initial = new Set<number>();
    for (let i = 0; i <= clampedInitialStep; i += 1) {
      initial.add(i);
    }
    return initial;
  });
  const [attempted, setAttempted] = useState<ReadonlySet<number>>(() => {
    const initial = new Set<number>();
    for (let i = 0; i < clampedInitialStep; i += 1) {
      initial.add(i);
    }
    return initial;
  });
  const [isProvisioned, setIsProvisioned] = useState(false);
  const [provisionPayload, setProvisionPayload] =
    useState<FormWizardVerticalProvisionPayload | null>(null);
  const [slugTouched, setSlugTouched] = useState(
    Boolean(initialValues?.workspaceSlug),
  );
  const [savedAtLabel, setSavedAtLabel] = useState<string>(() =>
    formatClock(new Date()),
  );
  const [hasUnsavedEdits, setHasUnsavedEdits] = useState(false);

  // Step 1 — Workspace Identity
  const [organizationName, setOrganizationName] = useState(
    mergedInitial.organizationName,
  );
  const [workspaceSlug, setWorkspaceSlug] = useState(mergedInitial.workspaceSlug);
  const [residencyRegion, setResidencyRegion] = useState<ResidencyRegionId>(
    mergedInitial.residencyRegion,
  );
  const [primaryAdminEmail, setPrimaryAdminEmail] = useState(
    mergedInitial.primaryAdminEmail,
  );

  // Step 2 — Identity Provider
  const [protocol, setProtocol] = useState<SsoProtocolId>(mergedInitial.protocol);
  const [idpVendor, setIdpVendor] = useState<IdpVendorId>(mergedInitial.idpVendor);
  const [entityOrDiscoveryUrl, setEntityOrDiscoveryUrl] = useState(
    mergedInitial.entityOrDiscoveryUrl,
  );
  const [oidcClientId, setOidcClientId] = useState(mergedInitial.oidcClientId);
  const [scimEndpointUrl, setScimEndpointUrl] = useState(
    mergedInitial.scimEndpointUrl,
  );
  const [autoDeprovision, setAutoDeprovision] = useState(
    mergedInitial.autoDeprovision,
  );
  const [enforceSso, setEnforceSso] = useState(mergedInitial.enforceSso);
  const [breakGlassEmail, setBreakGlassEmail] = useState(
    mergedInitial.breakGlassEmail,
  );

  // Step 3 — Access & Role Mapping
  const [defaultRole, setDefaultRole] = useState<WorkspaceRoleId>(
    mergedInitial.defaultRole,
  );
  const [groupRules, setGroupRules] = useState<GroupRuleId[]>(
    mergedInitial.groupRules,
  );
  const [sessionTimeoutMinutes, setSessionTimeoutMinutes] = useState(
    mergedInitial.sessionTimeoutMinutes,
  );
  const [requireHardwareMfa, setRequireHardwareMfa] = useState(
    mergedInitial.requireHardwareMfa,
  );
  const [allowPlatformPasskeys, setAllowPlatformPasskeys] = useState(
    mergedInitial.allowPlatformPasskeys,
  );

  // Step 4 — Audit & Notifications
  const [siemDestination, setSiemDestination] = useState<SiemDestinationId>(
    mergedInitial.siemDestination,
  );
  const [siemEndpointUrl, setSiemEndpointUrl] = useState(
    mergedInitial.siemEndpointUrl,
  );
  const [alertChannels, setAlertChannels] = useState<AlertChannelId[]>(
    mergedInitial.alertChannels,
  );
  const [alertEndpointUrl, setAlertEndpointUrl] = useState(
    mergedInitial.alertEndpointUrl,
  );
  const [logRetention, setLogRetention] = useState<LogRetentionId>(
    mergedInitial.logRetention,
  );

  // Step 5 — Review & Provision
  const [confirmedProvisioning, setConfirmedProvisioning] = useState(
    mergedInitial.confirmedProvisioning,
  );

  // Focus targets for validation jump-to-error
  const organizationNameRef = useRef<HTMLInputElement>(null);
  const workspaceSlugRef = useRef<HTMLInputElement>(null);
  const primaryAdminEmailRef = useRef<HTMLInputElement>(null);
  const entityOrDiscoveryUrlRef = useRef<HTMLInputElement>(null);
  const oidcClientIdRef = useRef<HTMLInputElement>(null);
  const scimEndpointUrlRef = useRef<HTMLInputElement>(null);
  const breakGlassEmailRef = useRef<HTMLInputElement>(null);
  const sessionTimeoutRef = useRef<HTMLInputElement>(null);
  const siemEndpointUrlRef = useRef<HTMLInputElement>(null);
  const alertEndpointUrlRef = useRef<HTMLInputElement>(null);
  const confirmedProvisioningRef = useRef<HTMLButtonElement>(null);
  const pendingFocusFieldRef = useRef<ValidatableFieldKey | null>(null);

  const focusField = useCallback((fieldKey: ValidatableFieldKey) => {
    const map: Partial<Record<ValidatableFieldKey, HTMLElement | null>> = {
      organizationName: organizationNameRef.current,
      workspaceSlug: workspaceSlugRef.current,
      primaryAdminEmail: primaryAdminEmailRef.current,
      entityOrDiscoveryUrl: entityOrDiscoveryUrlRef.current,
      oidcClientId: oidcClientIdRef.current,
      scimEndpointUrl: scimEndpointUrlRef.current,
      breakGlassEmail: breakGlassEmailRef.current,
      sessionTimeoutMinutes: sessionTimeoutRef.current,
      siemEndpointUrl: siemEndpointUrlRef.current,
      alertEndpointUrl: alertEndpointUrlRef.current,
      confirmedProvisioning: confirmedProvisioningRef.current,
    };
    const target = map[fieldKey];
    if (target) {
      target.focus();
      target.scrollIntoView({ block: "center", behavior: "smooth" });
    }
  }, []);

  useEffect(() => {
    const fieldKey = pendingFocusFieldRef.current;
    if (!fieldKey) return;
    pendingFocusFieldRef.current = null;
    focusField(fieldKey);
  }, [step, focusField]);

  // Derived lookup objects
  const selectedRegion = useMemo(
    () =>
      RESIDENCY_REGIONS.find((region) => region.id === residencyRegion) ??
      RESIDENCY_REGIONS[0],
    [residencyRegion],
  );
  const selectedProtocol = useMemo(
    () => PROTOCOLS.find((item) => item.value === protocol) ?? PROTOCOLS[0],
    [protocol],
  );
  const selectedVendor = useMemo(
    () => IDP_VENDORS.find((item) => item.value === idpVendor) ?? IDP_VENDORS[0],
    [idpVendor],
  );
  const selectedRole = useMemo(
    () =>
      DEFAULT_ROLES.find((item) => item.value === defaultRole) ?? DEFAULT_ROLES[1],
    [defaultRole],
  );
  const selectedSiem = useMemo(
    () =>
      SIEM_DESTINATIONS.find((item) => item.value === siemDestination) ??
      SIEM_DESTINATIONS[0],
    [siemDestination],
  );
  const selectedRetention = useMemo(
    () =>
      LOG_RETENTION_OPTIONS.find((item) => item.value === logRetention) ??
      LOG_RETENTION_OPTIONS[2],
    [logRetention],
  );

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

  const callbackUrl =
    protocol === "oidc"
      ? `https://${portalDomain}/oidc/${normalizedSlug || "tenant"}/callback`
      : `https://${portalDomain}/sso/${normalizedSlug || "tenant"}/acs`;

  const needsAlertWebhook =
    alertChannels.includes("webhook") || alertChannels.includes("slack");

  // Single source of truth for per-step validation
  const errorsByStep = useMemo<
    Array<Partial<Record<ValidatableFieldKey, string>>>
  >(() => {
    const step0: Partial<Record<ValidatableFieldKey, string>> = {};
    if (!organizationName.trim()) {
      step0.organizationName = "Enter your organization name.";
    }
    if (!normalizedSlug) {
      step0.workspaceSlug = "Enter a tenant 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 = `${portalDomain}/${normalizedSlug} is reserved.`;
    }
    if (!primaryAdminEmail.trim()) {
      step0.primaryAdminEmail = "Enter a primary security admin email.";
    } else if (!EMAIL_PATTERN.test(primaryAdminEmail.trim())) {
      step0.primaryAdminEmail = "Enter a valid corporate email address.";
    }

    const step1: Partial<Record<ValidatableFieldKey, string>> = {};
    if (!entityOrDiscoveryUrl.trim()) {
      step1.entityOrDiscoveryUrl =
        protocol === "oidc"
          ? "Enter your OIDC .well-known discovery URL."
          : "Enter your SAML IdP Entity ID or metadata URL.";
    } else if (!HTTPS_URL_PATTERN.test(entityOrDiscoveryUrl.trim())) {
      step1.entityOrDiscoveryUrl = "Metadata and discovery endpoints must use https://.";
    }
    if (protocol === "oidc" && !oidcClientId.trim()) {
      step1.oidcClientId = "Enter the OIDC Client ID issued by your identity provider.";
    }
    if (protocol === "scim-saml") {
      if (!scimEndpointUrl.trim()) {
        step1.scimEndpointUrl = "Enter your SCIM 2.0 directory endpoint URL.";
      } else if (!HTTPS_URL_PATTERN.test(scimEndpointUrl.trim())) {
        step1.scimEndpointUrl = "SCIM directory endpoint must use https://.";
      }
    }
    if (enforceSso) {
      if (!breakGlassEmail.trim()) {
        step1.breakGlassEmail =
          "Provide a break-glass recovery email when SSO enforcement is enabled.";
      } else if (!EMAIL_PATTERN.test(breakGlassEmail.trim())) {
        step1.breakGlassEmail = "Enter a valid recovery email address.";
      }
    }

    const step2: Partial<Record<ValidatableFieldKey, string>> = {};
    if (
      !Number.isFinite(sessionTimeoutMinutes) ||
      sessionTimeoutMinutes < 15 ||
      sessionTimeoutMinutes > 480
    ) {
      step2.sessionTimeoutMinutes =
        "Session idle timeout must be between 15 and 480 minutes.";
    }
    if (protocol === "scim-saml" && groupRules.length === 0) {
      step2.groupRules =
        "Select at least one group-to-role rule when SCIM + SAML provisioning is active.";
    }

    const step3: Partial<Record<ValidatableFieldKey, string>> = {};
    if (siemDestination !== "none") {
      if (!siemEndpointUrl.trim()) {
        step3.siemEndpointUrl = `Enter the ingestion URL for ${selectedSiem.label}.`;
      } else if (!HTTPS_URL_PATTERN.test(siemEndpointUrl.trim())) {
        step3.siemEndpointUrl = "SIEM ingestion endpoints must use https://.";
      }
    }
    if (alertChannels.length === 0) {
      step3.alertChannels = "Enable at least one security alert notification channel.";
    }
    if (alertChannels.includes("webhook")) {
      if (!alertEndpointUrl.trim()) {
        step3.alertEndpointUrl = "Enter the HTTPS webhook endpoint for alert delivery.";
      } else if (!HTTPS_URL_PATTERN.test(alertEndpointUrl.trim())) {
        step3.alertEndpointUrl = "Alert webhook endpoint must use https://.";
      }
    }

    const step4: Partial<Record<ValidatableFieldKey, string>> = {};
    if (!confirmedProvisioning) {
      step4.confirmedProvisioning =
        "Confirm the security controls and IdP configuration before provisioning.";
    }

    return [step0, step1, step2, step3, step4];
  }, [
    organizationName,
    normalizedSlug,
    portalDomain,
    primaryAdminEmail,
    entityOrDiscoveryUrl,
    protocol,
    oidcClientId,
    scimEndpointUrl,
    enforceSso,
    breakGlassEmail,
    sessionTimeoutMinutes,
    groupRules.length,
    siemDestination,
    siemEndpointUrl,
    selectedSiem.label,
    alertChannels,
    alertEndpointUrl,
    confirmedProvisioning,
  ]);

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

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

  // Live status per step for vertical rail, compact bar, and review cards
  const stepStatuses = useMemo<StepStatusKind[]>(() => {
    if (isProvisioned) {
      return STEPS.map(() => "completed");
    }
    return STEPS.map((_, index) => {
      const hasShownError = Object.keys(shownErrors(index)).length > 0;
      if (hasShownError) {
        return "needs-attention";
      }
      if (index === step) {
        return "in-progress";
      }
      if (attempted.has(index) && Object.keys(errorsByStep[index]).length === 0) {
        return "completed";
      }
      return "upcoming";
    });
  }, [isProvisioned, shownErrors, step, attempted, errorsByStep]);

  const completedCount = useMemo(
    () => stepStatuses.filter((status) => status === "completed").length,
    [stepStatuses],
  );
  const attentionCount = useMemo(
    () => stepStatuses.filter((status) => status === "needs-attention").length,
    [stepStatuses],
  );
  const completionPercent = Math.round((completedCount / STEPS.length) * 100);

  // Per-step dynamic summary subtitles in the vertical rail
  const stepSummaries = useMemo<string[]>(() => {
    const firstIssue = (index: number) => {
      const issues = Object.values(shownErrors(index));
      return issues.length > 0 ? issues[0] : null;
    };

    const s0Issue = firstIssue(0);
    const s1Issue = firstIssue(1);
    const s2Issue = firstIssue(2);
    const s3Issue = firstIssue(3);
    const s4Issue = firstIssue(4);

    const brokenPrior = errorsByStep
      .slice(0, 4)
      .filter((errs) => Object.keys(errs).length > 0).length;

    return [
      s0Issue ??
        `${organizationName.trim() || "Untitled tenant"} · ${selectedRegion.shortLabel}`,
      s1Issue ??
        `${selectedProtocol.label} · ${selectedVendor.label.split(" ")[0]}${
          enforceSso ? " · Enforced" : ""
        }`,
      s2Issue ??
        `${groupRules.length} ${groupRules.length === 1 ? "rule" : "rules"} · ${
          requireHardwareMfa ? "HW MFA" : "Standard MFA"
        } · ${sessionTimeoutMinutes}m`,
      s3Issue ??
        `${
          siemDestination === "none"
            ? "Boreal Vault"
            : selectedSiem.label.split(" ")[0]
        } · ${selectedRetention.label}`,
      s4Issue ??
        (isProvisioned
          ? "Tenant active & verified"
          : brokenPrior > 0
            ? `${brokenPrior} ${brokenPrior === 1 ? "section needs" : "sections need"} fixes`
            : "Final sign-off & launch"),
    ];
  }, [
    shownErrors,
    errorsByStep,
    organizationName,
    selectedRegion.shortLabel,
    selectedProtocol.label,
    selectedVendor.label,
    enforceSso,
    groupRules.length,
    requireHardwareMfa,
    sessionTimeoutMinutes,
    siemDestination,
    selectedSiem.label,
    selectedRetention.label,
    isProvisioned,
  ]);

  // Earlier steps with unresolved issues surfaced on Step 5 Review
  const outstandingSteps = useMemo(
    () =>
      STEPS.map((meta, index) => ({
        ...meta,
        index,
        issues: Object.values(errorsByStep[index]).filter((msg): msg is string =>
          Boolean(msg),
        ),
      })).filter((item) => item.index < STEPS.length - 1 && item.issues.length > 0),
    [errorsByStep],
  );

  const markDirty = useCallback(() => {
    setHasUnsavedEdits(true);
  }, []);

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

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

  const collectValues = useCallback((): FormWizardVerticalValues => {
    return {
      organizationName: organizationName.trim(),
      workspaceSlug: normalizedSlug,
      residencyRegion,
      primaryAdminEmail: primaryAdminEmail.trim(),
      protocol,
      idpVendor,
      entityOrDiscoveryUrl: entityOrDiscoveryUrl.trim(),
      oidcClientId: oidcClientId.trim(),
      scimEndpointUrl: scimEndpointUrl.trim(),
      autoDeprovision,
      enforceSso,
      breakGlassEmail: breakGlassEmail.trim(),
      defaultRole,
      groupRules: [...groupRules],
      sessionTimeoutMinutes,
      requireHardwareMfa,
      allowPlatformPasskeys,
      siemDestination,
      siemEndpointUrl: siemEndpointUrl.trim(),
      alertChannels: [...alertChannels],
      alertEndpointUrl: alertEndpointUrl.trim(),
      logRetention,
      confirmedProvisioning,
    };
  }, [
    organizationName,
    normalizedSlug,
    residencyRegion,
    primaryAdminEmail,
    protocol,
    idpVendor,
    entityOrDiscoveryUrl,
    oidcClientId,
    scimEndpointUrl,
    autoDeprovision,
    enforceSso,
    breakGlassEmail,
    defaultRole,
    groupRules,
    sessionTimeoutMinutes,
    requireHardwareMfa,
    allowPlatformPasskeys,
    siemDestination,
    siemEndpointUrl,
    alertChannels,
    alertEndpointUrl,
    logRetention,
    confirmedProvisioning,
  ]);

  const handleSaveDraft = () => {
    const snapshot = collectValues();
    setSavedAtLabel(formatClock(new Date()));
    setHasUnsavedEdits(false);
    onSaveDraft?.(snapshot);
    queue.info("Draft saved locally", {
      description: `Saved progress on ${STEPS[step].label} for ${
        snapshot.organizationName || "Boreal workspace"
      }.`,
    });
  };

  const canJumpToStep = useCallback(
    (targetIndex: number) => {
      if (isProvisioned) return false;
      if (targetIndex === step) return true;
      if (visited.has(targetIndex) || attempted.has(targetIndex)) return true;
      if (targetIndex === step + 1) return true;
      return false;
    },
    [isProvisioned, step, visited, attempted],
  );

  const goToStep = (targetIndex: number) => {
    if (!canJumpToStep(targetIndex) || targetIndex === step) return;
    if (targetIndex > step) {
      markAttempted(step);
    }
    markVisited(targetIndex);
    setStep(targetIndex);
  };

  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);
        markVisited(firstBrokenStep);
        pendingFocusFieldRef.current = brokenKeys[0] ?? null;
        setStep(firstBrokenStep);
        return;
      }

      const values = collectValues();
      const tenantId = buildTenantId(values.workspaceSlug);
      const portalUrl = `https://${portalDomain}/${values.workspaceSlug}`;
      const payload: FormWizardVerticalProvisionPayload = {
        tenantId,
        portalUrl,
        callbackUrl,
        provisionedAt: new Date().toISOString(),
        values,
      };

      setProvisionPayload(payload);
      setIsProvisioned(true);
      setHasUnsavedEdits(false);
      setSavedAtLabel(formatClock(new Date()));
      onProvision?.(payload);
      queue.success("Workspace provisioned", {
        description: `${values.organizationName} is live in ${selectedRegion.label} with ${selectedProtocol.label}.`,
      });
      return;
    }

    const nextIndex = Math.min(STEPS.length - 1, step + 1);
    markVisited(nextIndex);
    setStep(nextIndex);
  };

  const handleResetWizard = () => {
    setIsProvisioned(false);
    setProvisionPayload(null);
    setStep(0);
    setVisited(new Set([0]));
    setAttempted(new Set());
    setSlugTouched(Boolean(initialValues?.workspaceSlug));
    setOrganizationName(mergedInitial.organizationName);
    setWorkspaceSlug(mergedInitial.workspaceSlug);
    setResidencyRegion(mergedInitial.residencyRegion);
    setPrimaryAdminEmail(mergedInitial.primaryAdminEmail);
    setProtocol(mergedInitial.protocol);
    setIdpVendor(mergedInitial.idpVendor);
    setEntityOrDiscoveryUrl(mergedInitial.entityOrDiscoveryUrl);
    setOidcClientId(mergedInitial.oidcClientId);
    setScimEndpointUrl(mergedInitial.scimEndpointUrl);
    setAutoDeprovision(mergedInitial.autoDeprovision);
    setEnforceSso(mergedInitial.enforceSso);
    setBreakGlassEmail(mergedInitial.breakGlassEmail);
    setDefaultRole(mergedInitial.defaultRole);
    setGroupRules([...mergedInitial.groupRules]);
    setSessionTimeoutMinutes(mergedInitial.sessionTimeoutMinutes);
    setRequireHardwareMfa(mergedInitial.requireHardwareMfa);
    setAllowPlatformPasskeys(mergedInitial.allowPlatformPasskeys);
    setSiemDestination(mergedInitial.siemDestination);
    setSiemEndpointUrl(mergedInitial.siemEndpointUrl);
    setAlertChannels([...mergedInitial.alertChannels]);
    setAlertEndpointUrl(mergedInitial.alertEndpointUrl);
    setLogRetention(mergedInitial.logRetention);
    setConfirmedProvisioning(false);
    setHasUnsavedEdits(false);
    setSavedAtLabel(formatClock(new Date()));
  };

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

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

  const handleProtocolChange = (nextValue: string) => {
    if (nextValue !== "saml" && nextValue !== "oidc" && nextValue !== "scim-saml") {
      return;
    }
    setProtocol(nextValue);
    if (
      nextValue === "oidc" &&
      entityOrDiscoveryUrl.includes("/sso/saml/metadata")
    ) {
      setEntityOrDiscoveryUrl(
        "https://kestrel.okta.com/.well-known/openid-configuration",
      );
    } else if (
      nextValue !== "oidc" &&
      entityOrDiscoveryUrl.includes("/.well-known/openid-configuration")
    ) {
      setEntityOrDiscoveryUrl(
        "https://kestrel.okta.com/app/exk92a8b1c3d/sso/saml/metadata",
      );
    }
    markDirty();
  };

  const handleToggleGroupRule = (ruleId: GroupRuleId, checked: boolean) => {
    setGroupRules((prev) => {
      if (checked) {
        return prev.includes(ruleId) ? prev : [...prev, ruleId];
      }
      return prev.filter((item) => item !== ruleId);
    });
    markDirty();
  };

  const handleSiemDestinationChange = (nextValue: string | null) => {
    if (
      nextValue === "datadog" ||
      nextValue === "splunk" ||
      nextValue === "sentinel" ||
      nextValue === "chronicle" ||
      nextValue === "s3" ||
      nextValue === "none"
    ) {
      setSiemDestination(nextValue);
      const nextPreset = SIEM_DESTINATIONS.find((item) => item.value === nextValue);
      if (nextPreset && nextValue !== "none") {
        setSiemEndpointUrl(nextPreset.endpointPlaceholder);
      }
      markDirty();
    }
  };

  const activeStepStatus = stepStatuses[step];

  return (
    <VStack gap="0" palette={palette} style={[styles.root, style]}>
      {/* Sticky header bar + compact container-collapsed step bar */}
      <header {...stylex.props(styles.header)}>
        <VStack gap="3" style={styles.headerInner}>
          <HStack justify="between" wrap="wrap" gap="3">
            <HStack wrap="wrap" gap="2.5">
              <Square render={<span />} size="sm" style={styles.brandEmblem}>
                <ShieldEmblemIcon />
              </Square>
              <HStack wrap="wrap" gap="2">
                <Heading render={<h1 />} size="lg" style={styles.headingReset}>
                  {isProvisioned ? "Workspace provisioned" : title}
                </Heading>
                <Badge
                  variant="subtle"
                  size="sm"
                  palette={isProvisioned ? greenPalette : accentPalette}
                >
                  {isProvisioned ? "Provisioned" : suiteName}
                </Badge>
              </HStack>
            </HStack>

            <HStack wrap="wrap" gap="3">
              {!isProvisioned ? (
                <Status.Root
                  size="sm"
                  palette={hasUnsavedEdits ? amberPalette : greenPalette}
                >
                  <Status.Indicator />
                  <Text
                    render={<span />}
                    size="xs"
                    tone="muted"
                    style={styles.nowrap}
                  >
                    {hasUnsavedEdits
                      ? "Unsaved edits"
                      : `Draft saved · ${savedAtLabel}`}
                  </Text>
                </Status.Root>
              ) : (
                <Status.Root size="sm" palette={greenPalette}>
                  <Status.Indicator />
                  <Text
                    render={<span />}
                    size="xs"
                    tone="muted"
                    style={styles.nowrap}
                  >
                    Live · {selectedRegion.datacenter}
                  </Text>
                </Status.Root>
              )}
              <Button variant="ghost" size="sm" onClick={handleResetWizard}>
                Reset
              </Button>
            </HStack>
          </HStack>

          {/* Narrow container compact top step selector */}
          {!isProvisioned ? (
            <div
              {...stylex.props(styles.compactBar)}
              aria-label="Compact provisioning step selector"
            >
              <HStack justify="between" gap="2">
                <Text render={<span />} size="xs" weight="semibold">
                  Step {step + 1} of {STEPS.length} · {STEPS[step].label}
                </Text>
                <Text render={<span />} size="xs" tone="muted" tabular="true">
                  {completionPercent}% complete
                </Text>
              </HStack>

              <Progress.Root
                value={completionPercent}
                min={0}
                max={100}
                variant="subtle"
                size="xs"
                shape="full"
                palette={attentionCount > 0 ? redPalette : accentPalette}
              >
                <Progress.Track>
                  <Progress.Range />
                </Progress.Track>
              </Progress.Root>

              <ol {...stylex.props(styles.compactStepChips)}>
                {STEPS.map((meta, index) => {
                  const status = stepStatuses[index];
                  const clickable = canJumpToStep(index);
                  return (
                    <li key={meta.id} {...stylex.props(styles.compactChipItem)}>
                      <button
                        type="button"
                        disabled={!clickable}
                        aria-current={index === step ? "step" : undefined}
                        onClick={() => goToStep(index)}
                        {...stylex.props(
                          styles.compactChipButton,
                          index === step && styles.compactChipActive,
                          status === "needs-attention" && styles.compactChipError,
                          status === "completed" &&
                            index !== step &&
                            styles.compactChipDone,
                        )}
                      >
                        {status === "completed" ? (
                          <CheckIcon />
                        ) : status === "needs-attention" ? (
                          <AlertTriangleIcon />
                        ) : (
                          <span>{index + 1}.</span>
                        )}
                        <span>{meta.shortLabel}</span>
                      </button>
                    </li>
                  );
                })}
              </ol>
            </div>
          ) : null}
        </VStack>
      </header>

      {/* Two-column body: persistent vertical stepper rail + focused right form */}
      <Grid gap="0" style={styles.workspaceGrid}>
        <aside
          aria-label="Provisioning steps"
          {...stylex.props(styles.rail)}
        >
          <VStack gap="5" style={styles.railStickyInner}>
            <VStack gap="2">
              <HStack align="baseline" justify="between" gap="2">
                <Text render={<span />} variant="overline" tone="default">
                  Setup Progress
                </Text>
                <Text
                  render={<span />}
                  size="xs"
                  tone="muted"
                  weight="medium"
                  tabular="true"
                >
                  {completedCount}/{STEPS.length} · {completionPercent}%
                </Text>
              </HStack>
              <Progress.Root
                value={completionPercent}
                min={0}
                max={100}
                variant="subtle"
                size="sm"
                shape="full"
                palette={
                  isProvisioned
                    ? greenPalette
                    : attentionCount > 0
                      ? redPalette
                      : accentPalette
                }
              >
                <Progress.Track>
                  <Progress.Range />
                </Progress.Track>
              </Progress.Root>
              <Text
                size="xs"
                tone={attentionCount > 0 ? "error" : "muted"}
                weight={attentionCount > 0 ? "medium" : "inherit"}
              >
                {isProvisioned
                  ? "All 5 provisioning stages verified and live."
                  : attentionCount > 0
                    ? `${attentionCount} ${
                        attentionCount === 1 ? "step requires" : "steps require"
                      } attention before launch.`
                    : `${STEPS.length - completedCount} ${
                        STEPS.length - completedCount === 1 ? "step" : "steps"
                      } remaining to provision.`}
              </Text>
            </VStack>

            <nav aria-label="Wizard navigation">
              <VStack render={<ol />} gap="1.5" style={styles.listReset}>
                {STEPS.map((meta, index) => {
                  const status = stepStatuses[index];
                  const isActive = !isProvisioned && index === step;
                  const isLast = index === STEPS.length - 1;
                  const clickable = canJumpToStep(index);

                  return (
                    <li key={meta.id} {...stylex.props(styles.railStepLi)}>
                      <button
                        type="button"
                        disabled={!clickable}
                        aria-current={isActive ? "step" : undefined}
                        onClick={() => goToStep(index)}
                        {...stylex.props(
                          styles.railStepButton,
                          isActive && styles.railStepButtonActive,
                          status === "needs-attention" &&
                            styles.railStepButtonError,
                        )}
                      >
                        <VStack
                          render={<span />}
                          align="center"
                          gap="0"
                          style={styles.railTimelineCol}
                        >
                          <Circle
                            render={<span />}
                            style={[
                              styles.railIndicatorCircle,
                              status === "in-progress" &&
                                styles.railIndicatorActive,
                              status === "completed" &&
                                styles.railIndicatorCompleted,
                              status === "needs-attention" &&
                                styles.railIndicatorError,
                            ]}
                          >
                            {status === "completed" ? (
                              <CheckIcon />
                            ) : status === "needs-attention" ? (
                              <AlertTriangleIcon />
                            ) : (
                              index + 1
                            )}
                          </Circle>
                          {!isLast ? (
                            <span
                              aria-hidden="true"
                              {...stylex.props(
                                styles.railConnector,
                                status === "completed" &&
                                  styles.railConnectorCompleted,
                                status === "needs-attention" &&
                                  styles.railConnectorError,
                              )}
                            />
                          ) : null}
                        </VStack>

                        <VStack
                          render={<span />}
                          gap="1"
                          style={styles.railStepCopy}
                        >
                          <HStack render={<span />} justify="between" gap="2">
                            <Text
                              render={<span />}
                              size="sm"
                              truncate="true"
                              weight={
                                status === "upcoming" ? "medium" : "semibold"
                              }
                              tone={
                                status === "upcoming" ? "muted" : "default"
                              }
                            >
                              {meta.label}
                            </Text>
                          </HStack>
                          <Text
                            render={<span />}
                            size="xs"
                            truncate="true"
                            tone={
                              status === "needs-attention" ? "error" : "muted"
                            }
                            weight={
                              status === "needs-attention"
                                ? "medium"
                                : "inherit"
                            }
                          >
                            {stepSummaries[index]}
                          </Text>
                          <HStack
                            render={<span />}
                            gap="1.5"
                            style={styles.railStepStatusRow}
                          >
                            <Status.Root
                              size="sm"
                              palette={statusPaletteFor(status)}
                            >
                              <Status.Indicator />
                              <Text
                                render={<span />}
                                size="2xs"
                                weight="medium"
                                tone={
                                  status === "in-progress"
                                    ? "accent"
                                    : status === "completed"
                                      ? "success"
                                      : status === "needs-attention"
                                        ? "error"
                                        : "subtle"
                                }
                              >
                                {statusLabelFor(status)}
                              </Text>
                            </Status.Root>
                          </HStack>
                        </VStack>
                      </button>
                    </li>
                  );
                })}
              </VStack>
            </nav>

            <VStack gap="2.5" style={styles.railFooterBox}>
              <HStack render={<span />} gap="1.5" style={styles.mutedColor}>
                <LockIcon />
                <Text render={<span />} size="xs" tone="muted" weight="medium">
                  Active Security Posture
                </Text>
              </HStack>
              <HStack wrap="wrap" gap="1.5">
                <Badge variant="subtle" size="xs" palette={accentPalette}>
                  {selectedRegion.shortLabel}
                </Badge>
                <Badge variant="subtle" size="xs" palette={grayPalette}>
                  {selectedProtocol.label}
                </Badge>
                <Badge
                  variant="subtle"
                  size="xs"
                  palette={requireHardwareMfa ? greenPalette : amberPalette}
                >
                  {requireHardwareMfa ? "FIDO2 MFA" : "MFA Optional"}
                </Badge>
                <Badge variant="subtle" size="xs" palette={grayPalette}>
                  {selectedRetention.label}
                </Badge>
              </HStack>
            </VStack>
          </VStack>
        </aside>

        {/* Right-hand focused form column */}
        <VStack render={<main />} gap="0" style={styles.fullWidth}>
          <VStack gap="6" style={styles.mainInner}>
            {/* Provisioned Confirmation Screen */}
            {isProvisioned && provisionPayload ? (
              <VStack
                render={
                  <section aria-label="Provisioned workspace confirmation" />
                }
                gap="6"
                style={styles.fullWidth}
              >
                <Alert.Root
                  status="success"
                  variant="subtle"
                  size="md"
                  palette={greenPalette}
                >
                  <Alert.Indicator>
                    <CheckCircleIcon />
                  </Alert.Indicator>
                  <Alert.Content>
                    <Alert.Title>
                      {provisionPayload.values.organizationName} is provisioned in{" "}
                      {selectedRegion.label}
                    </Alert.Title>
                    <Alert.Description>
                      Tenant{" "}
                      <Text
                        render={<strong />}
                        variant="mono"
                        size="xs"
                        style={styles.breakWord}
                      >
                        {provisionPayload.tenantId}
                      </Text>{" "}
                      is active with {selectedProtocol.label} federation via{" "}
                      {selectedVendor.label}. Demo state is stored locally with no
                      external API requests.
                    </Alert.Description>
                  </Alert.Content>
                </Alert.Root>

                <VStack gap="1.5">
                  <Heading render={<h2 />} size="2xl" style={styles.headingReset}>
                    Enterprise SSO tenant ready
                  </Heading>
                  <Text variant="muted" size="sm">
                    Share the Service Provider callback URL with your identity
                    team, download the signed XML metadata, or launch the Boreal
                    security console.
                  </Text>
                </VStack>

                <Card.Root variant="outline" size="md">
                  <Card.Header style={styles.reviewCardHeader}>
                    <HStack wrap="wrap" gap="2">
                      <Card.Title>Provisioned tenant summary</Card.Title>
                      <Badge variant="subtle" size="xs" palette={greenPalette}>
                        Active
                      </Badge>
                    </HStack>
                  </Card.Header>
                  <Card.Body style={styles.reviewCardBody}>
                    <DataList.Root
                      orientation="horizontal"
                      variant="subtle"
                      size="md"
                    >
                      <DataList.Item style={styles.reviewDataItem}>
                        <DataList.ItemLabel style={styles.reviewDataLabel}>
                          Tenant ID
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          <Text
                            render={<span />}
                            variant="mono"
                            size="xs"
                            style={styles.breakWord}
                          >
                            {provisionPayload.tenantId}
                          </Text>
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item style={styles.reviewDataItem}>
                        <DataList.ItemLabel style={styles.reviewDataLabel}>
                          Workspace URL
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          <Text
                            render={<span />}
                            variant="mono"
                            size="xs"
                            style={styles.breakWord}
                          >
                            {provisionPayload.portalUrl}
                          </Text>
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item style={styles.reviewDataItem}>
                        <DataList.ItemLabel style={styles.reviewDataLabel}>
                          {protocol === "oidc" ? "Redirect URI" : "ACS Callback URL"}
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          <Text
                            render={<span />}
                            variant="mono"
                            size="xs"
                            style={styles.breakWord}
                          >
                            {provisionPayload.callbackUrl}
                          </Text>
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item style={styles.reviewDataItem}>
                        <DataList.ItemLabel style={styles.reviewDataLabel}>
                          Data residency
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {selectedRegion.label} ({selectedRegion.datacenter}) ·{" "}
                          {selectedRegion.compliance}
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item style={styles.reviewDataItem}>
                        <DataList.ItemLabel style={styles.reviewDataLabel}>
                          Identity provider
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {selectedProtocol.label} · {selectedVendor.label}
                          {enforceSso ? " · Strict SSO enforced" : " · Mixed auth"}
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item style={styles.reviewDataItem}>
                        <DataList.ItemLabel style={styles.reviewDataLabel}>
                          Access &amp; MFA
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {groupRules.length} mapped{" "}
                          {groupRules.length === 1 ? "group" : "groups"} ·{" "}
                          {sessionTimeoutMinutes} min timeout ·{" "}
                          {requireHardwareMfa
                            ? "Hardware MFA required"
                            : "Standard MFA"}
                        </DataList.ItemValue>
                      </DataList.Item>
                      <DataList.Item style={styles.reviewDataItem}>
                        <DataList.ItemLabel style={styles.reviewDataLabel}>
                          Audit &amp; retention
                        </DataList.ItemLabel>
                        <DataList.ItemValue>
                          {selectedSiem.label} · {selectedRetention.label} retention
                        </DataList.ItemValue>
                      </DataList.Item>
                    </DataList.Root>
                  </Card.Body>
                </Card.Root>

                <HStack wrap="wrap" gap="3">
                  <Button
                    variant="solid"
                    palette={accentPalette}
                    onClick={() =>
                      queue.success("IdP metadata XML downloaded", {
                        description: `boreal-${provisionPayload.values.workspaceSlug}-sp-metadata.xml is ready for ${selectedVendor.label}.`,
                      })
                    }
                  >
                    <DownloadIcon />
                    Download SP metadata XML
                  </Button>
                  <Button
                    variant="surface"
                    onClick={() =>
                      queue.info("Opening Boreal Security Console", {
                        description: `Routing to ${provisionPayload.portalUrl}`,
                      })
                    }
                  >
                    Open security console
                  </Button>
                  <Button variant="ghost" onClick={handleResetWizard}>
                    Configure another workspace
                  </Button>
                </HStack>
              </VStack>
            ) : null}

            {/* Step 1 — Workspace Identity */}
            {!isProvisioned && step === 0 ? (
              <VStack
                render={<section aria-label="Step 1: Workspace Identity" />}
                gap="6"
                style={styles.fullWidth}
              >
                <VStack gap="1.5">
                  <HStack wrap="wrap" gap="2.5">
                    <Text
                      render={<span />}
                      variant="overline"
                      tone="subtle"
                      tabular="true"
                    >
                      Step 1 of {STEPS.length}
                    </Text>
                    <Status.Root
                      size="sm"
                      palette={statusPaletteFor(activeStepStatus)}
                    >
                      <Status.Indicator />
                      <span>{statusLabelFor(activeStepStatus)}</span>
                    </Status.Root>
                  </HStack>
                  <Heading render={<h2 />} size="2xl" style={styles.headingReset}>
                    {STEPS[0].label}
                  </Heading>
                  <Text variant="muted" size="sm">
                    {STEPS[0].description}
                  </Text>
                </VStack>

                <VStack gap="6" style={styles.fullWidth}>
                  <Fieldset.Root size="md">
                    <Fieldset.Legend>Organization &amp; tenant identity</Fieldset.Legend>
                    <Fieldset.HelperText>
                      Used to generate your tenant subdomain, SAML Entity ID, and
                      primary break-glass ownership record.
                    </Fieldset.HelperText>
                    <Fieldset.Content>
                      <Field.Root
                        required
                        invalid={Boolean(currentErrors.organizationName)}
                      >
                        <Field.Label>
                          Organization name
                          <Field.RequiredIndicator />
                        </Field.Label>
                        <Input
                          ref={organizationNameRef}
                          value={organizationName}
                          onValueChange={handleOrganizationChange}
                          placeholder="Kestrel Financial Holdings"
                          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 slug
                          <Field.RequiredIndicator />
                        </Field.Label>
                        <InputGroup.Root variant="outline" size="md">
                          <InputGroup.Addon>{portalDomain}/</InputGroup.Addon>
                          <InputGroup.Input
                            id={slugInputId}
                            ref={workspaceSlugRef}
                            value={workspaceSlug}
                            onChange={(event) =>
                              handleSlugChange(event.currentTarget.value)
                            }
                            placeholder="kestrel-financial"
                            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.successColor}
                          >
                            <CheckCircleIcon />
                            <Text
                              render={<span />}
                              size="xs"
                              weight="medium"
                              tone="success"
                            >
                              https://{portalDomain}/{normalizedSlug} is available.
                            </Text>
                          </HStack>
                        ) : (
                          <Field.Description>
                            Lowercase letters, numbers, and hyphens only. Reserved
                            names like &ldquo;admin&rdquo; or &ldquo;sso&rdquo; are
                            unavailable.
                          </Field.Description>
                        )}
                      </Field.Root>

                      <Field.Root
                        required
                        invalid={Boolean(currentErrors.primaryAdminEmail)}
                      >
                        <Field.Label>
                          Primary security admin email
                          <Field.RequiredIndicator />
                        </Field.Label>
                        <Input
                          ref={primaryAdminEmailRef}
                          type="email"
                          value={primaryAdminEmail}
                          onValueChange={(nextValue) => {
                            setPrimaryAdminEmail(nextValue);
                            markDirty();
                          }}
                          placeholder="elena.lindholm@kestrelfin.example"
                          aria-invalid={
                            currentErrors.primaryAdminEmail ? true : undefined
                          }
                        />
                        <Field.Description>
                          Receives tenant activation credentials and root KMS key
                          attestation certificates.
                        </Field.Description>
                        {currentErrors.primaryAdminEmail ? (
                          <Field.Error match={true}>
                            {currentErrors.primaryAdminEmail}
                          </Field.Error>
                        ) : null}
                      </Field.Root>
                    </Fieldset.Content>
                  </Fieldset.Root>

                  <Separator decorative />

                  <Fieldset.Root size="md">
                    <Fieldset.Legend id={residencyGroupLabelId}>
                      Data residency region
                    </Fieldset.Legend>
                    <Fieldset.HelperText>
                      Permanently pins audit logs, identity directory snapshots,
                      and HSM encryption keys to a sovereign jurisdiction.
                    </Fieldset.HelperText>
                    <Fieldset.Content>
                      <RadioCard.Root
                        value={residencyRegion}
                        onValueChange={(nextRegion) => {
                          if (
                            nextRegion === "eu-central" ||
                            nextRegion === "us-east" ||
                            nextRegion === "ca-central"
                          ) {
                            setResidencyRegion(nextRegion);
                            markDirty();
                          }
                        }}
                        variant="outline"
                        size="md"
                        palette={accentPalette}
                        aria-labelledby={residencyGroupLabelId}
                        style={styles.threeColGrid}
                      >
                        {RESIDENCY_REGIONS.map((region) => (
                          <RadioCard.Item
                            key={region.id}
                            value={region.id}
                            style={styles.cardItemStretch}
                          >
                            <RadioCard.ItemControl style={styles.cardControlTop}>
                              <RadioCard.ItemContent
                                style={styles.cardContentStack}
                              >
                                <HStack
                                  justify="between"
                                  gap="2"
                                  style={styles.fullWidth}
                                >
                                  <HStack wrap="wrap" gap="1.5">
                                    <RadioCard.ItemText>
                                      {region.shortLabel}
                                    </RadioCard.ItemText>
                                    {region.recommended ? (
                                      <Badge
                                        variant="subtle"
                                        size="xs"
                                        palette={greenPalette}
                                      >
                                        Sovereign
                                      </Badge>
                                    ) : null}
                                  </HStack>
                                  <RadioCard.ItemIndicator />
                                </HStack>
                                <RadioCard.ItemDescription>
                                  {region.description}
                                </RadioCard.ItemDescription>
                                <HStack
                                  wrap="wrap"
                                  gap="1.5"
                                  style={styles.cardMetaRow}
                                >
                                  <span {...stylex.props(styles.monoCodeInline)}>
                                    {region.datacenter}
                                  </span>
                                  <Badge
                                    variant="surface"
                                    size="xs"
                                    palette={grayPalette}
                                  >
                                    {region.compliance}
                                  </Badge>
                                </HStack>
                              </RadioCard.ItemContent>
                            </RadioCard.ItemControl>
                          </RadioCard.Item>
                        ))}
                      </RadioCard.Root>
                    </Fieldset.Content>
                  </Fieldset.Root>
                </VStack>
              </VStack>
            ) : null}

            {/* Step 2 — Identity Provider */}
            {!isProvisioned && step === 1 ? (
              <VStack
                render={<section aria-label="Step 2: Identity Provider" />}
                gap="6"
                style={styles.fullWidth}
              >
                <VStack gap="1.5">
                  <HStack wrap="wrap" gap="2.5">
                    <Text
                      render={<span />}
                      variant="overline"
                      tone="subtle"
                      tabular="true"
                    >
                      Step 2 of {STEPS.length}
                    </Text>
                    <Status.Root
                      size="sm"
                      palette={statusPaletteFor(activeStepStatus)}
                    >
                      <Status.Indicator />
                      <span>{statusLabelFor(activeStepStatus)}</span>
                    </Status.Root>
                  </HStack>
                  <Heading render={<h2 />} size="2xl" style={styles.headingReset}>
                    {STEPS[1].label}
                  </Heading>
                  <Text variant="muted" size="sm">
                    {STEPS[1].description}
                  </Text>
                </VStack>

                <VStack gap="6" style={styles.fullWidth}>
                  <Fieldset.Root size="md">
                    <Fieldset.Legend>Federation protocol &amp; provider</Fieldset.Legend>
                    <Fieldset.HelperText>
                      Switching protocols adapts the endpoint fields and directory
                      sync requirements below.
                    </Fieldset.HelperText>
                    <Fieldset.Content>
                      <Field.Root>
                        <Field.Label id={protocolGroupLabelId}>
                          Authentication protocol
                        </Field.Label>
                        <div {...stylex.props(styles.segmentWrap)}>
                          <SegmentGroup.Root
                            value={protocol}
                            onValueChange={handleProtocolChange}
                            size="md"
                            aria-labelledby={protocolGroupLabelId}
                          >
                            {PROTOCOLS.map((option) => (
                              <SegmentGroup.Item
                                key={option.value}
                                value={option.value}
                              >
                                {option.label}
                              </SegmentGroup.Item>
                            ))}
                          </SegmentGroup.Root>
                        </div>
                      </Field.Root>

                      <Select.Root
                        items={IDP_VENDORS}
                        value={idpVendor}
                        onValueChange={(nextVendor) => {
                          if (
                            nextVendor === "okta" ||
                            nextVendor === "entra" ||
                            nextVendor === "google" ||
                            nextVendor === "ping" ||
                            nextVendor === "onelogin" ||
                            nextVendor === "custom"
                          ) {
                            setIdpVendor(nextVendor);
                            markDirty();
                          }
                        }}
                        placeholder="Select identity provider"
                        palette={accentPalette}
                      >
                        <Select.Label>Identity provider vendor</Select.Label>
                        <Select.Control>
                          <Select.Trigger>
                            <Select.Value />
                          </Select.Trigger>
                          <Select.IndicatorGroup>
                            <Select.Icon />
                          </Select.IndicatorGroup>
                        </Select.Control>
                        <Select.Content>
                          {IDP_VENDORS.map((vendor) => (
                            <Select.Item key={vendor.value} value={vendor.value}>
                              <Select.ItemText>{vendor.label}</Select.ItemText>
                              <Select.ItemIndicator />
                            </Select.Item>
                          ))}
                        </Select.Content>
                      </Select.Root>
                    </Fieldset.Content>
                  </Fieldset.Root>

                  <Separator decorative />

                  <Fieldset.Root size="md">
                    <Fieldset.Legend>
                      {protocol === "oidc"
                        ? "OpenID Connect endpoints"
                        : protocol === "scim-saml"
                          ? "SAML 2.0 & SCIM directory binding"
                          : "SAML 2.0 metadata configuration"}
                    </Fieldset.Legend>
                    <Fieldset.Content>
                      <Field.Root
                        required
                        invalid={Boolean(currentErrors.entityOrDiscoveryUrl)}
                      >
                        <Field.Label>
                          {protocol === "oidc"
                            ? "OIDC Discovery URL (.well-known)"
                            : "IdP Entity ID / Metadata URL"}
                          <Field.RequiredIndicator />
                        </Field.Label>
                        <Input
                          ref={entityOrDiscoveryUrlRef}
                          type="url"
                          value={entityOrDiscoveryUrl}
                          onValueChange={(nextValue) => {
                            setEntityOrDiscoveryUrl(nextValue);
                            markDirty();
                          }}
                          placeholder={
                            protocol === "oidc"
                              ? "https://idp.company.example/.well-known/openid-configuration"
                              : "https://idp.company.example/sso/saml/metadata"
                          }
                          aria-invalid={
                            currentErrors.entityOrDiscoveryUrl ? true : undefined
                          }
                        />
                        {currentErrors.entityOrDiscoveryUrl ? (
                          <Field.Error match={true}>
                            {currentErrors.entityOrDiscoveryUrl}
                          </Field.Error>
                        ) : (
                          <Field.Description>
                            Boreal refreshes signing certificates automatically
                            every 6 hours from this HTTPS endpoint.
                          </Field.Description>
                        )}
                      </Field.Root>

                      {protocol === "oidc" ? (
                        <Field.Root
                          required
                          invalid={Boolean(currentErrors.oidcClientId)}
                        >
                          <Field.Label>
                            OIDC Client ID
                            <Field.RequiredIndicator />
                          </Field.Label>
                          <Input
                            ref={oidcClientIdRef}
                            value={oidcClientId}
                            onValueChange={(nextValue) => {
                              setOidcClientId(nextValue);
                              markDirty();
                            }}
                            placeholder="0oa8f3k2m9p4q7r1s5t6"
                            aria-invalid={
                              currentErrors.oidcClientId ? true : undefined
                            }
                          />
                          {currentErrors.oidcClientId ? (
                            <Field.Error match={true}>
                              {currentErrors.oidcClientId}
                            </Field.Error>
                          ) : null}
                        </Field.Root>
                      ) : null}

                      {protocol === "scim-saml" ? (
                        <VStack gap="4" style={styles.conditionalIndent}>
                          <Field.Root
                            required
                            invalid={Boolean(currentErrors.scimEndpointUrl)}
                          >
                            <Field.Label>
                              SCIM 2.0 Directory Endpoint
                              <Field.RequiredIndicator />
                            </Field.Label>
                            <Input
                              ref={scimEndpointUrlRef}
                              type="url"
                              value={scimEndpointUrl}
                              onValueChange={(nextValue) => {
                                setScimEndpointUrl(nextValue);
                                markDirty();
                              }}
                              placeholder="https://kestrel.okta.com/scim/v2"
                              aria-invalid={
                                currentErrors.scimEndpointUrl ? true : undefined
                              }
                            />
                            {currentErrors.scimEndpointUrl ? (
                              <Field.Error match={true}>
                                {currentErrors.scimEndpointUrl}
                              </Field.Error>
                            ) : (
                              <Field.Description>
                                A scoped SCIM bearer token will be generated once
                                provisioning completes.
                              </Field.Description>
                            )}
                          </Field.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">
                                Auto-deprovision suspended directory users
                              </Text>
                              <Text render={<span />} size="xs" tone="muted">
                                Revoke active API tokens and console sessions
                                within 30 seconds of IdP suspension.
                              </Text>
                            </VStack>
                            <Switch.Control
                              checked={autoDeprovision}
                              onCheckedChange={(next) => {
                                setAutoDeprovision(next);
                                markDirty();
                              }}
                            />
                          </Switch.Root>
                        </VStack>
                      ) : null}

                      <VStack gap="1" style={styles.callbackBox}>
                        <Text
                          render={<span />}
                          size="xs"
                          tone="muted"
                          weight="medium"
                        >
                          {protocol === "oidc"
                            ? "Generated OIDC Redirect URI (paste into IdP app)"
                            : "Generated SAML ACS Callback URL (paste into IdP app)"}
                        </Text>
                        <Text
                          render={<span />}
                          variant="mono"
                          size="xs"
                          style={styles.breakAll}
                        >
                          {callbackUrl}
                        </Text>
                      </VStack>
                    </Fieldset.Content>
                  </Fieldset.Root>

                  <Separator decorative />

                  <VStack gap="4" style={styles.switchCard}>
                    <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">
                          Enforce SSO for all workspace members
                        </Text>
                        <Text render={<span />} size="xs" tone="muted">
                          Block password authentication after the first verified
                          IdP handshake. Break-glass recovery remains available.
                        </Text>
                      </VStack>
                      <Switch.Control
                        checked={enforceSso}
                        onCheckedChange={(next) => {
                          setEnforceSso(next);
                          markDirty();
                        }}
                      />
                    </Switch.Root>

                    {enforceSso ? (
                      <VStack gap="4" style={styles.conditionalIndent}>
                        <Field.Root
                          required
                          invalid={Boolean(currentErrors.breakGlassEmail)}
                        >
                          <Field.Label>
                            Break-glass recovery email
                            <Field.RequiredIndicator />
                          </Field.Label>
                          <Input
                            ref={breakGlassEmailRef}
                            type="email"
                            value={breakGlassEmail}
                            onValueChange={(nextValue) => {
                              setBreakGlassEmail(nextValue);
                              markDirty();
                            }}
                            placeholder="secops-breakglass@kestrelfin.example"
                            aria-invalid={
                              currentErrors.breakGlassEmail ? true : undefined
                            }
                          />
                          {currentErrors.breakGlassEmail ? (
                            <Field.Error match={true}>
                              {currentErrors.breakGlassEmail}
                            </Field.Error>
                          ) : (
                            <Field.Description>
                              Receives hardware-signed emergency sign-in links if
                              your IdP experiences an outage.
                            </Field.Description>
                          )}
                        </Field.Root>
                      </VStack>
                    ) : null}
                  </VStack>
                </VStack>
              </VStack>
            ) : null}

            {/* Step 3 — Access & Role Mapping */}
            {!isProvisioned && step === 2 ? (
              <VStack
                render={<section aria-label="Step 3: Access and Role Mapping" />}
                gap="6"
                style={styles.fullWidth}
              >
                <VStack gap="1.5">
                  <HStack wrap="wrap" gap="2.5">
                    <Text
                      render={<span />}
                      variant="overline"
                      tone="subtle"
                      tabular="true"
                    >
                      Step 3 of {STEPS.length}
                    </Text>
                    <Status.Root
                      size="sm"
                      palette={statusPaletteFor(activeStepStatus)}
                    >
                      <Status.Indicator />
                      <span>{statusLabelFor(activeStepStatus)}</span>
                    </Status.Root>
                  </HStack>
                  <Heading render={<h2 />} size="2xl" style={styles.headingReset}>
                    {STEPS[2].label}
                  </Heading>
                  <Text variant="muted" size="sm">
                    {STEPS[2].description}
                  </Text>
                </VStack>

                <VStack gap="6" style={styles.fullWidth}>
                  <Fieldset.Root size="md">
                    <Fieldset.Legend>Default role &amp; session lifetime</Fieldset.Legend>
                    <Fieldset.Content>
                      <Grid columns="2" gap="4" style={styles.twoColGrid}>
                        <Select.Root
                          items={DEFAULT_ROLES}
                          value={defaultRole}
                          onValueChange={(nextRole) => {
                            if (
                              nextRole === "viewer" ||
                              nextRole === "analyst" ||
                              nextRole === "operator" ||
                              nextRole === "admin"
                            ) {
                              setDefaultRole(nextRole);
                              markDirty();
                            }
                          }}
                          placeholder="Choose fallback role"
                          palette={accentPalette}
                        >
                          <Select.Label>Default member role</Select.Label>
                          <Select.Control>
                            <Select.Trigger>
                              <Select.Value />
                            </Select.Trigger>
                            <Select.IndicatorGroup>
                              <Select.Icon />
                            </Select.IndicatorGroup>
                          </Select.Control>
                          <Select.Content>
                            {DEFAULT_ROLES.map((role) => (
                              <Select.Item key={role.value} value={role.value}>
                                <Select.ItemText>{role.label}</Select.ItemText>
                                <Select.ItemIndicator />
                              </Select.Item>
                            ))}
                          </Select.Content>
                        </Select.Root>

                        <Field.Root
                          required
                          invalid={Boolean(currentErrors.sessionTimeoutMinutes)}
                        >
                          <Field.Label>
                            Session idle timeout (minutes)
                            <Field.RequiredIndicator />
                          </Field.Label>
                          <NumberInput.Root
                            value={sessionTimeoutMinutes}
                            onValueChange={(nextVal) => {
                              setSessionTimeoutMinutes(nextVal ?? 0);
                              markDirty();
                            }}
                            min={15}
                            max={480}
                            step={15}
                            palette={accentPalette}
                            style={styles.timeoutInputRoot}
                          >
                            <NumberInput.Group>
                              <NumberInput.Input
                                ref={sessionTimeoutRef}
                                aria-label="Session idle timeout in minutes"
                                aria-invalid={
                                  currentErrors.sessionTimeoutMinutes
                                    ? true
                                    : undefined
                                }
                              />
                              <NumberInput.Control />
                            </NumberInput.Group>
                          </NumberInput.Root>
                          {currentErrors.sessionTimeoutMinutes ? (
                            <Field.Error match={true}>
                              {currentErrors.sessionTimeoutMinutes}
                            </Field.Error>
                          ) : (
                            <Field.Description>
                              Range: 15 to 480 minutes.
                            </Field.Description>
                          )}
                        </Field.Root>
                      </Grid>
                    </Fieldset.Content>
                  </Fieldset.Root>

                  <Separator decorative />

                  <Fieldset.Root size="md">
                    <Fieldset.Legend>Group-to-role mapping rules</Fieldset.Legend>
                    <Fieldset.HelperText>
                      {protocol === "scim-saml"
                        ? "SCIM + SAML is active: select at least one IdP group rule to synchronize automatically."
                        : "Select the IdP group claims that map directly to Boreal workspace roles."}
                    </Fieldset.HelperText>
                    <Fieldset.Content>
                      <Grid columns="2" gap="3" style={styles.cardGridTwo}>
                        {GROUP_ROLE_RULES.map((rule) => {
                          const isChecked = groupRules.includes(rule.id);
                          return (
                            <CheckboxCard.Root
                              key={rule.id}
                              checked={isChecked}
                              onCheckedChange={(next) =>
                                handleToggleGroupRule(rule.id, next === true)
                              }
                              variant="outline"
                              size="md"
                              palette={accentPalette}
                              style={styles.cardItemStretch}
                            >
                              <CheckboxCard.Control style={styles.cardControlTop}>
                                <CheckboxCard.Content
                                  style={styles.cardContentStack}
                                >
                                  <HStack
                                    justify="between"
                                    gap="2"
                                    style={styles.fullWidth}
                                  >
                                    <span {...stylex.props(styles.monoCodeInline)}>
                                      {rule.groupName}
                                    </span>
                                    <CheckboxCard.Indicator />
                                  </HStack>
                                  <CheckboxCard.Label>
                                    {rule.mappedRole}
                                  </CheckboxCard.Label>
                                  <CheckboxCard.Description>
                                    {rule.description}
                                  </CheckboxCard.Description>
                                </CheckboxCard.Content>
                              </CheckboxCard.Control>
                            </CheckboxCard.Root>
                          );
                        })}
                      </Grid>
                    </Fieldset.Content>
                    {currentErrors.groupRules ? (
                      <Fieldset.ErrorText>
                        {currentErrors.groupRules}
                      </Fieldset.ErrorText>
                    ) : null}
                  </Fieldset.Root>

                  <Separator decorative />

                  <VStack gap="4" style={styles.switchCard}>
                    <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 MFA (FIDO2 / WebAuthn)
                        </Text>
                        <Text render={<span />} size="xs" tone="muted">
                          Require phishing-resistant cryptographic authentication
                          for all privileged security actions and vault unlocks.
                        </Text>
                      </VStack>
                      <Switch.Control
                        checked={requireHardwareMfa}
                        onCheckedChange={(next) => {
                          setRequireHardwareMfa(next);
                          markDirty();
                        }}
                      />
                    </Switch.Root>

                    {requireHardwareMfa ? (
                      <VStack gap="4" style={styles.conditionalIndent}>
                        <Checkbox.Root
                          size="md"
                          palette={accentPalette}
                          style={styles.checkboxRow}
                        >
                          <Checkbox.Control
                            checked={allowPlatformPasskeys}
                            onCheckedChange={(next) => {
                              setAllowPlatformPasskeys(next === true);
                              markDirty();
                            }}
                            style={styles.checkboxControlOffset}
                          />
                          <VStack render={<span />} gap="0.5">
                            <Checkbox.Label>
                              Allow platform passkeys (Touch ID / Windows Hello)
                            </Checkbox.Label>
                            <Text
                              render={<span />}
                              size="xs"
                              tone="muted"
                              weight="normal"
                            >
                              Uncheck to restrict enrollment strictly to roaming
                              USB / NFC security keys (e.g., YubiKey FIPS).
                            </Text>
                          </VStack>
                        </Checkbox.Root>
                      </VStack>
                    ) : null}
                  </VStack>
                </VStack>
              </VStack>
            ) : null}

            {/* Step 4 — Audit & Notifications */}
            {!isProvisioned && step === 3 ? (
              <VStack
                render={<section aria-label="Step 4: Audit and Notifications" />}
                gap="6"
                style={styles.fullWidth}
              >
                <VStack gap="1.5">
                  <HStack wrap="wrap" gap="2.5">
                    <Text
                      render={<span />}
                      variant="overline"
                      tone="subtle"
                      tabular="true"
                    >
                      Step 4 of {STEPS.length}
                    </Text>
                    <Status.Root
                      size="sm"
                      palette={statusPaletteFor(activeStepStatus)}
                    >
                      <Status.Indicator />
                      <span>{statusLabelFor(activeStepStatus)}</span>
                    </Status.Root>
                  </HStack>
                  <Heading render={<h2 />} size="2xl" style={styles.headingReset}>
                    {STEPS[3].label}
                  </Heading>
                  <Text variant="muted" size="sm">
                    {STEPS[3].description}
                  </Text>
                </VStack>

                <VStack gap="6" style={styles.fullWidth}>
                  <Fieldset.Root size="md">
                    <Fieldset.Legend>SIEM event streaming</Fieldset.Legend>
                    <Fieldset.HelperText>
                      Export authentication events, policy changes, and secret
                      reads from {selectedRegion.label} ({selectedRegion.datacenter}).
                    </Fieldset.HelperText>
                    <Fieldset.Content>
                      <Select.Root
                        items={SIEM_DESTINATIONS}
                        value={siemDestination}
                        onValueChange={handleSiemDestinationChange}
                        placeholder="Select SIEM target"
                        palette={accentPalette}
                      >
                        <Select.Label>SIEM destination</Select.Label>
                        <Select.Control>
                          <Select.Trigger>
                            <Select.Value />
                          </Select.Trigger>
                          <Select.IndicatorGroup>
                            <Select.Icon />
                          </Select.IndicatorGroup>
                        </Select.Control>
                        <Select.Content>
                          {SIEM_DESTINATIONS.map((dest) => (
                            <Select.Item key={dest.value} value={dest.value}>
                              <Select.ItemText>{dest.label}</Select.ItemText>
                              <Select.ItemIndicator />
                            </Select.Item>
                          ))}
                        </Select.Content>
                      </Select.Root>

                      {siemDestination !== "none" ? (
                        <VStack gap="4" style={styles.conditionalIndent}>
                          <Field.Root
                            required
                            invalid={Boolean(currentErrors.siemEndpointUrl)}
                          >
                            <Field.Label>
                              SIEM ingestion endpoint URL
                              <Field.RequiredIndicator />
                            </Field.Label>
                            <Input
                              ref={siemEndpointUrlRef}
                              type="url"
                              value={siemEndpointUrl}
                              onValueChange={(nextValue) => {
                                setSiemEndpointUrl(nextValue);
                                markDirty();
                              }}
                              placeholder={selectedSiem.endpointPlaceholder}
                              aria-invalid={
                                currentErrors.siemEndpointUrl ? true : undefined
                              }
                            />
                            {currentErrors.siemEndpointUrl ? (
                              <Field.Error match={true}>
                                {currentErrors.siemEndpointUrl}
                              </Field.Error>
                            ) : (
                              <Field.Description>
                                Events leave {selectedRegion.shortLabel} over TLS
                                1.3 with mutual certificate pinning.
                              </Field.Description>
                            )}
                          </Field.Root>
                        </VStack>
                      ) : null}
                    </Fieldset.Content>
                  </Fieldset.Root>

                  <Separator decorative />

                  <Fieldset.Root size="md">
                    <Fieldset.Legend>Security alert channels</Fieldset.Legend>
                    <Fieldset.HelperText>
                      Select where high-severity SSO failures, break-glass logins,
                      and anomalous token grants are routed.
                    </Fieldset.HelperText>
                    <Fieldset.Content>
                      <CheckboxGroup.Root
                        value={alertChannels}
                        onValueChange={(nextChannels) => {
                          setAlertChannels(nextChannels as AlertChannelId[]);
                          markDirty();
                        }}
                        variant="solid"
                        size="md"
                        orientation="vertical"
                        palette={accentPalette}
                      >
                        {ALERT_CHANNELS.map((channel) => (
                          <CheckboxGroup.Item
                            key={channel.id}
                            style={styles.checkboxRow}
                          >
                            <CheckboxGroup.ItemControl
                              value={channel.id}
                              style={styles.checkboxControlOffset}
                            />
                            <VStack render={<span />} gap="0.5">
                              <CheckboxGroup.ItemLabel>
                                {channel.label}
                              </CheckboxGroup.ItemLabel>
                              <Text
                                render={<span />}
                                size="xs"
                                tone="muted"
                                weight="normal"
                              >
                                {channel.description}
                              </Text>
                            </VStack>
                          </CheckboxGroup.Item>
                        ))}
                      </CheckboxGroup.Root>

                      {needsAlertWebhook ? (
                        <VStack gap="4" style={styles.conditionalIndent}>
                          <Field.Root
                            required={alertChannels.includes("webhook")}
                            invalid={Boolean(currentErrors.alertEndpointUrl)}
                          >
                            <Field.Label>
                              {alertChannels.includes("webhook")
                                ? "Signed webhook destination URL"
                                : "Slack webhook URL"}
                              {alertChannels.includes("webhook") ? (
                                <Field.RequiredIndicator />
                              ) : (
                                <Text
                                  render={<span />}
                                  size="xs"
                                  tone="subtle"
                                  weight="normal"
                                >
                                  Optional
                                </Text>
                              )}
                            </Field.Label>
                            <Input
                              ref={alertEndpointUrlRef}
                              type="url"
                              value={alertEndpointUrl}
                              onValueChange={(nextValue) => {
                                setAlertEndpointUrl(nextValue);
                                markDirty();
                              }}
                              placeholder="https://hooks.slack.example/services/..."
                              aria-invalid={
                                currentErrors.alertEndpointUrl ? true : undefined
                              }
                            />
                            {currentErrors.alertEndpointUrl ? (
                              <Field.Error match={true}>
                                {currentErrors.alertEndpointUrl}
                              </Field.Error>
                            ) : null}
                          </Field.Root>
                        </VStack>
                      ) : null}
                    </Fieldset.Content>
                    {currentErrors.alertChannels ? (
                      <Fieldset.ErrorText>
                        {currentErrors.alertChannels}
                      </Fieldset.ErrorText>
                    ) : null}
                  </Fieldset.Root>

                  <Separator decorative />

                  <Fieldset.Root size="md">
                    <Fieldset.Legend id={retentionGroupLabelId}>
                      Immutable audit log retention
                    </Fieldset.Legend>
                    <Fieldset.Content>
                      <div {...stylex.props(styles.segmentWrap)}>
                        <SegmentGroup.Root
                          value={logRetention}
                          onValueChange={(nextValue) => {
                            if (
                              nextValue === "90d" ||
                              nextValue === "1y" ||
                              nextValue === "3y" ||
                              nextValue === "7y"
                            ) {
                              setLogRetention(nextValue);
                              markDirty();
                            }
                          }}
                          size="md"
                          aria-labelledby={retentionGroupLabelId}
                        >
                          {LOG_RETENTION_OPTIONS.map((option) => (
                            <SegmentGroup.Item
                              key={option.value}
                              value={option.value}
                            >
                              {option.label}
                            </SegmentGroup.Item>
                          ))}
                        </SegmentGroup.Root>
                      </div>
                      <Fieldset.HelperText>
                        {selectedRetention.complianceNote} Stored in{" "}
                        {selectedRegion.label}.
                      </Fieldset.HelperText>
                    </Fieldset.Content>
                  </Fieldset.Root>
                </VStack>
              </VStack>
            ) : null}

            {/* Step 5 — Review & Provision */}
            {!isProvisioned && step === 4 ? (
              <VStack
                render={<section aria-label="Step 5: Review and Provision" />}
                gap="6"
                style={styles.fullWidth}
              >
                <VStack gap="1.5">
                  <HStack wrap="wrap" gap="2.5">
                    <Text
                      render={<span />}
                      variant="overline"
                      tone="subtle"
                      tabular="true"
                    >
                      Step 5 of {STEPS.length}
                    </Text>
                    <Status.Root
                      size="sm"
                      palette={
                        outstandingSteps.length > 0
                          ? redPalette
                          : statusPaletteFor(activeStepStatus)
                      }
                    >
                      <Status.Indicator />
                      <span>
                        {outstandingSteps.length > 0
                          ? "Blocked by issues"
                          : statusLabelFor(activeStepStatus)}
                      </span>
                    </Status.Root>
                  </HStack>
                  <Heading render={<h2 />} size="2xl" style={styles.headingReset}>
                    {STEPS[4].label}
                  </Heading>
                  <Text variant="muted" size="sm">
                    {STEPS[4].description}
                  </Text>
                </VStack>

                {/* Readiness Alert */}
                {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
                          ? "section needs"
                          : "sections need"}{" "}
                        attention before provisioning
                      </Alert.Title>
                      <VStack gap="1.5" style={styles.issuesList}>
                        {outstandingSteps.map((broken) => (
                          <Text key={broken.id} size="xs">
                            <Text render={<span />} size="xs" weight="semibold">
                              {broken.label}:
                            </Text>{" "}
                            {broken.issues.join(" ")}
                          </Text>
                        ))}
                        <HStack
                          wrap="wrap"
                          gap="2"
                          style={styles.issueButtonsRow}
                        >
                          {outstandingSteps.map((broken) => (
                            <Button
                              key={broken.id}
                              variant="surface"
                              size="xs"
                              onClick={() => {
                                markAttempted(broken.index);
                                markVisited(broken.index);
                                const [firstKey] = Object.keys(
                                  errorsByStep[broken.index],
                                ) as ValidatableFieldKey[];
                                pendingFocusFieldRef.current = firstKey ?? null;
                                setStep(broken.index);
                              }}
                            >
                              Fix {broken.shortLabel}
                            </Button>
                          ))}
                        </HStack>
                      </VStack>
                    </Alert.Content>
                  </Alert.Root>
                ) : (
                  <Alert.Root
                    status="success"
                    variant="subtle"
                    size="md"
                    palette={greenPalette}
                  >
                    <Alert.Indicator>
                      <CheckCircleIcon />
                    </Alert.Indicator>
                    <Alert.Content>
                      <Alert.Title>
                        All security controls verified and ready to provision
                      </Alert.Title>
                      <Alert.Description>
                        {selectedRegion.label} residency, {selectedProtocol.label}{" "}
                        federation, {requireHardwareMfa ? "FIDO2 MFA" : "standard MFA"},
                        and {selectedRetention.label} audit retention pass policy
                        validation.
                      </Alert.Description>
                    </Alert.Content>
                  </Alert.Root>
                )}

                {/* Grouped DataList Summary Cards with Edit Jump Links */}
                <VStack gap="4" style={styles.fullWidth}>
                  {/* Section 1: Workspace Identity */}
                  <Card.Root variant="outline" size="md">
                    <Card.Header style={styles.reviewCardHeader}>
                      <HStack wrap="wrap" gap="2">
                        <Card.Title>1. Workspace Identity</Card.Title>
                        {Object.keys(errorsByStep[0]).length > 0 ? (
                          <Badge variant="subtle" size="xs" palette={redPalette}>
                            Needs Attention
                          </Badge>
                        ) : (
                          <Badge variant="subtle" size="xs" palette={greenPalette}>
                            Verified
                          </Badge>
                        )}
                      </HStack>
                      <Button
                        variant="ghost"
                        size="xs"
                        onClick={() => goToStep(0)}
                      >
                        <EditPencilIcon />
                        Edit
                      </Button>
                    </Card.Header>
                    <Card.Body style={styles.reviewCardBody}>
                      <DataList.Root
                        orientation="horizontal"
                        variant="subtle"
                        size="md"
                      >
                        <DataList.Item style={styles.reviewDataItem}>
                          <DataList.ItemLabel style={styles.reviewDataLabel}>
                            Organization
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            {organizationName.trim() || "—"}
                          </DataList.ItemValue>
                        </DataList.Item>
                        <DataList.Item style={styles.reviewDataItem}>
                          <DataList.ItemLabel style={styles.reviewDataLabel}>
                            Tenant URL
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            <Text
                              render={<span />}
                              variant="mono"
                              size="xs"
                              style={styles.breakWord}
                            >
                              https://{portalDomain}/{normalizedSlug || "—"}
                            </Text>
                          </DataList.ItemValue>
                        </DataList.Item>
                        <DataList.Item style={styles.reviewDataItem}>
                          <DataList.ItemLabel style={styles.reviewDataLabel}>
                            Data residency
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            {selectedRegion.label} ({selectedRegion.datacenter})
                          </DataList.ItemValue>
                        </DataList.Item>
                        <DataList.Item style={styles.reviewDataItem}>
                          <DataList.ItemLabel style={styles.reviewDataLabel}>
                            Primary admin
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            {primaryAdminEmail.trim() || "—"}
                          </DataList.ItemValue>
                        </DataList.Item>
                      </DataList.Root>
                    </Card.Body>
                  </Card.Root>

                  {/* Section 2: Identity Provider */}
                  <Card.Root variant="outline" size="md">
                    <Card.Header style={styles.reviewCardHeader}>
                      <HStack wrap="wrap" gap="2">
                        <Card.Title>2. Identity Provider</Card.Title>
                        {Object.keys(errorsByStep[1]).length > 0 ? (
                          <Badge variant="subtle" size="xs" palette={redPalette}>
                            Needs Attention
                          </Badge>
                        ) : (
                          <Badge variant="subtle" size="xs" palette={greenPalette}>
                            Verified
                          </Badge>
                        )}
                      </HStack>
                      <Button
                        variant="ghost"
                        size="xs"
                        onClick={() => goToStep(1)}
                      >
                        <EditPencilIcon />
                        Edit
                      </Button>
                    </Card.Header>
                    <Card.Body style={styles.reviewCardBody}>
                      <DataList.Root
                        orientation="horizontal"
                        variant="subtle"
                        size="md"
                      >
                        <DataList.Item style={styles.reviewDataItem}>
                          <DataList.ItemLabel style={styles.reviewDataLabel}>
                            Protocol &amp; vendor
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            {selectedProtocol.label} · {selectedVendor.label}
                          </DataList.ItemValue>
                        </DataList.Item>
                        <DataList.Item style={styles.reviewDataItem}>
                          <DataList.ItemLabel style={styles.reviewDataLabel}>
                            {protocol === "oidc" ? "Discovery URL" : "Metadata URL"}
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            <Text
                              render={<span />}
                              variant="mono"
                              size="xs"
                              style={styles.breakWord}
                            >
                              {entityOrDiscoveryUrl.trim() || "—"}
                            </Text>
                          </DataList.ItemValue>
                        </DataList.Item>
                        {protocol === "oidc" ? (
                          <DataList.Item style={styles.reviewDataItem}>
                            <DataList.ItemLabel style={styles.reviewDataLabel}>
                              OIDC Client ID
                            </DataList.ItemLabel>
                            <DataList.ItemValue>
                              <Text
                                render={<span />}
                                variant="mono"
                                size="xs"
                                style={styles.breakWord}
                              >
                                {oidcClientId.trim() || "—"}
                              </Text>
                            </DataList.ItemValue>
                          </DataList.Item>
                        ) : null}
                        {protocol === "scim-saml" ? (
                          <DataList.Item style={styles.reviewDataItem}>
                            <DataList.ItemLabel style={styles.reviewDataLabel}>
                              SCIM directory
                            </DataList.ItemLabel>
                            <DataList.ItemValue>
                              <Text
                                render={<span />}
                                variant="mono"
                                size="xs"
                                style={styles.breakWord}
                              >
                                {scimEndpointUrl.trim() || "—"}
                              </Text>
                            </DataList.ItemValue>
                          </DataList.Item>
                        ) : null}
                        <DataList.Item style={styles.reviewDataItem}>
                          <DataList.ItemLabel style={styles.reviewDataLabel}>
                            SSO enforcement
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            {enforceSso
                              ? `Strict SSO (break-glass: ${
                                  breakGlassEmail.trim() || "missing"
                                })`
                              : "Optional (password sign-in allowed)"}
                          </DataList.ItemValue>
                        </DataList.Item>
                      </DataList.Root>
                    </Card.Body>
                  </Card.Root>

                  {/* Section 3: Access & Role Mapping */}
                  <Card.Root variant="outline" size="md">
                    <Card.Header style={styles.reviewCardHeader}>
                      <HStack wrap="wrap" gap="2">
                        <Card.Title>3. Access &amp; Role Mapping</Card.Title>
                        {Object.keys(errorsByStep[2]).length > 0 ? (
                          <Badge variant="subtle" size="xs" palette={redPalette}>
                            Needs Attention
                          </Badge>
                        ) : (
                          <Badge variant="subtle" size="xs" palette={greenPalette}>
                            Verified
                          </Badge>
                        )}
                      </HStack>
                      <Button
                        variant="ghost"
                        size="xs"
                        onClick={() => goToStep(2)}
                      >
                        <EditPencilIcon />
                        Edit
                      </Button>
                    </Card.Header>
                    <Card.Body style={styles.reviewCardBody}>
                      <DataList.Root
                        orientation="horizontal"
                        variant="subtle"
                        size="md"
                      >
                        <DataList.Item style={styles.reviewDataItem}>
                          <DataList.ItemLabel style={styles.reviewDataLabel}>
                            Default role
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            {selectedRole.label.split(" — ")[0]}
                          </DataList.ItemValue>
                        </DataList.Item>
                        <DataList.Item style={styles.reviewDataItem}>
                          <DataList.ItemLabel style={styles.reviewDataLabel}>
                            Mapped IdP groups
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            {groupRules.length === 0
                              ? "None selected"
                              : GROUP_ROLE_RULES.filter((rule) =>
                                  groupRules.includes(rule.id),
                                )
                                  .map(
                                    (rule) =>
                                      `${rule.groupName} → ${rule.mappedRole}`,
                                  )
                                  .join(", ")}
                          </DataList.ItemValue>
                        </DataList.Item>
                        <DataList.Item style={styles.reviewDataItem}>
                          <DataList.ItemLabel style={styles.reviewDataLabel}>
                            Session timeout
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            {sessionTimeoutMinutes} minutes idle
                          </DataList.ItemValue>
                        </DataList.Item>
                        <DataList.Item style={styles.reviewDataItem}>
                          <DataList.ItemLabel style={styles.reviewDataLabel}>
                            Hardware MFA
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            {requireHardwareMfa
                              ? allowPlatformPasskeys
                                ? "Required (FIDO2 keys + platform passkeys)"
                                : "Required (roaming FIDO2 keys only)"
                              : "Optional (IdP MFA policy only)"}
                          </DataList.ItemValue>
                        </DataList.Item>
                      </DataList.Root>
                    </Card.Body>
                  </Card.Root>

                  {/* Section 4: Audit & Notifications */}
                  <Card.Root variant="outline" size="md">
                    <Card.Header style={styles.reviewCardHeader}>
                      <HStack wrap="wrap" gap="2">
                        <Card.Title>4. Audit &amp; Notifications</Card.Title>
                        {Object.keys(errorsByStep[3]).length > 0 ? (
                          <Badge variant="subtle" size="xs" palette={redPalette}>
                            Needs Attention
                          </Badge>
                        ) : (
                          <Badge variant="subtle" size="xs" palette={greenPalette}>
                            Verified
                          </Badge>
                        )}
                      </HStack>
                      <Button
                        variant="ghost"
                        size="xs"
                        onClick={() => goToStep(3)}
                      >
                        <EditPencilIcon />
                        Edit
                      </Button>
                    </Card.Header>
                    <Card.Body style={styles.reviewCardBody}>
                      <DataList.Root
                        orientation="horizontal"
                        variant="subtle"
                        size="md"
                      >
                        <DataList.Item style={styles.reviewDataItem}>
                          <DataList.ItemLabel style={styles.reviewDataLabel}>
                            SIEM destination
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            {selectedSiem.label}
                          </DataList.ItemValue>
                        </DataList.Item>
                        {siemDestination !== "none" ? (
                          <DataList.Item style={styles.reviewDataItem}>
                            <DataList.ItemLabel style={styles.reviewDataLabel}>
                              Ingestion endpoint
                            </DataList.ItemLabel>
                            <DataList.ItemValue>
                              <Text
                                render={<span />}
                                variant="mono"
                                size="xs"
                                style={styles.breakWord}
                              >
                                {siemEndpointUrl.trim() || "—"}
                              </Text>
                            </DataList.ItemValue>
                          </DataList.Item>
                        ) : null}
                        <DataList.Item style={styles.reviewDataItem}>
                          <DataList.ItemLabel style={styles.reviewDataLabel}>
                            Alert channels
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            {alertChannels.length === 0
                              ? "None"
                              : ALERT_CHANNELS.filter((item) =>
                                  alertChannels.includes(item.id),
                                )
                                  .map((item) => item.label)
                                  .join(", ")}
                          </DataList.ItemValue>
                        </DataList.Item>
                        <DataList.Item style={styles.reviewDataItem}>
                          <DataList.ItemLabel style={styles.reviewDataLabel}>
                            Audit retention
                          </DataList.ItemLabel>
                          <DataList.ItemValue>
                            {selectedRetention.label} ({selectedRegion.shortLabel})
                          </DataList.ItemValue>
                        </DataList.Item>
                      </DataList.Root>
                    </Card.Body>
                  </Card.Root>
                </VStack>

                <Separator decorative />

                <Field.Root
                  required
                  invalid={Boolean(currentErrors.confirmedProvisioning)}
                >
                  <Checkbox.Root
                    size="md"
                    palette={accentPalette}
                    style={styles.checkboxRow}
                  >
                    <Checkbox.Control
                      ref={confirmedProvisioningRef}
                      checked={confirmedProvisioning}
                      onCheckedChange={(next) => {
                        setConfirmedProvisioning(next === true);
                        markDirty();
                      }}
                      aria-invalid={
                        currentErrors.confirmedProvisioning ? true : undefined
                      }
                      style={styles.checkboxControlOffset}
                    />
                    <VStack render={<span />} gap="0.5">
                      <Checkbox.Label>
                        I approve these SSO metadata, residency, and audit controls
                        for production workspace provisioning
                      </Checkbox.Label>
                      <Text
                        render={<span />}
                        size="xs"
                        tone="muted"
                        weight="normal"
                      >
                        Data residency in {selectedRegion.label} is permanent once
                        the tenant vault is initialized.
                      </Text>
                    </VStack>
                  </Checkbox.Root>
                  {currentErrors.confirmedProvisioning ? (
                    <Field.Error match={true}>
                      {currentErrors.confirmedProvisioning}
                    </Field.Error>
                  ) : null}
                </Field.Root>
              </VStack>
            ) : null}
          </VStack>

          {/* Sticky footer action bar */}
          {!isProvisioned ? (
            <footer {...stylex.props(styles.footer)}>
              <HStack
                justify="between"
                wrap="wrap"
                gap="3"
                style={styles.footerInner}
              >
                <HStack gap="2.5">
                  <Button
                    variant="surface"
                    disabled={step === 0}
                    onClick={() => setStep((current) => Math.max(0, current - 1))}
                  >
                    <ArrowLeftIcon />
                    Back
                  </Button>
                  <Text render={<span />} size="xs" tone="muted" tabular="true">
                    Step {step + 1} of {STEPS.length}
                  </Text>
                </HStack>

                <HStack justify="end" wrap="wrap" gap="2.5">
                  <Button variant="outline" onClick={handleSaveDraft}>
                    <SaveDraftIcon />
                    Save draft
                  </Button>
                  <Button
                    variant="solid"
                    palette={accentPalette}
                    onClick={goNext}
                  >
                    {isLastStep ? (
                      <>
                        <ShieldEmblemIcon />
                        Provision workspace
                      </>
                    ) : (
                      <>
                        Continue
                        <ArrowRightIcon />
                      </>
                    )}
                  </Button>
                </HStack>
              </HStack>
            </footer>
          ) : null}
        </VStack>
      </Grid>

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

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