---
title: "Settings Dialog · UI SDK — StyleX Blocks"
description: "Two-pane desktop preferences modal with a categorized navigation rail, keyboard-navigable live settings search, responsive container-query collapse, accent swatch and scale controls, connected app toggles, shortcut bindings, quota progress meters, and a docked dirty-state save bar."
url: "https://stylexblocks.com/block/ui-sdk/settings-dialog/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Settings Dialog block

Two-pane desktop preferences modal with a categorized navigation rail, keyboard-navigable live settings search, responsive container-query collapse, accent swatch and scale controls, connected app toggles, shortcut bindings, quota progress meters, and a docked dirty-state save bar.

- Behavior engine: UI SDK
- Category: [Settings](https://stylexblocks.com/blocks/settings.md)
- Built with: [Avatar](https://stylexblocks.com/components/ui-sdk/avatar.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), [Color Swatch](https://stylexblocks.com/components/ui-sdk/color-swatch.md), [Grid](https://stylexblocks.com/components/ui-sdk/grid.md), [Heading](https://stylexblocks.com/components/ui-sdk/heading.md), [Icon](https://stylexblocks.com/components/ui-sdk/icon.md), [Icon Badge](https://stylexblocks.com/components/ui-sdk/icon-badge.md), [Icon Button](https://stylexblocks.com/components/ui-sdk/icon-button.md), [Input](https://stylexblocks.com/components/ui-sdk/input.md), [Kbd](https://stylexblocks.com/components/ui-sdk/kbd.md), [Progress](https://stylexblocks.com/components/ui-sdk/progress.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), [Sidebar](https://stylexblocks.com/components/ui-sdk/sidebar.md), [Sidebar Nav Item](https://stylexblocks.com/components/ui-sdk/sidebar-nav-item.md), [Slider](https://stylexblocks.com/components/ui-sdk/slider.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/settings-dialog/

## Install

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

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

Then add the item as source you own:

```sh
npx stylexblocks add settings-dialog
```

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

## Usage

```tsx
import { SettingsDialog } from "#components/blocks/ui-sdk/settings-dialog.tsx";

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

## Source

`components/blocks/ui-sdk/settings-dialog.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import {
  type KeyboardEvent,
  type ReactNode,
  useCallback,
  useEffect,
  useId,
  useMemo,
  useRef,
  useState,
} from "react";
import { Avatar } from "#components/ui/ui-sdk/avatar.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 { Center } from "#components/ui/ui-sdk/center.tsx";
import { ColorSwatch } from "#components/ui/ui-sdk/color-swatch.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 { IconBadge } from "#components/ui/ui-sdk/icon-badge.tsx";
import { IconButton } from "#components/ui/ui-sdk/icon-button.tsx";
import { Input } from "#components/ui/ui-sdk/input.tsx";
import { Kbd } from "#components/ui/ui-sdk/kbd.tsx";
import { Progress } from "#components/ui/ui-sdk/progress.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 { Sidebar } from "#components/ui/ui-sdk/sidebar.tsx";
import {
  SidebarNavItem,
  sidebarNavItemActive,
} from "#components/ui/ui-sdk/sidebar-nav-item.tsx";
import { Slider } from "#components/ui/ui-sdk/slider.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 { 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,
  bluePalette,
  emeraldPalette,
  grayPalette,
  greenPalette,
  indigoPalette,
  redPalette,
  rosePalette,
  tealPalette,
} 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 { sizes } from "@stylexblocks/ui/tokens/sizes.stylex.ts";
import { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";
import { zIndices } from "@stylexblocks/ui/tokens/z-indices.stylex.ts";
import type { StyleOverrideProps } from "#lib/recipe-props.ts";

// ── Container Queries ─────────────────────────────────────────────────────────

const DIALOG_NARROW = "@container settings-dialog-frame (max-width: 720px)";
const PANEL_STACK = "@container settings-dialog-panel (max-width: 480px)";
const STAGE_COMPACT = "@container settings-dialog-stage (max-width: 680px)";

// ── Types ─────────────────────────────────────────────────────────────────────

export type SettingsDialogSectionId =
  | "profile"
  | "notifications"
  | "security"
  | "appearance"
  | "integrations"
  | "shortcuts"
  | "billing";

export type PresenceStatus = "active" | "focus" | "away";
export type ThemePreference = "light" | "dark" | "system";
export type DensityPreference = "compact" | "default" | "spacious";
export type AccentChoice =
  | "indigo"
  | "blue"
  | "teal"
  | "emerald"
  | "amber"
  | "rose";
export type QuietHoursPreset = "off" | "evenings" | "weekends";

export interface SettingsDialogState {
  // Profile
  displayName: string;
  handle: string;
  roleTitle: string;
  timezone: string;
  landingView: string;
  presence: PresenceStatus;
  showLocalTime: boolean;
  // Notifications
  digestCadence: string;
  quietHours: QuietHoursPreset;
  alertVolume: number;
  desktopPush: boolean;
  reviewMentions: boolean;
  commentReplies: boolean;
  weeklySummary: boolean;
  releaseNotes: boolean;
  // Security
  twoFactorEnabled: boolean;
  passkeyDeploys: boolean;
  sessionTimeout: string;
  // Appearance
  themeMode: ThemePreference;
  accentColor: AccentChoice;
  uiScale: number;
  density: DensityPreference;
  reduceMotion: boolean;
  translucentChrome: boolean;
  // Integrations
  webhookEndpoint: string;
  retryWebhooks: boolean;
  // Shortcuts
  singleKeyShortcuts: boolean;
  vimNavigation: boolean;
  showTooltipHints: boolean;
  // Billing
  billingCycle: string;
  autoTopUp: boolean;
}

interface NavItemConfig {
  id: SettingsDialogSectionId;
  label: string;
  shortLabel: string;
  description: string;
  group: "Account" | "Workspace";
}

interface SearchableSettingItem {
  id: string;
  title: string;
  description: string;
  keywords: string;
  section: SettingsDialogSectionId;
}

interface SessionDevice {
  id: string;
  name: string;
  client: string;
  location: string;
  lastSeen: string;
  current?: boolean;
  kind: "laptop" | "tablet" | "cli";
}

interface IntegrationItem {
  id: string;
  name: string;
  category: string;
  description: string;
  connected: boolean;
  accountLabel: string;
  palette: typeof indigoPalette;
}

interface ShortcutBinding {
  id: string;
  label: string;
  category: string;
  keys: string[];
  altKeys: string[];
  usingAlt?: boolean;
  enabled: boolean;
}

export interface SettingsDialogProps extends StyleOverrideProps {
  /** Workspace name shown in the host backdrop and preferences header. */
  workspaceName?: string;
  /** Initial active preference category. */
  initialSection?: SettingsDialogSectionId;
  /** Controlled open state of the preferences dialog. */
  open?: boolean;
  /** Uncontrolled initial open state (defaults to true so the dialog is immediately visible in stage). */
  defaultOpen?: boolean;
  /** Called when the dialog opens or closes. */
  onOpenChange?: (open: boolean) => void;
  /** Called when modified preferences are saved. */
  onSave?: (settings: SettingsDialogState) => void;
}

// ── Static Data ───────────────────────────────────────────────────────────────

const INITIAL_SETTINGS: SettingsDialogState = {
  displayName: "Soren Lindqvist",
  handle: "@soren.l",
  roleTitle: "Principal Design Technologist",
  timezone: "Europe/Amsterdam",
  landingView: "canvas",
  presence: "active",
  showLocalTime: true,
  digestCadence: "realtime",
  quietHours: "evenings",
  alertVolume: 65,
  desktopPush: true,
  reviewMentions: true,
  commentReplies: true,
  weeklySummary: false,
  releaseNotes: true,
  twoFactorEnabled: true,
  passkeyDeploys: true,
  sessionTimeout: "24h",
  themeMode: "system",
  accentColor: "indigo",
  uiScale: 100,
  density: "default",
  reduceMotion: false,
  translucentChrome: true,
  webhookEndpoint: "https://hooks.vela.studio/v1/events/ds-core",
  retryWebhooks: true,
  singleKeyShortcuts: true,
  vimNavigation: false,
  showTooltipHints: true,
  billingCycle: "annual",
  autoTopUp: true,
};

const NAV_GROUPS: Array<{
  label: "Account" | "Workspace";
  items: NavItemConfig[];
}> = [
  {
    label: "Account",
    items: [
      {
        id: "profile",
        label: "Profile",
        shortLabel: "Profile",
        description:
          "How your identity, availability, and local time appear across Vela Studio.",
        group: "Account",
      },
      {
        id: "notifications",
        label: "Notifications",
        shortLabel: "Alerts",
        description:
          "Control delivery cadence, quiet hours, alert volume, and workspace triggers.",
        group: "Account",
      },
      {
        id: "security",
        label: "Security",
        shortLabel: "Security",
        description:
          "Manage multi-factor protection, session expiry, and signed-in devices.",
        group: "Account",
      },
    ],
  },
  {
    label: "Workspace",
    items: [
      {
        id: "appearance",
        label: "Appearance",
        shortLabel: "Appearance",
        description:
          "Customize color theme, accent swatch, interface scale, and visual density.",
        group: "Workspace",
      },
      {
        id: "integrations",
        label: "Integrations",
        shortLabel: "Apps",
        description:
          "Connect external design, code, and issue-tracking tools to this workspace.",
        group: "Workspace",
      },
      {
        id: "shortcuts",
        label: "Keyboard Shortcuts",
        shortLabel: "Shortcuts",
        description:
          "Configure navigation chords, tooltip key hints, and quick canvas bindings.",
        group: "Workspace",
      },
      {
        id: "billing",
        label: "Billing & Quota",
        shortLabel: "Billing",
        description:
          "Track workspace seat allocation, render hours, asset storage, and plan cycle.",
        group: "Workspace",
      },
    ],
  },
];

const ALL_NAV_ITEMS: NavItemConfig[] = NAV_GROUPS.flatMap((g) => g.items);

const SECTION_KEYS: Record<
  SettingsDialogSectionId,
  Array<keyof SettingsDialogState>
> = {
  profile: [
    "displayName",
    "handle",
    "roleTitle",
    "timezone",
    "landingView",
    "presence",
    "showLocalTime",
  ],
  notifications: [
    "digestCadence",
    "quietHours",
    "alertVolume",
    "desktopPush",
    "reviewMentions",
    "commentReplies",
    "weeklySummary",
    "releaseNotes",
  ],
  security: ["twoFactorEnabled", "passkeyDeploys", "sessionTimeout"],
  appearance: [
    "themeMode",
    "accentColor",
    "uiScale",
    "density",
    "reduceMotion",
    "translucentChrome",
  ],
  integrations: ["webhookEndpoint", "retryWebhooks"],
  shortcuts: ["singleKeyShortcuts", "vimNavigation", "showTooltipHints"],
  billing: ["billingCycle", "autoTopUp"],
};

const SEARCHABLE_SETTINGS: SearchableSettingItem[] = [
  {
    id: "display-name",
    title: "Display name & handle",
    description: "Name shown on canvas cursors and review comments",
    keywords: "name avatar identity user",
    section: "profile",
  },
  {
    id: "presence",
    title: "Availability status",
    description: "Switch between Active, Focus, and Away",
    keywords: "status online focus away presence",
    section: "profile",
  },
  {
    id: "timezone",
    title: "Time zone & local clock",
    description: "Regional offset for schedules and timestamps",
    keywords: "clock region locale utc amsterdam",
    section: "profile",
  },
  {
    id: "digest",
    title: "Notification cadence",
    description: "Real-time, hourly, or daily activity digests",
    keywords: "email push alerts inbox summary",
    section: "notifications",
  },
  {
    id: "quiet-hours",
    title: "Quiet hours & sound volume",
    description: "Mute desktop alerts during evenings or weekends",
    keywords: "mute audio volume sound dnd",
    section: "notifications",
  },
  {
    id: "two-factor",
    title: "Two-factor authentication",
    description: "Authenticator code and passkey sign-in protection",
    keywords: "2fa mfa passkey security hardware key",
    section: "security",
  },
  {
    id: "sessions",
    title: "Active devices & sessions",
    description: "Review and sign out devices using this account",
    keywords: "devices logout revoke macbook cli",
    section: "security",
  },
  {
    id: "theme-accent",
    title: "Color theme & accent swatch",
    description: "Light, dark, or system theme with custom accent",
    keywords: "color dark mode light palette swatch indigo",
    section: "appearance",
  },
  {
    id: "ui-scale",
    title: "Interface scale & density",
    description: "Adjust text zoom (90%–125%) and row spacing",
    keywords: "zoom font size compact spacious motion",
    section: "appearance",
  },
  {
    id: "connected-apps",
    title: "Connected workspace apps",
    description: "GitHub, Figma Sync, Linear, Slack, and Vercel",
    keywords: "apps plugins github linear slack figma webhook",
    section: "integrations",
  },
  {
    id: "keybindings",
    title: "Keyboard shortcuts & Vim mode",
    description: "Command palette, single-key chords, and key hints",
    keywords: "hotkeys kbd keymap bindings vim command",
    section: "shortcuts",
  },
  {
    id: "billing-quota",
    title: "Plan cycle & usage quotas",
    description: "Seats, cloud render hours, storage, and invoices",
    keywords: "plan invoice seats storage quota limit pro",
    section: "billing",
  },
];

const TIMEZONE_OPTIONS = [
  { value: "Europe/Amsterdam", label: "(UTC+01:00) Amsterdam · CET" },
  { value: "Europe/London", label: "(UTC+00:00) London · GMT" },
  { value: "America/New_York", label: "(UTC−05:00) New York · EST" },
  { value: "America/Los_Angeles", label: "(UTC−08:00) San Francisco · PST" },
  { value: "Asia/Tokyo", label: "(UTC+09:00) Tokyo · JST" },
] as const;

const LANDING_VIEW_OPTIONS = [
  { value: "canvas", label: "Design Canvas" },
  { value: "components", label: "Component Library" },
  { value: "activity", label: "Team Activity Feed" },
] as const;

const DIGEST_OPTIONS = [
  { value: "realtime", label: "Real-time delivery" },
  { value: "hourly", label: "Hourly rollup" },
  { value: "daily", label: "Daily digest at 09:00" },
] as const;

const SESSION_TIMEOUT_OPTIONS = [
  { value: "30m", label: "30 minutes" },
  { value: "4h", label: "4 hours" },
  { value: "24h", label: "24 hours" },
  { value: "7d", label: "7 days" },
] as const;

const BILLING_CYCLE_OPTIONS = [
  { value: "annual", label: "Annual billing (save 20%)" },
  { value: "monthly", label: "Monthly billing" },
] as const;

const ACCENT_OPTIONS: Array<{
  id: AccentChoice;
  label: string;
  palette: typeof indigoPalette;
}> = [
  { id: "indigo", label: "Indigo", palette: indigoPalette },
  { id: "blue", label: "Cobalt", palette: bluePalette },
  { id: "teal", label: "Teal", palette: tealPalette },
  { id: "emerald", label: "Emerald", palette: emeraldPalette },
  { id: "amber", label: "Amber", palette: amberPalette },
  { id: "rose", label: "Rose", palette: rosePalette },
];

const INITIAL_SESSIONS: SessionDevice[] = [
  {
    id: "sess-mbp",
    name: "MacBook Pro 16 · macOS 15.5",
    client: "Vela Studio Desktop 3.4",
    location: "Amsterdam, NL",
    lastSeen: "Active now",
    current: true,
    kind: "laptop",
  },
  {
    id: "sess-ipad",
    name: "iPad Pro M4 · iPadOS 19",
    client: "Vela Companion",
    location: "Utrecht, NL",
    lastSeen: "2 hours ago",
    kind: "tablet",
  },
  {
    id: "sess-cli",
    name: "Vela CLI v2.4.1",
    client: "Token sync · eu-west-1",
    location: "Frankfurt, DE",
    lastSeen: "Yesterday at 18:42",
    kind: "cli",
  },
];

const INITIAL_INTEGRATIONS: IntegrationItem[] = [
  {
    id: "int-github",
    name: "GitHub",
    category: "Code",
    description: "Sync design tokens and open PRs on snapshot publish.",
    connected: true,
    accountLabel: "vela-studio/design-system",
    palette: grayPalette,
  },
  {
    id: "int-linear",
    name: "Linear",
    category: "Issues",
    description: "Link canvas review threads directly to engineering cycles.",
    connected: true,
    accountLabel: "VELA team · 2-way sync",
    palette: indigoPalette,
  },
  {
    id: "int-slack",
    name: "Slack",
    category: "Messaging",
    description: "Post prototype approvals and quota alerts to #design-ops.",
    connected: true,
    accountLabel: "#design-ops",
    palette: tealPalette,
  },
  {
    id: "int-vercel",
    name: "Vercel",
    category: "Deployments",
    description: "Attach live Storybook preview URLs to every branch.",
    connected: false,
    accountLabel: "Not connected",
    palette: bluePalette,
  },
];

const INITIAL_SHORTCUTS: ShortcutBinding[] = [
  {
    id: "sc-cmd",
    label: "Open command palette",
    category: "Global",
    keys: ["⌘", "K"],
    altKeys: ["⌘", "P"],
    enabled: true,
  },
  {
    id: "sc-prefs",
    label: "Open preferences",
    category: "Global",
    keys: ["⌘", ","],
    altKeys: ["⌥", ","],
    enabled: true,
  },
  {
    id: "sc-frame",
    label: "Insert frame tool",
    category: "Canvas",
    keys: ["F"],
    altKeys: ["A"],
    enabled: true,
  },
  {
    id: "sc-inspector",
    label: "Toggle property inspector",
    category: "Canvas",
    keys: ["⌥", "I"],
    altKeys: ["⌘", "."],
    enabled: true,
  },
  {
    id: "sc-publish",
    label: "Publish library snapshot",
    category: "Workspace",
    keys: ["⇧", "⌘", "P"],
    altKeys: ["⌥", "⌘", "S"],
    enabled: true,
  },
  {
    id: "sc-zoom",
    label: "Reset canvas zoom to 100%",
    category: "Canvas",
    keys: ["⌘", "0"],
    altKeys: ["⇧", "0"],
    enabled: true,
  },
];

const QUOTA_METRICS = [
  {
    id: "seats",
    label: "Editor seats",
    usedLabel: "8 of 12 seats",
    percent: 67,
    hint: "4 seats available before next tier",
  },
  {
    id: "renders",
    label: "Cloud render hours",
    usedLabel: "47.5 of 60 hrs",
    percent: 79,
    hint: "Resets on Jan 1 · Auto-top-up protects CI",
  },
  {
    id: "storage",
    label: "Design asset storage",
    usedLabel: "18.4 of 25 GB",
    percent: 74,
    hint: "Includes versioned snapshots & font packs",
  },
  {
    id: "webhooks",
    label: "Webhook deliveries",
    usedLabel: "64k of 100k events",
    percent: 64,
    hint: "99.98% delivery success over last 30 days",
  },
];

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

function getInitials(name: string): string {
  const parts = name.trim().split(/\s+/).filter(Boolean);
  if (parts.length === 0) return "VS";
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return `${parts[0][0] ?? ""}${parts[parts.length - 1][0] ?? ""}`.toUpperCase();
}

function getSectionMeta(id: SettingsDialogSectionId): NavItemConfig {
  return ALL_NAV_ITEMS.find((item) => item.id === id) ?? ALL_NAV_ITEMS[0];
}

function countDirtyInSection(
  section: SettingsDialogSectionId,
  draft: SettingsDialogState,
  saved: SettingsDialogState,
): number {
  let count = 0;
  for (const key of SECTION_KEYS[section]) {
    if (draft[key] !== saved[key]) count += 1;
  }
  return count;
}

function getAccentPalette(accent: AccentChoice) {
  return (
    ACCENT_OPTIONS.find((item) => item.id === accent)?.palette ?? indigoPalette
  );
}

// ── Inline SVG Icons (uniform 1.6 stroke weight) ──────────────────────────────

function VelaMark() {
  return (
    <Icon
      size="sm"
      viewBox="0 0 20 20"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.7"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M4 15.5 10 3.5l6 12" />
      <path d="M10 3.5v12" />
      <path d="M4 15.5h12" />
    </Icon>
  );
}

function SectionGlyph({ id }: { id: SettingsDialogSectionId }) {
  switch (id) {
    case "profile":
      return (
        <>
          <circle cx="10" cy="6.5" r="3" />
          <path d="M4.2 16a5.8 5.8 0 0 1 11.6 0" />
        </>
      );
    case "notifications":
      return (
        <>
          <path d="M5.5 8.5a4.5 4.5 0 0 1 9 0c0 3.3 1.3 4.4 1.8 5H3.7c.5-.6 1.8-1.7 1.8-5Z" />
          <path d="M8.5 16a1.7 1.7 0 0 0 3 0" />
        </>
      );
    case "security":
      return (
        <>
          <path d="M10 2.8 4.2 5.2v4.3c0 3.6 2.4 6.5 5.8 7.7 3.4-1.2 5.8-4.1 5.8-7.7V5.2L10 2.8Z" />
          <path d="m7.7 10.1 1.6 1.6 3.2-3.4" />
        </>
      );
    case "appearance":
      return (
        <>
          <circle cx="10" cy="10" r="3" />
          <path d="M10 2.5v2M10 15.5v2M2.5 10h2M15.5 10h2M4.7 4.7l1.4 1.4M13.9 13.9l1.4 1.4M15.3 4.7l-1.4 1.4M6.1 13.9l-1.4 1.4" />
        </>
      );
    case "integrations":
      return (
        <>
          <rect x="3" y="3" width="5.5" height="5.5" rx="1.2" />
          <rect x="11.5" y="3" width="5.5" height="5.5" rx="1.2" />
          <rect x="3" y="11.5" width="5.5" height="5.5" rx="1.2" />
          <path d="M14.25 11.5v5.5M11.5 14.25H17" />
        </>
      );
    case "shortcuts":
      return (
        <>
          <rect x="2.5" y="4.5" width="15" height="11" rx="2" />
          <path d="M5.5 8h1.5M9.25 8h1.5M13 8h1.5M6 12h8" />
        </>
      );
    case "billing":
      return (
        <>
          <rect x="2.8" y="4.5" width="14.4" height="11" rx="2" />
          <path d="M2.8 8.5h14.4" />
          <path d="M6 12.2h3.4" />
        </>
      );
  }
}

function SearchGlyph() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 20 20"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.7"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <circle cx="8.8" cy="8.8" r="5.3" />
      <path d="m16.8 16.8-3.8-3.8" />
    </Icon>
  );
}

function CloseGlyph() {
  return (
    <Icon
      size="sm"
      viewBox="0 0 20 20"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.7"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="m5.5 5.5 9 9m0-9-9 9" />
    </Icon>
  );
}

function SlidersGlyph() {
  return (
    <Icon
      size="xs"
      viewBox="0 0 20 20"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.7"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M3.5 6h9M15.5 6h1M3.5 10h3M9.5 10h7M3.5 14h7M13.5 14h3" />
      <circle cx="14" cy="6" r="1.5" />
      <circle cx="8" cy="10" r="1.5" />
      <circle cx="12" cy="14" r="1.5" />
    </Icon>
  );
}

function DeviceGlyph({ kind }: { kind: SessionDevice["kind"] }) {
  if (kind === "cli") {
    return (
      <Icon
        size="sm"
        viewBox="0 0 20 20"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.6"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        <rect x="2.5" y="3.5" width="15" height="13" rx="2" />
        <path d="m6 8 2.5 2L6 12" />
        <path d="M10.5 12H14" />
      </Icon>
    );
  }
  if (kind === "tablet") {
    return (
      <Icon
        size="sm"
        viewBox="0 0 20 20"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.6"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        <rect x="4" y="2.5" width="12" height="15" rx="2" />
        <path d="M9 14.5h2" />
      </Icon>
    );
  }
  return (
    <Icon
      size="sm"
      viewBox="0 0 20 20"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.6"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <rect x="3" y="4" width="14" height="9.5" rx="1.5" />
      <path d="M2 15.5h16" />
    </Icon>
  );
}

function IntegrationGlyph({ id }: { id: string }) {
  switch (id) {
    case "int-github":
      return (
        <Icon
          size="sm"
          viewBox="0 0 20 20"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.6"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <path d="M7.5 15.5c-3 1-3-1.5-4.5-2m9 3.5v-2.8a2.4 2.4 0 0 0-.7-1.9c2.3-.3 4.7-1.1 4.7-5a3.9 3.9 0 0 0-1-2.7 3.6 3.6 0 0 0-.1-2.7s-.8-.3-2.8 1a9.6 9.6 0 0 0-5 0c-2-1.3-2.8-1-2.8-1a3.6 3.6 0 0 0-.1 2.7 3.9 3.9 0 0 0-1 2.7c0 3.9 2.4 4.7 4.7 5a2.4 2.4 0 0 0-.7 1.9V17" />
        </Icon>
      );
    case "int-linear":
      return (
        <Icon
          size="sm"
          viewBox="0 0 20 20"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.6"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <circle cx="10" cy="10" r="6.8" />
          <path d="m5.6 14.4 8.8-8.8" />
          <path d="m4.5 11.2 4.3 4.3" />
        </Icon>
      );
    case "int-slack":
      return (
        <Icon
          size="sm"
          viewBox="0 0 20 20"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.6"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <path d="M7.5 3.5v13M12.5 3.5v13M3.5 7.5h13M3.5 12.5h13" />
        </Icon>
      );
    default:
      return (
        <Icon
          size="sm"
          viewBox="0 0 20 20"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.6"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <path d="M10 4 16.5 15.5h-13L10 4Z" />
        </Icon>
      );
  }
}

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

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

const swatchColors = stylex.create({
  indigo: { "--color": semanticColors.indigoSolid },
  blue: { "--color": semanticColors.blueSolid },
  teal: { "--color": semanticColors.tealSolid },
  emerald: { "--color": semanticColors.emeraldSolid },
  amber: { "--color": semanticColors.amberSolid },
  rose: { "--color": semanticColors.roseSolid },
});

const styles = stylex.create({
  stage: {
    backgroundColor: semanticColors.bgInset,
    color: semanticColors.fg,
    containerName: "settings-dialog-stage",
    containerType: "inline-size",
    fontFamily: fonts.body,
    minHeight: "48rem",
    overflow: "hidden",
    position: "relative",
    width: "100%",
  },
  fullWidth: {
    width: "100%",
  },
  shrink0: {
    flexShrink: 0,
  },
  gap3_5: {
    gap: spacing._3_5,
  },

  // ── Host Workspace Backdrop ──
  hostTopBar: {
    backgroundColor: semanticColors.bgPanel,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    paddingBlock: spacing._3,
    paddingInline: spacing._5,
  },
  hostHealthStatus: {
    display: {
      default: "inline-flex",
      [STAGE_COMPACT]: "none",
    },
  },
  hostCanvas: {
    flexGrow: 1,
    marginInline: "auto",
    maxWidth: "60rem",
    paddingBlock: spacing._6,
    paddingInline: spacing._5,
    width: "100%",
  },
  hostGrid: {
    gridTemplateColumns: {
      default: "repeat(3, minmax(0, 1fr))",
      [STAGE_COMPACT]: "1fr",
    },
  },
  hostQuickCard: {
    cursor: "pointer",
    transitionProperty: "border-color, box-shadow",
    transitionDuration: durations.fast,
  },
  hostQuickCardBody: {
    display: "flex",
    flexDirection: "column",
    gap: spacing._3,
  },
  hostMetricRow: {
    marginTop: "auto",
  },
  hostFooterBanner: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
  },

  // ── Contained Modal Overlay (never escapes the block stage) ──
  modalOverlay: {
    backdropFilter: "blur(3px)",
    backgroundColor: semanticColors.bgBackdrop,
    bottom: 0,
    left: 0,
    paddingBlock: {
      default: spacing._5,
      [STAGE_COMPACT]: spacing._2_5,
    },
    paddingInline: {
      default: spacing._5,
      [STAGE_COMPACT]: spacing._2_5,
    },
    position: "absolute",
    right: 0,
    top: 0,
    zIndex: zIndices.layer2,
  },
  dialogFrame: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panelLg,
    borderStyle: "solid",
    borderWidth: "1px",
    boxShadow: semanticShadows.overlay,
    containerName: "settings-dialog-frame",
    containerType: "inline-size",
    flexDirection: {
      default: "row",
      [DIALOG_NARROW]: "column",
    },
    height: "min(44rem, 100%)",
    maxWidth: "60rem",
    overflow: "hidden",
    width: "100%",
  },

  // ── Desktop Left Categorized Rail ──
  leftRail: {
    "--sidebar-width": "16.25rem",
    "--sidebar-min-width": "16.25rem",
    display: {
      default: "flex",
      [DIALOG_NARROW]: "none",
    },
    flexShrink: 0,
    minHeight: 0,
  },
  railHeader: {
    alignItems: "center",
    justifyContent: "space-between",
    paddingBottom: spacing._2_5,
    paddingInline: spacing._3_5,
    paddingTop: spacing._3_5,
  },
  railTitle: {
    marginBlock: 0,
  },
  railSearchWrap: {
    paddingBottom: spacing._2_5,
    paddingInline: spacing._3,
  },
  railBody: {
    flexGrow: 1,
    gap: spacing._3_5,
    minHeight: 0,
    paddingTop: 0,
    paddingBottom: spacing._3,
    paddingInline: spacing._2_5,
  },
  navGroupLabel: {
    paddingInline: spacing._2_5,
  },
  navList: {
    listStyle: "none",
    marginBlock: 0,
    marginInline: 0,
    paddingBlock: 0,
    paddingInline: 0,
  },
  dirtyDot: {
    backgroundColor: semanticColors.accentSolid,
    borderRadius: radii.full,
    display: "inline-block",
    flexShrink: 0,
    height: sizes._1_5,
    width: sizes._1_5,
  },
  railFooter: {
    borderTopColor: semanticColors.sidebarBorder,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
    paddingBlock: spacing._3,
    paddingInline: spacing._3_5,
  },

  // ── Search Field & Results ──
  searchFieldBox: {
    position: "relative",
    width: "100%",
  },
  searchLeadingIcon: {
    color: semanticColors.fgSubtle,
    left: spacing._2_5,
    pointerEvents: "none",
    position: "absolute",
    zIndex: 1,
  },
  searchInput: {
    paddingInlineEnd: spacing._7,
    paddingInlineStart: spacing._7,
  },
  searchClearButton: {
    height: sizes._5,
    minWidth: sizes._5,
    position: "absolute",
    right: spacing._1_5,
    width: sizes._5,
  },
  searchResultButton: {
    alignItems: "flex-start",
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.sidebarAccentBg,
    },
    borderColor: "transparent",
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.fg,
    cursor: "pointer",
    display: "flex",
    flexDirection: "column",
    gap: spacing._0_5,
    paddingBlock: spacing._2,
    paddingInline: spacing._2_5,
    textAlign: "start",
    width: "100%",
  },
  searchResultButtonActive: {
    backgroundColor: semanticColors.sidebarAccentBg,
    borderColor: semanticColors.border,
  },
  searchEmptyBox: {
    paddingBlock: spacing._3,
    paddingInline: spacing._2,
  },

  // ── Narrow Responsive Top Shell ──
  narrowHeader: {
    backgroundColor: semanticColors.sidebarBg,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    display: {
      default: "none",
      [DIALOG_NARROW]: "flex",
    },
    flexShrink: 0,
    paddingBlock: spacing._3,
    paddingInline: spacing._3_5,
  },
  narrowCategoryRail: {
    overflowX: "auto",
    paddingBottom: spacing._0_5,
  },
  narrowCategoryPill: {
    alignItems: "center",
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.bgSubtle,
    },
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    color: semanticColors.fgMuted,
    cursor: "pointer",
    display: "inline-flex",
    flexShrink: 0,
    fontFamily: fonts.body,
    fontSize: fontSizes.xs,
    fontWeight: fontWeights.medium,
    gap: spacing._1_5,
    lineHeight: lineHeights.xs,
    paddingBlock: spacing._1_5,
    paddingInline: spacing._2_5,
  },
  narrowCategoryPillActive: {
    backgroundColor: semanticColors.accentSubtle,
    borderColor: semanticColors.accentBorder,
    color: semanticColors.accentFg,
  },
  narrowSearchResultsPane: {
    maxHeight: "14rem",
    overflowY: "auto",
  },

  // ── Right Scrollable Content Pane ──
  contentColumn: {
    backgroundColor: semanticColors.bg,
    flexGrow: 1,
    minHeight: 0,
    minWidth: 0,
    position: "relative",
  },
  contentHeader: {
    borderBottomColor: semanticColors.borderMuted,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    flexShrink: 0,
    paddingBlock: spacing._4,
    paddingInline: {
      default: spacing._6,
      [DIALOG_NARROW]: spacing._4,
    },
  },
  contentTitle: {
    marginBlock: 0,
  },
  desktopCloseWrap: {
    display: {
      default: "inline-flex",
      [DIALOG_NARROW]: "none",
    },
  },
  scrollArea: {
    containerName: "settings-dialog-panel",
    containerType: "inline-size",
    flexGrow: 1,
    minHeight: 0,
    overflowY: "auto",
    paddingBlock: spacing._5,
    paddingInline: {
      default: spacing._6,
      [DIALOG_NARROW]: spacing._4,
    },
  },

  // ── Settings Group & Unified Responsive Row Idiom ──
  groupHeading: {
    letterSpacing: "0.02em",
  },
  groupCard: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    overflow: "hidden",
  },
  settingRowOuter: {
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
  },
  settingRowLine: {
    alignItems: {
      default: "center",
      [PANEL_STACK]: "stretch",
    },
    flexDirection: {
      default: "row",
      [PANEL_STACK]: "column",
    },
    gap: {
      default: spacing._4,
      [PANEL_STACK]: spacing._2_5,
    },
  },
  settingRowText: {
    flexGrow: 1,
    maxWidth: {
      default: "26rem",
      [PANEL_STACK]: "none",
    },
  },
  controlFixedWidth: {
    width: {
      default: "13rem",
      [PANEL_STACK]: "100%",
    },
  },
  sliderFlex: {
    flexGrow: 1,
    minWidth: 0,
  },
  tabularValue: {
    minWidth: "2.75rem",
  },

  // ── Profile Hero ──
  profileHero: {
    gap: spacing._3_5,
    paddingBlock: spacing._4,
    paddingInline: spacing._4,
  },

  // ── Appearance Swatches & Live Preview ──
  swatchButton: {
    alignItems: "center",
    backgroundColor: "transparent",
    borderColor: "transparent",
    borderRadius: radii.full,
    borderStyle: "solid",
    borderWidth: "2px",
    cursor: "pointer",
    display: "inline-flex",
    justifyContent: "center",
    paddingBlock: "2px",
    paddingInline: "2px",
    position: "relative",
    transitionProperty: "transform, border-color",
    transitionDuration: durations.fast,
  },
  swatchButtonActive: {
    borderColor: semanticColors.fg,
  },
  swatchCheckOverlay: {
    color: semanticColors.accentContrast,
    pointerEvents: "none",
    position: "absolute",
  },
  livePreviewCard: {
    backgroundColor: semanticColors.bgSubtle,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._3,
    paddingInline: spacing._3_5,
  },
  livePreviewBarPrimary: {
    backgroundColor: semanticColors.borderEmphasized,
    borderRadius: radii.full,
    height: "6px",
    width: "58%",
  },
  livePreviewBarSecondary: {
    backgroundColor: semanticColors.border,
    borderRadius: radii.full,
    height: "5px",
    width: "38%",
  },

  // ── Lists (Sessions, Integrations, Shortcuts, Quotas) ──
  itemRow: {
    alignItems: {
      default: "center",
      [PANEL_STACK]: "flex-start",
    },
    flexDirection: {
      default: "row",
      [PANEL_STACK]: "column",
    },
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
  },
  quotaRow: {
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
  },
  planBanner: {
    paddingBlock: spacing._4,
    paddingInline: spacing._4,
  },

  // ── Docked Dirty-State Save Bar inside Dialog ──
  dirtyBar: {
    backgroundColor: semanticColors.bgElevated,
    borderTopColor: semanticColors.border,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
    flexShrink: 0,
    paddingBlock: spacing._3,
    paddingInline: {
      default: spacing._6,
      [DIALOG_NARROW]: spacing._4,
    },
  },
});

// ── Composable Settings Primitives ────────────────────────────────────────────

function SettingsGroup({
  title,
  action,
  children,
}: {
  title: string;
  action?: ReactNode;
  children: ReactNode;
}) {
  return (
    <VStack render={<section />} gap="2">
      <HStack gap="2" justify="between">
        <Text
          render={<h3 />}
          variant="muted"
          size="xs"
          weight="semibold"
          style={styles.groupHeading}
        >
          {title}
        </Text>
        {action}
      </HStack>
      <VStack gap="0" style={styles.groupCard}>
        {children}
      </VStack>
    </VStack>
  );
}

function SettingsRow({
  title,
  description,
  badge,
  control,
  detail,
}: {
  title: string;
  description?: string;
  badge?: { label: string; palette: typeof accentPalette };
  control?: ReactNode;
  detail?: ReactNode;
}) {
  return (
    <VStack gap="3" style={styles.settingRowOuter}>
      <HStack justify="between" style={styles.settingRowLine}>
        <VStack gap="0.5" style={styles.settingRowText}>
          <HStack gap="1.5" wrap="wrap">
            <Text render={<span />} size="sm" weight="medium">
              {title}
            </Text>
            {badge ? (
              <Badge variant="subtle" size="xs" palette={badge.palette}>
                {badge.label}
              </Badge>
            ) : null}
          </HStack>
          {description ? (
            <Text variant="muted" size="xs">
              {description}
            </Text>
          ) : null}
        </VStack>
        {control ? (
          <HStack gap="2" style={styles.shrink0}>
            {control}
          </HStack>
        ) : null}
      </HStack>
      {detail}
    </VStack>
  );
}

// ── Main Component ────────────────────────────────────────────────────────────

/**
 * SettingsDialog — Two-pane desktop-app preferences modal for Vela Studio with
 * a categorized navigation rail, live keyboard-navigable settings search,
 * responsive container-query collapse, interactive preference controls, live
 * dirty-state save/discard bar, and toast feedback — safely contained inside
 * an interactive workspace stage so it never hijacks the host page.
 */
export function SettingsDialog({
  workspaceName = "Vela Studio",
  initialSection = "appearance",
  open,
  defaultOpen = true,
  onOpenChange,
  onSave,
  palette,
  style,
}: SettingsDialogProps) {
  const titleId = useId();
  const searchResultsId = useId();
  const searchInputRef = useRef<HTMLInputElement>(null);
  const queue = useMemo(() => Toast.createToaster(), []);

  const [internalOpen, setInternalOpen] = useState(defaultOpen);
  const isOpen = open ?? internalOpen;

  const setDialogOpen = useCallback(
    (next: boolean) => {
      if (open === undefined) setInternalOpen(next);
      onOpenChange?.(next);
    },
    [open, onOpenChange],
  );

  const [activeSection, setActiveSection] =
    useState<SettingsDialogSectionId>(initialSection);
  const [searchQuery, setSearchQuery] = useState("");
  const [searchActiveIndex, setSearchActiveIndex] = useState(0);

  const [saved, setSaved] = useState<SettingsDialogState>(INITIAL_SETTINGS);
  const [draft, setDraft] = useState<SettingsDialogState>(INITIAL_SETTINGS);

  const [sessions, setSessions] = useState<SessionDevice[]>(INITIAL_SESSIONS);
  const [integrations, setIntegrations] =
    useState<IntegrationItem[]>(INITIAL_INTEGRATIONS);
  const [shortcuts, setShortcuts] =
    useState<ShortcutBinding[]>(INITIAL_SHORTCUTS);

  const updateDraft = useCallback(
    <K extends keyof SettingsDialogState>(
      key: K,
      value: SettingsDialogState[K],
    ) => {
      setDraft((prev) => ({ ...prev, [key]: value }));
    },
    [],
  );

  // Dirty-state calculations
  const dirtyBySection = useMemo(
    () => ({
      profile: countDirtyInSection("profile", draft, saved),
      notifications: countDirtyInSection("notifications", draft, saved),
      security: countDirtyInSection("security", draft, saved),
      appearance: countDirtyInSection("appearance", draft, saved),
      integrations: countDirtyInSection("integrations", draft, saved),
      shortcuts: countDirtyInSection("shortcuts", draft, saved),
      billing: countDirtyInSection("billing", draft, saved),
    }),
    [draft, saved],
  );

  const totalDirtyCount =
    dirtyBySection.profile +
    dirtyBySection.notifications +
    dirtyBySection.security +
    dirtyBySection.appearance +
    dirtyBySection.integrations +
    dirtyBySection.shortcuts +
    dirtyBySection.billing;

  // Live search across all settings
  const normalizedQuery = searchQuery.trim().toLowerCase();
  const isSearching = normalizedQuery.length > 0;
  const searchResults = useMemo(() => {
    if (!isSearching) return [];
    return SEARCHABLE_SETTINGS.filter((item) => {
      const sectionLabel = getSectionMeta(item.section).label.toLowerCase();
      return (
        item.title.toLowerCase().includes(normalizedQuery) ||
        item.description.toLowerCase().includes(normalizedQuery) ||
        item.keywords.toLowerCase().includes(normalizedQuery) ||
        sectionLabel.includes(normalizedQuery)
      );
    });
  }, [isSearching, normalizedQuery]);

  useEffect(() => {
    setSearchActiveIndex(0);
  }, [normalizedQuery]);

  const activeAccentPalette = getAccentPalette(draft.accentColor);
  const activeMeta = getSectionMeta(activeSection);
  const connectedCount = integrations.filter((item) => item.connected).length;
  const initials = getInitials(draft.displayName);

  const selectSection = useCallback((section: SettingsDialogSectionId) => {
    setActiveSection(section);
    setSearchQuery("");
  }, []);

  const openToSection = useCallback(
    (section: SettingsDialogSectionId) => {
      setActiveSection(section);
      setDialogOpen(true);
    },
    [setDialogOpen],
  );

  const handleSearchKeyDown = useCallback(
    (event: KeyboardEvent<HTMLInputElement>) => {
      if (event.key === "Escape" && isSearching) {
        event.preventDefault();
        event.stopPropagation();
        setSearchQuery("");
        return;
      }
      if (!isSearching || searchResults.length === 0) return;
      if (event.key === "ArrowDown") {
        event.preventDefault();
        setSearchActiveIndex((idx) => (idx + 1) % searchResults.length);
      } else if (event.key === "ArrowUp") {
        event.preventDefault();
        setSearchActiveIndex(
          (idx) => (idx - 1 + searchResults.length) % searchResults.length,
        );
      } else if (event.key === "Enter") {
        event.preventDefault();
        const match = searchResults[searchActiveIndex];
        if (match) {
          selectSection(match.section);
        }
      }
    },
    [isSearching, searchResults, searchActiveIndex, selectSection],
  );

  const handleDialogKeyDown = useCallback(
    (event: KeyboardEvent<HTMLDivElement>) => {
      if (event.key === "Escape") {
        if (isSearching) {
          event.preventDefault();
          setSearchQuery("");
        } else {
          event.preventDefault();
          setDialogOpen(false);
        }
      }
    },
    [isSearching, setDialogOpen],
  );

  const handleSave = useCallback(() => {
    setSaved(draft);
    onSave?.(draft);
    queue.success("Preferences saved", {
      description: `Updated ${totalDirtyCount} ${totalDirtyCount === 1 ? "setting" : "settings"} in ${workspaceName}.`,
    });
  }, [draft, onSave, queue, totalDirtyCount, workspaceName]);

  const handleDiscard = useCallback(() => {
    setDraft(saved);
    queue.info("Changes discarded", {
      description: "Restored all modified fields to their saved values.",
    });
  }, [saved, queue]);

  const handleRevokeSession = useCallback(
    (session: SessionDevice) => {
      setSessions((prev) => prev.filter((item) => item.id !== session.id));
      queue.success("Device signed out", {
        description: `${session.name} has been disconnected.`,
      });
    },
    [queue],
  );

  const handleRevokeOtherSessions = useCallback(() => {
    const others = sessions.filter((item) => !item.current).length;
    if (others === 0) return;
    setSessions((prev) => prev.filter((item) => item.current));
    queue.success("Signed out other devices", {
      description: `Revoked ${others} remote ${others === 1 ? "session" : "sessions"}.`,
    });
  }, [sessions, queue]);

  const handleToggleIntegration = useCallback(
    (item: IntegrationItem) => {
      const nextConnected = !item.connected;
      setIntegrations((prev) =>
        prev.map((entry) =>
          entry.id === item.id
            ? {
                ...entry,
                connected: nextConnected,
                accountLabel: nextConnected
                  ? item.id === "int-vercel"
                    ? "vela-studio · preview builds"
                    : entry.accountLabel === "Not connected"
                      ? "Connected workspace"
                      : entry.accountLabel
                  : "Not connected",
              }
            : entry,
        ),
      );
      if (nextConnected) {
        queue.success(`${item.name} connected`, {
          description: `${workspaceName} can now exchange events with ${item.name}.`,
        });
      } else {
        queue.warning(`${item.name} disconnected`, {
          description: `Syncing with ${item.name} has been paused.`,
        });
      }
    },
    [queue, workspaceName],
  );

  const handleCycleShortcut = useCallback(
    (item: ShortcutBinding) => {
      const nextUsingAlt = !item.usingAlt;
      setShortcuts((prev) =>
        prev.map((entry) =>
          entry.id === item.id ? { ...entry, usingAlt: nextUsingAlt } : entry,
        ),
      );
      const nextCombo = (nextUsingAlt ? item.altKeys : item.keys).join(" ");
      queue.info(`Updated "${item.label}"`, {
        description: `Bound to ${nextCombo}.`,
      });
    },
    [queue],
  );

  const handleToggleShortcutEnabled = useCallback((id: string, enabled: boolean) => {
    setShortcuts((prev) =>
      prev.map((entry) => (entry.id === id ? { ...entry, enabled } : entry)),
    );
  }, []);

  const handleResetShortcuts = useCallback(() => {
    setShortcuts(INITIAL_SHORTCUTS);
    queue.info("Shortcuts reset", {
      description: "Restored default Vela Studio key bindings.",
    });
  }, [queue]);

  const handleCopyWebhook = useCallback(() => {
    if (typeof navigator !== "undefined" && navigator.clipboard) {
      void navigator.clipboard.writeText(draft.webhookEndpoint).catch(() => {});
    }
    queue.info("Webhook URL copied", {
      description: draft.webhookEndpoint,
    });
  }, [draft.webhookEndpoint, queue]);

  const presencePalette =
    draft.presence === "active"
      ? greenPalette
      : draft.presence === "focus"
        ? amberPalette
        : grayPalette;

  const presenceLabel =
    draft.presence === "active"
      ? "Active"
      : draft.presence === "focus"
        ? "In Focus"
        : "Away";

  const renderSearchBox = () => (
    <HStack gap="0" style={styles.searchFieldBox}>
      <Center
        render={<span />}
        display="inline"
        style={styles.searchLeadingIcon}
      >
        <SearchGlyph />
      </Center>
      <Input
        ref={searchInputRef}
        size="sm"
        variant="outline"
        value={searchQuery}
        onChange={(e) => setSearchQuery(e.target.value)}
        onKeyDown={handleSearchKeyDown}
        placeholder="Search settings…"
        aria-label="Search settings"
        role="combobox"
        aria-autocomplete="list"
        aria-expanded={isSearching}
        aria-controls={searchResultsId}
        aria-activedescendant={
          isSearching && searchResults.length > 0
            ? `${searchResultsId}-${searchActiveIndex}`
            : undefined
        }
        style={styles.searchInput}
      />
      {isSearching ? (
        <IconButton
          type="button"
          variant="ghost"
          size="2xs"
          aria-label="Clear search"
          onClick={() => setSearchQuery("")}
          style={styles.searchClearButton}
        >
          <CloseGlyph />
        </IconButton>
      ) : null}
    </HStack>
  );

  const renderSearchResults = () => {
    if (searchResults.length === 0) {
      return (
        <VStack id={searchResultsId} gap="2" style={styles.searchEmptyBox}>
          <Text render={<span />} size="sm" weight="medium">
            No matching settings
          </Text>
          <Text variant="muted" size="xs">
            Try jumping to one of these common preferences:
          </Text>
          <HStack gap="1.5" wrap="wrap">
            {["accent", "2FA", "shortcuts", "quota"].map((term) => (
              <Button
                key={term}
                size="2xs"
                variant="surface"
                onClick={() => setSearchQuery(term)}
              >
                {term}
              </Button>
            ))}
          </HStack>
        </VStack>
      );
    }

    return (
      <VStack
        render={<ul />}
        id={searchResultsId}
        role="listbox"
        aria-label="Matching settings"
        gap="1"
        style={styles.navList}
      >
        {searchResults.map((item, idx) => {
          const isHighlighted = idx === searchActiveIndex;
          return (
            <li key={item.id} role="presentation">
              <button
                id={`${searchResultsId}-${idx}`}
                type="button"
                role="option"
                aria-selected={isHighlighted}
                onMouseEnter={() => setSearchActiveIndex(idx)}
                onClick={() => selectSection(item.section)}
                {...stylex.props(
                  styles.searchResultButton,
                  isHighlighted && styles.searchResultButtonActive,
                )}
              >
                <HStack
                  render={<span />}
                  gap="1.5"
                  justify="between"
                  style={styles.fullWidth}
                >
                  <Text render={<span />} size="xs" weight="semibold">
                    {item.title}
                  </Text>
                  <Badge variant="subtle" size="xs" palette={grayPalette}>
                    {getSectionMeta(item.section).shortLabel}
                  </Badge>
                </HStack>
                <Text render={<span />} variant="muted" size="xs">
                  {item.description}
                </Text>
              </button>
            </li>
          );
        })}
      </VStack>
    );
  };

  return (
    <VStack gap="0" palette={palette} style={[styles.stage, style]}>
      {/* ── Host Workspace Backdrop (visible when dialog is dismissed) ── */}
      <HStack
        render={<header />}
        gap="3"
        justify="between"
        wrap="wrap"
        style={styles.hostTopBar}
      >
        <HStack gap="2.5">
          <IconBadge variant="solid" size="sm" palette={activeAccentPalette}>
            <VelaMark />
          </IconBadge>
          <HStack gap="1.5">
            <Text render={<span />} size="sm" weight="semibold">
              {workspaceName}
            </Text>
            <Text render={<span />} size="sm" tone="subtle" aria-hidden="true">
              /
            </Text>
            <Text render={<span />} variant="muted" size="sm" truncate="true">
              Design System v3
            </Text>
          </HStack>
        </HStack>

        <HStack gap="2.5">
          <Status.Root
            size="sm"
            palette={greenPalette}
            style={styles.hostHealthStatus}
          >
            <Status.Indicator />
            <span>Synced</span>
          </Status.Root>
          <Button
            size="sm"
            variant={isOpen ? "surface" : "solid"}
            palette={isOpen ? grayPalette : activeAccentPalette}
            onClick={() => setDialogOpen(true)}
          >
            <SlidersGlyph />
            <span>Open Settings</span>
            <Kbd size="xs" variant="outline">
              ⌘ ,
            </Kbd>
          </Button>
        </HStack>
      </HStack>

      <VStack gap="5" style={styles.hostCanvas} aria-hidden={isOpen}>
        <HStack gap="4" justify="between" wrap="wrap">
          <VStack gap="1">
            <Heading render={<h2 />} size="xl" style={styles.contentTitle}>
              Workspace Overview
            </Heading>
            <Text variant="muted" size="sm">
              Live preferences from the dialog apply across your Vela Studio
              environment.
            </Text>
          </VStack>
          <Button
            size="sm"
            variant="solid"
            palette={activeAccentPalette}
            onClick={() => openToSection(activeSection)}
          >
            Configure preferences
          </Button>
        </HStack>

        <Grid columns="3" gap="4" style={styles.hostGrid}>
          <Card.Root
            variant="outline"
            size="md"
            style={styles.hostQuickCard}
            onClick={() => openToSection("appearance")}
          >
            <Card.Body style={styles.hostQuickCardBody}>
              <HStack gap="2" justify="between">
                <Text render={<span />} size="sm" weight="medium">
                  Theme & Accent
                </Text>
                <ColorSwatch
                  size="sm"
                  shape="circle"
                  style={swatchColors[draft.accentColor]}
                />
              </HStack>
              <Text variant="muted" size="xs">
                Mode: {draft.themeMode} · Density: {draft.density} · Scale:{" "}
                {draft.uiScale}%
              </Text>
              <HStack gap="2" wrap="wrap" style={styles.hostMetricRow}>
                <Badge variant="subtle" size="xs" palette={activeAccentPalette}>
                  {draft.accentColor}
                </Badge>
                {draft.translucentChrome ? (
                  <Badge variant="outline" size="xs" palette={grayPalette}>
                    Translucent
                  </Badge>
                ) : null}
              </HStack>
            </Card.Body>
          </Card.Root>

          <Card.Root
            variant="outline"
            size="md"
            style={styles.hostQuickCard}
            onClick={() => openToSection("integrations")}
          >
            <Card.Body style={styles.hostQuickCardBody}>
              <HStack gap="2" justify="between">
                <Text render={<span />} size="sm" weight="medium">
                  Integrations
                </Text>
                <Status.Root size="sm" palette={greenPalette}>
                  <Status.Indicator />
                  <span>{connectedCount} live</span>
                </Status.Root>
              </HStack>
              <Text variant="muted" size="xs">
                {integrations
                  .filter((i) => i.connected)
                  .map((i) => i.name)
                  .join(", ") || "No apps connected"}
              </Text>
              <HStack gap="2" wrap="wrap" style={styles.hostMetricRow}>
                <Badge variant="subtle" size="xs" palette={grayPalette}>
                  Webhooks {draft.retryWebhooks ? "auto-retry" : "manual"}
                </Badge>
              </HStack>
            </Card.Body>
          </Card.Root>

          <Card.Root
            variant="outline"
            size="md"
            style={styles.hostQuickCard}
            onClick={() => openToSection("billing")}
          >
            <Card.Body style={styles.hostQuickCardBody}>
              <HStack gap="2" justify="between">
                <Text render={<span />} size="sm" weight="medium">
                  Billing & Quota
                </Text>
                <Badge variant="subtle" size="xs" palette={activeAccentPalette}>
                  Pro · {draft.billingCycle}
                </Badge>
              </HStack>
              <Text variant="muted" size="xs">
                8 of 12 editor seats used · 47.5 / 60 render hours
              </Text>
              <Progress.Root
                value={79}
                size="xs"
                shape="full"
                palette={amberPalette}
              >
                <Progress.Track>
                  <Progress.Range />
                </Progress.Track>
              </Progress.Root>
            </Card.Body>
          </Card.Root>
        </Grid>

        <HStack
          gap="3"
          justify="between"
          wrap="wrap"
          style={styles.hostFooterBanner}
        >
          <HStack gap="3">
            <Avatar.Root
              size="md"
              variant="solid"
              palette={activeAccentPalette}
            >
              <Avatar.Fallback>{initials}</Avatar.Fallback>
            </Avatar.Root>
            <VStack gap="0.5">
              <HStack gap="1.5" wrap="wrap">
                <Text render={<span />} size="sm" weight="medium">
                  {draft.displayName}
                </Text>
                <Status.Root size="sm" palette={presencePalette}>
                  <Status.Indicator />
                  <span>{presenceLabel}</span>
                </Status.Root>
              </HStack>
              <Text render={<span />} variant="muted" size="xs">
                {draft.roleTitle} · {draft.timezone}
              </Text>
            </VStack>
          </HStack>
          <Button
            size="sm"
            variant="outline"
            onClick={() => openToSection("shortcuts")}
          >
            View shortcuts
          </Button>
        </HStack>
      </VStack>

      {/* ── Contained Two-Pane Preferences Modal ── */}
      {isOpen ? (
        <Center
          style={styles.modalOverlay}
          onClick={() => setDialogOpen(false)}
        >
          <HStack
            gap="0"
            align="stretch"
            role="dialog"
            aria-modal="true"
            aria-labelledby={titleId}
            tabIndex={-1}
            onKeyDown={handleDialogKeyDown}
            onClick={(e) => e.stopPropagation()}
            style={styles.dialogFrame}
          >
            {/* Desktop Left Categorized Navigation Rail */}
            <Sidebar.Root
              variant="sidebar"
              mode="collapsible"
              size="md"
              aria-label="Preferences navigation"
              style={styles.leftRail}
            >
              <Sidebar.Header style={styles.railHeader}>
                <HStack gap="2">
                  <IconBadge
                    variant="solid"
                    size="sm"
                    palette={activeAccentPalette}
                  >
                    <VelaMark />
                  </IconBadge>
                  <Heading
                    render={<h2 />}
                    id={titleId}
                    size="md"
                    style={styles.railTitle}
                  >
                    Preferences
                  </Heading>
                </HStack>
                <Kbd size="xs" variant="subtle">
                  ⌘ ,
                </Kbd>
              </Sidebar.Header>

              <div {...stylex.props(styles.railSearchWrap)}>
                {renderSearchBox()}
              </div>

              <Sidebar.Body style={styles.railBody}>
                {isSearching
                  ? renderSearchResults()
                  : NAV_GROUPS.map((group) => (
                      <Sidebar.Group key={group.label}>
                        <Sidebar.GroupHeader>
                          <Sidebar.GroupTitle style={styles.navGroupLabel}>
                            {group.label}
                          </Sidebar.GroupTitle>
                        </Sidebar.GroupHeader>
                        <Sidebar.GroupContent>
                          <VStack render={<ul />} gap="0.5" style={styles.navList}>
                            {group.items.map((item) => {
                              const isActive = activeSection === item.id;
                              const dirtyCount = dirtyBySection[item.id];
                              return (
                                <SidebarNavItem.Item key={item.id} size="md">
                                  <SidebarNavItem.Button
                                    type="button"
                                    aria-current={isActive ? "page" : undefined}
                                    style={
                                      isActive ? sidebarNavItemActive : undefined
                                    }
                                    onClick={() => selectSection(item.id)}
                                  >
                                    <SidebarNavItem.Icon
                                      viewBox="0 0 20 20"
                                      fill="none"
                                      stroke="currentColor"
                                      strokeWidth="1.6"
                                      strokeLinecap="round"
                                      strokeLinejoin="round"
                                      aria-hidden="true"
                                    >
                                      <SectionGlyph id={item.id} />
                                    </SidebarNavItem.Icon>
                                    <span>{item.label}</span>
                                    <SidebarNavItem.EndElement>
                                      <HStack render={<span />} gap="1.5">
                                        {dirtyCount > 0 ? (
                                          <span
                                            aria-label={`${dirtyCount} unsaved`}
                                            {...stylex.props(styles.dirtyDot)}
                                          />
                                        ) : null}
                                        {item.id === "integrations" ? (
                                          <Badge
                                            variant="subtle"
                                            size="xs"
                                            palette={grayPalette}
                                          >
                                            {connectedCount}/{integrations.length}
                                          </Badge>
                                        ) : null}
                                        {item.id === "security" ? (
                                          <Badge
                                            variant="subtle"
                                            size="xs"
                                            palette={grayPalette}
                                          >
                                            {sessions.length}
                                          </Badge>
                                        ) : null}
                                      </HStack>
                                    </SidebarNavItem.EndElement>
                                  </SidebarNavItem.Button>
                                </SidebarNavItem.Item>
                              );
                            })}
                          </VStack>
                        </Sidebar.GroupContent>
                      </Sidebar.Group>
                    ))}
              </Sidebar.Body>

              <Sidebar.Footer style={styles.railFooter}>
                <HStack gap="2.5" justify="between">
                  <HStack gap="2.5">
                    <Avatar.Root
                      size="sm"
                      variant="solid"
                      palette={activeAccentPalette}
                    >
                      <Avatar.Fallback>{initials}</Avatar.Fallback>
                    </Avatar.Root>
                    <VStack gap="0">
                      <Text
                        render={<span />}
                        size="xs"
                        weight="semibold"
                        truncate="true"
                      >
                        {draft.displayName || "Soren Lindqvist"}
                      </Text>
                      <Text
                        render={<span />}
                        variant="mono"
                        size="xs"
                        tone="muted"
                        truncate="true"
                      >
                        {workspaceName}
                      </Text>
                    </VStack>
                  </HStack>
                  <Badge variant="subtle" size="xs" palette={activeAccentPalette}>
                    Pro
                  </Badge>
                </HStack>
              </Sidebar.Footer>
            </Sidebar.Root>

            {/* Narrow Container Top Navigation Strip */}
            <VStack gap="2.5" style={styles.narrowHeader}>
              <HStack gap="2" justify="between">
                <HStack gap="2">
                  <IconBadge
                    variant="solid"
                    size="sm"
                    palette={activeAccentPalette}
                  >
                    <VelaMark />
                  </IconBadge>
                  <Text render={<span />} size="sm" weight="semibold">
                    Preferences
                  </Text>
                </HStack>
                <HStack gap="1.5">
                  {totalDirtyCount > 0 ? (
                    <Badge variant="subtle" size="xs" palette={amberPalette}>
                      {totalDirtyCount} unsaved
                    </Badge>
                  ) : null}
                  <IconButton
                    variant="ghost"
                    size="xs"
                    aria-label="Close preferences"
                    onClick={() => setDialogOpen(false)}
                  >
                    <CloseGlyph />
                  </IconButton>
                </HStack>
              </HStack>

              {renderSearchBox()}

              {isSearching ? (
                <div {...stylex.props(styles.narrowSearchResultsPane)}>
                  {renderSearchResults()}
                </div>
              ) : (
                <HStack
                  render={<nav />}
                  aria-label="Preference categories"
                  gap="1.5"
                  style={styles.narrowCategoryRail}
                >
                  {ALL_NAV_ITEMS.map((item) => {
                    const isActive = activeSection === item.id;
                    return (
                      <button
                        key={item.id}
                        type="button"
                        aria-current={isActive ? "page" : undefined}
                        onClick={() => selectSection(item.id)}
                        {...stylex.props(
                          styles.narrowCategoryPill,
                          isActive && styles.narrowCategoryPillActive,
                        )}
                      >
                        <Icon
                          size="xs"
                          viewBox="0 0 20 20"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="1.6"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          aria-hidden="true"
                        >
                          <SectionGlyph id={item.id} />
                        </Icon>
                        <span>{item.shortLabel}</span>
                        {dirtyBySection[item.id] > 0 ? (
                          <span {...stylex.props(styles.dirtyDot)} />
                        ) : null}
                      </button>
                    );
                  })}
                </HStack>
              )}
            </VStack>

            {/* Right Scrollable Content Pane */}
            <VStack gap="0" style={styles.contentColumn}>
              <HStack
                render={<header />}
                align="start"
                gap="3"
                justify="between"
                style={styles.contentHeader}
              >
                <VStack gap="0.5">
                  <Heading
                    render={<h3 />}
                    size="lg"
                    style={styles.contentTitle}
                  >
                    {activeMeta.label}
                  </Heading>
                  <Text variant="muted" size="sm">
                    {activeMeta.description}
                  </Text>
                </VStack>

                <HStack gap="2" style={styles.shrink0}>
                  {totalDirtyCount > 0 ? (
                    <Badge variant="subtle" size="sm" palette={amberPalette}>
                      {totalDirtyCount} unsaved
                    </Badge>
                  ) : (
                    <Badge variant="outline" size="sm" palette={grayPalette}>
                      Saved
                    </Badge>
                  )}
                  <span {...stylex.props(styles.desktopCloseWrap)}>
                    <IconButton
                      variant="ghost"
                      size="sm"
                      aria-label="Close preferences"
                      onClick={() => setDialogOpen(false)}
                    >
                      <CloseGlyph />
                    </IconButton>
                  </span>
                </HStack>
              </HStack>

              <div {...stylex.props(styles.scrollArea)}>
                <VStack gap="5">
                  {/* ── 1. Profile ── */}
                  {activeSection === "profile" && (
                    <>
                      <SettingsGroup title="Account Identity">
                        <HStack
                          justify="between"
                          wrap="wrap"
                          style={styles.profileHero}
                        >
                          <HStack style={styles.gap3_5}>
                            <Avatar.Root
                              size="lg"
                              variant="solid"
                              palette={activeAccentPalette}
                            >
                              <Avatar.Fallback>{initials}</Avatar.Fallback>
                            </Avatar.Root>
                            <VStack gap="0.5">
                              <HStack gap="1.5" wrap="wrap">
                                <Text render={<span />} size="sm" weight="medium">
                                  {draft.displayName || "Unnamed member"}
                                </Text>
                                <Badge
                                  variant="subtle"
                                  size="xs"
                                  palette={greenPalette}
                                >
                                  Verified
                                </Badge>
                              </HStack>
                              <Text variant="muted" size="xs">
                                {draft.handle} · {draft.roleTitle}
                              </Text>
                            </VStack>
                          </HStack>
                          <Button
                            size="sm"
                            variant="surface"
                            onClick={() => {
                              const currentIdx = ACCENT_OPTIONS.findIndex(
                                (item) => item.id === draft.accentColor,
                              );
                              const next =
                                ACCENT_OPTIONS[
                                  (currentIdx + 1) % ACCENT_OPTIONS.length
                                ];
                              if (next) {
                                updateDraft("accentColor", next.id);
                                queue.info("Avatar tint updated", {
                                  description: `Switched workspace tint to ${next.label}.`,
                                });
                              }
                            }}
                          >
                            Cycle tint
                          </Button>
                        </HStack>

                        <Separator decorative />

                        <SettingsRow
                          title="Display name"
                          description="Shown on multiplayer cursors, snapshots, and review threads."
                          control={
                            <Input
                              size="sm"
                              value={draft.displayName}
                              aria-label="Display name"
                              onChange={(e) =>
                                updateDraft("displayName", e.target.value)
                              }
                              style={styles.controlFixedWidth}
                            />
                          }
                        />

                        <Separator decorative />

                        <SettingsRow
                          title="Handle"
                          description="Used when teammates mention you in comments."
                          control={
                            <Input
                              size="sm"
                              value={draft.handle}
                              aria-label="Handle"
                              onChange={(e) =>
                                updateDraft("handle", e.target.value)
                              }
                              style={styles.controlFixedWidth}
                            />
                          }
                        />

                        <Separator decorative />

                        <SettingsRow
                          title="Availability status"
                          description="Let collaborators know if you are open to live pairing."
                          control={
                            <SegmentGroup.Root
                              size="xs"
                              value={draft.presence}
                              onValueChange={(value) =>
                                updateDraft(
                                  "presence",
                                  value as PresenceStatus,
                                )
                              }
                            >
                              <SegmentGroup.Item value="active">
                                Active
                              </SegmentGroup.Item>
                              <SegmentGroup.Item value="focus">
                                Focus
                              </SegmentGroup.Item>
                              <SegmentGroup.Item value="away">
                                Away
                              </SegmentGroup.Item>
                            </SegmentGroup.Root>
                          }
                        />
                      </SettingsGroup>

                      <SettingsGroup title="Region & Startup">
                        <SettingsRow
                          title="Time zone"
                          description="Applied to scheduled releases and version history timestamps."
                          control={
                            <Select.Root
                              size="sm"
                              items={TIMEZONE_OPTIONS}
                              value={draft.timezone}
                              onValueChange={(next) => {
                                if (next) {
                                  updateDraft("timezone", next);
                                }
                              }}
                              style={styles.controlFixedWidth}
                            >
                              <Select.Control>
                                <Select.Trigger>
                                  <Select.Value placeholder="Choose time zone" />
                                </Select.Trigger>
                                <Select.IndicatorGroup>
                                  <Select.Icon />
                                </Select.IndicatorGroup>
                              </Select.Control>
                              <Select.Content>
                                {TIMEZONE_OPTIONS.map((opt) => (
                                  <Select.Item
                                    key={opt.value}
                                    value={opt.value}
                                  >
                                    <Select.ItemText>
                                      {opt.label}
                                    </Select.ItemText>
                                    <Select.ItemIndicator />
                                  </Select.Item>
                                ))}
                              </Select.Content>
                            </Select.Root>
                          }
                        />

                        <Separator decorative />

                        <SettingsRow
                          title="Default landing view"
                          description="Choose the surface opened when launching Vela Studio."
                          control={
                            <Select.Root
                              size="sm"
                              items={LANDING_VIEW_OPTIONS}
                              value={draft.landingView}
                              onValueChange={(next) => {
                                if (next) {
                                  updateDraft("landingView", next);
                                }
                              }}
                              style={styles.controlFixedWidth}
                            >
                              <Select.Control>
                                <Select.Trigger>
                                  <Select.Value placeholder="Landing view" />
                                </Select.Trigger>
                                <Select.IndicatorGroup>
                                  <Select.Icon />
                                </Select.IndicatorGroup>
                              </Select.Control>
                              <Select.Content>
                                {LANDING_VIEW_OPTIONS.map((opt) => (
                                  <Select.Item
                                    key={opt.value}
                                    value={opt.value}
                                  >
                                    <Select.ItemText>
                                      {opt.label}
                                    </Select.ItemText>
                                    <Select.ItemIndicator />
                                  </Select.Item>
                                ))}
                              </Select.Content>
                            </Select.Root>
                          }
                        />

                        <Separator decorative />

                        <SettingsRow
                          title="Show local time on profile"
                          description="Helps distributed teammates avoid paging outside working hours."
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.showLocalTime}
                                onCheckedChange={(checked) =>
                                  updateDraft("showLocalTime", checked)
                                }
                                aria-label="Show local time on profile"
                              />
                            </Switch.Root>
                          }
                        />
                      </SettingsGroup>
                    </>
                  )}

                  {/* ── 2. Notifications ── */}
                  {activeSection === "notifications" && (
                    <>
                      <SettingsGroup title="Delivery & Quiet Hours">
                        <SettingsRow
                          title="Activity digest cadence"
                          description="How often email summaries are bundled when you are offline."
                          control={
                            <Select.Root
                              size="sm"
                              items={DIGEST_OPTIONS}
                              value={draft.digestCadence}
                              onValueChange={(next) => {
                                if (next) {
                                  updateDraft("digestCadence", next);
                                }
                              }}
                              style={styles.controlFixedWidth}
                            >
                              <Select.Control>
                                <Select.Trigger>
                                  <Select.Value placeholder="Select cadence" />
                                </Select.Trigger>
                                <Select.IndicatorGroup>
                                  <Select.Icon />
                                </Select.IndicatorGroup>
                              </Select.Control>
                              <Select.Content>
                                {DIGEST_OPTIONS.map((opt) => (
                                  <Select.Item
                                    key={opt.value}
                                    value={opt.value}
                                  >
                                    <Select.ItemText>
                                      {opt.label}
                                    </Select.ItemText>
                                    <Select.ItemIndicator />
                                  </Select.Item>
                                ))}
                              </Select.Content>
                            </Select.Root>
                          }
                        />

                        <Separator decorative />

                        <SettingsRow
                          title="Quiet hours schedule"
                          description="Hold non-urgent desktop alerts while you are away."
                          control={
                            <SegmentGroup.Root
                              size="xs"
                              value={draft.quietHours}
                              onValueChange={(value) =>
                                updateDraft(
                                  "quietHours",
                                  value as QuietHoursPreset,
                                )
                              }
                            >
                              <SegmentGroup.Item value="off">
                                Off
                              </SegmentGroup.Item>
                              <SegmentGroup.Item value="evenings">
                                Evenings
                              </SegmentGroup.Item>
                              <SegmentGroup.Item value="weekends">
                                Weekends
                              </SegmentGroup.Item>
                            </SegmentGroup.Root>
                          }
                        />

                        <Separator decorative />

                        <SettingsRow
                          title="Alert chime volume"
                          description="Output level for direct mentions and published build notices."
                          control={
                            <HStack gap="3" style={styles.controlFixedWidth}>
                              <Slider.Root
                                size="sm"
                                min={0}
                                max={100}
                                step={5}
                                value={draft.alertVolume}
                                palette={activeAccentPalette}
                                onValueChange={(next) => {
                                  const val = Array.isArray(next)
                                    ? (next[0] ?? 0)
                                    : next;
                                  updateDraft("alertVolume", val);
                                }}
                                style={styles.sliderFlex}
                              >
                                <Slider.Control>
                                  <Slider.Track>
                                    <Slider.Indicator />
                                    <Slider.Thumb aria-label="Alert chime volume" />
                                  </Slider.Track>
                                </Slider.Control>
                              </Slider.Root>
                              <Text
                                render={<span />}
                                variant="mono"
                                size="xs"
                                weight="semibold"
                                align="end"
                                tabular="true"
                                style={styles.tabularValue}
                              >
                                {draft.alertVolume}%
                              </Text>
                            </HStack>
                          }
                        />
                      </SettingsGroup>

                      <SettingsGroup title="Event Subscriptions">
                        <SettingsRow
                          title="Desktop push alerts"
                          description="Show native banners for direct mentions and approval requests."
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.desktopPush}
                                onCheckedChange={(checked) =>
                                  updateDraft("desktopPush", checked)
                                }
                                aria-label="Desktop push alerts"
                              />
                            </Switch.Root>
                          }
                        />
                        <Separator decorative />
                        <SettingsRow
                          title="Design review mentions"
                          description="Alert immediately when someone tags your handle on a frame."
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.reviewMentions}
                                onCheckedChange={(checked) =>
                                  updateDraft("reviewMentions", checked)
                                }
                                aria-label="Design review mentions"
                              />
                            </Switch.Root>
                          }
                        />
                        <Separator decorative />
                        <SettingsRow
                          title="Comment thread replies"
                          description="Notify when teammates respond in discussions you follow."
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.commentReplies}
                                onCheckedChange={(checked) =>
                                  updateDraft("commentReplies", checked)
                                }
                                aria-label="Comment thread replies"
                              />
                            </Switch.Root>
                          }
                        />
                        <Separator decorative />
                        <SettingsRow
                          title="Weekly workspace summary"
                          description="Monday morning recap of published libraries and active branches."
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.weeklySummary}
                                onCheckedChange={(checked) =>
                                  updateDraft("weeklySummary", checked)
                                }
                                aria-label="Weekly workspace summary"
                              />
                            </Switch.Root>
                          }
                        />
                        <Separator decorative />
                        <SettingsRow
                          title="Product changelog notes"
                          description="Occasional updates on new Vela Studio editor capabilities."
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.releaseNotes}
                                onCheckedChange={(checked) =>
                                  updateDraft("releaseNotes", checked)
                                }
                                aria-label="Product changelog notes"
                              />
                            </Switch.Root>
                          }
                        />
                      </SettingsGroup>
                    </>
                  )}

                  {/* ── 3. Security ── */}
                  {activeSection === "security" && (
                    <>
                      <SettingsGroup title="Sign-in Protection">
                        <SettingsRow
                          title="Two-factor authentication"
                          description="Require a time-based authenticator code on unrecognized devices."
                          badge={{
                            label: "Recommended",
                            palette: greenPalette,
                          }}
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.twoFactorEnabled}
                                onCheckedChange={(checked) =>
                                  updateDraft("twoFactorEnabled", checked)
                                }
                                aria-label="Two-factor authentication"
                              />
                            </Switch.Root>
                          }
                        />
                        <Separator decorative />
                        <SettingsRow
                          title="Require passkey for library releases"
                          description="Prompt Touch ID or hardware security key before publishing to prod."
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.passkeyDeploys}
                                onCheckedChange={(checked) =>
                                  updateDraft("passkeyDeploys", checked)
                                }
                                aria-label="Require passkey for library releases"
                              />
                            </Switch.Root>
                          }
                        />
                        <Separator decorative />
                        <SettingsRow
                          title="Idle session timeout"
                          description="Automatically lock desktop sessions after prolonged inactivity."
                          control={
                            <Select.Root
                              size="sm"
                              items={SESSION_TIMEOUT_OPTIONS}
                              value={draft.sessionTimeout}
                              onValueChange={(next) => {
                                if (next) {
                                  updateDraft("sessionTimeout", next);
                                }
                              }}
                              style={styles.controlFixedWidth}
                            >
                              <Select.Control>
                                <Select.Trigger>
                                  <Select.Value placeholder="Timeout" />
                                </Select.Trigger>
                                <Select.IndicatorGroup>
                                  <Select.Icon />
                                </Select.IndicatorGroup>
                              </Select.Control>
                              <Select.Content>
                                {SESSION_TIMEOUT_OPTIONS.map((opt) => (
                                  <Select.Item
                                    key={opt.value}
                                    value={opt.value}
                                  >
                                    <Select.ItemText>
                                      {opt.label}
                                    </Select.ItemText>
                                    <Select.ItemIndicator />
                                  </Select.Item>
                                ))}
                              </Select.Content>
                            </Select.Root>
                          }
                        />
                      </SettingsGroup>

                      <SettingsGroup
                        title={`Active Sessions (${sessions.length})`}
                        action={
                          sessions.length > 1 ? (
                            <Button
                              size="2xs"
                              variant="ghost"
                              palette={redPalette}
                              onClick={handleRevokeOtherSessions}
                            >
                              Sign out others
                            </Button>
                          ) : null
                        }
                      >
                        {sessions.map((session, idx) => (
                          <div key={session.id}>
                            {idx > 0 ? <Separator decorative /> : null}
                            <HStack
                              gap="3"
                              justify="between"
                              style={styles.itemRow}
                            >
                              <HStack gap="3">
                                <IconBadge
                                  variant="subtle"
                                  size="md"
                                  palette={
                                    session.current
                                      ? activeAccentPalette
                                      : grayPalette
                                  }
                                >
                                  <DeviceGlyph kind={session.kind} />
                                </IconBadge>
                                <VStack gap="0.5">
                                  <HStack gap="1.5" wrap="wrap">
                                    <Text
                                      render={<span />}
                                      size="sm"
                                      weight="medium"
                                    >
                                      {session.name}
                                    </Text>
                                    {session.current ? (
                                      <Status.Root
                                        size="sm"
                                        palette={greenPalette}
                                      >
                                        <Status.Indicator />
                                        <span>This device</span>
                                      </Status.Root>
                                    ) : null}
                                  </HStack>
                                  <Text variant="muted" size="xs">
                                    {session.client} · {session.location} ·{" "}
                                    {session.lastSeen}
                                  </Text>
                                </VStack>
                              </HStack>
                              {!session.current ? (
                                <Button
                                  size="xs"
                                  variant="surface"
                                  onClick={() => handleRevokeSession(session)}
                                >
                                  Sign out
                                </Button>
                              ) : null}
                            </HStack>
                          </div>
                        ))}
                      </SettingsGroup>
                    </>
                  )}

                  {/* ── 4. Appearance ── */}
                  {activeSection === "appearance" && (
                    <>
                      <SettingsGroup title="Theme & Accent">
                        <SettingsRow
                          title="Color mode"
                          description="Follow your operating system or lock Vela Studio to light or dark."
                          control={
                            <SegmentGroup.Root
                              size="xs"
                              value={draft.themeMode}
                              onValueChange={(value) =>
                                updateDraft(
                                  "themeMode",
                                  value as ThemePreference,
                                )
                              }
                            >
                              <SegmentGroup.Item value="light">
                                Light
                              </SegmentGroup.Item>
                              <SegmentGroup.Item value="dark">
                                Dark
                              </SegmentGroup.Item>
                              <SegmentGroup.Item value="system">
                                System
                              </SegmentGroup.Item>
                            </SegmentGroup.Root>
                          }
                        />

                        <Separator decorative />

                        <SettingsRow
                          title="Accent color"
                          description="Applied to active controls, selection rings, and canvas cursors."
                          control={
                            <HStack
                              gap="2"
                              wrap="wrap"
                              role="radiogroup"
                              aria-label="Accent color"
                            >
                              {ACCENT_OPTIONS.map((option) => {
                                const selected =
                                  draft.accentColor === option.id;
                                return (
                                  <button
                                    key={option.id}
                                    type="button"
                                    role="radio"
                                    aria-checked={selected}
                                    aria-label={option.label}
                                    onClick={() =>
                                      updateDraft("accentColor", option.id)
                                    }
                                    {...stylex.props(
                                      styles.swatchButton,
                                      selected && styles.swatchButtonActive,
                                    )}
                                  >
                                    <ColorSwatch
                                      size="md"
                                      shape="circle"
                                      style={swatchColors[option.id]}
                                    />
                                    {selected ? (
                                      <Center
                                        render={<span />}
                                        display="inline"
                                        style={styles.swatchCheckOverlay}
                                      >
                                        <CheckGlyph />
                                      </Center>
                                    ) : null}
                                  </button>
                                );
                              })}
                            </HStack>
                          }
                          detail={
                            <VStack gap="2.5" style={styles.livePreviewCard}>
                              <HStack gap="2" justify="between" wrap="wrap">
                                <HStack gap="1.5" wrap="wrap">
                                  <Badge
                                    variant="solid"
                                    size="xs"
                                    palette={activeAccentPalette}
                                  >
                                    Live preview
                                  </Badge>
                                  <Text
                                    render={<span />}
                                    variant="muted"
                                    size="xs"
                                  >
                                    {draft.themeMode} · {draft.density} ·{" "}
                                    {draft.uiScale}%
                                  </Text>
                                </HStack>
                                <Status.Root
                                  size="sm"
                                  palette={activeAccentPalette}
                                >
                                  <Status.Indicator />
                                  <span>
                                    {ACCENT_OPTIONS.find(
                                      (a) => a.id === draft.accentColor,
                                    )?.label ?? "Indigo"}
                                  </span>
                                </Status.Root>
                              </HStack>
                              <VStack gap="1.5">
                                <div
                                  {...stylex.props(
                                    styles.livePreviewBarPrimary,
                                  )}
                                />
                                <div
                                  {...stylex.props(
                                    styles.livePreviewBarSecondary,
                                  )}
                                />
                              </VStack>
                            </VStack>
                          }
                        />
                      </SettingsGroup>

                      <SettingsGroup title="Scale & Visual Comfort">
                        <SettingsRow
                          title="Interface scale"
                          description="Adjust text and control magnification across panels and toolbars."
                          control={
                            <HStack gap="3" style={styles.controlFixedWidth}>
                              <Slider.Root
                                size="sm"
                                min={90}
                                max={125}
                                step={5}
                                value={draft.uiScale}
                                palette={activeAccentPalette}
                                onValueChange={(next) => {
                                  const val = Array.isArray(next)
                                    ? (next[0] ?? 100)
                                    : next;
                                  updateDraft("uiScale", val);
                                }}
                                style={styles.sliderFlex}
                              >
                                <Slider.Control>
                                  <Slider.Track>
                                    <Slider.Indicator />
                                    <Slider.Thumb aria-label="Interface scale" />
                                  </Slider.Track>
                                </Slider.Control>
                              </Slider.Root>
                              <Text
                                render={<span />}
                                variant="mono"
                                size="xs"
                                weight="semibold"
                                align="end"
                                tabular="true"
                                style={styles.tabularValue}
                              >
                                {draft.uiScale}%
                              </Text>
                            </HStack>
                          }
                        />

                        <Separator decorative />

                        <SettingsRow
                          title="Interface density"
                          description="Controls row padding in layer trees, inspectors, and tables."
                          control={
                            <SegmentGroup.Root
                              size="xs"
                              value={draft.density}
                              onValueChange={(value) =>
                                updateDraft(
                                  "density",
                                  value as DensityPreference,
                                )
                              }
                            >
                              <SegmentGroup.Item value="compact">
                                Compact
                              </SegmentGroup.Item>
                              <SegmentGroup.Item value="default">
                                Default
                              </SegmentGroup.Item>
                              <SegmentGroup.Item value="spacious">
                                Spacious
                              </SegmentGroup.Item>
                            </SegmentGroup.Root>
                          }
                        />

                        <Separator decorative />

                        <SettingsRow
                          title="Reduce motion"
                          description="Replace spring transitions and zoom animations with subtle fades."
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.reduceMotion}
                                onCheckedChange={(checked) =>
                                  updateDraft("reduceMotion", checked)
                                }
                                aria-label="Reduce motion"
                              />
                            </Switch.Root>
                          }
                        />

                        <Separator decorative />

                        <SettingsRow
                          title="Translucent window chrome"
                          description="Blend sidebar and floating toolbar surfaces with canvas depth."
                          badge={{ label: "Beta", palette: bluePalette }}
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.translucentChrome}
                                onCheckedChange={(checked) =>
                                  updateDraft("translucentChrome", checked)
                                }
                                aria-label="Translucent window chrome"
                              />
                            </Switch.Root>
                          }
                        />
                      </SettingsGroup>
                    </>
                  )}

                  {/* ── 5. Integrations ── */}
                  {activeSection === "integrations" && (
                    <>
                      <SettingsGroup title="Connected Services">
                        {integrations.map((item, idx) => (
                          <div key={item.id}>
                            {idx > 0 ? <Separator decorative /> : null}
                            <HStack
                              gap="3"
                              justify="between"
                              style={styles.itemRow}
                            >
                              <HStack gap="3">
                                <IconBadge
                                  variant="subtle"
                                  size="md"
                                  palette={item.palette}
                                >
                                  <IntegrationGlyph id={item.id} />
                                </IconBadge>
                                <VStack gap="0.5">
                                  <HStack gap="1.5" wrap="wrap">
                                    <Text
                                      render={<span />}
                                      size="sm"
                                      weight="medium"
                                    >
                                      {item.name}
                                    </Text>
                                    <Badge
                                      variant="subtle"
                                      size="xs"
                                      palette={grayPalette}
                                    >
                                      {item.category}
                                    </Badge>
                                  </HStack>
                                  <Text variant="muted" size="xs">
                                    {item.description}
                                  </Text>
                                  <Status.Root
                                    size="sm"
                                    palette={
                                      item.connected
                                        ? greenPalette
                                        : grayPalette
                                    }
                                  >
                                    <Status.Indicator />
                                    <Text
                                      render={<span />}
                                      variant="muted"
                                      size="xs"
                                    >
                                      {item.accountLabel}
                                    </Text>
                                  </Status.Root>
                                </VStack>
                              </HStack>

                              <Button
                                size="xs"
                                variant={item.connected ? "surface" : "solid"}
                                palette={
                                  item.connected
                                    ? grayPalette
                                    : activeAccentPalette
                                }
                                onClick={() => handleToggleIntegration(item)}
                              >
                                {item.connected ? "Disconnect" : "Connect"}
                              </Button>
                            </HStack>
                          </div>
                        ))}
                      </SettingsGroup>

                      <SettingsGroup title="Outgoing Webhooks">
                        <SettingsRow
                          title="Event endpoint URL"
                          description="Receives signed JSON payloads whenever tokens or libraries publish."
                          control={
                            <HStack gap="2" style={styles.shrink0}>
                              <Input
                                size="sm"
                                value={draft.webhookEndpoint}
                                aria-label="Event endpoint URL"
                                onChange={(e) =>
                                  updateDraft("webhookEndpoint", e.target.value)
                                }
                                style={styles.controlFixedWidth}
                              />
                              <Button
                                size="sm"
                                variant="surface"
                                onClick={handleCopyWebhook}
                              >
                                Copy
                              </Button>
                            </HStack>
                          }
                        />
                        <Separator decorative />
                        <SettingsRow
                          title="Exponential backoff retries"
                          description="Retry failed deliveries up to 5 times over 60 minutes."
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.retryWebhooks}
                                onCheckedChange={(checked) =>
                                  updateDraft("retryWebhooks", checked)
                                }
                                aria-label="Exponential backoff retries"
                              />
                            </Switch.Root>
                          }
                        />
                      </SettingsGroup>
                    </>
                  )}

                  {/* ── 6. Keyboard Shortcuts ── */}
                  {activeSection === "shortcuts" && (
                    <>
                      <SettingsGroup title="Input Behavior">
                        <SettingsRow
                          title="Single-key canvas chords"
                          description="Trigger tools like Frame (F) without holding a modifier key."
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.singleKeyShortcuts}
                                onCheckedChange={(checked) =>
                                  updateDraft("singleKeyShortcuts", checked)
                                }
                                aria-label="Single-key canvas chords"
                              />
                            </Switch.Root>
                          }
                        />
                        <Separator decorative />
                        <SettingsRow
                          title="Vim-style list navigation"
                          description="Move through layers and command results with J / K keys."
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.vimNavigation}
                                onCheckedChange={(checked) =>
                                  updateDraft("vimNavigation", checked)
                                }
                                aria-label="Vim-style list navigation"
                              />
                            </Switch.Root>
                          }
                        />
                        <Separator decorative />
                        <SettingsRow
                          title="Show shortcut hints in tooltips"
                          description="Display key combinations alongside toolbar button labels."
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.showTooltipHints}
                                onCheckedChange={(checked) =>
                                  updateDraft("showTooltipHints", checked)
                                }
                                aria-label="Show shortcut hints in tooltips"
                              />
                            </Switch.Root>
                          }
                        />
                      </SettingsGroup>

                      <SettingsGroup
                        title="Key Bindings"
                        action={
                          <Button
                            size="2xs"
                            variant="ghost"
                            onClick={handleResetShortcuts}
                          >
                            Reset defaults
                          </Button>
                        }
                      >
                        {shortcuts.map((item, idx) => {
                          const combo = item.usingAlt
                            ? item.altKeys
                            : item.keys;
                          return (
                            <div key={item.id}>
                              {idx > 0 ? <Separator decorative /> : null}
                              <HStack
                                gap="3"
                                justify="between"
                                style={styles.itemRow}
                              >
                                <VStack gap="0.5">
                                  <HStack gap="1.5" wrap="wrap">
                                    <Text
                                      render={<span />}
                                      size="sm"
                                      weight="medium"
                                    >
                                      {item.label}
                                    </Text>
                                    <Badge
                                      variant="subtle"
                                      size="xs"
                                      palette={grayPalette}
                                    >
                                      {item.category}
                                    </Badge>
                                  </HStack>
                                  <Text
                                    render={<span />}
                                    variant="muted"
                                    size="xs"
                                  >
                                    {item.usingAlt
                                      ? "Alternate binding active"
                                      : "Default binding"}
                                  </Text>
                                </VStack>

                                <HStack gap="2.5" style={styles.shrink0}>
                                  <HStack render={<span />} gap="1">
                                    {combo.map((key) => (
                                      <Kbd
                                        key={key}
                                        size="sm"
                                        variant="raised"
                                      >
                                        {key}
                                      </Kbd>
                                    ))}
                                  </HStack>
                                  <Button
                                    size="2xs"
                                    variant="surface"
                                    onClick={() => handleCycleShortcut(item)}
                                  >
                                    Swap
                                  </Button>
                                  <Switch.Root
                                    size="xs"
                                    palette={activeAccentPalette}
                                  >
                                    <Switch.Control
                                      checked={item.enabled}
                                      onCheckedChange={(checked) =>
                                        handleToggleShortcutEnabled(
                                          item.id,
                                          checked,
                                        )
                                      }
                                      aria-label={`Enable ${item.label}`}
                                    />
                                  </Switch.Root>
                                </HStack>
                              </HStack>
                            </div>
                          );
                        })}
                      </SettingsGroup>
                    </>
                  )}

                  {/* ── 7. Billing & Quota ── */}
                  {activeSection === "billing" && (
                    <>
                      <SettingsGroup title="Subscription Plan">
                        <HStack
                          gap="3"
                          justify="between"
                          wrap="wrap"
                          style={styles.planBanner}
                        >
                          <VStack gap="0.5">
                            <HStack gap="1.5" wrap="wrap">
                              <Text render={<span />} size="sm" weight="medium">
                                {workspaceName} Pro
                              </Text>
                              <Status.Root size="sm" palette={greenPalette}>
                                <Status.Indicator />
                                <span>Active</span>
                              </Status.Root>
                            </HStack>
                            <HStack align="baseline" gap="1.5">
                              <Text
                                render={<span />}
                                size="2xl"
                                weight="semibold"
                                tabular="true"
                              >
                                {draft.billingCycle === "annual"
                                  ? "$36"
                                  : "$45"}
                              </Text>
                              <Text
                                render={<span />}
                                variant="muted"
                                size="xs"
                              >
                                per editor / month · renews Jan 1, 2027
                              </Text>
                            </HStack>
                          </VStack>
                          <Button
                            size="sm"
                            variant="surface"
                            onClick={() =>
                              queue.info("Invoice downloaded", {
                                description:
                                  "Saved vela-studio-invoice-2026-12.pdf.",
                              })
                            }
                          >
                            Latest invoice
                          </Button>
                        </HStack>

                        <Separator decorative />

                        <SettingsRow
                          title="Billing cycle"
                          description="Annual billing includes priority cloud rendering and 20% savings."
                          control={
                            <Select.Root
                              size="sm"
                              items={BILLING_CYCLE_OPTIONS}
                              value={draft.billingCycle}
                              onValueChange={(next) => {
                                if (next) {
                                  updateDraft("billingCycle", next);
                                }
                              }}
                              style={styles.controlFixedWidth}
                            >
                              <Select.Control>
                                <Select.Trigger>
                                  <Select.Value placeholder="Billing cycle" />
                                </Select.Trigger>
                                <Select.IndicatorGroup>
                                  <Select.Icon />
                                </Select.IndicatorGroup>
                              </Select.Control>
                              <Select.Content>
                                {BILLING_CYCLE_OPTIONS.map((opt) => (
                                  <Select.Item
                                    key={opt.value}
                                    value={opt.value}
                                  >
                                    <Select.ItemText>
                                      {opt.label}
                                    </Select.ItemText>
                                    <Select.ItemIndicator />
                                  </Select.Item>
                                ))}
                              </Select.Content>
                            </Select.Root>
                          }
                        />

                        <Separator decorative />

                        <SettingsRow
                          title="Auto-top-up render hours"
                          description="Add 15-hour compute blocks automatically if CI builds exceed quota."
                          control={
                            <Switch.Root
                              size="sm"
                              palette={activeAccentPalette}
                            >
                              <Switch.Control
                                checked={draft.autoTopUp}
                                onCheckedChange={(checked) =>
                                  updateDraft("autoTopUp", checked)
                                }
                                aria-label="Auto-top-up render hours"
                              />
                            </Switch.Root>
                          }
                        />
                      </SettingsGroup>

                      <SettingsGroup title="Current Cycle Usage">
                        {QUOTA_METRICS.map((metric, idx) => (
                          <div key={metric.id}>
                            {idx > 0 ? <Separator decorative /> : null}
                            <VStack gap="2" style={styles.quotaRow}>
                              <HStack
                                align="baseline"
                                gap="2"
                                justify="between"
                              >
                                <Text
                                  render={<span />}
                                  size="sm"
                                  weight="medium"
                                >
                                  {metric.label}
                                </Text>
                                <Text
                                  render={<span />}
                                  variant="mono"
                                  size="xs"
                                  weight="semibold"
                                  align="end"
                                  tabular="true"
                                  style={styles.tabularValue}
                                >
                                  {metric.usedLabel}
                                </Text>
                              </HStack>
                              <Progress.Root
                                value={metric.percent}
                                size="sm"
                                shape="full"
                                palette={
                                  metric.percent >= 75
                                    ? amberPalette
                                    : activeAccentPalette
                                }
                              >
                                <Progress.Track>
                                  <Progress.Range />
                                </Progress.Track>
                              </Progress.Root>
                              <Text
                                render={<span />}
                                variant="muted"
                                size="xs"
                              >
                                {metric.hint}
                              </Text>
                            </VStack>
                          </div>
                        ))}
                      </SettingsGroup>
                    </>
                  )}
                </VStack>
              </div>

              {/* Live Dirty-State Save / Discard Bar docked inside dialog */}
              {totalDirtyCount > 0 ? (
                <HStack
                  gap="3"
                  justify="between"
                  wrap="wrap"
                  role="status"
                  aria-live="polite"
                  style={styles.dirtyBar}
                >
                  <HStack gap="2">
                    <Status.Root size="sm" palette={amberPalette}>
                      <Status.Indicator />
                      <span>
                        {totalDirtyCount}{" "}
                        {totalDirtyCount === 1
                          ? "unsaved change"
                          : "unsaved changes"}
                      </span>
                    </Status.Root>
                  </HStack>
                  <HStack gap="2">
                    <Button size="sm" variant="ghost" onClick={handleDiscard}>
                      Discard
                    </Button>
                    <Button
                      size="sm"
                      variant="solid"
                      palette={activeAccentPalette}
                      onClick={handleSave}
                    >
                      Save changes
                    </Button>
                  </HStack>
                </HStack>
              ) : null}
            </VStack>
          </HStack>
        </Center>
      ) : null}

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

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