---
title: "Settings Panels · UI SDK — StyleX Blocks"
description: "Multi-section workspace settings layout with grouped sidebar navigation, responsive mobile tabs, a sticky dirty-state save bar, API token management, session controls, and team billing quotas."
url: "https://stylexblocks.com/block/ui-sdk/settings-panels/"
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 Panels block

Multi-section workspace settings layout with grouped sidebar navigation, responsive mobile tabs, a sticky dirty-state save bar, API token management, session controls, and team billing quotas.

- Behavior engine: UI SDK
- Category: [Settings](https://stylexblocks.com/blocks/settings.md)
- Built with: [Action Bar](https://stylexblocks.com/components/ui-sdk/action-bar.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), [Card](https://stylexblocks.com/components/ui-sdk/card.md), [Code](https://stylexblocks.com/components/ui-sdk/code.md), [Field](https://stylexblocks.com/components/ui-sdk/field.md), [Grid](https://stylexblocks.com/components/ui-sdk/grid.md), [Heading](https://stylexblocks.com/components/ui-sdk/heading.md), [Icon](https://stylexblocks.com/components/ui-sdk/icon.md), [Icon Badge](https://stylexblocks.com/components/ui-sdk/icon-badge.md), [Input](https://stylexblocks.com/components/ui-sdk/input.md), [Native Select](https://stylexblocks.com/components/ui-sdk/native-select.md), [Progress](https://stylexblocks.com/components/ui-sdk/progress.md), [Radio Card](https://stylexblocks.com/components/ui-sdk/radio-card.md), [Segment Group](https://stylexblocks.com/components/ui-sdk/segment-group.md), [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), [Stack](https://stylexblocks.com/components/ui-sdk/stack.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-panels/

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

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

## Usage

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

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

## Source

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

```tsx
import * as stylex from "@stylexjs/stylex";
import { type FormEvent, useCallback, useId, useMemo, useState } from "react";
import { ActionBar } from "#components/ui/ui-sdk/action-bar.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 { Card } from "#components/ui/ui-sdk/card.tsx";
import { Code } from "#components/ui/ui-sdk/code.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 { IconBadge } from "#components/ui/ui-sdk/icon-badge.tsx";
import { Input } from "#components/ui/ui-sdk/input.tsx";
import { NativeSelect } from "#components/ui/ui-sdk/native-select.tsx";
import { Progress } from "#components/ui/ui-sdk/progress.tsx";
import { RadioCard } from "#components/ui/ui-sdk/radio-card.tsx";
import { SegmentGroup } from "#components/ui/ui-sdk/segment-group.tsx";
import { 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 { HStack, VStack } from "#components/ui/ui-sdk/stack.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,
  bluePalette,
  emeraldPalette,
  grayPalette,
  greenPalette,
  indigoPalette,
  redPalette,
  tealPalette,
} from "@stylexblocks/ui/themes/palettes.ts";
import { fontSizes } from "@stylexblocks/ui/tokens/font-sizes.stylex.ts";
import { fontWeights } from "@stylexblocks/ui/tokens/font-weights.stylex.ts";
import { fonts } from "@stylexblocks/ui/tokens/fonts.stylex.ts";
import { lineHeights } from "@stylexblocks/ui/tokens/line-heights.stylex.ts";
import { 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";

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

export type SettingsSectionId =
  | "profile"
  | "appearance"
  | "notifications"
  | "security"
  | "billing";

export type ThemeMode = "light" | "dark" | "system";
export type InterfaceDensity = "compact" | "comfortable" | "spacious";
export type TokenScope = "read" | "deploy" | "admin";
export type MemberRole = "owner" | "admin" | "developer" | "viewer";

export interface SettingsState {
  // Profile
  displayName: string;
  email: string;
  roleTitle: string;
  timezone: string;
  bio: string;
  // Appearance
  theme: ThemeMode;
  density: InterfaceDensity;
  codeFont: string;
  timestampFormat: string;
  reduceMotion: boolean;
  keyboardHints: boolean;
  highContrastSyntax: boolean;
  // Notifications
  digestCadence: string;
  alertChannel: string;
  quietHours: boolean;
  notifyDeployFailures: boolean;
  notifyProdPromotions: boolean;
  notifyCanaryLatency: boolean;
  notifyNewDevice: boolean;
  notifyTokenExpiry: boolean;
  notifyWeeklyDigest: boolean;
  notifyInvoiceAlerts: boolean;
  // Security preferences
  requirePasskeyForDeploys: boolean;
  enforceSamlSso: boolean;
  // Team role assignments
  memberRoles: Record<string, MemberRole>;
}

interface SessionItem {
  id: string;
  device: string;
  client: string;
  location: string;
  lastActive: string;
  current?: boolean;
  kind: "laptop" | "terminal" | "mobile";
}

interface ApiTokenItem {
  id: string;
  name: string;
  prefix: string;
  scope: TokenScope;
  createdAt: string;
  lastUsed: string;
}

interface TeamMemberItem {
  id: string;
  name: string;
  email: string;
  initials: string;
  palette: typeof indigoPalette;
  pending?: boolean;
}

export interface SettingsPanelsProps extends StyleOverrideProps {
  /** Workspace display name shown in the sidebar header. */
  workspaceName?: string;
  /** Workspace slug rendered in identity metadata and the sidebar caption. */
  workspaceSlug?: string;
  /** Active section selected on initial render. */
  initialSection?: SettingsSectionId;
  /** Called when the user saves dirty settings from the save bar. */
  onSave?: (settings: SettingsState) => void;
}

// ── Demo Data ─────────────────────────────────────────────────────────────────

const INITIAL_MEMBERS: TeamMemberItem[] = [
  {
    id: "m-maya",
    name: "Maya Lin",
    email: "maya.lin@kestrel.cloud",
    initials: "ML",
    palette: accentPalette,
  },
  {
    id: "m-devon",
    name: "Devon Brooks",
    email: "devon.brooks@kestrel.cloud",
    initials: "DB",
    palette: bluePalette,
  },
  {
    id: "m-priya",
    name: "Priya Nair",
    email: "priya.nair@kestrel.cloud",
    initials: "PN",
    palette: tealPalette,
  },
  {
    id: "m-tomas",
    name: "Tomasz Zielinski",
    email: "tomasz.z@kestrel.cloud",
    initials: "TZ",
    palette: indigoPalette,
  },
  {
    id: "m-claire",
    name: "Claire Okafor",
    email: "claire.okafor@kestrel.cloud",
    initials: "CO",
    palette: emeraldPalette,
  },
];

const INITIAL_SETTINGS: SettingsState = {
  displayName: "Maya Lin",
  email: "maya.lin@kestrel.cloud",
  roleTitle: "Staff Infrastructure Engineer",
  timezone: "Europe/Berlin",
  bio: "Leads edge runtime reliability, multi-region failover, and zero-downtime deployment pipelines at Kestrel Cloud.",
  theme: "system",
  density: "comfortable",
  codeFont: "jetbrains-mono",
  timestampFormat: "iso-24h",
  reduceMotion: false,
  keyboardHints: true,
  highContrastSyntax: false,
  digestCadence: "instant",
  alertChannel: "email-and-app",
  quietHours: true,
  notifyDeployFailures: true,
  notifyProdPromotions: true,
  notifyCanaryLatency: true,
  notifyNewDevice: true,
  notifyTokenExpiry: true,
  notifyWeeklyDigest: false,
  notifyInvoiceAlerts: true,
  requirePasskeyForDeploys: true,
  enforceSamlSso: true,
  memberRoles: {
    "m-maya": "owner",
    "m-devon": "admin",
    "m-priya": "admin",
    "m-tomas": "developer",
    "m-claire": "viewer",
  },
};

const INITIAL_SESSIONS: SessionItem[] = [
  {
    id: "s-macbook",
    device: "MacBook Pro 16 · macOS 15.4",
    client: "Safari 19.1",
    location: "Berlin, Germany",
    lastActive: "Active now",
    current: true,
    kind: "laptop",
  },
  {
    id: "s-cli",
    device: "Kestrel CLI v4.8.2",
    client: "SSH bastion · eu-central-1",
    location: "Frankfurt, Germany",
    lastActive: "18 minutes ago",
    kind: "terminal",
  },
  {
    id: "s-iphone",
    device: "iPhone 16 Pro · iOS 19",
    client: "Kestrel Mobile",
    location: "Munich, Germany",
    lastActive: "Yesterday at 21:14",
    kind: "mobile",
  },
];

const INITIAL_TOKENS: ApiTokenItem[] = [
  {
    id: "tok-ci",
    name: "GitHub Actions · Production Deploy",
    prefix: "kstr_live_9f4a…c81e",
    scope: "deploy",
    createdAt: "Oct 14, 2026",
    lastUsed: "12 minutes ago",
  },
  {
    id: "tok-grafana",
    name: "Grafana Telemetry Exporter",
    prefix: "kstr_read_2b71…40d9",
    scope: "read",
    createdAt: "Sep 02, 2026",
    lastUsed: "3 minutes ago",
  },
  {
    id: "tok-terraform",
    name: "Terraform State Provisioner",
    prefix: "kstr_adm_71e0…a35f",
    scope: "admin",
    createdAt: "Aug 19, 2026",
    lastUsed: "4 days ago",
  },
];

const TIMEZONES = [
  { value: "UTC", label: "(UTC+00:00) Coordinated Universal Time" },
  { value: "Europe/London", label: "(UTC+00:00) London" },
  { value: "Europe/Berlin", label: "(UTC+01:00) Berlin · Frankfurt" },
  { value: "America/New_York", label: "(UTC-05:00) Eastern Time (US)" },
  { value: "America/Los_Angeles", label: "(UTC-08:00) Pacific Time (US)" },
  { value: "Asia/Tokyo", label: "(UTC+09:00) Tokyo" },
];

const CODE_FONTS = [
  { value: "jetbrains-mono", label: "JetBrains Mono" },
  { value: "ibm-plex-mono", label: "IBM Plex Mono" },
  { value: "geist-mono", label: "Geist Mono" },
  { value: "system-mono", label: "System monospace" },
];

const TIMESTAMP_FORMATS = [
  { value: "iso-24h", label: "24-hour ISO (2026-12-01 14:32 UTC)" },
  { value: "local-12h", label: "12-hour local (Dec 1, 2:32 PM)" },
  { value: "relative", label: "Relative (14 minutes ago)" },
];

const DIGEST_CADENCES = [
  { value: "instant", label: "Instant delivery" },
  { value: "hourly", label: "Hourly rollup" },
  { value: "daily", label: "Daily summary at 09:00" },
];

const ALERT_CHANNELS = [
  { value: "email-and-app", label: "Email & in-app inbox" },
  { value: "slack-ops", label: "Slack (#ops-alerts)" },
  { value: "pagerduty", label: "PagerDuty (critical incidents)" },
];

const SCOPE_LABELS: Record<TokenScope, string> = {
  read: "Read-only",
  deploy: "Deploy & logs",
  admin: "Full admin",
};

const NAV_GROUPS: Array<{
  title: string;
  items: Array<{
    id: SettingsSectionId;
    label: string;
    shortLabel: string;
    description: string;
  }>;
}> = [
  {
    title: "Account",
    items: [
      {
        id: "profile",
        label: "Profile",
        shortLabel: "Profile",
        description:
          "Manage your personal details, regional timezone, and workspace identity.",
      },
      {
        id: "appearance",
        label: "Appearance",
        shortLabel: "Appearance",
        description:
          "Tune color mode, layout density, and readability preferences across the console.",
      },
      {
        id: "notifications",
        label: "Notifications",
        shortLabel: "Notifications",
        description:
          "Choose how deployment alerts, security notices, and billing updates reach you.",
      },
    ],
  },
  {
    title: "Workspace",
    items: [
      {
        id: "security",
        label: "Security & API keys",
        shortLabel: "Security",
        description:
          "Configure sign-in policies, review active sessions, and manage scoped API tokens.",
      },
      {
        id: "billing",
        label: "Team & Billing",
        shortLabel: "Team & Billing",
        description:
          "Monitor workspace quotas, manage seats and roles, and review your active plan.",
      },
    ],
  },
];

const ALL_NAV_ITEMS = NAV_GROUPS.flatMap((group) => group.items);

const SECTION_KEYS: Record<SettingsSectionId, Array<keyof SettingsState>> = {
  profile: ["displayName", "email", "roleTitle", "timezone", "bio"],
  appearance: [
    "theme",
    "density",
    "codeFont",
    "timestampFormat",
    "reduceMotion",
    "keyboardHints",
    "highContrastSyntax",
  ],
  notifications: [
    "digestCadence",
    "alertChannel",
    "quietHours",
    "notifyDeployFailures",
    "notifyProdPromotions",
    "notifyCanaryLatency",
    "notifyNewDevice",
    "notifyTokenExpiry",
    "notifyWeeklyDigest",
    "notifyInvoiceAlerts",
  ],
  security: ["requirePasskeyForDeploys", "enforceSamlSso"],
  billing: ["memberRoles"],
};

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

function countDirtyInSection(
  section: SettingsSectionId,
  draft: SettingsState,
  saved: SettingsState,
): number {
  let count = 0;
  for (const key of SECTION_KEYS[section]) {
    if (key === "memberRoles") {
      const ids = new Set([
        ...Object.keys(draft.memberRoles),
        ...Object.keys(saved.memberRoles),
      ]);
      for (const id of ids) {
        if (draft.memberRoles[id] !== saved.memberRoles[id]) count += 1;
      }
    } else if (draft[key] !== saved[key]) {
      count += 1;
    }
  }
  return count;
}

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

function createTokenSecret(scope: TokenScope): { full: string; prefix: string } {
  const tag = scope === "admin" ? "adm" : scope === "deploy" ? "live" : "read";
  const alphabet = "abcdef0123456789";
  let tail = "";
  for (let i = 0; i < 20; i += 1) {
    tail += alphabet[Math.floor(Math.random() * alphabet.length)];
  }
  const full = `kstr_${tag}_${tail}`;
  const prefix = `kstr_${tag}_${tail.slice(0, 4)}…${tail.slice(-4)}`;
  return { full, prefix };
}

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

function KestrelMark() {
  return (
    <Icon
      size="sm"
      viewBox="0 0 20 20"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M3.5 14.5 10 3.5l6.5 11" />
      <path d="M6.5 14.5 10 8.5l3.5 6" />
      <path d="M4.5 14.5h11" />
    </Icon>
  );
}

function SectionGlyph({ id }: { id: SettingsSectionId }) {
  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 "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 "notifications":
      return (
        <>
          <path d="M5.5 8.5a4.5 4.5 0 0 1 9 0c0 3.4 1.3 4.5 1.8 5H3.7c.5-.5 1.8-1.6 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 "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.3h3.2" />
        </>
      );
  }
}

function DeviceGlyph({ kind }: { kind: SessionItem["kind"] }) {
  if (kind === "terminal") {
    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 === "mobile") {
    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="5.5" y="2.5" width="9" 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>
  );
}

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

const styles = stylex.create({
  root: {
    backgroundColor: semanticColors.bg,
    color: semanticColors.fg,
    flexDirection: {
      default: "row",
      "@media (max-width: 768px)": "column",
    },
    fontFamily: fonts.body,
    minHeight: "100%",
    width: "100%",
  },
  desktopSidebar: {
    "--sidebar-width": "16.5rem",
    "--sidebar-min-width": "15.5rem",
    display: {
      default: "flex",
      "@media (max-width: 768px)": "none",
    },
    flexShrink: 0,
    minHeight: "100%",
  },
  brandHeader: {
    paddingBlock: spacing._2,
    width: "100%",
  },
  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,
  },
  sidebarAccount: {
    borderTopColor: semanticColors.sidebarBorder,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
    paddingTop: spacing._3,
    width: "100%",
  },
  mobileHeader: {
    backgroundColor: semanticColors.sidebarBg,
    borderBottomColor: semanticColors.border,
    borderBottomStyle: "solid",
    borderBottomWidth: "1px",
    display: {
      default: "none",
      "@media (max-width: 768px)": "flex",
    },
    paddingBlock: spacing._3,
    paddingInline: spacing._4,
  },
  mobileNavRail: {
    overflowX: "auto",
    paddingBottom: spacing._0_5,
  },
  mobileNavButton: {
    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,
  },
  mobileNavButtonActive: {
    backgroundColor: semanticColors.accentSubtle,
    borderColor: semanticColors.accentBorder,
    color: semanticColors.accentFg,
  },
  main: {
    flexGrow: 1,
    minWidth: 0,
    overflowY: "auto",
    paddingBlock: {
      default: spacing._8,
      "@media (max-width: 768px)": spacing._5,
    },
    paddingInline: {
      default: spacing._8,
      "@media (max-width: 768px)": spacing._4,
    },
  },
  container: {
    marginInline: "auto",
    maxWidth: "48rem",
    width: "100%",
  },
  pageHeading: {
    marginBlock: 0,
  },
  cardBodyStack: {
    display: "flex",
    flexDirection: "column",
    gap: spacing._4,
  },
  profileIdentity: {
    gap: spacing._3_5,
  },
  twoColGrid: {
    gridTemplateColumns: {
      default: "repeat(2, minmax(0, 1fr))",
      "@media (max-width: 640px)": "1fr",
    },
  },
  threeColGrid: {
    display: "grid",
    gap: spacing._3,
    gridTemplateColumns: {
      default: "repeat(3, minmax(0, 1fr))",
      "@media (max-width: 640px)": "1fr",
    },
  },
  tabsPanelBody: {
    paddingBottom: 0,
    paddingInline: 0,
    paddingTop: spacing._5,
  },
  tokenFormGrid: {
    gridTemplateColumns: {
      default: "minmax(0, 1.4fr) minmax(0, 1fr) auto",
      "@media (max-width: 640px)": "1fr",
    },
  },
  tokenReveal: {
    backgroundColor: semanticColors.bgMuted,
    borderColor: semanticColors.accentBorder,
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._3,
    paddingInline: spacing._3_5,
  },
  tokenCode: {
    wordBreak: "break-all",
  },
  roleSelectRoot: {
    width: "8.25rem",
  },
  saveBarPositioner: {
    bottom: spacing._4,
    marginTop: spacing._2,
    position: "sticky",
    zIndex: zIndices.dropdown,
  },
  saveBarContent: {
    flexWrap: "wrap",
    justifyContent: "space-between",
    maxWidth: "100%",
  },
  saveBarStatus: {
    paddingInline: spacing._1,
  },
  previewSwatchRow: {
    backgroundColor: semanticColors.bgMuted,
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.control,
    borderStyle: "solid",
    borderWidth: "1px",
    paddingBlock: spacing._3,
    paddingInline: spacing._3_5,
  },
  emptyNote: {
    paddingBlock: spacing._2,
  },
});

// ── Reusable Setting Toggle Row ───────────────────────────────────────────────

interface ToggleRowProps {
  label: string;
  description: string;
  checked: boolean;
  onCheckedChange: (checked: boolean) => void;
  badge?: { label: string; palette: typeof redPalette };
}

function ToggleRow({
  label,
  description,
  checked,
  onCheckedChange,
  badge,
}: ToggleRowProps) {
  return (
    <HStack gap="4" justify="between">
      <VStack gap="0.5">
        <HStack gap="2" wrap="wrap">
          <Text render={<span />} size="sm" weight="semibold">
            {label}
          </Text>
          {badge ? (
            <Badge variant="subtle" size="xs" palette={badge.palette}>
              {badge.label}
            </Badge>
          ) : null}
        </HStack>
        <Text variant="muted" size="xs">
          {description}
        </Text>
      </VStack>
      <Switch.Root size="md" palette={accentPalette}>
        <Switch.Control
          checked={checked}
          onCheckedChange={onCheckedChange}
          aria-label={label}
        />
      </Switch.Root>
    </HStack>
  );
}

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

/**
 * SettingsPanels — multi-section workspace settings experience for Kestrel Cloud
 * featuring grouped sidebar navigation, responsive mobile tabs, a sticky dirty-state
 * save bar, interactive form controls, active session sign-out, API token generation
 * and revocation, team role management, and toast notifications.
 */
export function SettingsPanels({
  workspaceName = "Kestrel Cloud",
  workspaceSlug = "kestrel-prod",
  initialSection = "profile",
  onSave,
  palette,
  style,
}: SettingsPanelsProps) {
  const uid = useId();
  const queue = useMemo(() => Toast.createToaster(), []);

  const [activeSection, setActiveSection] =
    useState<SettingsSectionId>(initialSection);
  const [securityTab, setSecurityTab] = useState<"auth" | "tokens">("auth");

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

  const [sessions, setSessions] = useState<SessionItem[]>(INITIAL_SESSIONS);
  const [tokens, setTokens] = useState<ApiTokenItem[]>(INITIAL_TOKENS);
  const [newTokenName, setNewTokenName] = useState("");
  const [newTokenScope, setNewTokenScope] = useState<TokenScope>("deploy");
  const [revealedToken, setRevealedToken] = useState<{
    name: string;
    secret: string;
  } | null>(null);

  const [members, setMembers] = useState<TeamMemberItem[]>(INITIAL_MEMBERS);
  const [inviteEmail, setInviteEmail] = useState("");
  const [inviteRole, setInviteRole] = useState<Exclude<MemberRole, "owner">>(
    "developer",
  );

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

  const sectionDirtyCounts = useMemo(
    () => ({
      profile: countDirtyInSection("profile", draft, saved),
      appearance: countDirtyInSection("appearance", draft, saved),
      notifications: countDirtyInSection("notifications", draft, saved),
      security: countDirtyInSection("security", draft, saved),
      billing: countDirtyInSection("billing", draft, saved),
    }),
    [draft, saved],
  );

  const totalDirtyCount =
    sectionDirtyCounts.profile +
    sectionDirtyCounts.appearance +
    sectionDirtyCounts.notifications +
    sectionDirtyCounts.security +
    sectionDirtyCounts.billing;

  const isDirty = totalDirtyCount > 0;

  const activeNavMeta =
    ALL_NAV_ITEMS.find((item) => item.id === activeSection) ?? ALL_NAV_ITEMS[0];

  const handleSave = useCallback(() => {
    setSaved(draft);
    onSave?.(draft);
    queue.success("Settings saved", {
      description: `${totalDirtyCount} ${totalDirtyCount === 1 ? "preference" : "preferences"} updated for ${workspaceSlug}.`,
    });
  }, [draft, onSave, queue, totalDirtyCount, workspaceSlug]);

  const handleDiscard = useCallback(() => {
    setDraft(saved);
    queue.info("Unsaved changes discarded", {
      description: "Reverted all modified fields to your last saved state.",
    });
  }, [saved, queue]);

  const handleCopyText = useCallback(
    (value: string, label: string) => {
      if (typeof navigator !== "undefined" && navigator.clipboard) {
        void navigator.clipboard.writeText(value).catch(() => {});
      }
      queue.info(`${label} copied`, {
        description: value,
      });
    },
    [queue],
  );

  const handleMuteNonCritical = useCallback(() => {
    setDraft((prev) => ({
      ...prev,
      notifyProdPromotions: false,
      notifyCanaryLatency: false,
      notifyWeeklyDigest: false,
      quietHours: true,
    }));
    queue.info("Non-critical alerts muted", {
      description: "Save changes to keep deployment failures and security alerts only.",
    });
  }, [queue]);

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

  const handleRevokeOtherSessions = useCallback(() => {
    const others = sessions.filter((s) => !s.current).length;
    if (others === 0) return;
    setSessions((prev) => prev.filter((s) => s.current));
    queue.success("Other sessions signed out", {
      description: `Revoked ${others} active ${others === 1 ? "session" : "sessions"} outside this browser.`,
    });
  }, [sessions, queue]);

  const handleGenerateToken = useCallback(
    (e: FormEvent) => {
      e.preventDefault();
      const trimmed = newTokenName.trim();
      if (!trimmed) {
        queue.error("Token name required", {
          description: "Enter a descriptive label before generating an API token.",
        });
        return;
      }
      const { full, prefix } = createTokenSecret(newTokenScope);
      const created: ApiTokenItem = {
        id: `tok-${Date.now()}`,
        name: trimmed,
        prefix,
        scope: newTokenScope,
        createdAt: "Just now",
        lastUsed: "Never used",
      };
      setTokens((prev) => [created, ...prev]);
      setRevealedToken({ name: trimmed, secret: full });
      setNewTokenName("");
      queue.success("API token generated", {
        description: `Scoped to ${SCOPE_LABELS[newTokenScope]}. Copy it now—it won't be shown again.`,
      });
    },
    [newTokenName, newTokenScope, queue],
  );

  const handleRevokeToken = useCallback(
    (token: ApiTokenItem) => {
      setTokens((prev) => prev.filter((item) => item.id !== token.id));
      queue.warning("API token revoked", {
        description: `${token.name} (${token.prefix}) can no longer authenticate.`,
      });
    },
    [queue],
  );

  const handleInviteMember = useCallback(
    (e: FormEvent) => {
      e.preventDefault();
      const email = inviteEmail.trim().toLowerCase();
      if (!email || !email.includes("@")) {
        queue.error("Enter a valid email address", {
          description: "Invitations require a work email such as alex@kestrel.cloud.",
        });
        return;
      }
      if (members.some((m) => m.email.toLowerCase() === email)) {
        queue.warning("Already in workspace", {
          description: `${email} is already a member or has a pending invite.`,
        });
        return;
      }
      const localPart = email.split("@")[0] ?? "member";
      const displayName = localPart
        .split(/[._-]+/)
        .filter(Boolean)
        .map((chunk) => `${chunk[0]?.toUpperCase() ?? ""}${chunk.slice(1)}`)
        .join(" ");
      const id = `m-${Date.now()}`;
      const invited: TeamMemberItem = {
        id,
        name: displayName || email,
        email,
        initials: getInitials(displayName || email),
        palette: indigoPalette,
        pending: true,
      };
      setMembers((prev) => [...prev, invited]);
      setSaved((prev) => ({
        ...prev,
        memberRoles: { ...prev.memberRoles, [id]: inviteRole },
      }));
      setDraft((prev) => ({
        ...prev,
        memberRoles: { ...prev.memberRoles, [id]: inviteRole },
      }));
      setInviteEmail("");
      queue.success("Invitation sent", {
        description: `Invited ${email} as ${inviteRole}.`,
      });
    },
    [inviteEmail, inviteRole, members, queue],
  );

  const handleRemoveMember = useCallback(
    (member: TeamMemberItem) => {
      setMembers((prev) => prev.filter((item) => item.id !== member.id));
      setSaved((prev) => {
        const nextRoles = { ...prev.memberRoles };
        delete nextRoles[member.id];
        return { ...prev, memberRoles: nextRoles };
      });
      setDraft((prev) => {
        const nextRoles = { ...prev.memberRoles };
        delete nextRoles[member.id];
        return { ...prev, memberRoles: nextRoles };
      });
      queue.info("Member removed", {
        description: `${member.name} no longer has access to ${workspaceSlug}.`,
      });
    },
    [queue, workspaceSlug],
  );

  const handleMemberRoleChange = useCallback(
    (memberId: string, role: MemberRole) => {
      setDraft((prev) => ({
        ...prev,
        memberRoles: { ...prev.memberRoles, [memberId]: role },
      }));
    },
    [],
  );

  const displayInitials = getInitials(draft.displayName);
  const seatsUsedPct = Math.min(100, Math.round((members.length / 10) * 100));

  return (
    <HStack gap="0" align="stretch" palette={palette} style={[styles.root, style]}>
      {/* Desktop sidebar */}
      <Sidebar.Root
        variant="sidebar"
        mode="collapsible"
        size="md"
        style={styles.desktopSidebar}
      >
        <Sidebar.Header>
          <HStack gap="2.5" style={styles.brandHeader}>
            <IconBadge variant="solid" size="sm" palette={accentPalette}>
              <KestrelMark />
            </IconBadge>
            <VStack gap="0">
              <Text render={<span />} size="sm" weight="semibold" truncate="true">
                {workspaceName}
              </Text>
              <Text
                render={<span />}
                variant="mono"
                size="xs"
                tone="muted"
                truncate="true"
              >
                {workspaceSlug} · Scale
              </Text>
            </VStack>
          </HStack>
        </Sidebar.Header>

        <Sidebar.Body>
          {NAV_GROUPS.map((group) => (
            <Sidebar.Group key={group.title}>
              <Sidebar.GroupHeader>
                <Sidebar.GroupTitle>{group.title}</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 dirtyInSection = sectionDirtyCounts[item.id];
                    return (
                      <SidebarNavItem.Item key={item.id}>
                        <SidebarNavItem.Button
                          type="button"
                          aria-current={isActive ? "page" : undefined}
                          style={isActive ? sidebarNavItemActive : undefined}
                          onClick={() => setActiveSection(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">
                              {dirtyInSection > 0 ? (
                                <span
                                  aria-label={`${dirtyInSection} unsaved`}
                                  {...stylex.props(styles.dirtyDot)}
                                />
                              ) : null}
                              {item.id === "security" ? (
                                <Badge variant="subtle" size="xs" palette={grayPalette}>
                                  {tokens.length}
                                </Badge>
                              ) : null}
                              {item.id === "billing" ? (
                                <Badge variant="subtle" size="xs" palette={grayPalette}>
                                  {members.length}
                                </Badge>
                              ) : null}
                            </HStack>
                          </SidebarNavItem.EndElement>
                        </SidebarNavItem.Button>
                      </SidebarNavItem.Item>
                    );
                  })}
                </VStack>
              </Sidebar.GroupContent>
            </Sidebar.Group>
          ))}
        </Sidebar.Body>

        <Sidebar.Footer>
          <HStack gap="2.5" style={styles.sidebarAccount}>
            <Avatar.Root size="sm" variant="solid" palette={accentPalette}>
              <Avatar.Fallback>{displayInitials}</Avatar.Fallback>
            </Avatar.Root>
            <VStack gap="0">
              <Text render={<span />} size="sm" weight="semibold" truncate="true">
                {draft.displayName || "Maya Lin"}
              </Text>
              <Text
                render={<span />}
                variant="mono"
                size="xs"
                tone="muted"
                truncate="true"
              >
                {draft.email}
              </Text>
            </VStack>
          </HStack>
        </Sidebar.Footer>
      </Sidebar.Root>

      {/* Mobile navigation strip */}
      <VStack render={<header />} gap="3" style={styles.mobileHeader}>
        <HStack gap="2" justify="between">
          <HStack gap="2">
            <IconBadge variant="solid" size="sm" palette={accentPalette}>
              <KestrelMark />
            </IconBadge>
            <VStack gap="0">
              <Text render={<span />} size="sm" weight="semibold" truncate="true">
                {workspaceName}
              </Text>
              <Text
                render={<span />}
                variant="mono"
                size="xs"
                tone="muted"
                truncate="true"
              >
                {workspaceSlug}
              </Text>
            </VStack>
          </HStack>
          {isDirty ? (
            <Badge variant="subtle" size="sm" palette={amberPalette}>
              {totalDirtyCount} unsaved
            </Badge>
          ) : (
            <Badge variant="subtle" size="sm" palette={greenPalette}>
              Synced
            </Badge>
          )}
        </HStack>
        <HStack
          render={<nav />}
          aria-label="Settings sections"
          gap="1.5"
          style={styles.mobileNavRail}
        >
          {ALL_NAV_ITEMS.map((item) => {
            const isActive = activeSection === item.id;
            return (
              <button
                key={item.id}
                type="button"
                aria-current={isActive ? "page" : undefined}
                onClick={() => setActiveSection(item.id)}
                {...stylex.props(
                  styles.mobileNavButton,
                  isActive && styles.mobileNavButtonActive,
                )}
              >
                <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>
                {sectionDirtyCounts[item.id] > 0 ? (
                  <span {...stylex.props(styles.dirtyDot)} />
                ) : null}
              </button>
            );
          })}
        </HStack>
      </VStack>

      {/* Main settings content */}
      <main {...stylex.props(styles.main)}>
        <VStack gap="6" style={styles.container}>
          <HStack render={<header />} align="start" gap="3" justify="between" wrap="wrap">
            <VStack gap="1">
              <Heading render={<h1 />} size="2xl" style={styles.pageHeading}>
                {activeNavMeta.label}
              </Heading>
              <Text variant="muted" size="sm">
                {activeNavMeta.description}
              </Text>
            </VStack>
            {isDirty ? (
              <Badge variant="subtle" size="sm" palette={amberPalette}>
                {totalDirtyCount} unsaved {totalDirtyCount === 1 ? "change" : "changes"}
              </Badge>
            ) : (
              <Badge variant="outline" size="sm" palette={grayPalette}>
                All changes saved
              </Badge>
            )}
          </HStack>

          <Separator />

          {/* ── 1. Profile ── */}
          {activeSection === "profile" && (
            <VStack gap="5">
              <Card.Root variant="outline" size="lg">
                <Card.Body style={styles.cardBodyStack}>
                  <HStack gap="4" justify="between" wrap="wrap">
                    <HStack style={styles.profileIdentity}>
                      <Avatar.Root size="xl" variant="solid" palette={accentPalette}>
                        <Avatar.Fallback>{displayInitials}</Avatar.Fallback>
                      </Avatar.Root>
                      <VStack gap="0.5">
                        <HStack gap="2" wrap="wrap">
                          <Text render={<span />} size="sm" weight="semibold">
                            {draft.displayName || "Unnamed user"}
                          </Text>
                          <Badge variant="subtle" size="xs" palette={greenPalette}>
                            Verified
                          </Badge>
                        </HStack>
                        <Text variant="muted" size="xs">
                          {draft.roleTitle} · {workspaceName}
                        </Text>
                      </VStack>
                    </HStack>
                    <Button
                      variant="surface"
                      size="sm"
                      onClick={() =>
                        queue.info("Avatar upload", {
                          description:
                            "PNG, JPG, or SVG up to 2 MB are supported for profile portraits.",
                        })
                      }
                    >
                      Update photo
                    </Button>
                  </HStack>

                  <Separator />

                  <Grid columns="2" gap="4" style={styles.twoColGrid}>
                    <Field.Root>
                      <Field.Label>Display name</Field.Label>
                      <Input
                        value={draft.displayName}
                        onChange={(e) => updateDraft("displayName", e.target.value)}
                        placeholder="Full name"
                      />
                    </Field.Root>

                    <Field.Root>
                      <Field.Label>Work email</Field.Label>
                      <Input
                        type="email"
                        value={draft.email}
                        onChange={(e) => updateDraft("email", e.target.value)}
                        placeholder="you@kestrel.cloud"
                      />
                    </Field.Root>

                    <Field.Root>
                      <Field.Label>Role / title</Field.Label>
                      <Input
                        value={draft.roleTitle}
                        onChange={(e) => updateDraft("roleTitle", e.target.value)}
                        placeholder="Engineering role"
                      />
                    </Field.Root>

                    <Field.Root>
                      <Field.Label htmlFor={`${uid}-timezone`}>Time zone</Field.Label>
                      <NativeSelect.Root variant="outline" size="md">
                        <NativeSelect.Field
                          id={`${uid}-timezone`}
                          value={draft.timezone}
                          onChange={(e) => updateDraft("timezone", e.target.value)}
                        >
                          {TIMEZONES.map((tz) => (
                            <option key={tz.value} value={tz.value}>
                              {tz.label}
                            </option>
                          ))}
                        </NativeSelect.Field>
                        <NativeSelect.Indicator />
                      </NativeSelect.Root>
                    </Field.Root>
                  </Grid>

                  <Field.Root>
                    <Field.Label>Bio</Field.Label>
                    <Textarea
                      rows={3}
                      value={draft.bio}
                      onChange={(e) => updateDraft("bio", e.target.value)}
                      placeholder="Short summary for teammates and audit trails"
                    />
                    <Field.Description>
                      Visible to workspace members and attached to deployment approvals.
                    </Field.Description>
                  </Field.Root>
                </Card.Body>
              </Card.Root>

              <Card.Root variant="outline" size="lg">
                <Card.Header>
                  <Card.Title>Workspace identity</Card.Title>
                  <Card.Description>
                    Canonical identifiers used by the Kestrel CLI, webhooks, and audit logs.
                  </Card.Description>
                </Card.Header>
                <Card.Body style={styles.cardBodyStack}>
                  <HStack gap="3" justify="between" wrap="wrap">
                    <VStack gap="0.5">
                      <Text render={<span />} size="sm" weight="semibold">
                        Workspace slug
                      </Text>
                      <Text variant="muted" size="xs">
                        Used in deployment URLs and CLI targets
                      </Text>
                    </VStack>
                    <HStack gap="2">
                      <Code variant="subtle" size="sm">
                        {workspaceSlug}
                      </Code>
                      <Button
                        variant="ghost"
                        size="xs"
                        onClick={() => handleCopyText(workspaceSlug, "Workspace slug")}
                      >
                        Copy
                      </Button>
                    </HStack>
                  </HStack>
                  <Separator />
                  <HStack gap="3" justify="between" wrap="wrap">
                    <VStack gap="0.5">
                      <Text render={<span />} size="sm" weight="semibold">
                        Data residency
                      </Text>
                      <Text variant="muted" size="xs">
                        Primary control plane and encrypted state backups
                      </Text>
                    </VStack>
                    <Code variant="subtle" size="sm">
                      eu-central-1 · Frankfurt
                    </Code>
                  </HStack>
                  <Separator />
                  <HStack gap="3" justify="between" wrap="wrap">
                    <VStack gap="0.5">
                      <Text render={<span />} size="sm" weight="semibold">
                        Verified domain
                      </Text>
                      <Text variant="muted" size="xs">
                        Automatic SAML enrollment for company emails
                      </Text>
                    </VStack>
                    <HStack gap="2">
                      <Code variant="subtle" size="sm">
                        kestrel.cloud
                      </Code>
                      <Badge variant="subtle" size="xs" palette={greenPalette}>
                        Active
                      </Badge>
                    </HStack>
                  </HStack>
                </Card.Body>
              </Card.Root>

              <Card.Root variant="subtle" size="lg" palette={grayPalette}>
                <Card.Body style={styles.cardBodyStack}>
                  <HStack align="start" gap="3">
                    <IconBadge variant="outline" size="md" palette={grayPalette}>
                      <Icon
                        size="sm"
                        viewBox="0 0 20 20"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="1.6"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        aria-hidden="true"
                      >
                        <SectionGlyph id="security" />
                      </Icon>
                    </IconBadge>
                    <VStack gap="0.5">
                      <Text render={<span />} size="sm" weight="semibold">
                        Audit attribution &amp; identity
                      </Text>
                      <Text variant="muted" size="sm">
                        Updating your display name or timezone adjusts how timestamps and
                        approvals appear in live deployment logs without rotating your keys.
                      </Text>
                    </VStack>
                  </HStack>
                </Card.Body>
              </Card.Root>
            </VStack>
          )}

          {/* ── 2. Appearance ── */}
          {activeSection === "appearance" && (
            <VStack gap="5">
              <Card.Root variant="outline" size="lg">
                <Card.Header>
                  <Card.Title>Theme mode</Card.Title>
                  <Card.Description>
                    Choose how surfaces and syntax themes adapt to your workspace lighting.
                  </Card.Description>
                </Card.Header>
                <Card.Body style={styles.cardBodyStack}>
                  <RadioCard.Root
                    value={draft.theme}
                    onValueChange={(next) => {
                      if (next === "light" || next === "dark" || next === "system") {
                        updateDraft("theme", next);
                      }
                    }}
                    variant="outline"
                    size="md"
                    palette={accentPalette}
                    aria-label="Theme mode"
                    style={styles.threeColGrid}
                  >
                    <RadioCard.Item value="light">
                      <RadioCard.ItemControl>
                        <RadioCard.ItemContent>
                          <RadioCard.ItemText>Light</RadioCard.ItemText>
                          <RadioCard.ItemDescription>
                            High-clarity daylight surfaces
                          </RadioCard.ItemDescription>
                        </RadioCard.ItemContent>
                        <RadioCard.ItemIndicator />
                      </RadioCard.ItemControl>
                    </RadioCard.Item>

                    <RadioCard.Item value="dark">
                      <RadioCard.ItemControl>
                        <RadioCard.ItemContent>
                          <RadioCard.ItemText>Dark</RadioCard.ItemText>
                          <RadioCard.ItemDescription>
                            Low-glare slate for log streams
                          </RadioCard.ItemDescription>
                        </RadioCard.ItemContent>
                        <RadioCard.ItemIndicator />
                      </RadioCard.ItemControl>
                    </RadioCard.Item>

                    <RadioCard.Item value="system">
                      <RadioCard.ItemControl>
                        <RadioCard.ItemContent>
                          <RadioCard.ItemText>System</RadioCard.ItemText>
                          <RadioCard.ItemDescription>
                            Sync automatically with OS
                          </RadioCard.ItemDescription>
                        </RadioCard.ItemContent>
                        <RadioCard.ItemIndicator />
                      </RadioCard.ItemControl>
                    </RadioCard.Item>
                  </RadioCard.Root>

                  <HStack
                    gap="3"
                    justify="between"
                    wrap="wrap"
                    style={styles.previewSwatchRow}
                  >
                    <VStack gap="0.5">
                      <Text render={<span />} size="sm" weight="semibold">
                        Active preset summary
                      </Text>
                      <Text variant="muted" size="xs">
                        Applied across dashboards, edge trace views, and SQL explorers.
                      </Text>
                    </VStack>
                    <HStack gap="2" wrap="wrap">
                      <Badge variant="subtle" size="sm" palette={accentPalette}>
                        Theme: {draft.theme}
                      </Badge>
                      <Badge variant="outline" size="sm" palette={grayPalette}>
                        Density: {draft.density}
                      </Badge>
                    </HStack>
                  </HStack>
                </Card.Body>
              </Card.Root>

              <Card.Root variant="outline" size="lg">
                <Card.Header>
                  <Card.Title>Layout &amp; typography</Card.Title>
                  <Card.Description>
                    Control spacing density, monospace rendering, and accessibility cues.
                  </Card.Description>
                </Card.Header>
                <Card.Body style={styles.cardBodyStack}>
                  <HStack gap="4" justify="between">
                    <VStack gap="0.5">
                      <Text render={<span />} size="sm" weight="semibold">
                        Interface density
                      </Text>
                      <Text variant="muted" size="xs">
                        Adjust vertical rhythm in tables, deployment lists, and inspectors.
                      </Text>
                    </VStack>
                    <SegmentGroup.Root
                      size="sm"
                      value={draft.density}
                      onValueChange={(next) => {
                        if (
                          next === "compact" ||
                          next === "comfortable" ||
                          next === "spacious"
                        ) {
                          updateDraft("density", next);
                        }
                      }}
                      aria-label="Interface density"
                    >
                      <SegmentGroup.Item value="compact">Compact</SegmentGroup.Item>
                      <SegmentGroup.Item value="comfortable">
                        Comfortable
                      </SegmentGroup.Item>
                      <SegmentGroup.Item value="spacious">Spacious</SegmentGroup.Item>
                    </SegmentGroup.Root>
                  </HStack>

                  <Separator />

                  <Grid columns="2" gap="4" style={styles.twoColGrid}>
                    <Field.Root>
                      <Field.Label htmlFor={`${uid}-code-font`}>
                        Code &amp; log font
                      </Field.Label>
                      <NativeSelect.Root variant="outline" size="md">
                        <NativeSelect.Field
                          id={`${uid}-code-font`}
                          value={draft.codeFont}
                          onChange={(e) => updateDraft("codeFont", e.target.value)}
                        >
                          {CODE_FONTS.map((opt) => (
                            <option key={opt.value} value={opt.value}>
                              {opt.label}
                            </option>
                          ))}
                        </NativeSelect.Field>
                        <NativeSelect.Indicator />
                      </NativeSelect.Root>
                    </Field.Root>

                    <Field.Root>
                      <Field.Label htmlFor={`${uid}-timestamp`}>
                        Timestamp format
                      </Field.Label>
                      <NativeSelect.Root variant="outline" size="md">
                        <NativeSelect.Field
                          id={`${uid}-timestamp`}
                          value={draft.timestampFormat}
                          onChange={(e) =>
                            updateDraft("timestampFormat", e.target.value)
                          }
                        >
                          {TIMESTAMP_FORMATS.map((opt) => (
                            <option key={opt.value} value={opt.value}>
                              {opt.label}
                            </option>
                          ))}
                        </NativeSelect.Field>
                        <NativeSelect.Indicator />
                      </NativeSelect.Root>
                    </Field.Root>
                  </Grid>

                  <Separator />

                  <ToggleRow
                    label="Reduce motion"
                    description="Minimize panel transitions, chart interpolations, and toast motion."
                    checked={draft.reduceMotion}
                    onCheckedChange={(checked) => updateDraft("reduceMotion", checked)}
                  />
                  <Separator />
                  <ToggleRow
                    label="Inline keyboard shortcuts"
                    description="Display command-palette and navigation keycaps across the console."
                    checked={draft.keyboardHints}
                    onCheckedChange={(checked) => updateDraft("keyboardHints", checked)}
                  />
                  <Separator />
                  <ToggleRow
                    label="High-contrast syntax tokens"
                    description="Increase color separation inside live build logs and diff panels."
                    checked={draft.highContrastSyntax}
                    onCheckedChange={(checked) =>
                      updateDraft("highContrastSyntax", checked)
                    }
                  />
                </Card.Body>
              </Card.Root>
            </VStack>
          )}

          {/* ── 3. Notifications ── */}
          {activeSection === "notifications" && (
            <VStack gap="5">
              <Card.Root variant="outline" size="lg">
                <Card.Header>
                  <Card.Title>Delivery schedule</Card.Title>
                  <Card.Description>
                    Route operational notifications to the right channel and cadence.
                  </Card.Description>
                </Card.Header>
                <Card.Body style={styles.cardBodyStack}>
                  <Grid columns="2" gap="4" style={styles.twoColGrid}>
                    <Field.Root>
                      <Field.Label htmlFor={`${uid}-cadence`}>
                        Delivery frequency
                      </Field.Label>
                      <NativeSelect.Root variant="outline" size="md">
                        <NativeSelect.Field
                          id={`${uid}-cadence`}
                          value={draft.digestCadence}
                          onChange={(e) => updateDraft("digestCadence", e.target.value)}
                        >
                          {DIGEST_CADENCES.map((opt) => (
                            <option key={opt.value} value={opt.value}>
                              {opt.label}
                            </option>
                          ))}
                        </NativeSelect.Field>
                        <NativeSelect.Indicator />
                      </NativeSelect.Root>
                    </Field.Root>

                    <Field.Root>
                      <Field.Label htmlFor={`${uid}-channel`}>
                        Primary alert route
                      </Field.Label>
                      <NativeSelect.Root variant="outline" size="md">
                        <NativeSelect.Field
                          id={`${uid}-channel`}
                          value={draft.alertChannel}
                          onChange={(e) => updateDraft("alertChannel", e.target.value)}
                        >
                          {ALERT_CHANNELS.map((opt) => (
                            <option key={opt.value} value={opt.value}>
                              {opt.label}
                            </option>
                          ))}
                        </NativeSelect.Field>
                        <NativeSelect.Indicator />
                      </NativeSelect.Root>
                    </Field.Root>
                  </Grid>

                  <Separator />

                  <ToggleRow
                    label="Quiet hours (22:00 – 07:00)"
                    description="Hold routine digests overnight. Critical production failures still deliver."
                    checked={draft.quietHours}
                    onCheckedChange={(checked) => updateDraft("quietHours", checked)}
                  />
                </Card.Body>
              </Card.Root>

              <Card.Root variant="outline" size="lg">
                <Card.Header>
                  <HStack align="start" gap="3" justify="between" wrap="wrap">
                    <VStack gap="1">
                      <Card.Title>Event subscriptions</Card.Title>
                      <Card.Description>
                        Fine-tune which runtime, security, and billing events notify you.
                      </Card.Description>
                    </VStack>
                    <Button variant="ghost" size="xs" onClick={handleMuteNonCritical}>
                      Mute non-critical
                    </Button>
                  </HStack>
                </Card.Header>
                <Card.Body style={styles.cardBodyStack}>
                  <ToggleRow
                    label="Production deployment failures"
                    description="Immediate alert when a release fails health checks or rolls back."
                    checked={draft.notifyDeployFailures}
                    onCheckedChange={(checked) =>
                      updateDraft("notifyDeployFailures", checked)
                    }
                    badge={{ label: "Critical", palette: redPalette }}
                  />
                  <Separator />
                  <ToggleRow
                    label="Edge build promotions"
                    description="Notify when a preview build is promoted to global production."
                    checked={draft.notifyProdPromotions}
                    onCheckedChange={(checked) =>
                      updateDraft("notifyProdPromotions", checked)
                    }
                  />
                  <Separator />
                  <ToggleRow
                    label="Canary latency regressions"
                    description="Alert when p99 edge response time exceeds baseline by 20%."
                    checked={draft.notifyCanaryLatency}
                    onCheckedChange={(checked) =>
                      updateDraft("notifyCanaryLatency", checked)
                    }
                  />
                  <Separator />
                  <ToggleRow
                    label="New device sign-ins"
                    description="Email notice whenever a session starts from a new browser or CLI host."
                    checked={draft.notifyNewDevice}
                    onCheckedChange={(checked) =>
                      updateDraft("notifyNewDevice", checked)
                    }
                    badge={{ label: "Recommended", palette: bluePalette }}
                  />
                  <Separator />
                  <ToggleRow
                    label="Expiring API tokens"
                    description="Send a reminder 7 days before any workspace API key expires."
                    checked={draft.notifyTokenExpiry}
                    onCheckedChange={(checked) =>
                      updateDraft("notifyTokenExpiry", checked)
                    }
                  />
                  <Separator />
                  <ToggleRow
                    label="Weekly usage summary"
                    description="Monday morning recap of edge requests, cache hit ratio, and build minutes."
                    checked={draft.notifyWeeklyDigest}
                    onCheckedChange={(checked) =>
                      updateDraft("notifyWeeklyDigest", checked)
                    }
                  />
                  <Separator />
                  <ToggleRow
                    label="Invoice & quota warnings"
                    description="Alert when workspace usage crosses 80% of monthly plan allowances."
                    checked={draft.notifyInvoiceAlerts}
                    onCheckedChange={(checked) =>
                      updateDraft("notifyInvoiceAlerts", checked)
                    }
                  />
                </Card.Body>
              </Card.Root>
            </VStack>
          )}

          {/* ── 4. Security & API keys ── */}
          {activeSection === "security" && (
            <Tabs.Root<"auth" | "tokens">
              value={securityTab}
              onValueChange={setSecurityTab}
              variant="line"
              size="md"
              palette={accentPalette}
            >
              <Tabs.List aria-label="Security sections">
                <Tabs.Tab value="auth">Authentication &amp; sessions</Tabs.Tab>
                <Tabs.Tab value="tokens">
                  <span>API tokens</span>
                  <Badge variant="subtle" size="xs" palette={grayPalette}>
                    {tokens.length}
                  </Badge>
                </Tabs.Tab>
              </Tabs.List>

              <Tabs.Panel value="auth" style={styles.tabsPanelBody}>
                <VStack gap="5">
                  <Card.Root variant="outline" size="lg">
                    <Card.Header>
                      <Card.Title>Sign-in &amp; protection</Card.Title>
                      <Card.Description>
                        Hardware keys, single sign-on, and deployment verification rules.
                      </Card.Description>
                    </Card.Header>
                    <Card.Body style={styles.cardBodyStack}>
                      <ToggleRow
                        label="Require hardware passkey for production deploys"
                        description="Prompt for WebAuthn verification before approving production rollouts."
                        checked={draft.requirePasskeyForDeploys}
                        onCheckedChange={(checked) =>
                          updateDraft("requirePasskeyForDeploys", checked)
                        }
                        badge={{ label: "2 keys registered", palette: greenPalette }}
                      />
                      <Separator />
                      <ToggleRow
                        label="Enforce SAML SSO (Okta)"
                        description="Require all kestrel.cloud members to authenticate through Okta."
                        checked={draft.enforceSamlSso}
                        onCheckedChange={(checked) =>
                          updateDraft("enforceSamlSso", checked)
                        }
                      />
                      <Separator />
                      <HStack gap="3" justify="between" wrap="wrap">
                        <VStack gap="0.5">
                          <Text render={<span />} size="sm" weight="semibold">
                            Recovery codes
                          </Text>
                          <Text variant="muted" size="xs">
                            8 of 10 single-use backup codes remain available.
                          </Text>
                        </VStack>
                        <Button
                          variant="surface"
                          size="sm"
                          onClick={() =>
                            queue.info("Recovery codes rotated", {
                              description:
                                "Generated 10 fresh backup codes. Store them in your password vault.",
                            })
                          }
                        >
                          Regenerate codes
                        </Button>
                      </HStack>
                    </Card.Body>
                  </Card.Root>

                  <Card.Root variant="outline" size="lg">
                    <Card.Header>
                      <HStack align="start" gap="3" justify="between" wrap="wrap">
                        <VStack gap="1">
                          <Card.Title>Active sessions</Card.Title>
                          <Card.Description>
                            Devices and CLI hosts currently authenticated to your account.
                          </Card.Description>
                        </VStack>
                        {sessions.length > 1 ? (
                          <Button
                            variant="outline"
                            size="xs"
                            palette={redPalette}
                            onClick={handleRevokeOtherSessions}
                          >
                            Sign out others
                          </Button>
                        ) : null}
                      </HStack>
                    </Card.Header>
                    <Card.Body style={styles.cardBodyStack}>
                      {sessions.map((session, idx) => (
                        <VStack key={session.id} gap="4">
                          {idx > 0 ? <Separator /> : null}
                          <HStack gap="3" justify="between" wrap="wrap">
                            <HStack gap="3">
                              <IconBadge variant="subtle" size="md" palette={grayPalette}>
                                <DeviceGlyph kind={session.kind} />
                              </IconBadge>
                              <VStack gap="0.5">
                                <HStack gap="2" wrap="wrap">
                                  <Text render={<span />} size="sm" weight="semibold">
                                    {session.device}
                                  </Text>
                                  {session.current ? (
                                    <Badge
                                      variant="subtle"
                                      size="xs"
                                      palette={greenPalette}
                                    >
                                      Current session
                                    </Badge>
                                  ) : null}
                                </HStack>
                                <Text variant="muted" size="xs">
                                  {session.client} · {session.location} · {session.lastActive}
                                </Text>
                              </VStack>
                            </HStack>
                            {!session.current ? (
                              <Button
                                variant="ghost"
                                size="xs"
                                onClick={() => handleRevokeSession(session)}
                              >
                                Sign out
                              </Button>
                            ) : null}
                          </HStack>
                        </VStack>
                      ))}
                    </Card.Body>
                  </Card.Root>
                </VStack>
              </Tabs.Panel>

              <Tabs.Panel value="tokens" style={styles.tabsPanelBody}>
                <VStack gap="5">
                  <Card.Root variant="outline" size="lg">
                    <Card.Header>
                      <Card.Title>Generate API token</Card.Title>
                      <Card.Description>
                        Issue scoped bearer credentials for CI pipelines, telemetry, or CLI automation.
                      </Card.Description>
                    </Card.Header>
                    <Card.Body style={styles.cardBodyStack}>
                      <Grid
                        render={<form onSubmit={handleGenerateToken} />}
                        align="end"
                        gap="3"
                        style={styles.tokenFormGrid}
                      >
                        <Field.Root>
                          <Field.Label>Token label</Field.Label>
                          <Input
                            value={newTokenName}
                            onChange={(e) => setNewTokenName(e.target.value)}
                            placeholder="e.g. Preview Deploys · Staging"
                          />
                        </Field.Root>

                        <Field.Root>
                          <Field.Label htmlFor={`${uid}-scope`}>Permission scope</Field.Label>
                          <NativeSelect.Root variant="outline" size="md">
                            <NativeSelect.Field
                              id={`${uid}-scope`}
                              value={newTokenScope}
                              onChange={(e) =>
                                setNewTokenScope(e.target.value as TokenScope)
                              }
                            >
                              <option value="read">Read-only</option>
                              <option value="deploy">Deploy &amp; logs</option>
                              <option value="admin">Full admin</option>
                            </NativeSelect.Field>
                            <NativeSelect.Indicator />
                          </NativeSelect.Root>
                        </Field.Root>

                        <Button type="submit" variant="solid" size="md" palette={accentPalette}>
                          Generate token
                        </Button>
                      </Grid>

                      {revealedToken ? (
                        <VStack gap="2.5" style={styles.tokenReveal}>
                          <HStack gap="2" justify="between" wrap="wrap">
                            <Text render={<span />} size="sm" weight="semibold">
                              New token created: {revealedToken.name}
                            </Text>
                            <HStack gap="2">
                              <Button
                                variant="surface"
                                size="xs"
                                onClick={() =>
                                  handleCopyText(revealedToken.secret, "API token")
                                }
                              >
                                Copy secret
                              </Button>
                              <Button
                                variant="ghost"
                                size="xs"
                                onClick={() => setRevealedToken(null)}
                              >
                                Dismiss
                              </Button>
                            </HStack>
                          </HStack>
                          <Code variant="outline" size="sm" style={styles.tokenCode}>
                            {revealedToken.secret}
                          </Code>
                        </VStack>
                      ) : null}
                    </Card.Body>
                  </Card.Root>

                  <Card.Root variant="outline" size="lg">
                    <Card.Header>
                      <Card.Title>Active API tokens</Card.Title>
                      <Card.Description>
                        Revoking a key immediately invalidates all in-flight automation requests.
                      </Card.Description>
                    </Card.Header>
                    <Card.Body style={styles.cardBodyStack}>
                      {tokens.length === 0 ? (
                        <Text
                          variant="muted"
                          size="sm"
                          align="center"
                          style={styles.emptyNote}
                        >
                          No active API tokens. Generate one above to connect CI or telemetry tools.
                        </Text>
                      ) : (
                        tokens.map((token, idx) => (
                          <VStack key={token.id} gap="4">
                            {idx > 0 ? <Separator /> : null}
                            <HStack gap="3" justify="between" wrap="wrap">
                              <VStack gap="1">
                                <HStack gap="2" wrap="wrap">
                                  <Text render={<span />} size="sm" weight="semibold">
                                    {token.name}
                                  </Text>
                                  <Badge
                                    variant="subtle"
                                    size="xs"
                                    palette={
                                      token.scope === "admin"
                                        ? amberPalette
                                        : token.scope === "deploy"
                                          ? bluePalette
                                          : grayPalette
                                    }
                                  >
                                    {SCOPE_LABELS[token.scope]}
                                  </Badge>
                                </HStack>
                                <HStack gap="2" wrap="wrap">
                                  <Code variant="subtle" size="xs">
                                    {token.prefix}
                                  </Code>
                                  <Text render={<span />} variant="muted" size="xs">
                                    Created {token.createdAt} · Last used {token.lastUsed}
                                  </Text>
                                </HStack>
                              </VStack>
                              <Button
                                variant="outline"
                                size="xs"
                                palette={redPalette}
                                onClick={() => handleRevokeToken(token)}
                              >
                                Revoke
                              </Button>
                            </HStack>
                          </VStack>
                        ))
                      )}
                    </Card.Body>
                  </Card.Root>
                </VStack>
              </Tabs.Panel>
            </Tabs.Root>
          )}

          {/* ── 5. Team & Billing ── */}
          {activeSection === "billing" && (
            <VStack gap="5">
              <Card.Root variant="outline" size="lg">
                <Card.Body style={styles.cardBodyStack}>
                  <HStack align="start" gap="3" justify="between" wrap="wrap">
                    <VStack gap="0.5">
                      <HStack gap="2" wrap="wrap">
                        <Heading render={<h2 />} size="lg" style={styles.pageHeading}>
                          Kestrel Scale
                        </Heading>
                        <Badge variant="subtle" size="xs" palette={greenPalette}>
                          Active
                        </Badge>
                      </HStack>
                      <Text variant="muted" size="xs">
                        Renews Jan 1, 2027 · Visa ending in 8421
                      </Text>
                    </VStack>
                    <HStack align="baseline" gap="1.5">
                      <Text
                        render={<span />}
                        size="2xl"
                        weight="semibold"
                        tabular="true"
                      >
                        $240
                      </Text>
                      <Text render={<span />} variant="muted" size="xs">
                        / month
                      </Text>
                    </HStack>
                  </HStack>

                  <Separator />

                  <Grid columns="3" gap="3" style={styles.threeColGrid}>
                    <VStack gap="2">
                      <HStack align="baseline" gap="2" justify="between">
                        <Text render={<span />} variant="muted" size="xs">
                          Edge requests
                        </Text>
                        <Text
                          render={<span />}
                          size="xs"
                          weight="semibold"
                          tabular="true"
                        >
                          14.2M / 20M
                        </Text>
                      </HStack>
                      <Progress.Root
                        value={71}
                        max={100}
                        size="sm"
                        shape="full"
                        palette={accentPalette}
                        aria-label="Edge requests usage"
                      >
                        <Progress.Track>
                          <Progress.Range />
                        </Progress.Track>
                      </Progress.Root>
                    </VStack>

                    <VStack gap="2">
                      <HStack align="baseline" gap="2" justify="between">
                        <Text render={<span />} variant="muted" size="xs">
                          Workspace seats
                        </Text>
                        <Text
                          render={<span />}
                          size="xs"
                          weight="semibold"
                          tabular="true"
                        >
                          {members.length} / 10 seats
                        </Text>
                      </HStack>
                      <Progress.Root
                        value={seatsUsedPct}
                        max={100}
                        size="sm"
                        shape="full"
                        palette={bluePalette}
                        aria-label="Workspace seats usage"
                      >
                        <Progress.Track>
                          <Progress.Range />
                        </Progress.Track>
                      </Progress.Root>
                    </VStack>

                    <VStack gap="2">
                      <HStack align="baseline" gap="2" justify="between">
                        <Text render={<span />} variant="muted" size="xs">
                          Build minutes
                        </Text>
                        <Text
                          render={<span />}
                          size="xs"
                          weight="semibold"
                          tabular="true"
                        >
                          1,840 / 3,000
                        </Text>
                      </HStack>
                      <Progress.Root
                        value={61}
                        max={100}
                        size="sm"
                        shape="full"
                        palette={tealPalette}
                        aria-label="Build minutes usage"
                      >
                        <Progress.Track>
                          <Progress.Range />
                        </Progress.Track>
                      </Progress.Root>
                    </VStack>
                  </Grid>
                </Card.Body>
                <Card.Footer>
                  <Button
                    variant="surface"
                    size="sm"
                    onClick={() =>
                      queue.info("Invoice downloaded", {
                        description: "Kestrel-Scale-2026-12.pdf saved to downloads.",
                      })
                    }
                  >
                    Download latest invoice
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() =>
                      queue.info("Billing portal", {
                        description: "Payment methods and VAT details open in Stripe Portal.",
                      })
                    }
                  >
                    Update payment method
                  </Button>
                </Card.Footer>
              </Card.Root>

              <Card.Root variant="outline" size="lg">
                <Card.Header>
                  <Card.Title>Team members</Card.Title>
                  <Card.Description>
                    Invite collaborators or update workspace roles. Role edits apply when saved.
                  </Card.Description>
                </Card.Header>
                <Card.Body style={styles.cardBodyStack}>
                  <Grid
                    render={<form onSubmit={handleInviteMember} />}
                    align="end"
                    gap="3"
                    style={styles.tokenFormGrid}
                  >
                    <Field.Root>
                      <Field.Label>Invite by email</Field.Label>
                      <Input
                        type="email"
                        value={inviteEmail}
                        onChange={(e) => setInviteEmail(e.target.value)}
                        placeholder="engineer@kestrel.cloud"
                      />
                    </Field.Root>

                    <Field.Root>
                      <Field.Label htmlFor={`${uid}-invite-role`}>Role</Field.Label>
                      <NativeSelect.Root variant="outline" size="md">
                        <NativeSelect.Field
                          id={`${uid}-invite-role`}
                          value={inviteRole}
                          onChange={(e) =>
                            setInviteRole(
                              e.target.value as Exclude<MemberRole, "owner">,
                            )
                          }
                        >
                          <option value="admin">Admin</option>
                          <option value="developer">Developer</option>
                          <option value="viewer">Viewer</option>
                        </NativeSelect.Field>
                        <NativeSelect.Indicator />
                      </NativeSelect.Root>
                    </Field.Root>

                    <Button type="submit" variant="solid" size="md" palette={accentPalette}>
                      Send invite
                    </Button>
                  </Grid>

                  <Separator />

                  {members.map((member, idx) => {
                    const role = draft.memberRoles[member.id] ?? "viewer";
                    const isOwner = role === "owner";
                    return (
                      <VStack key={member.id} gap="4">
                        {idx > 0 ? <Separator /> : null}
                        <HStack gap="3" justify="between" wrap="wrap">
                          <HStack gap="3">
                            <Avatar.Root
                              size="md"
                              variant="subtle"
                              palette={member.palette}
                            >
                              <Avatar.Fallback>{member.initials}</Avatar.Fallback>
                            </Avatar.Root>
                            <VStack gap="0.5">
                              <HStack gap="2" wrap="wrap">
                                <Text render={<span />} size="sm" weight="semibold">
                                  {member.name}
                                </Text>
                                {member.pending ? (
                                  <Badge
                                    variant="subtle"
                                    size="xs"
                                    palette={amberPalette}
                                  >
                                    Pending invite
                                  </Badge>
                                ) : null}
                              </HStack>
                              <Text variant="muted" size="xs">
                                {member.email}
                              </Text>
                            </VStack>
                          </HStack>

                          <HStack gap="2">
                            {isOwner ? (
                              <Badge variant="outline" size="sm" palette={accentPalette}>
                                Owner
                              </Badge>
                            ) : (
                              <>
                                <NativeSelect.Root
                                  variant="outline"
                                  size="sm"
                                  style={styles.roleSelectRoot}
                                >
                                  <NativeSelect.Field
                                    aria-label={`Role for ${member.name}`}
                                    value={role}
                                    onChange={(e) =>
                                      handleMemberRoleChange(
                                        member.id,
                                        e.target.value as MemberRole,
                                      )
                                    }
                                  >
                                    <option value="admin">Admin</option>
                                    <option value="developer">Developer</option>
                                    <option value="viewer">Viewer</option>
                                  </NativeSelect.Field>
                                  <NativeSelect.Indicator />
                                </NativeSelect.Root>
                                <Button
                                  variant="ghost"
                                  size="xs"
                                  palette={redPalette}
                                  onClick={() => handleRemoveMember(member)}
                                >
                                  Remove
                                </Button>
                              </>
                            )}
                          </HStack>
                        </HStack>
                      </VStack>
                    );
                  })}
                </Card.Body>
              </Card.Root>
            </VStack>
          )}

          {/* Sticky dirty-state save bar */}
          {isDirty ? (
            <ActionBar.Positioner style={styles.saveBarPositioner}>
              <ActionBar.Content style={styles.saveBarContent}>
                <HStack gap="2" style={styles.saveBarStatus}>
                  <span {...stylex.props(styles.dirtyDot)} />
                  <Text render={<span />} size="sm" weight="semibold">
                    {totalDirtyCount} unsaved{" "}
                    {totalDirtyCount === 1 ? "change" : "changes"}
                  </Text>
                </HStack>
                <ActionBar.Separator />
                <HStack gap="2">
                  <Button variant="ghost" size="sm" onClick={handleDiscard}>
                    Discard
                  </Button>
                  <Button
                    variant="solid"
                    size="sm"
                    palette={accentPalette}
                    onClick={handleSave}
                  >
                    Save changes
                  </Button>
                </HStack>
              </ActionBar.Content>
            </ActionBar.Positioner>
          ) : null}
        </VStack>
      </main>

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

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