---
title: "Settings Form · UI SDK — StyleX Blocks"
description: "Account and workspace preferences page with quick-jump settings search, responsive sidebar-to-tabs navigation, profile details, timezone and appearance controls, notification switches, password and security options, dirty-state detection, and Save / Reset actions."
url: "https://stylexblocks.com/block/ui-sdk/settings-form/"
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 Form block

Account and workspace preferences page with quick-jump settings search, responsive sidebar-to-tabs navigation, profile details, timezone and appearance controls, notification switches, password and security options, dirty-state detection, and Save / Reset actions.

- Behavior engine: UI SDK
- Category: [Settings](https://stylexblocks.com/blocks/settings.md)
- Built with: [Autocomplete](https://stylexblocks.com/components/ui-sdk/autocomplete.md), [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), [Center](https://stylexblocks.com/components/ui-sdk/center.md), [Checkbox](https://stylexblocks.com/components/ui-sdk/checkbox.md), [Field](https://stylexblocks.com/components/ui-sdk/field.md), [Grid](https://stylexblocks.com/components/ui-sdk/grid.md), [Heading](https://stylexblocks.com/components/ui-sdk/heading.md), [Icon](https://stylexblocks.com/components/ui-sdk/icon.md), [Input](https://stylexblocks.com/components/ui-sdk/input.md), [Input Addon](https://stylexblocks.com/components/ui-sdk/input-addon.md), [Password Input](https://stylexblocks.com/components/ui-sdk/password-input.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 Nav Item](https://stylexblocks.com/components/ui-sdk/sidebar-nav-item.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), [Tabs](https://stylexblocks.com/components/ui-sdk/tabs.md), [Text](https://stylexblocks.com/components/ui-sdk/text.md), [Textarea](https://stylexblocks.com/components/ui-sdk/textarea.md), [Toast](https://stylexblocks.com/components/ui-sdk/toast.md)
- HTML page: https://stylexblocks.com/block/ui-sdk/settings-form/

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

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

## Usage

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

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

## Source

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

```tsx
import * as stylex from "@stylexjs/stylex";
import { useCallback, useMemo, useState } from "react";
import { Autocomplete } from "#components/ui/ui-sdk/autocomplete.tsx";
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 { Center } from "#components/ui/ui-sdk/center.tsx";
import { Checkbox } from "#components/ui/ui-sdk/checkbox.tsx";
import { Field } from "#components/ui/ui-sdk/field.tsx";
import { Grid } from "#components/ui/ui-sdk/grid.tsx";
import { Heading } from "#components/ui/ui-sdk/heading.tsx";
import { Icon } from "#components/ui/ui-sdk/icon.tsx";
import { InputGroup } from "#components/ui/ui-sdk/input-addon.tsx";
import { Input } from "#components/ui/ui-sdk/input.tsx";
import { PasswordInput } from "#components/ui/ui-sdk/password-input.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 {
  SidebarNavItem,
  sidebarNavItemActive,
} from "#components/ui/ui-sdk/sidebar-nav-item.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 { Tabs } from "#components/ui/ui-sdk/tabs.tsx";
import { Text } from "#components/ui/ui-sdk/text.tsx";
import { Textarea } from "#components/ui/ui-sdk/textarea.tsx";
import { Toast, Toaster } from "#components/ui/ui-sdk/toast.tsx";
import { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";
import { semanticRadii } from "@stylexblocks/ui/semantic-tokens/radii.stylex.ts";
import {
  accentPalette,
  amberPalette,
  emeraldPalette,
} from "@stylexblocks/ui/themes/palettes.ts";
import { fonts } from "@stylexblocks/ui/tokens/fonts.stylex.ts";
import { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";
import type { StyleOverrideProps } from "#lib/recipe-props.ts";

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

export type SettingsNavId =
  | "account"
  | "members"
  | "billing"
  | "integrations"
  | "audit"
  | "api";

export type AppearancePreference = "system" | "light" | "dark";

export type WeekStartDay = "monday" | "sunday" | "saturday";

export interface SettingsFormValues {
  fullName: string;
  handle: string;
  email: string;
  role: string;
  bio: string;
  timezone: string;
  appearance: AppearancePreference;
  weekStartsOn: WeekStartDay;
  compactDensity: boolean;
  deployAlerts: boolean;
  reviewMentions: boolean;
  weeklyDigest: boolean;
  releaseNotes: boolean;
  twoFactorEnabled: boolean;
  dataExportAccess: boolean;
  autoRevokeSessions: boolean;
}

export interface SettingsSavePayload {
  values: SettingsFormValues;
  passwordChanged: boolean;
  savedAt: string;
}

export interface SettingsFormProps extends StyleOverrideProps {
  /** Workspace name displayed in the sidebar and page header. */
  workspaceName?: string;
  /** Primary page heading. */
  title?: string;
  /** Supporting subtitle beneath the heading. */
  description?: string;
  /** Initial values for account and workspace preferences. */
  initialValues?: Partial<SettingsFormValues>;
  /** Called with the validated values when the user saves changes. */
  onSave?: (payload: SettingsSavePayload) => void;
  /** Called when the user discards unsaved changes via Reset. */
  onReset?: () => void;
  /** Called when the user selects another workspace settings section. */
  onNavigateSection?: (sectionId: SettingsNavId) => void;
}

interface SettingsFormErrors {
  fullName?: string;
  handle?: string;
  email?: string;
  currentPassword?: string;
  newPassword?: string;
  confirmPassword?: string;
}

interface NavItemConfig {
  id: SettingsNavId;
  label: string;
  badge?: string;
}

interface SearchableSetting {
  label: string;
  sectionId: string;
  sectionName: string;
}

interface SelectOption<T extends string = string> {
  value: T;
  label: string;
}

// ── Demo Data & Constants ─────────────────────────────────────────────────────

const ACTIVE_NAV_ID: SettingsNavId = "account";

const NAV_ITEMS: NavItemConfig[] = [
  { id: "account", label: "Account" },
  { id: "members", label: "Members", badge: "12" },
  { id: "billing", label: "Billing" },
  { id: "integrations", label: "Integrations", badge: "4" },
  { id: "audit", label: "Audit log" },
  { id: "api", label: "API keys" },
];

const SEARCHABLE_SETTINGS: SearchableSetting[] = [
  { label: "Full name", sectionId: "settings-profile", sectionName: "Profile" },
  { label: "Handle", sectionId: "settings-profile", sectionName: "Profile" },
  { label: "Work email", sectionId: "settings-profile", sectionName: "Profile" },
  { label: "Role & bio", sectionId: "settings-profile", sectionName: "Profile" },
  {
    label: "Timezone",
    sectionId: "settings-preferences",
    sectionName: "Workspace preferences",
  },
  {
    label: "Appearance & theme",
    sectionId: "settings-preferences",
    sectionName: "Workspace preferences",
  },
  {
    label: "Compact sidebar density",
    sectionId: "settings-preferences",
    sectionName: "Workspace preferences",
  },
  {
    label: "Deployment alerts",
    sectionId: "settings-notifications",
    sectionName: "Notifications",
  },
  {
    label: "Review mentions & comments",
    sectionId: "settings-notifications",
    sectionName: "Notifications",
  },
  {
    label: "Weekly workspace digest",
    sectionId: "settings-notifications",
    sectionName: "Notifications",
  },
  {
    label: "Change password",
    sectionId: "settings-security",
    sectionName: "Security & access",
  },
  {
    label: "Two-factor authentication",
    sectionId: "settings-security",
    sectionName: "Security & access",
  },
  {
    label: "Workspace data exports",
    sectionId: "settings-security",
    sectionName: "Security & access",
  },
];

const TIMEZONE_OPTIONS = [
  { value: "America/Los_Angeles", label: "(UTC−08:00) Pacific Time — Los Angeles" },
  { value: "America/Denver", label: "(UTC−07:00) Mountain Time — Denver" },
  { value: "America/Chicago", label: "(UTC−06:00) Central Time — Chicago" },
  { value: "America/New_York", label: "(UTC−05:00) Eastern Time — New York" },
  { value: "Europe/London", label: "(UTC+00:00) Greenwich Mean Time — London" },
  { value: "Europe/Berlin", label: "(UTC+01:00) Central European Time — Berlin" },
  { value: "Asia/Tokyo", label: "(UTC+09:00) Japan Standard Time — Tokyo" },
  { value: "Australia/Sydney", label: "(UTC+10:00) Australian Eastern — Sydney" },
] as const satisfies readonly SelectOption[];

const WEEK_START_OPTIONS = [
  { value: "monday", label: "Monday (ISO 8601)" },
  { value: "sunday", label: "Sunday" },
  { value: "saturday", label: "Saturday" },
] as const satisfies readonly SelectOption<WeekStartDay>[];

const APPEARANCE_HINTS: Record<AppearancePreference, string> = {
  system: "Automatically matches your operating system light or dark appearance.",
  light: "Always render Kestrel surfaces in crisp light mode.",
  dark: "Always render Kestrel surfaces in low-glare dark mode.",
};

const DEFAULT_VALUES: SettingsFormValues = {
  fullName: "Maya Lin",
  handle: "mayalin",
  email: "maya@kestrel.dev",
  role: "Staff Product Designer",
  bio: "Leading design systems, semantic tokens, and runtime ergonomics for Kestrel Cloud.",
  timezone: "America/Los_Angeles",
  appearance: "system",
  weekStartsOn: "monday",
  compactDensity: false,
  deployAlerts: true,
  reviewMentions: true,
  weeklyDigest: false,
  releaseNotes: true,
  twoFactorEnabled: true,
  dataExportAccess: false,
  autoRevokeSessions: true,
};

const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const HANDLE_PATTERN = /^[a-z0-9](?:[a-z0-9-_]{1,28}[a-z0-9])?$/i;
const BIO_MAX_LENGTH = 180;

const VALUE_KEYS = Object.keys(DEFAULT_VALUES) as Array<keyof SettingsFormValues>;

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

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

// ── Inline SVG Icons ──────────────────────────────────────────────────────────

function SearchIcon() {
  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="9" cy="9" r="5.75" />
      <path d="m13.5 13.5 3.5 3.5" />
    </Icon>
  );
}

function NavGlyph({ id }: { id: SettingsNavId }) {
  if (id === "account") {
    return (
      <SidebarNavItem.Icon
        viewBox="0 0 20 20"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.6"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        <circle cx="10" cy="6.75" r="3" />
        <path d="M4.25 16.25a5.75 5.75 0 0 1 11.5 0" />
      </SidebarNavItem.Icon>
    );
  }
  if (id === "members") {
    return (
      <SidebarNavItem.Icon
        viewBox="0 0 20 20"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.6"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        <circle cx="7.5" cy="7" r="2.5" />
        <path d="M3 16a4.5 4.5 0 0 1 9 0" />
        <circle cx="13.75" cy="7.5" r="2" />
        <path d="M13.5 11.75A3.75 3.75 0 0 1 17 15.5" />
      </SidebarNavItem.Icon>
    );
  }
  if (id === "billing") {
    return (
      <SidebarNavItem.Icon
        viewBox="0 0 20 20"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.6"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        <rect x="2.5" y="4.5" width="15" height="11" rx="2" />
        <path d="M2.5 8.25h15" />
        <path d="M6 12h3" />
      </SidebarNavItem.Icon>
    );
  }
  if (id === "integrations") {
    return (
      <SidebarNavItem.Icon
        viewBox="0 0 20 20"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.6"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        <rect x="3" y="3" width="5.5" height="5.5" rx="1.25" />
        <rect x="11.5" y="3" width="5.5" height="5.5" rx="1.25" />
        <rect x="3" y="11.5" width="5.5" height="5.5" rx="1.25" />
        <path d="M14.25 11.5v5.5M11.5 14.25H17" />
      </SidebarNavItem.Icon>
    );
  }
  if (id === "audit") {
    return (
      <SidebarNavItem.Icon
        viewBox="0 0 20 20"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.6"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        <path d="M10 3.25 4 5.75v4.5c0 3.55 2.55 5.9 6 6.75 3.45-.85 6-3.2 6-6.75v-4.5l-6-2.5Z" />
        <path d="m7.75 10.25 1.6 1.6 3.15-3.35" />
      </SidebarNavItem.Icon>
    );
  }
  return (
    <SidebarNavItem.Icon
      viewBox="0 0 20 20"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.6"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <circle cx="7" cy="10" r="3" />
      <path d="M10 10h7" />
      <path d="M14.5 10v2.5" />
      <path d="M17 10v2" />
    </SidebarNavItem.Icon>
  );
}

function AppearanceIcon({ mode }: { mode: AppearancePreference }) {
  if (mode === "light") {
    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="3.25" />
        <path d="M10 2.75v1.5M10 15.75v1.5M2.75 10h1.5M15.75 10h1.5M4.87 4.87l1.06 1.06M14.07 14.07l1.06 1.06M15.13 4.87l-1.06 1.06M5.93 14.07l-1.06 1.06" />
      </Icon>
    );
  }
  if (mode === "dark") {
    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="M15.75 12.1A6.25 6.25 0 0 1 7.9 4.25a6.5 6.5 0 1 0 7.85 7.85Z" />
      </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="2.75" y="3.75" width="14.5" height="9.75" rx="1.75" />
      <path d="M7.25 16.5h5.5M10 13.5v3" />
    </Icon>
  );
}

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

const styles = stylex.create({
  root: {
    backgroundColor: semanticColors.bg,
    color: semanticColors.fg,
    fontFamily: fonts.body,
    minHeight: "100%",
    width: "100%",
  },
  fullWidth: {
    width: "100%",
  },
  header: {
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    width: "100%",
  },
  headerInner: {
    marginInline: "auto",
    maxWidth: "82rem",
    paddingBlock: spacing._5,
    paddingInline: {
      default: spacing._8,
      "@media (max-width: 640px)": spacing._4,
    },
    width: "100%",
  },
  pageHeading: {
    marginBlock: 0,
  },
  searchWrap: {
    flexShrink: 0,
    maxWidth: "100%",
    width: {
      default: "18rem",
      "@media (max-width: 640px)": "100%",
    },
  },
  searchLeadingIcon: {
    color: semanticColors.fgMuted,
    insetBlock: 0,
    insetInlineStart: spacing._3,
    pointerEvents: "none",
    position: "absolute",
    zIndex: 1,
  },
  searchInput: {
    paddingInlineStart: spacing._9,
  },
  shell: {
    flexGrow: 1,
    gap: {
      default: spacing._10,
      "@media (max-width: 1024px)": spacing._6,
    },
    marginInline: "auto",
    maxWidth: "82rem",
    paddingBlock: {
      default: spacing._8,
      "@media (max-width: 640px)": spacing._5,
    },
    paddingInline: {
      default: spacing._8,
      "@media (max-width: 640px)": spacing._4,
    },
    width: "100%",
  },
  sidebar: {
    display: {
      default: "flex",
      "@media (max-width: 860px)": "none",
    },
    flexShrink: 0,
    position: "sticky",
    top: spacing._6,
    width: "14rem",
  },
  workspaceCard: {
    paddingInline: spacing._2,
  },
  navList: {
    listStyle: "none",
    marginBlock: 0,
    marginInline: 0,
    paddingBlock: 0,
    paddingInline: 0,
  },
  mobileTabs: {
    display: {
      default: "none",
      "@media (max-width: 860px)": "block",
    },
    marginBottom: spacing._6,
    width: "100%",
  },
  mobileTabList: {
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    overflowX: "auto",
    width: "100%",
  },
  main: {
    flexGrow: 1,
    minWidth: 0,
    width: "100%",
  },
  sectionGrid: {
    gap: {
      default: spacing._10,
      "@media (max-width: 720px)": spacing._5,
    },
    gridTemplateColumns: {
      default: "minmax(12.5rem, 17rem) minmax(0, 1fr)",
      "@media (max-width: 720px)": "1fr",
    },
    scrollMarginTop: spacing._6,
  },
  sectionHeading: {
    marginBlock: 0,
  },
  sectionFields: {
    maxWidth: "36rem",
    width: "100%",
  },
  avatarSummary: {
    gap: spacing._3_5,
  },
  gridTwo: {
    gridTemplateColumns: {
      default: "repeat(2, minmax(0, 1fr))",
      "@media (max-width: 560px)": "1fr",
    },
    width: "100%",
  },
  labelRow: {
    alignItems: "center",
    display: "flex",
    gap: spacing._2,
    justifyContent: "space-between",
    width: "100%",
  },
  textarea: {
    minHeight: "5.25rem",
    resize: "vertical",
  },
  switchList: {
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    overflow: "hidden",
    width: "100%",
  },
  switchRow: {
    alignItems: "center",
    backgroundColor: semanticColors.bgPanel,
    borderTopColor: semanticColors.border,
    borderTopStyle: "solid",
    borderTopWidth: {
      default: "1px",
      ":first-child": 0,
    },
    display: "flex",
    gap: spacing._4,
    justifyContent: "space-between",
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
    width: "100%",
  },
  singleSwitchRow: {
    alignItems: "center",
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    display: "flex",
    gap: spacing._4,
    justifyContent: "space-between",
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
    width: "100%",
  },
  checkboxItem: {
    alignItems: "flex-start",
    display: "flex",
  },
  checkboxControlOffset: {
    marginTop: "0.125rem",
  },
  actionBar: {
    backgroundColor: semanticColors.bgPanel,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._3_5,
    paddingInline: spacing._4,
    width: "100%",
  },
});

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

/**
 * SettingsForm — multi-section account and workspace preferences page with
 * quick-jump settings search, responsive sidebar-to-tabs navigation, profile
 * details, timezone and appearance controls, notification switches, password
 * and security policies, dirty-state detection, and Save / Reset actions.
 */
export function SettingsForm({
  workspaceName = "Kestrel Cloud",
  title = "Account & Workspace Preferences",
  description = "Manage your personal profile, display defaults, notification channels, and workspace security.",
  initialValues,
  onSave,
  onReset,
  onNavigateSection,
  palette,
  style,
}: SettingsFormProps) {
  const queue = useMemo(() => Toast.createToaster(), []);

  const startingValues = useMemo<SettingsFormValues>(
    () => ({ ...DEFAULT_VALUES, ...initialValues }),
    [initialValues],
  );

  const [savedValues, setSavedValues] = useState<SettingsFormValues>(startingValues);
  const [draft, setDraft] = useState<SettingsFormValues>(startingValues);

  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");

  const [searchQuery, setSearchQuery] = useState("");
  const [attemptedSave, setAttemptedSave] = useState(false);
  const [lastSavedAt, setLastSavedAt] = useState<string | null>(null);

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

  const hasPasswordInput =
    currentPassword.length > 0 || newPassword.length > 0 || confirmPassword.length > 0;

  const dirtyCount = useMemo(() => {
    let count = 0;
    for (const key of VALUE_KEYS) {
      if (draft[key] !== savedValues[key]) {
        count += 1;
      }
    }
    if (hasPasswordInput) {
      count += 1;
    }
    return count;
  }, [draft, hasPasswordInput, savedValues]);

  const isDirty = dirtyCount > 0;

  const validate = useCallback((): SettingsFormErrors => {
    const nextErrors: SettingsFormErrors = {};
    const trimmedName = draft.fullName.trim();
    const trimmedHandle = draft.handle.trim();
    const trimmedEmail = draft.email.trim();

    if (!trimmedName) {
      nextErrors.fullName = "Enter your full name.";
    }
    if (!trimmedHandle) {
      nextErrors.handle = "Choose a workspace handle.";
    } else if (!HANDLE_PATTERN.test(trimmedHandle)) {
      nextErrors.handle = "Use 3–30 letters, numbers, hyphens, or underscores.";
    }
    if (!trimmedEmail) {
      nextErrors.email = "Enter your work email address.";
    } else if (!EMAIL_PATTERN.test(trimmedEmail)) {
      nextErrors.email = "Enter a valid email address.";
    }

    if (hasPasswordInput) {
      if (!currentPassword) {
        nextErrors.currentPassword = "Enter your current password to confirm this change.";
      }
      if (newPassword.length < 8) {
        nextErrors.newPassword = "New password must be at least 8 characters.";
      }
      if (confirmPassword !== newPassword) {
        nextErrors.confirmPassword = "Passwords do not match.";
      }
    }

    return nextErrors;
  }, [confirmPassword, currentPassword, draft.email, draft.fullName, draft.handle, hasPasswordInput, newPassword]);

  const errors: SettingsFormErrors = attemptedSave ? validate() : {};

  const handleNavSelect = useCallback(
    (sectionId: SettingsNavId) => {
      if (sectionId === ACTIVE_NAV_ID) {
        return;
      }
      const navItem = NAV_ITEMS.find((item) => item.id === sectionId);
      onNavigateSection?.(sectionId);
      queue.info(`${navItem?.label ?? sectionId} settings`, {
        description: `This preview focuses on ${title}. Route ${navItem?.label ?? sectionId} to its dedicated page.`,
      });
    },
    [onNavigateSection, queue, title],
  );

  const handleJumpToSetting = useCallback(
    (selectedLabel: string) => {
      const match = SEARCHABLE_SETTINGS.find(
        (item) => item.label.toLowerCase() === selectedLabel.trim().toLowerCase(),
      );
      if (!match) return;
      const target =
        typeof document !== "undefined" ? document.getElementById(match.sectionId) : null;
      target?.scrollIntoView({ behavior: "smooth", block: "start" });
      queue.info(`Jumped to ${match.label}`, {
        description: `Located in ${match.sectionName}.`,
      });
    },
    [queue],
  );

  const handleAvatarUpload = useCallback(() => {
    queue.info("Avatar upload", {
      description: "Connect your storage bucket or file picker to replace Maya Lin's photo.",
    });
  }, [queue]);

  const handleAvatarRemove = useCallback(() => {
    queue.info("Using monogram avatar", {
      description: `Falling back to initials (${getInitials(draft.fullName)}) across ${workspaceName}.`,
    });
  }, [draft.fullName, queue, workspaceName]);

  const handleReset = useCallback(() => {
    setDraft(savedValues);
    setCurrentPassword("");
    setNewPassword("");
    setConfirmPassword("");
    setAttemptedSave(false);
    onReset?.();
    queue.info("Changes discarded", {
      description: "All fields were restored to your last saved preferences.",
    });
  }, [onReset, queue, savedValues]);

  const handleSave = useCallback(
    (event: React.FormEvent<HTMLFormElement>) => {
      event.preventDefault();
      setAttemptedSave(true);

      const currentErrors = validate();
      const errorCount = Object.values(currentErrors).filter(Boolean).length;
      if (errorCount > 0) {
        queue.error("Review highlighted fields", {
          description:
            errorCount === 1
              ? "1 field needs attention before saving."
              : `${errorCount} fields need attention before saving.`,
        });
        return;
      }

      const normalized: SettingsFormValues = {
        ...draft,
        fullName: draft.fullName.trim(),
        handle: draft.handle.trim().toLowerCase(),
        email: draft.email.trim(),
        role: draft.role.trim(),
        bio: draft.bio.trim(),
      };

      const timestamp = formatSavedTime(new Date());
      setSavedValues(normalized);
      setDraft(normalized);
      setCurrentPassword("");
      setNewPassword("");
      setConfirmPassword("");
      setAttemptedSave(false);
      setLastSavedAt(timestamp);

      onSave?.({
        values: normalized,
        passwordChanged: hasPasswordInput,
        savedAt: timestamp,
      });

      queue.success("Preferences saved", {
        description: hasPasswordInput
          ? `Account preferences and password updated for @${normalized.handle}.`
          : `Updated preferences for ${normalized.fullName} (@${normalized.handle}).`,
      });
    },
    [draft, hasPasswordInput, onSave, queue, validate],
  );

  const initials = getInitials(draft.fullName);

  return (
    <VStack gap="0" palette={palette} style={[styles.root, style]}>
      {/* Top Header */}
      <header {...stylex.props(styles.header)}>
        <HStack gap="4" justify="between" wrap="wrap" style={styles.headerInner}>
          <VStack gap="1">
            <HStack gap="2.5" wrap="wrap">
              <Heading render={<h1 />} size="2xl" style={styles.pageHeading}>
                {title}
              </Heading>
              {isDirty ? (
                <Badge variant="subtle" size="sm" palette={amberPalette}>
                  Unsaved changes
                </Badge>
              ) : null}
            </HStack>
            <Text variant="muted" size="sm">
              {workspaceName} · {description}
            </Text>
          </VStack>

          <div {...stylex.props(styles.searchWrap)}>
            <Autocomplete.Root
              value={searchQuery}
              onValueChange={(next) => setSearchQuery(next)}
              onSubmit={(value) => handleJumpToSetting(value)}
              openOnFocus
              submitOnSelect
              size="md"
              variant="outline"
            >
              <Autocomplete.Control>
                <Center
                  render={<span />}
                  display="inline"
                  style={styles.searchLeadingIcon}
                  aria-hidden="true"
                >
                  <SearchIcon />
                </Center>
                <Autocomplete.Input
                  aria-label="Search settings"
                  placeholder="Search settings…"
                  style={styles.searchInput}
                />
                <Autocomplete.IndicatorGroup>
                  <Autocomplete.Clear />
                </Autocomplete.IndicatorGroup>
              </Autocomplete.Control>
              <Autocomplete.Content>
                <Autocomplete.List>
                  {SEARCHABLE_SETTINGS.map((item) => (
                    <Autocomplete.Item key={item.label} value={item.label}>
                      <HStack
                        render={<span />}
                        gap="2"
                        justify="between"
                        style={styles.fullWidth}
                      >
                        <Autocomplete.ItemText>{item.label}</Autocomplete.ItemText>
                        <Text render={<span />} size="xs" tone="subtle">
                          {item.sectionName}
                        </Text>
                      </HStack>
                    </Autocomplete.Item>
                  ))}
                  <Autocomplete.Empty>No matching settings</Autocomplete.Empty>
                </Autocomplete.List>
              </Autocomplete.Content>
            </Autocomplete.Root>
          </div>
        </HStack>
      </header>

      {/* Sidebar + Main Settings Content */}
      <HStack align="start" style={styles.shell}>
        <VStack
          render={<aside />}
          aria-label="Workspace settings navigation"
          gap="5"
          style={styles.sidebar}
        >
          <HStack gap="2.5" style={styles.workspaceCard}>
            <Avatar.Root size="sm" variant="subtle" shape="full" palette={accentPalette}>
              <Avatar.Fallback>{initials}</Avatar.Fallback>
            </Avatar.Root>
            <VStack gap="0">
              <Text render={<span />} size="sm" weight="medium" truncate="true">
                {draft.fullName.trim() || "Maya Lin"}
              </Text>
              <Text render={<span />} variant="muted" size="xs" truncate="true">
                @{draft.handle.trim() || "mayalin"}
              </Text>
            </VStack>
          </HStack>

          <nav aria-label="Settings sections">
            <VStack render={<ul />} gap="0.5" style={styles.navList}>
              {NAV_ITEMS.map((item) => {
                const isActive = item.id === ACTIVE_NAV_ID;
                return (
                  <SidebarNavItem.Item key={item.id} variant="muted" size="md">
                    <SidebarNavItem.Button
                      type="button"
                      aria-current={isActive ? "page" : undefined}
                      style={isActive ? sidebarNavItemActive : undefined}
                      onClick={() => handleNavSelect(item.id)}
                    >
                      <NavGlyph id={item.id} />
                      <span>{item.label}</span>
                      {item.badge ? (
                        <SidebarNavItem.EndElement>
                          <Text render={<span />} size="xs" tone="subtle" tabular="true">
                            {item.badge}
                          </Text>
                        </SidebarNavItem.EndElement>
                      ) : null}
                    </SidebarNavItem.Button>
                  </SidebarNavItem.Item>
                );
              })}
            </VStack>
          </nav>
        </VStack>

        <main {...stylex.props(styles.main)}>
          {/* Narrow-screen horizontal tabs */}
          <div {...stylex.props(styles.mobileTabs)}>
            <Tabs.Root<SettingsNavId>
              value={ACTIVE_NAV_ID}
              onValueChange={handleNavSelect}
              variant="line"
              size="sm"
            >
              <Tabs.List aria-label="Settings sections" style={styles.mobileTabList}>
                {NAV_ITEMS.map((item) => (
                  <Tabs.Tab key={item.id} value={item.id}>
                    {item.label}
                  </Tabs.Tab>
                ))}
              </Tabs.List>
            </Tabs.Root>
          </div>

          <VStack
            render={<form noValidate onSubmit={handleSave} />}
            gap="8"
            style={styles.fullWidth}
          >
            {/* Section 1: Profile */}
            <Grid
              render={<section />}
              id="settings-profile"
              aria-labelledby="settings-profile-heading"
              align="start"
              style={styles.sectionGrid}
            >
              <VStack gap="1.5">
                <Heading id="settings-profile-heading" size="md" style={styles.sectionHeading}>
                  Profile
                </Heading>
                <Text variant="muted" size="sm">
                  Public identity and contact details shown alongside commits, comments, and
                  workspace activity.
                </Text>
              </VStack>

              <VStack gap="5" style={styles.sectionFields}>
                <HStack gap="4" justify="between" wrap="wrap">
                  <HStack style={styles.avatarSummary}>
                    <Avatar.Root
                      size="lg"
                      variant="subtle"
                      shape="full"
                      palette={accentPalette}
                    >
                      <Avatar.Fallback>{initials}</Avatar.Fallback>
                    </Avatar.Root>
                    <VStack gap="0.5">
                      <Text render={<span />} size="sm" weight="medium">
                        Profile photo
                      </Text>
                      <Text render={<span />} variant="muted" size="xs">
                        PNG, JPG, or SVG up to 2 MB.
                      </Text>
                    </VStack>
                  </HStack>

                  <HStack gap="2" wrap="wrap">
                    <Button
                      type="button"
                      variant="surface"
                      size="sm"
                      onClick={handleAvatarUpload}
                    >
                      Upload photo
                    </Button>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={handleAvatarRemove}
                    >
                      Remove
                    </Button>
                  </HStack>
                </HStack>

                <Grid columns="2" gap="4" style={styles.gridTwo}>
                  <Field.Root required invalid={Boolean(errors.fullName)}>
                    <Field.Label>
                      Full name
                      <Field.RequiredIndicator />
                    </Field.Label>
                    <Input
                      autoComplete="name"
                      placeholder="Maya Lin"
                      value={draft.fullName}
                      onValueChange={(next) => updateField("fullName", next)}
                    />
                    {errors.fullName ? (
                      <Field.Error match>{errors.fullName}</Field.Error>
                    ) : null}
                  </Field.Root>

                  <Field.Root required invalid={Boolean(errors.handle)}>
                    <Field.Label>
                      Handle
                      <Field.RequiredIndicator />
                    </Field.Label>
                    <InputGroup.Root variant="outline" size="md">
                      <InputGroup.Addon>@</InputGroup.Addon>
                      <InputGroup.Input
                        autoComplete="username"
                        placeholder="mayalin"
                        aria-invalid={errors.handle ? "true" : undefined}
                        value={draft.handle}
                        onChange={(event) => updateField("handle", event.currentTarget.value)}
                      />
                    </InputGroup.Root>
                    {errors.handle ? (
                      <Field.Error match>{errors.handle}</Field.Error>
                    ) : null}
                  </Field.Root>
                </Grid>

                <Grid columns="2" gap="4" style={styles.gridTwo}>
                  <Field.Root required invalid={Boolean(errors.email)}>
                    <Field.Label>
                      Work email
                      <Field.RequiredIndicator />
                    </Field.Label>
                    <Input
                      type="email"
                      autoComplete="email"
                      placeholder="maya@kestrel.dev"
                      value={draft.email}
                      onValueChange={(next) => updateField("email", next)}
                    />
                    {errors.email ? (
                      <Field.Error match>{errors.email}</Field.Error>
                    ) : null}
                  </Field.Root>

                  <Field.Root>
                    <Field.Label>Role</Field.Label>
                    <Input
                      autoComplete="organization-title"
                      placeholder="Staff Product Designer"
                      value={draft.role}
                      onValueChange={(next) => updateField("role", next)}
                    />
                  </Field.Root>
                </Grid>

                <Field.Root>
                  <Field.Label style={styles.labelRow}>
                    <span>Bio</span>
                    <Text
                      render={<span />}
                      size="xs"
                      tone="subtle"
                      weight="normal"
                      tabular="true"
                    >
                      {draft.bio.length} / {BIO_MAX_LENGTH}
                    </Text>
                  </Field.Label>
                  <Textarea
                    rows={3}
                    maxLength={BIO_MAX_LENGTH}
                    placeholder="Share what you focus on across the workspace…"
                    value={draft.bio}
                    onValueChange={(next) => updateField("bio", next)}
                    style={styles.textarea}
                  />
                  <Field.Description>
                    Displayed on your profile hover card and team directory listing.
                  </Field.Description>
                </Field.Root>
              </VStack>
            </Grid>

            <Separator decorative />

            {/* Section 2: Workspace preferences */}
            <Grid
              render={<section />}
              id="settings-preferences"
              aria-labelledby="settings-preferences-heading"
              align="start"
              style={styles.sectionGrid}
            >
              <VStack gap="1.5">
                <Heading
                  id="settings-preferences-heading"
                  size="md"
                  style={styles.sectionHeading}
                >
                  Workspace preferences
                </Heading>
                <Text variant="muted" size="sm">
                  Set your regional timezone, preferred interface theme, and navigation density.
                </Text>
              </VStack>

              <VStack gap="5" style={styles.sectionFields}>
                <Field.Root>
                  <Field.Label>Timezone</Field.Label>
                  <Select.Root
                    items={TIMEZONE_OPTIONS}
                    value={draft.timezone}
                    onValueChange={(next) => {
                      if (next) updateField("timezone", next);
                    }}
                    style={styles.fullWidth}
                  >
                    <Select.Control>
                      <Select.Trigger>
                        <Select.Value placeholder="Choose a timezone" />
                      </Select.Trigger>
                      <Select.IndicatorGroup>
                        <Select.Icon />
                      </Select.IndicatorGroup>
                    </Select.Control>
                    <Select.Content>
                      {TIMEZONE_OPTIONS.map((option) => (
                        <Select.Item key={option.value} value={option.value}>
                          <Select.ItemText>{option.label}</Select.ItemText>
                          <Select.ItemIndicator />
                        </Select.Item>
                      ))}
                    </Select.Content>
                  </Select.Root>
                  <Field.Description>
                    Used for deployment timestamps, audit trails, and digest schedules.
                  </Field.Description>
                </Field.Root>

                <VStack gap="2">
                  <Text
                    render={<span />}
                    id="settings-appearance-label"
                    size="sm"
                    weight="medium"
                  >
                    Appearance
                  </Text>
                  <div>
                    <SegmentGroup.Root
                      size="md"
                      value={draft.appearance}
                      onValueChange={(next) =>
                        updateField("appearance", next as AppearancePreference)
                      }
                      aria-labelledby="settings-appearance-label"
                    >
                      <SegmentGroup.Item value="system">
                        <AppearanceIcon mode="system" />
                        System
                      </SegmentGroup.Item>
                      <SegmentGroup.Item value="light">
                        <AppearanceIcon mode="light" />
                        Light
                      </SegmentGroup.Item>
                      <SegmentGroup.Item value="dark">
                        <AppearanceIcon mode="dark" />
                        Dark
                      </SegmentGroup.Item>
                    </SegmentGroup.Root>
                  </div>
                  <Text variant="muted" size="xs">
                    {APPEARANCE_HINTS[draft.appearance]}
                  </Text>
                </VStack>

                <Field.Root>
                  <Field.Label>Week starts on</Field.Label>
                  <Select.Root
                    items={WEEK_START_OPTIONS}
                    value={draft.weekStartsOn}
                    onValueChange={(next) => {
                      if (next) updateField("weekStartsOn", next);
                    }}
                    style={styles.fullWidth}
                  >
                    <Select.Control>
                      <Select.Trigger>
                        <Select.Value placeholder="Choose first day of week" />
                      </Select.Trigger>
                      <Select.IndicatorGroup>
                        <Select.Icon />
                      </Select.IndicatorGroup>
                    </Select.Control>
                    <Select.Content>
                      {WEEK_START_OPTIONS.map((option) => (
                        <Select.Item key={option.value} value={option.value}>
                          <Select.ItemText>{option.label}</Select.ItemText>
                          <Select.ItemIndicator />
                        </Select.Item>
                      ))}
                    </Select.Content>
                  </Select.Root>
                </Field.Root>

                <Switch.Root
                  variant="solid"
                  size="md"
                  palette={accentPalette}
                  style={styles.singleSwitchRow}
                >
                  <VStack render={<span />} gap="0.5">
                    <Text render={<span />} size="sm" weight="medium">
                      Compact sidebar density
                    </Text>
                    <Text render={<span />} variant="muted" size="xs">
                      Tighten navigation spacing to display more projects without scrolling.
                    </Text>
                  </VStack>
                  <Switch.Control
                    checked={draft.compactDensity}
                    onCheckedChange={(checked) => updateField("compactDensity", checked)}
                  />
                </Switch.Root>
              </VStack>
            </Grid>

            <Separator decorative />

            {/* Section 3: Notifications */}
            <Grid
              render={<section />}
              id="settings-notifications"
              aria-labelledby="settings-notifications-heading"
              align="start"
              style={styles.sectionGrid}
            >
              <VStack gap="1.5">
                <Heading
                  id="settings-notifications-heading"
                  size="md"
                  style={styles.sectionHeading}
                >
                  Notifications
                </Heading>
                <Text variant="muted" size="sm">
                  Choose which workspace events send real-time alerts or scheduled email
                  summaries.
                </Text>
              </VStack>

              <VStack gap="5" style={styles.sectionFields}>
                <VStack gap="0" style={styles.switchList}>
                  <Switch.Root
                    variant="solid"
                    size="md"
                    palette={accentPalette}
                    style={styles.switchRow}
                  >
                    <VStack render={<span />} gap="0.5">
                      <Text render={<span />} size="sm" weight="medium">
                        Deployment alerts
                      </Text>
                      <Text render={<span />} variant="muted" size="xs">
                        Notify immediately when a production release fails or rolls back.
                      </Text>
                    </VStack>
                    <Switch.Control
                      checked={draft.deployAlerts}
                      onCheckedChange={(checked) => updateField("deployAlerts", checked)}
                    />
                  </Switch.Root>

                  <Switch.Root
                    variant="solid"
                    size="md"
                    palette={accentPalette}
                    style={styles.switchRow}
                  >
                    <VStack render={<span />} gap="0.5">
                      <Text render={<span />} size="sm" weight="medium">
                        Review mentions &amp; comments
                      </Text>
                      <Text render={<span />} variant="muted" size="xs">
                        Send email updates when teammates request a review or mention @
                        {draft.handle.trim() || "mayalin"}.
                      </Text>
                    </VStack>
                    <Switch.Control
                      checked={draft.reviewMentions}
                      onCheckedChange={(checked) => updateField("reviewMentions", checked)}
                    />
                  </Switch.Root>

                  <Switch.Root
                    variant="solid"
                    size="md"
                    palette={accentPalette}
                    style={styles.switchRow}
                  >
                    <VStack render={<span />} gap="0.5">
                      <Text render={<span />} size="sm" weight="medium">
                        Weekly workspace digest
                      </Text>
                      <Text render={<span />} variant="muted" size="xs">
                        Summary of active builds, token updates, and seat usage every Monday.
                      </Text>
                    </VStack>
                    <Switch.Control
                      checked={draft.weeklyDigest}
                      onCheckedChange={(checked) => updateField("weeklyDigest", checked)}
                    />
                  </Switch.Root>

                  <Switch.Root
                    variant="solid"
                    size="md"
                    palette={accentPalette}
                    style={styles.switchRow}
                  >
                    <VStack render={<span />} gap="0.5">
                      <Text render={<span />} size="sm" weight="medium">
                        Product release notes
                      </Text>
                      <Text render={<span />} variant="muted" size="xs">
                        Occasional changelog highlights for new Kestrel APIs and UI updates.
                      </Text>
                    </VStack>
                    <Switch.Control
                      checked={draft.releaseNotes}
                      onCheckedChange={(checked) => updateField("releaseNotes", checked)}
                    />
                  </Switch.Root>
                </VStack>
              </VStack>
            </Grid>

            <Separator decorative />

            {/* Section 4: Security & access */}
            <Grid
              render={<section />}
              id="settings-security"
              aria-labelledby="settings-security-heading"
              align="start"
              style={styles.sectionGrid}
            >
              <VStack gap="1.5">
                <Heading
                  id="settings-security-heading"
                  size="md"
                  style={styles.sectionHeading}
                >
                  Security &amp; access
                </Heading>
                <Text variant="muted" size="sm">
                  Rotate your account password and manage authentication and data backup
                  policies.
                </Text>
              </VStack>

              <VStack gap="5" style={styles.sectionFields}>
                <PasswordInput.Root
                  autoComplete="current-password"
                  value={currentPassword}
                  onValueChange={(next) => setCurrentPassword(next)}
                  invalid={Boolean(errors.currentPassword)}
                >
                  <PasswordInput.Label>Current password</PasswordInput.Label>
                  <PasswordInput.Control>
                    <PasswordInput.Input placeholder="Enter current password to rotate" />
                    <PasswordInput.VisibilityTrigger />
                  </PasswordInput.Control>
                  {errors.currentPassword ? (
                    <Field.Error match>{errors.currentPassword}</Field.Error>
                  ) : null}
                </PasswordInput.Root>

                <Grid columns="2" gap="4" style={styles.gridTwo}>
                  <PasswordInput.Root
                    autoComplete="new-password"
                    value={newPassword}
                    onValueChange={(next) => setNewPassword(next)}
                    invalid={Boolean(errors.newPassword)}
                  >
                    <PasswordInput.Label>New password</PasswordInput.Label>
                    <PasswordInput.Control>
                      <PasswordInput.Input placeholder="At least 8 characters" />
                      <PasswordInput.VisibilityTrigger />
                    </PasswordInput.Control>
                    {errors.newPassword ? (
                      <Field.Error match>{errors.newPassword}</Field.Error>
                    ) : null}
                  </PasswordInput.Root>

                  <PasswordInput.Root
                    autoComplete="new-password"
                    value={confirmPassword}
                    onValueChange={(next) => setConfirmPassword(next)}
                    invalid={Boolean(errors.confirmPassword)}
                  >
                    <PasswordInput.Label>Confirm new password</PasswordInput.Label>
                    <PasswordInput.Control>
                      <PasswordInput.Input placeholder="Re-enter new password" />
                      <PasswordInput.VisibilityTrigger />
                    </PasswordInput.Control>
                    {errors.confirmPassword ? (
                      <Field.Error match>{errors.confirmPassword}</Field.Error>
                    ) : null}
                  </PasswordInput.Root>
                </Grid>

                <VStack gap="4" style={styles.fullWidth}>
                  <Checkbox.Root
                    size="md"
                    palette={accentPalette}
                    style={styles.checkboxItem}
                  >
                    <Checkbox.Control
                      checked={draft.twoFactorEnabled}
                      onCheckedChange={(next) =>
                        updateField("twoFactorEnabled", next === true)
                      }
                      style={styles.checkboxControlOffset}
                    />
                    <VStack render={<span />} gap="0.5">
                      <Checkbox.Label>Require two-factor authentication</Checkbox.Label>
                      <Text render={<span />} variant="muted" size="xs" weight="normal">
                        Prompt for a passkey or authenticator code when signing in on a new
                        device.
                      </Text>
                    </VStack>
                  </Checkbox.Root>

                  <Checkbox.Root
                    size="md"
                    palette={accentPalette}
                    style={styles.checkboxItem}
                  >
                    <Checkbox.Control
                      checked={draft.dataExportAccess}
                      onCheckedChange={(next) =>
                        updateField("dataExportAccess", next === true)
                      }
                      style={styles.checkboxControlOffset}
                    />
                    <VStack render={<span />} gap="0.5">
                      <Checkbox.Label>Allow workspace data exports</Checkbox.Label>
                      <Text render={<span />} variant="muted" size="xs" weight="normal">
                        Permit scheduled JSON and CSV snapshots of personal activity and
                        backups.
                      </Text>
                    </VStack>
                  </Checkbox.Root>

                  <Checkbox.Root
                    size="md"
                    palette={accentPalette}
                    style={styles.checkboxItem}
                  >
                    <Checkbox.Control
                      checked={draft.autoRevokeSessions}
                      onCheckedChange={(next) =>
                        updateField("autoRevokeSessions", next === true)
                      }
                      style={styles.checkboxControlOffset}
                    />
                    <VStack render={<span />} gap="0.5">
                      <Checkbox.Label>Sign out inactive sessions</Checkbox.Label>
                      <Text render={<span />} variant="muted" size="xs" weight="normal">
                        Automatically revoke browser sessions that remain idle for over 14
                        days.
                      </Text>
                    </VStack>
                  </Checkbox.Root>
                </VStack>
              </VStack>
            </Grid>

            {/* Dirty-state Action Bar */}
            <HStack
              gap="4"
              justify="between"
              wrap="wrap"
              role="region"
              aria-label="Save changes"
              style={styles.actionBar}
            >
              <Status.Root
                size="sm"
                palette={isDirty ? amberPalette : emeraldPalette}
              >
                <Status.Indicator />
                <Text render={<span />} variant="muted" size="xs">
                  {isDirty
                    ? `${dirtyCount} unsaved ${dirtyCount === 1 ? "change" : "changes"}`
                    : lastSavedAt
                      ? `All changes saved · ${lastSavedAt}`
                      : "All changes saved"}
                </Text>
              </Status.Root>

              <HStack gap="2.5" wrap="wrap">
                <Button
                  type="button"
                  variant="surface"
                  size="md"
                  disabled={!isDirty}
                  onClick={handleReset}
                >
                  Reset
                </Button>
                <Button
                  type="submit"
                  variant="solid"
                  size="md"
                  palette={accentPalette}
                  disabled={!isDirty}
                >
                  Save changes
                </Button>
              </HStack>
            </HStack>
          </VStack>
        </main>
      </HStack>

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

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