{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "settings-and-plans",
  "type": "registry:block",
  "title": "Settings & Plans",
  "description": "Workspace, members, API keys and billing in one calm settings screen: grouped rows, an unsaved-changes bar that springs up, invites and role changes, keys shown once, and usage bars that fill when you open Billing.",
  "categories": [
    "screen",
    "Product"
  ],
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "utils",
    "https://coss.com/ui/r/alert.json",
    "https://coss.com/ui/r/alert-dialog.json",
    "https://coss.com/ui/r/avatar.json",
    "https://coss.com/ui/r/badge.json",
    "https://coss.com/ui/r/button.json",
    "https://coss.com/ui/r/input.json",
    "https://coss.com/ui/r/input-group.json",
    "https://coss.com/ui/r/label.json",
    "https://coss.com/ui/r/menu.json",
    "https://coss.com/ui/r/select.json",
    "https://coss.com/ui/r/switch.json"
  ],
  "files": [
    {
      "path": "registry/devl/settings-and-plans.tsx",
      "type": "registry:component",
      "content": "\"use client\";\n\nimport {\n  AlertTriangleIcon,\n  ArrowLeftIcon,\n  BellIcon,\n  CheckIcon,\n  CopyIcon,\n  CreditCardIcon,\n  DownloadIcon,\n  EllipsisIcon,\n  EyeIcon,\n  EyeOffIcon,\n  KeyRoundIcon,\n  MailIcon,\n  PaletteIcon,\n  PlusIcon,\n  SettingsIcon,\n  ShieldIcon,\n  Trash2Icon,\n  UserIcon,\n  UsersIcon,\n} from \"lucide-react\";\nimport { AnimatePresence, animate, motion, useMotionValue, useReducedMotion, useTransform } from \"motion/react\";\nimport { type ReactNode, useEffect, useId, useRef, useState } from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport { Alert, AlertAction, AlertDescription, AlertTitle } from \"@/components/ui/alert\";\nimport {\n  AlertDialog,\n  AlertDialogClose,\n  AlertDialogDescription,\n  AlertDialogFooter,\n  AlertDialogHeader,\n  AlertDialogPopup,\n  AlertDialogTitle,\n} from \"@/components/ui/alert-dialog\";\nimport { Avatar, AvatarFallback } from \"@/components/ui/avatar\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { InputGroup, InputGroupAddon, InputGroupInput, InputGroupText } from \"@/components/ui/input-group\";\nimport { Label } from \"@/components/ui/label\";\nimport { Menu, MenuItem, MenuPopup, MenuSeparator, MenuTrigger } from \"@/components/ui/menu\";\nimport { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from \"@/components/ui/select\";\nimport { Switch } from \"@/components/ui/switch\";\n\nfunction useReducedMotionAfterMount() {\n  const prefers = useReducedMotion();\n  const [mounted, setMounted] = useState(false);\n  useEffect(() => setMounted(true), []);\n  return mounted && Boolean(prefers);\n}\n\nexport type SettingsSectionId =\n  | \"profile\"\n  | \"appearance\"\n  | \"notifications\"\n  | \"security\"\n  | \"general\"\n  | \"members\"\n  | \"billing\"\n  | \"developer\";\n\nexport type SettingsTab = \"workspace\" | \"members\" | \"keys\" | \"billing\";\nexport type MemberRole = \"owner\" | \"admin\" | \"member\" | \"viewer\";\nexport type KeyScope = \"read\" | \"write\" | \"admin\";\n\nexport interface SettingsMember {\n  id: string;\n  name: string;\n  email: string;\n  role: MemberRole;\n  lastActive: string;\n  invited?: boolean;\n}\n\nexport interface SettingsApiKey {\n  id: string;\n  name: string;\n  secret: string;\n  scope: KeyScope;\n  created: string;\n  lastUsed: string;\n}\n\nexport interface SettingsUsage {\n  label: string;\n  used: number;\n  limit: number;\n  projected?: number;\n  unit?: string;\n}\n\nexport interface SettingsInvoice {\n  id: string;\n  date: string;\n  amount: number;\n  status: \"paid\" | \"due\" | \"failed\";\n}\n\nexport interface SettingsPlan {\n  id: string;\n  name: string;\n  price: number;\n  blurb: string;\n}\n\nexport interface SettingsCard {\n  brand?: string;\n  last4: string;\n  expires: string;\n  holder: string;\n  email?: string;\n}\n\nexport interface SettingsAndPlansProps {\n  className?: string;\n  defaultTab?: SettingsTab;\n  workspace?: { name: string; slug: string; region: string };\n  members?: SettingsMember[];\n  apiKeys?: SettingsApiKey[];\n  plans?: SettingsPlan[];\n  currentPlan?: string;\n  renewsOn?: string;\n  usage?: SettingsUsage[];\n  invoices?: SettingsInvoice[];\n  card?: SettingsCard;\n  cycleDaysLeft?: number;\n  overagePer1k?: number;\n  domain?: string;\n  onNavigate?: (section: SettingsSectionId) => void;\n}\n\nconst spring = { type: \"spring\", stiffness: 420, damping: 40 } as const;\nconst easeOut = [0.23, 1, 0.32, 1] as const;\nconst press = \"transition-[scale,background-color,box-shadow] duration-150 ease-out motion-safe:active:scale-[0.97]\";\n\nconst navGroups: { label: string; items: { id: SettingsSectionId; label: string; icon: ReactNode }[] }[] = [\n  {\n    label: \"Account\",\n    items: [\n      { id: \"profile\", label: \"Profile\", icon: <UserIcon /> },\n      { id: \"appearance\", label: \"Appearance\", icon: <PaletteIcon /> },\n      { id: \"notifications\", label: \"Notifications\", icon: <BellIcon /> },\n      { id: \"security\", label: \"Security\", icon: <ShieldIcon /> },\n    ],\n  },\n  {\n    label: \"Workspace\",\n    items: [\n      { id: \"general\", label: \"General\", icon: <SettingsIcon /> },\n      { id: \"members\", label: \"Members & roles\", icon: <UsersIcon /> },\n      { id: \"billing\", label: \"Billing\", icon: <CreditCardIcon /> },\n    ],\n  },\n  {\n    label: \"Developer\",\n    items: [{ id: \"developer\", label: \"API keys & webhooks\", icon: <KeyRoundIcon /> }],\n  },\n];\n\nconst tabForNav: Partial<Record<SettingsSectionId, SettingsTab>> = {\n  general: \"workspace\",\n  members: \"members\",\n  billing: \"billing\",\n  developer: \"keys\",\n};\n\nconst navForTab: Record<SettingsTab, SettingsSectionId> = {\n  workspace: \"general\",\n  members: \"members\",\n  billing: \"billing\",\n  keys: \"developer\",\n};\n\nconst tabOrder: SettingsTab[] = [\"workspace\", \"members\", \"keys\", \"billing\"];\n\nconst tabCopy: Record<SettingsTab, { title: string; description: string }> = {\n  workspace: { title: \"General\", description: \"Your workspace's name, address and where its data lives.\" },\n  members: { title: \"Members\", description: \"Who can get in, and what they can touch.\" },\n  keys: { title: \"API keys\", description: \"Secret keys for scripts, CI and server-side calls.\" },\n  billing: { title: \"Billing\", description: \"Your plan, this cycle's usage, how you pay and past invoices.\" },\n};\n\nconst regions = [\n  { value: \"us-east\", label: \"US East · Virginia\" },\n  { value: \"eu-central\", label: \"EU Central · Frankfurt\" },\n  { value: \"ap-northeast\", label: \"AP Northeast · Tokyo\" },\n];\n\nconst roleItems: { value: MemberRole; label: string; hint: string }[] = [\n  { value: \"owner\", label: \"Owner\", hint: \"Billing and deleting the workspace\" },\n  { value: \"admin\", label: \"Admin\", hint: \"Members, keys and settings\" },\n  { value: \"member\", label: \"Member\", hint: \"Create and edit projects\" },\n  { value: \"viewer\", label: \"Viewer\", hint: \"Read-only access\" },\n];\n\nconst scopeItems: { value: KeyScope; label: string; hint: string }[] = [\n  { value: \"read\", label: \"Read\", hint: \"List and fetch\" },\n  { value: \"write\", label: \"Read & write\", hint: \"Create runs, edit data\" },\n  { value: \"admin\", label: \"Admin\", hint: \"Everything, incl. members\" },\n];\n\nconst defaultMembers: SettingsMember[] = [\n  { id: \"m1\", name: \"Ada Lindqvist\", email: \"ada@ridgeline.app\", role: \"owner\", lastActive: \"Now\" },\n  { id: \"m2\", name: \"Theo Marsh\", email: \"theo@ridgeline.app\", role: \"admin\", lastActive: \"12 min ago\" },\n  { id: \"m3\", name: \"Priya Raman\", email: \"priya@ridgeline.app\", role: \"member\", lastActive: \"2 h ago\" },\n  { id: \"m4\", name: \"Jonah Feld\", email: \"jonah@ridgeline.app\", role: \"member\", lastActive: \"Yesterday\" },\n  { id: \"m5\", name: \"Sara Whitlock\", email: \"sara@ridgeline.app\", role: \"viewer\", lastActive: \"4 days ago\" },\n];\n\nconst defaultKeys: SettingsApiKey[] = [\n  { id: \"k1\", name: \"Production server\", secret: \"rl_test_7Hq2vN9xRmT4bW8cYp3sKd1f\", scope: \"write\", created: \"Aug 02\", lastUsed: \"3 min ago\" },\n  { id: \"k2\", name: \"CI deploys\", secret: \"rl_test_Zt5uA0eJ6gLq9rXn2VbM8hC4\", scope: \"read\", created: \"Sep 18\", lastUsed: \"1 h ago\" },\n  { id: \"k3\", name: \"Analytics export\", secret: \"rl_test_Pw3kS7yD1oF5iQ0zU6aE9jB2\", scope: \"read\", created: \"Oct 01\", lastUsed: \"Never\" },\n];\n\nconst defaultPlans: SettingsPlan[] = [\n  { id: \"starter\", name: \"Starter\", price: 0, blurb: \"3 seats, 2k runs\" },\n  { id: \"team\", name: \"Team\", price: 24, blurb: \"10 seats, 25k runs\" },\n  { id: \"scale\", name: \"Scale\", price: 59, blurb: \"Unlimited seats, 250k runs, SSO\" },\n];\n\nconst defaultUsage: SettingsUsage[] = [\n  { label: \"Agent runs\", used: 18420, limit: 25000, projected: 26300 },\n  { label: \"Seats\", used: 5, limit: 10 },\n  { label: \"Storage\", used: 43.6, limit: 50, unit: \"GB\" },\n];\n\nconst defaultInvoices: SettingsInvoice[] = [\n  { id: \"INV-2026-0010\", date: \"Oct 14, 2026\", amount: 120, status: \"due\" },\n  { id: \"INV-2026-0009\", date: \"Sep 14, 2026\", amount: 120, status: \"paid\" },\n  { id: \"INV-2026-0008\", date: \"Aug 14, 2026\", amount: 96, status: \"failed\" },\n  { id: \"INV-2026-0007\", date: \"Jul 14, 2026\", amount: 96, status: \"paid\" },\n];\n\nconst avatarHues = [\n  \"from-violet-400 to-indigo-500\",\n  \"from-sky-300 to-blue-500\",\n  \"from-teal-300 to-emerald-500\",\n  \"from-amber-300 to-orange-500\",\n  \"from-rose-300 to-pink-500\",\n  \"from-indigo-400 to-violet-700\",\n];\n\nconst invoiceBadge: Record<SettingsInvoice[\"status\"], { label: string; variant: \"success\" | \"warning\" | \"error\" }> = {\n  paid: { label: \"Paid\", variant: \"success\" },\n  due: { label: \"Due\", variant: \"warning\" },\n  failed: { label: \"Failed\", variant: \"error\" },\n};\n\nfunction initials(name: string) {\n  return name\n    .split(/\\s+/)\n    .filter(Boolean)\n    .map((p) => p[0])\n    .join(\"\")\n    .slice(0, 2)\n    .toUpperCase();\n}\n\nfunction mask(secret: string) {\n  return `${secret.slice(0, 8)}…${secret.slice(-4)}`;\n}\n\nfunction makeSecret() {\n  const chars = \"ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789\";\n  let out = \"rl_test_\";\n  for (let i = 0; i < 24; i++) out += chars[Math.floor(Math.random() * chars.length)];\n  return out;\n}\n\nconst formatInt = (n: number) => Math.round(n).toLocaleString(\"en-US\");\nconst formatMoney = (n: number) => `$${Math.round(n).toLocaleString(\"en-US\")}`;\nconst formatCents = (n: number) => `$${n.toFixed(2)}`;\n\nfunction RollingNumber({ value, format = formatInt }: { value: number; format?: (n: number) => string }) {\n  const reduce = useReducedMotionAfterMount();\n  const mv = useMotionValue(value);\n  const text = useTransform(mv, format);\n  useEffect(() => {\n    if (reduce) {\n      mv.set(value);\n      return;\n    }\n    const controls = animate(mv, value, { duration: 0.45, ease: easeOut });\n    return () => controls.stop();\n  }, [value, reduce, mv]);\n  return <motion.span className=\"tabular-nums\">{text}</motion.span>;\n}\n\nfunction Collapse({ show, children }: { show: boolean; children: ReactNode }) {\n  const reduce = useReducedMotionAfterMount();\n  return (\n    <AnimatePresence initial={false}>\n      {show && (\n        <motion.div\n          animate={{ height: \"auto\", opacity: 1 }}\n          className=\"overflow-hidden\"\n          exit={{ height: 0, opacity: 0 }}\n          initial={{ height: 0, opacity: 0 }}\n          transition={reduce ? { duration: 0 } : spring}\n        >\n          {children}\n        </motion.div>\n      )}\n    </AnimatePresence>\n  );\n}\n\nfunction Swap({ id, children, className }: { id: string; children: ReactNode; className?: string }) {\n  const reduce = useReducedMotionAfterMount();\n  return (\n    <AnimatePresence initial={false} mode=\"popLayout\">\n      <motion.span\n        animate={{ opacity: 1, y: 0 }}\n        className={cn(\"block\", className)}\n        exit={{ opacity: 0, y: reduce ? 0 : -3 }}\n        initial={{ opacity: 0, y: reduce ? 0 : 3 }}\n        key={id}\n        transition={{ duration: 0.16, ease: easeOut }}\n      >\n        {children}\n      </motion.span>\n    </AnimatePresence>\n  );\n}\n\nfunction Section({\n  title,\n  description,\n  action,\n  children,\n}: {\n  title: ReactNode;\n  description?: ReactNode;\n  action?: ReactNode;\n  children: ReactNode;\n}) {\n  return (\n    <section className=\"mt-10\">\n      <div className=\"flex items-end justify-between gap-4\">\n        <div className=\"min-w-0\">\n          <h2 className=\"font-medium text-sm\">{title}</h2>\n          {description && <p className=\"mt-0.5 text-pretty text-muted-foreground text-sm\">{description}</p>}\n        </div>\n        {action}\n      </div>\n      {children}\n    </section>\n  );\n}\n\nfunction Rows({ children, className }: { children: ReactNode; className?: string }) {\n  return <div className={cn(\"mt-3 divide-y overflow-hidden rounded-xl border bg-card\", className)}>{children}</div>;\n}\n\nfunction Row({\n  label,\n  help,\n  htmlFor,\n  children,\n  wide,\n}: {\n  label: ReactNode;\n  help?: ReactNode;\n  htmlFor?: string;\n  children?: ReactNode;\n  wide?: boolean;\n}) {\n  return (\n    <div className=\"flex flex-wrap items-center gap-x-4 gap-y-2.5 px-4 py-3.5\">\n      <div className=\"min-w-0 flex-1 basis-44\">\n        {htmlFor ? (\n          <Label className=\"font-medium text-sm\" htmlFor={htmlFor}>\n            {label}\n          </Label>\n        ) : (\n          <p className=\"font-medium text-sm\">{label}</p>\n        )}\n        {help && <div className=\"mt-0.5 text-pretty text-muted-foreground text-xs\">{help}</div>}\n      </div>\n      {children && <div className={cn(\"flex shrink-0 items-center gap-2\", wide && \"w-full sm:w-64\")}>{children}</div>}\n    </div>\n  );\n}\n\nfunction TableHeadRow({ className, children }: { className: string; children: ReactNode }) {\n  return (\n    <div className={cn(\"hidden items-center gap-4 bg-muted/30 px-4 py-2 font-medium text-muted-foreground text-xs sm:grid\", className)}>\n      {children}\n    </div>\n  );\n}\n\nfunction RidgelineShell({\n  active,\n  onNavigate,\n  children,\n  className,\n}: {\n  active: SettingsSectionId;\n  onNavigate?: (section: SettingsSectionId) => void;\n  children: ReactNode;\n  className?: string;\n}) {\n  const pillsRef = useRef<HTMLDivElement>(null);\n\n  useEffect(() => {\n    const scroller = pillsRef.current;\n    const el = scroller?.querySelector<HTMLElement>(`[data-section=\"${active}\"]`);\n    if (!scroller || !el || scroller.scrollWidth <= scroller.clientWidth) return;\n    scroller.scrollLeft = el.offsetLeft - 16;\n  }, [active]);\n\n  return (\n    <div className={cn(\"flex h-[760px] w-full bg-background text-foreground\", className)}>\n      <aside className=\"hidden w-60 shrink-0 flex-col border-r bg-muted/30 px-3 py-4 md:flex\">\n        <button\n          className=\"flex h-8 cursor-pointer items-center gap-2 rounded-md px-2 text-muted-foreground text-sm outline-none transition-colors hover:bg-accent/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n          type=\"button\"\n        >\n          <ArrowLeftIcon className=\"size-4\" />\n          Back to Ridgeline\n        </button>\n        <nav aria-label=\"Settings\" className=\"flex flex-col\">\n          {navGroups.map((group) => (\n            <div className=\"flex flex-col\" key={group.label}>\n              <span className=\"px-2 pt-5 pb-1.5 font-medium text-muted-foreground text-xs\">{group.label}</span>\n              <div className=\"flex flex-col gap-0.5\">\n                {group.items.map((item) => {\n                  const current = item.id === active;\n                  return (\n                    <button\n                      aria-current={current ? \"page\" : undefined}\n                      className={cn(\n                        \"flex h-8 cursor-pointer items-center gap-2 rounded-md px-2 text-left text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring [&_svg]:size-4 [&_svg]:shrink-0 [&_svg]:text-muted-foreground\",\n                        current ? \"bg-accent font-medium text-foreground\" : \"text-foreground/80 hover:bg-accent/60\",\n                      )}\n                      key={item.id}\n                      onClick={() => onNavigate?.(item.id)}\n                      type=\"button\"\n                    >\n                      {item.icon}\n                      <span className=\"truncate\">{item.label}</span>\n                    </button>\n                  );\n                })}\n              </div>\n            </div>\n          ))}\n        </nav>\n        <div className=\"mt-auto flex items-center gap-2.5 px-2 pt-4\">\n          <span className=\"flex size-7 shrink-0 items-center justify-center rounded-full bg-foreground font-medium text-[11px] text-background\">\n            AL\n          </span>\n          <span className=\"flex min-w-0 flex-col\">\n            <span className=\"truncate font-medium text-sm\">Ada Lindqvist</span>\n            <span className=\"truncate text-muted-foreground text-xs\">ada@ridgeline.app</span>\n          </span>\n        </div>\n      </aside>\n      <div className=\"flex min-w-0 flex-1 flex-col\">\n        <div className=\"md:hidden\">\n          <div className=\"flex h-12 items-center gap-2 border-b px-4\">\n            <button\n              aria-label=\"Back to Ridgeline\"\n              className=\"-ms-1.5 flex size-8 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-accent/60 focus-visible:ring-2 focus-visible:ring-ring\"\n              type=\"button\"\n            >\n              <ArrowLeftIcon className=\"size-4\" />\n            </button>\n            <span className=\"font-medium text-sm\">Settings</span>\n          </div>\n          <nav\n            aria-label=\"Settings\"\n            className=\"overflow-x-auto border-b px-4 py-2.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\"\n            ref={pillsRef}\n          >\n            <div className=\"flex w-max gap-1.5\">\n              {navGroups.flatMap((g) => g.items).map((item) => {\n                const current = item.id === active;\n                return (\n                  <button\n                    aria-current={current ? \"page\" : undefined}\n                    className={cn(\n                      \"flex h-7 cursor-pointer items-center rounded-full px-3 text-xs outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring\",\n                      current\n                        ? \"bg-foreground font-medium text-background\"\n                        : \"bg-muted text-muted-foreground hover:text-foreground\",\n                    )}\n                    data-section={item.id}\n                    key={item.id}\n                    onClick={() => onNavigate?.(item.id)}\n                    type=\"button\"\n                  >\n                    {item.label}\n                  </button>\n                );\n              })}\n            </div>\n          </nav>\n        </div>\n        <div className=\"min-h-0 flex-1 overflow-y-auto\">{children}</div>\n      </div>\n    </div>\n  );\n}\n\ntype WorkspaceDraft = { name: string; slug: string; region: string };\n\nfunction workspaceErrors(draft: WorkspaceDraft) {\n  return {\n    name: draft.name.trim() ? null : \"Give your workspace a name.\",\n    slug: /^[a-z0-9](?:[a-z0-9-]{1,30})[a-z0-9]$/.test(draft.slug) ? null : \"Use 3–32 letters, numbers or dashes.\",\n  };\n}\n\nfunction FieldError({ id, children }: { id: string; children: string | null }) {\n  return (\n    <Collapse show={Boolean(children)}>\n      <p className=\"pt-1.5 text-destructive-foreground text-xs\" id={id}>\n        {children}\n      </p>\n    </Collapse>\n  );\n}\n\nfunction WorkspaceMark({ name, className }: { name: string; className?: string }) {\n  const reduce = useReducedMotionAfterMount();\n  const text = initials(name || \"?\");\n  return (\n    <span className={cn(\"relative flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-foreground font-semibold text-background text-xs\", className)}>\n      <AnimatePresence initial={false} mode=\"popLayout\">\n        <motion.span\n          animate={{ opacity: 1, y: 0 }}\n          exit={{ opacity: 0, y: reduce ? 0 : -8 }}\n          initial={{ opacity: 0, y: reduce ? 0 : 8 }}\n          key={text}\n          transition={{ duration: 0.18, ease: easeOut }}\n        >\n          {text}\n        </motion.span>\n      </AnimatePresence>\n    </span>\n  );\n}\n\nfunction WorkspacePanel({\n  draft,\n  setDraft,\n  savedSlug,\n  domain,\n}: {\n  draft: WorkspaceDraft;\n  setDraft: (fn: (d: WorkspaceDraft) => WorkspaceDraft) => void;\n  savedSlug: string;\n  domain: string;\n}) {\n  const [prefs, setPrefs] = useState({ agents: true, sso: false, digest: true });\n  const [confirmOpen, setConfirmOpen] = useState(false);\n  const [typed, setTyped] = useState(\"\");\n  const [scheduled, setScheduled] = useState(false);\n  const errors = workspaceErrors(draft);\n  const ids = useId();\n\n  return (\n    <>\n      <Section description=\"Shown in the switcher, in emails and on shared links.\" title=\"Workspace\">\n        <Rows>\n          <Row help=\"Square image, at least 128px. Initials until you add one.\" label=\"Logo\">\n            <WorkspaceMark name={draft.name} />\n            <Button className={press} size=\"sm\" variant=\"outline\">\n              Upload\n            </Button>\n          </Row>\n          <Row htmlFor={`${ids}-name`} label=\"Name\" wide>\n            <div className=\"w-full\">\n              <Input\n                aria-describedby={errors.name ? `${ids}-name-error` : undefined}\n                aria-invalid={Boolean(errors.name) || undefined}\n                id={`${ids}-name`}\n                onChange={(e) => setDraft((d) => ({ ...d, name: e.target.value }))}\n                value={draft.name}\n              />\n              <FieldError id={`${ids}-name-error`}>{errors.name}</FieldError>\n            </div>\n          </Row>\n          <Row help=\"Changing it breaks links people have saved.\" htmlFor={`${ids}-slug`} label=\"URL\" wide>\n            <div className=\"w-full\">\n              <InputGroup>\n                <InputGroupAddon>\n                  <InputGroupText>{domain}/</InputGroupText>\n                </InputGroupAddon>\n                <InputGroupInput\n                  aria-describedby={errors.slug ? `${ids}-slug-error` : undefined}\n                  aria-invalid={Boolean(errors.slug) || undefined}\n                  id={`${ids}-slug`}\n                  onChange={(e) => setDraft((d) => ({ ...d, slug: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, \"-\") }))}\n                  value={draft.slug}\n                />\n              </InputGroup>\n              <FieldError id={`${ids}-slug-error`}>{errors.slug}</FieldError>\n            </div>\n          </Row>\n          <Row help=\"Moving copies your data and takes about an hour.\" label=\"Data region\" wide>\n            <Select items={regions} onValueChange={(v) => v && setDraft((d) => ({ ...d, region: v as string }))} value={draft.region}>\n              <SelectTrigger aria-label=\"Data region\" className=\"w-full\">\n                <SelectValue />\n              </SelectTrigger>\n              <SelectPopup>\n                {regions.map((r) => (\n                  <SelectItem key={r.value} value={r.value}>\n                    {r.label}\n                  </SelectItem>\n                ))}\n              </SelectPopup>\n            </Select>\n          </Row>\n        </Rows>\n      </Section>\n\n      <Section description=\"Defaults that apply to everyone in the workspace.\" title=\"Preferences\">\n        <Rows>\n          {(\n            [\n              [\"agents\", \"Members can create agents\", \"Otherwise only admins can publish new agents.\"],\n              [\"sso\", \"Require single sign-on\", \"Everyone signs in through your identity provider.\"],\n              [\"digest\", \"Weekly digest\", \"A Monday summary of runs, spend and failures.\"],\n            ] as const\n          ).map(([key, label, hint]) => (\n            <label className=\"flex cursor-pointer items-center gap-4 px-4 py-3.5\" key={key}>\n              <span className=\"flex min-w-0 flex-1 flex-col gap-0.5\">\n                <span className=\"font-medium text-sm\">{label}</span>\n                <span className=\"text-pretty text-muted-foreground text-xs\">{hint}</span>\n              </span>\n              <Switch checked={prefs[key]} onCheckedChange={(v) => setPrefs((p) => ({ ...p, [key]: v }))} />\n            </label>\n          ))}\n        </Rows>\n      </Section>\n\n      <Section title=\"Danger zone\">\n        <Rows className=\"border-destructive/24\">\n          <Row\n            help={\n              <Swap id={scheduled ? \"scheduled\" : \"idle\"}>\n                {scheduled ? (\n                  <span className=\"text-destructive-foreground\">Scheduled for Nov 3. Everyone keeps access until then.</span>\n                ) : (\n                  \"Removes projects, runs and keys after a 7-day grace period.\"\n                )}\n              </Swap>\n            }\n            label=\"Delete workspace\"\n          >\n            {scheduled ? (\n              <Button className={press} onClick={() => setScheduled(false)} size=\"sm\" variant=\"outline\">\n                Cancel deletion\n              </Button>\n            ) : (\n              <Button\n                className={press}\n                onClick={() => {\n                  setTyped(\"\");\n                  setConfirmOpen(true);\n                }}\n                size=\"sm\"\n                variant=\"destructive-outline\"\n              >\n                Delete…\n              </Button>\n            )}\n          </Row>\n        </Rows>\n      </Section>\n\n      <AlertDialog onOpenChange={setConfirmOpen} open={confirmOpen}>\n        <AlertDialogPopup>\n          <AlertDialogHeader>\n            <AlertDialogTitle>Delete {draft.name || \"this workspace\"}?</AlertDialogTitle>\n            <AlertDialogDescription>\n              Projects, runs and API keys are removed after 7 days. You can cancel any time before then.\n            </AlertDialogDescription>\n            <div className=\"mt-2 flex flex-col gap-2\">\n              <Label htmlFor={`${ids}-confirm`}>\n                Type <span className=\"font-mono\">{savedSlug}</span> to confirm\n              </Label>\n              <Input autoComplete=\"off\" className=\"font-mono\" id={`${ids}-confirm`} onChange={(e) => setTyped(e.target.value)} value={typed} />\n            </div>\n          </AlertDialogHeader>\n          <AlertDialogFooter>\n            <AlertDialogClose render={<Button variant=\"ghost\" />}>Cancel</AlertDialogClose>\n            <AlertDialogClose\n              disabled={typed !== savedSlug}\n              render={<Button disabled={typed !== savedSlug} onClick={() => setScheduled(true)} variant=\"destructive\" />}\n            >\n              Delete workspace\n            </AlertDialogClose>\n          </AlertDialogFooter>\n        </AlertDialogPopup>\n      </AlertDialog>\n    </>\n  );\n}\n\nfunction RoleSelect({ member, onRole }: { member: SettingsMember; onRole: (id: string, role: MemberRole) => void }) {\n  if (member.role === \"owner\") return <span className=\"inline-flex h-7 items-center px-2.5 text-muted-foreground text-sm\">Owner</span>;\n  return (\n    <Select\n      items={roleItems.slice(1).map((r) => ({ value: r.value, label: r.label }))}\n      onValueChange={(v) => v && onRole(member.id, v as MemberRole)}\n      value={member.role}\n    >\n      <SelectTrigger aria-label={`Role for ${member.name}`} className=\"w-32 min-w-0\" size=\"sm\">\n        <SelectValue />\n      </SelectTrigger>\n      <SelectPopup alignItemWithTrigger={false} className=\"w-60\">\n        {roleItems.slice(1).map((r) => (\n          <SelectItem className=\"items-start py-1.5 [&>span:first-child]:mt-0.5\" key={r.value} value={r.value}>\n            <span className=\"flex flex-col\">\n              <span className=\"font-medium\">{r.label}</span>\n              <span className=\"text-muted-foreground text-xs\">{r.hint}</span>\n            </span>\n          </SelectItem>\n        ))}\n      </SelectPopup>\n    </Select>\n  );\n}\n\nconst memberGrid = \"sm:grid-cols-[minmax(0,1fr)_8rem_6.5rem_2rem]\";\n\nfunction MembersPanel({ initial, seatLimit }: { initial: SettingsMember[]; seatLimit: number }) {\n  const [members, setMembers] = useState(() => initial.map((m, i) => ({ ...m, hue: avatarHues[i % avatarHues.length] })));\n  const [email, setEmail] = useState(\"\");\n  const [role, setRole] = useState<MemberRole>(\"member\");\n  const [error, setError] = useState<string | null>(null);\n  const [sending, setSending] = useState<string | null>(null);\n  const [notice, setNotice] = useState<string | null>(null);\n  const [removing, setRemoving] = useState<SettingsMember | null>(null);\n  const reduce = useReducedMotionAfterMount();\n  const hintId = useId();\n  const full = members.length >= seatLimit;\n\n  useEffect(() => {\n    if (!sending) return;\n    const address = sending;\n    const t = setTimeout(() => {\n      const name = address\n        .split(\"@\")[0]\n        .split(/[._-]/)\n        .map((p) => p.charAt(0).toUpperCase() + p.slice(1))\n        .join(\" \");\n      setMembers((m) => [\n        ...m,\n        { id: `m-${address}`, name, email: address, role, lastActive: \"Invite sent\", invited: true, hue: avatarHues[m.length % avatarHues.length] },\n      ]);\n      setSending(null);\n      setNotice(`Invite sent to ${address}.`);\n      setEmail(\"\");\n    }, 700);\n    return () => clearTimeout(t);\n  }, [sending, role]);\n\n  useEffect(() => {\n    if (!notice) return;\n    const t = setTimeout(() => setNotice(null), 2600);\n    return () => clearTimeout(t);\n  }, [notice]);\n\n  const invite = () => {\n    const address = email.trim().toLowerCase();\n    if (!address) return setError(\"Enter an email address to send an invite.\");\n    if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/.test(address)) return setError(\"That doesn't look like a full email address.\");\n    if (members.some((m) => m.email.toLowerCase() === address)) return setError(`${address} is already in this workspace.`);\n    if (full) return setError(`All ${seatLimit} seats are in use. Remove someone or upgrade to add more.`);\n    setError(null);\n    setNotice(null);\n    setSending(address);\n  };\n\n  const hint = error\n    ? { key: `e-${error}`, tone: \"text-destructive-foreground\", text: error }\n    : notice\n      ? { key: `n-${notice}`, tone: \"text-success-foreground\", text: notice }\n      : { key: \"idle\", tone: \"text-muted-foreground\", text: \"Invites expire after 7 days. Resend them from the list.\" };\n\n  const setRoleFor = (id: string, next: MemberRole) => setMembers((all) => all.map((x) => (x.id === id ? { ...x, role: next } : x)));\n\n  return (\n    <>\n      <Section\n        description={\n          <>\n            <span className=\"tabular-nums\">\n              <RollingNumber value={members.length} /> of {seatLimit}\n            </span>{\" \"}\n            seats used.\n          </>\n        }\n        title=\"Invite people\"\n      >\n        <Rows>\n          <form\n            className=\"flex flex-col gap-2 p-3 sm:flex-row\"\n            noValidate\n            onSubmit={(e) => {\n              e.preventDefault();\n              invite();\n            }}\n          >\n            <Input\n              aria-describedby={hintId}\n              aria-invalid={Boolean(error) || undefined}\n              aria-label=\"Email address\"\n              className=\"flex-1\"\n              disabled={Boolean(sending)}\n              onChange={(e) => {\n                setEmail(e.target.value);\n                if (error) setError(null);\n              }}\n              placeholder=\"name@company.com\"\n              type=\"email\"\n              value={email}\n            />\n            <div className=\"flex gap-2\">\n              <Select\n                items={roleItems.slice(1).map((r) => ({ value: r.value, label: r.label }))}\n                onValueChange={(v) => v && setRole(v as MemberRole)}\n                value={role}\n              >\n                <SelectTrigger aria-label=\"Role for invite\" className=\"w-28 min-w-0\">\n                  <SelectValue />\n                </SelectTrigger>\n                <SelectPopup>\n                  {roleItems.slice(1).map((r) => (\n                    <SelectItem key={r.value} value={r.value}>\n                      {r.label}\n                    </SelectItem>\n                  ))}\n                </SelectPopup>\n              </Select>\n              <Button className={cn(press, \"flex-1 sm:flex-none\")} loading={Boolean(sending)} type=\"submit\">\n                <MailIcon />\n                Invite\n              </Button>\n            </div>\n          </form>\n        </Rows>\n        <div aria-live=\"polite\" className=\"mt-2 min-h-4 px-1 text-xs\" id={hintId}>\n          <Swap className={cn(\"text-pretty\", hint.tone)} id={hint.key}>\n            {hint.text}\n          </Swap>\n        </div>\n      </Section>\n\n      <Section description={`${members.length} people, including pending invites.`} title=\"Members\">\n        <Rows>\n          <TableHeadRow className={memberGrid}>\n            <span>Member</span>\n            <span>Role</span>\n            <span>Last active</span>\n            <span className=\"sr-only\">Actions</span>\n          </TableHeadRow>\n          <AnimatePresence initial={false}>\n            {members.map((m) => (\n              <motion.div\n                animate={{ opacity: 1, height: \"auto\" }}\n                className=\"overflow-hidden\"\n                exit={{ opacity: 0, height: 0 }}\n                initial={reduce ? false : { opacity: 0, height: 0 }}\n                key={m.id}\n                transition={reduce ? { duration: 0 } : spring}\n              >\n                <div className={cn(\"grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-2 px-4 py-3 sm:gap-x-4\", memberGrid)}>\n                  <div className=\"col-start-1 row-start-1 flex min-w-0 items-center gap-3\">\n                    <Avatar className=\"size-8\">\n                      <AvatarFallback className={cn(\"bg-gradient-to-br font-medium text-white text-xs\", m.hue)}>{initials(m.name)}</AvatarFallback>\n                    </Avatar>\n                    <div className=\"min-w-0\">\n                      <p className=\"flex min-w-0 items-center gap-2 font-medium text-sm\">\n                        <span className=\"truncate\">{m.name}</span>\n                        {m.invited && (\n                          <Badge size=\"sm\" variant=\"info\">\n                            Invited\n                          </Badge>\n                        )}\n                      </p>\n                      <p className=\"truncate text-muted-foreground text-xs\">{m.email}</p>\n                    </div>\n                  </div>\n                  <div className=\"col-start-1 row-start-2 ps-11 sm:col-start-2 sm:row-start-1 sm:ps-0\">\n                    <RoleSelect member={m} onRole={setRoleFor} />\n                  </div>\n                  <span className=\"col-start-2 row-start-2 truncate text-right text-muted-foreground text-xs sm:col-start-3 sm:row-start-1 sm:text-left sm:text-sm\">\n                    {m.lastActive}\n                  </span>\n                  <div className=\"col-start-2 row-start-1 flex justify-end sm:col-start-4\">\n                    {m.role === \"owner\" ? (\n                      <span aria-hidden className=\"size-8 sm:size-7\" />\n                    ) : (\n                      <Menu>\n                        <MenuTrigger render={<Button aria-label={`Actions for ${m.name}`} size=\"icon-sm\" variant=\"ghost\" />}>\n                          <EllipsisIcon />\n                        </MenuTrigger>\n                        <MenuPopup align=\"end\">\n                          {m.invited && <MenuItem onClick={() => setNotice(`Invite resent to ${m.email}.`)}>Resend invite</MenuItem>}\n                          <MenuItem\n                            onClick={() => {\n                              navigator.clipboard?.writeText(m.email).catch(() => {});\n                              setNotice(`Copied ${m.email}.`);\n                            }}\n                          >\n                            <CopyIcon />\n                            Copy email\n                          </MenuItem>\n                          <MenuSeparator />\n                          <MenuItem onClick={() => setRemoving(m)} variant=\"destructive\">\n                            <Trash2Icon />\n                            {m.invited ? \"Revoke invite\" : \"Remove from workspace\"}\n                          </MenuItem>\n                        </MenuPopup>\n                      </Menu>\n                    )}\n                  </div>\n                </div>\n              </motion.div>\n            ))}\n          </AnimatePresence>\n        </Rows>\n      </Section>\n\n      <AlertDialog onOpenChange={(open) => !open && setRemoving(null)} open={Boolean(removing)}>\n        <AlertDialogPopup>\n          <AlertDialogHeader>\n            <AlertDialogTitle>{removing?.invited ? `Revoke the invite for ${removing.email}?` : `Remove ${removing?.name}?`}</AlertDialogTitle>\n            <AlertDialogDescription>\n              {removing?.invited\n                ? \"The link in their email stops working straight away.\"\n                : \"They lose access straight away and their seat frees up. Projects they made stay put.\"}\n            </AlertDialogDescription>\n          </AlertDialogHeader>\n          <AlertDialogFooter>\n            <AlertDialogClose render={<Button variant=\"ghost\" />}>Cancel</AlertDialogClose>\n            <AlertDialogClose\n              render={\n                <Button\n                  onClick={() => {\n                    if (!removing) return;\n                    const target = removing;\n                    setMembers((all) => all.filter((x) => x.id !== target.id));\n                    setNotice(target.invited ? `Invite for ${target.email} revoked.` : `${target.name} removed.`);\n                  }}\n                  variant=\"destructive\"\n                />\n              }\n            >\n              {removing?.invited ? \"Revoke invite\" : \"Remove\"}\n            </AlertDialogClose>\n          </AlertDialogFooter>\n        </AlertDialogPopup>\n      </AlertDialog>\n    </>\n  );\n}\n\nconst keyGrid = \"sm:grid-cols-[minmax(0,1fr)_6.5rem_6.5rem_2rem]\";\n\nfunction CopyButton({ text, label = \"Copy\" }: { text: string; label?: string }) {\n  const [copied, setCopied] = useState(false);\n  useEffect(() => {\n    if (!copied) return;\n    const t = setTimeout(() => setCopied(false), 1500);\n    return () => clearTimeout(t);\n  }, [copied]);\n  return (\n    <Button\n      className={cn(press, \"min-w-21\")}\n      onClick={() => {\n        navigator.clipboard?.writeText(text).catch(() => {});\n        setCopied(true);\n      }}\n      size=\"sm\"\n      variant=\"outline\"\n    >\n      <Swap className=\"inline-flex\" id={copied ? \"y\" : \"n\"}>\n        {copied ? <CheckIcon className=\"size-3.5 text-success-foreground\" /> : <CopyIcon className=\"size-3.5\" />}\n      </Swap>\n      {copied ? \"Copied\" : label}\n    </Button>\n  );\n}\n\nfunction KeysPanel({ initial }: { initial: SettingsApiKey[] }) {\n  const [keys, setKeys] = useState(initial);\n  const [creating, setCreating] = useState(false);\n  const [name, setName] = useState(\"\");\n  const [scope, setScope] = useState<KeyScope>(\"read\");\n  const [fresh, setFresh] = useState<SettingsApiKey | null>(null);\n  const [revealed, setRevealed] = useState<string[]>([]);\n  const [revoking, setRevoking] = useState<SettingsApiKey | null>(null);\n  const reduce = useReducedMotionAfterMount();\n  const ids = useId();\n\n  const create = () => {\n    if (!name.trim()) return;\n    const key: SettingsApiKey = {\n      id: `k-${keys.length}-${name.trim()}`,\n      name: name.trim(),\n      secret: makeSecret(),\n      scope,\n      created: \"Just now\",\n      lastUsed: \"Never\",\n    };\n    setFresh(key);\n    setKeys((k) => [key, ...k]);\n    setCreating(false);\n    setName(\"\");\n    setScope(\"read\");\n  };\n\n  return (\n    <>\n      <Section\n        action={\n          <Button className={press} disabled={creating || Boolean(fresh)} onClick={() => setCreating(true)} size=\"sm\">\n            <PlusIcon />\n            Create key\n          </Button>\n        }\n        description=\"Keys act as the workspace. Keep them out of client-side code.\"\n        title=\"Secret keys\"\n      >\n        <Rows>\n          <Collapse show={creating}>\n            <form\n              className=\"flex flex-col gap-4 bg-muted/30 p-4\"\n              onKeyDown={(e) => e.key === \"Escape\" && setCreating(false)}\n              onSubmit={(e) => {\n                e.preventDefault();\n                create();\n              }}\n            >\n              <div className=\"flex flex-col gap-2\">\n                <Label htmlFor={`${ids}-name`}>Name</Label>\n                <Input autoFocus id={`${ids}-name`} onChange={(e) => setName(e.target.value)} placeholder=\"e.g. Staging worker\" value={name} />\n              </div>\n              <div className=\"flex flex-col gap-2\">\n                <span className=\"font-medium text-sm\" id={`${ids}-scope`}>\n                  Scope\n                </span>\n                <div aria-labelledby={`${ids}-scope`} className=\"grid gap-2 sm:grid-cols-3\" role=\"radiogroup\">\n                  {scopeItems.map((s) => {\n                    const on = scope === s.value;\n                    return (\n                      <button\n                        aria-checked={on}\n                        className={cn(\n                          \"relative flex cursor-pointer flex-col items-start gap-0.5 rounded-lg border bg-background px-3 py-2.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n                          press,\n                          !on && \"hover:bg-accent/60\",\n                        )}\n                        key={s.value}\n                        onClick={() => setScope(s.value)}\n                        role=\"radio\"\n                        type=\"button\"\n                      >\n                        {on && (\n                          <motion.span\n                            className=\"absolute -inset-px rounded-lg border-2 border-foreground\"\n                            layoutId={`${ids}-ring`}\n                            transition={reduce ? { duration: 0 } : spring}\n                          />\n                        )}\n                        <span className=\"font-medium text-sm\">{s.label}</span>\n                        <span className=\"text-muted-foreground text-xs\">{s.hint}</span>\n                      </button>\n                    );\n                  })}\n                </div>\n              </div>\n              <div className=\"flex justify-end gap-2\">\n                <Button className={press} onClick={() => setCreating(false)} size=\"sm\" variant=\"ghost\">\n                  Cancel\n                </Button>\n                <Button className={press} disabled={!name.trim()} size=\"sm\" type=\"submit\">\n                  Create key\n                </Button>\n              </div>\n            </form>\n          </Collapse>\n          <Collapse show={Boolean(fresh)}>\n            {fresh && (\n              <div className=\"flex flex-col gap-3 bg-success/6 p-4\">\n                <p className=\"flex items-start gap-2 text-sm\">\n                  <CheckIcon className=\"mt-0.5 size-4 shrink-0 text-success-foreground\" />\n                  <span className=\"text-pretty\">\n                    <span className=\"font-medium\">{fresh.name}</span> is ready. Copy it now: you won't see it again.\n                  </span>\n                </p>\n                <div className=\"flex items-center gap-2 rounded-lg border bg-background p-1 ps-3\">\n                  <code className=\"min-w-0 flex-1 truncate font-mono text-xs\">{fresh.secret}</code>\n                  <CopyButton text={fresh.secret} />\n                </div>\n                <Button className={cn(press, \"self-end\")} onClick={() => setFresh(null)} size=\"sm\">\n                  I've saved it\n                </Button>\n              </div>\n            )}\n          </Collapse>\n          <TableHeadRow className={keyGrid}>\n            <span>Name</span>\n            <span>Scope</span>\n            <span>Last used</span>\n            <span className=\"sr-only\">Actions</span>\n          </TableHeadRow>\n          <AnimatePresence initial={false}>\n            {keys.map((k) => {\n              const show = revealed.includes(k.id) && k.id !== fresh?.id;\n              return (\n                <motion.div\n                  animate={{ opacity: 1, height: \"auto\" }}\n                  className=\"overflow-hidden\"\n                  exit={{ opacity: 0, height: 0 }}\n                  initial={reduce ? false : { opacity: 0, height: 0 }}\n                  key={k.id}\n                  transition={reduce ? { duration: 0 } : spring}\n                >\n                  <div className={cn(\"grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-1.5 px-4 py-3 sm:gap-x-4\", keyGrid)}>\n                    <div className=\"col-start-1 row-start-1 min-w-0\">\n                      <p className=\"truncate font-medium text-sm\">{k.name}</p>\n                      <code className=\"block truncate font-mono text-muted-foreground text-xs\">{show ? k.secret : mask(k.secret)}</code>\n                    </div>\n                    <div className=\"col-start-1 row-start-2 flex items-center gap-2 sm:col-start-2 sm:row-start-1\">\n                      <Badge size=\"sm\" variant={k.scope === \"admin\" ? \"warning\" : k.scope === \"write\" ? \"info\" : \"secondary\"}>\n                        {scopeItems.find((s) => s.value === k.scope)?.label}\n                      </Badge>\n                      <span className=\"text-muted-foreground text-xs sm:hidden\">\n                        {/^never$/i.test(k.lastUsed) ? \"Never used\" : `Used ${k.lastUsed}`}\n                      </span>\n                    </div>\n                    <span className=\"hidden truncate text-muted-foreground text-sm sm:col-start-3 sm:row-start-1 sm:block\">{k.lastUsed}</span>\n                    <div className=\"col-start-2 row-start-1 flex justify-end sm:col-start-4\">\n                      <Menu>\n                        <MenuTrigger render={<Button aria-label={`Actions for ${k.name}`} size=\"icon-sm\" variant=\"ghost\" />}>\n                          <EllipsisIcon />\n                        </MenuTrigger>\n                        <MenuPopup align=\"end\">\n                          <MenuItem\n                            disabled={k.id === fresh?.id}\n                            onClick={() => setRevealed((r) => (r.includes(k.id) ? r.filter((x) => x !== k.id) : [...r, k.id]))}\n                          >\n                            {show ? <EyeOffIcon /> : <EyeIcon />}\n                            {show ? \"Hide key\" : \"Reveal key\"}\n                          </MenuItem>\n                          <MenuItem onClick={() => navigator.clipboard?.writeText(k.secret).catch(() => {})}>\n                            <CopyIcon />\n                            Copy key\n                          </MenuItem>\n                          <MenuSeparator />\n                          <MenuItem onClick={() => setRevoking(k)} variant=\"destructive\">\n                            <Trash2Icon />\n                            Revoke\n                          </MenuItem>\n                        </MenuPopup>\n                      </Menu>\n                    </div>\n                  </div>\n                </motion.div>\n              );\n            })}\n          </AnimatePresence>\n          {keys.length === 0 && (\n            <div className=\"flex flex-col items-center gap-1 px-4 py-10 text-center\">\n              <KeyRoundIcon className=\"size-4 text-muted-foreground\" />\n              <p className=\"font-medium text-sm\">No keys yet</p>\n              <p className=\"text-muted-foreground text-xs\">Create one for your server or CI.</p>\n            </div>\n          )}\n        </Rows>\n      </Section>\n\n      <AlertDialog onOpenChange={(open) => !open && setRevoking(null)} open={Boolean(revoking)}>\n        <AlertDialogPopup>\n          <AlertDialogHeader>\n            <AlertDialogTitle>Revoke {revoking?.name}?</AlertDialogTitle>\n            <AlertDialogDescription>Anything still using this key starts getting 401s immediately. This can't be undone.</AlertDialogDescription>\n          </AlertDialogHeader>\n          <AlertDialogFooter>\n            <AlertDialogClose render={<Button variant=\"ghost\" />}>Keep key</AlertDialogClose>\n            <AlertDialogClose\n              render={\n                <Button\n                  onClick={() => {\n                    if (!revoking) return;\n                    const target = revoking;\n                    setKeys((all) => all.filter((x) => x.id !== target.id));\n                    if (fresh?.id === target.id) setFresh(null);\n                  }}\n                  variant=\"destructive\"\n                />\n              }\n            >\n              Revoke key\n            </AlertDialogClose>\n          </AlertDialogFooter>\n        </AlertDialogPopup>\n      </AlertDialog>\n    </>\n  );\n}\n\nfunction UsageRow({ item, shown }: { item: SettingsUsage; shown: boolean }) {\n  const reduce = useReducedMotionAfterMount();\n  const pct = Math.min(100, (item.used / item.limit) * 100);\n  const projPct = item.projected ? Math.min(100, (item.projected / item.limit) * 100) : 0;\n  const over = (item.projected ?? 0) > item.limit;\n  const fmt = item.unit ? (n: number) => n.toFixed(1) : formatInt;\n  const fill = { duration: reduce ? 0 : 0.6, ease: easeOut };\n  return (\n    <div className=\"flex flex-col gap-2.5 px-4 py-3.5\">\n      <div className=\"flex items-baseline justify-between gap-3\">\n        <span className=\"font-medium text-sm\">{item.label}</span>\n        <span className=\"text-sm tabular-nums\">\n          <RollingNumber format={fmt} value={shown ? item.used : 0} />\n          <span className=\"text-muted-foreground\">\n            {\" \"}\n            / {item.limit.toLocaleString(\"en-US\")}\n            {item.unit ? ` ${item.unit}` : \"\"}\n          </span>\n        </span>\n      </div>\n      <div\n        aria-label={item.label}\n        aria-valuemax={item.limit}\n        aria-valuemin={0}\n        aria-valuenow={item.used}\n        className=\"relative h-1.5 overflow-hidden rounded-full bg-muted\"\n        role=\"meter\"\n      >\n        {projPct > pct && (\n          <motion.div\n            animate={{ scaleX: shown ? 1 : 0 }}\n            className={cn(\"absolute inset-y-0 left-0 origin-left rounded-full\", over ? \"bg-warning/32\" : \"bg-foreground/12\")}\n            initial={false}\n            style={{ width: `${projPct}%` }}\n            transition={{ ...fill, delay: reduce ? 0 : 0.15 }}\n          />\n        )}\n        <motion.div\n          animate={{ scaleX: shown ? 1 : 0 }}\n          className={cn(\"absolute inset-y-0 left-0 origin-left rounded-full\", pct >= 85 ? \"bg-warning\" : \"bg-primary\")}\n          initial={false}\n          style={{ width: `${pct}%` }}\n          transition={fill}\n        />\n      </div>\n    </div>\n  );\n}\n\nfunction BillingPanel({\n  active,\n  plans,\n  current,\n  renewsOn,\n  seats,\n  usage,\n  invoices: initialInvoices,\n  card,\n  daysLeft,\n  overagePer1k,\n}: {\n  active: boolean;\n  plans: SettingsPlan[];\n  current: string;\n  renewsOn: string;\n  seats: number;\n  usage: SettingsUsage[];\n  invoices: SettingsInvoice[];\n  card: SettingsCard;\n  daysLeft: number;\n  overagePer1k: number;\n}) {\n  const [planId, setPlanId] = useState(current);\n  const [picking, setPicking] = useState(false);\n  const [choice, setChoice] = useState(current);\n  const [switching, setSwitching] = useState(false);\n  const [invoices, setInvoices] = useState(initialInvoices);\n  const [retrying, setRetrying] = useState(false);\n  const [recovered, setRecovered] = useState<SettingsInvoice | null>(null);\n  const [hasOpened, setHasOpened] = useState(active);\n  const reduce = useReducedMotionAfterMount();\n  const pickerId = useId();\n  const plan = plans.find((p) => p.id === planId) ?? plans[0];\n  const failed = invoices.find((i) => i.status === \"failed\");\n  const runs = usage.find((u) => u.projected !== undefined);\n  const overRuns = runs?.projected ? Math.max(0, runs.projected - runs.limit) : 0;\n\n  useEffect(() => {\n    if (active) setHasOpened(true);\n  }, [active]);\n\n  useEffect(() => {\n    if (!switching) return;\n    const t = setTimeout(() => {\n      setPlanId(choice);\n      setSwitching(false);\n      setPicking(false);\n    }, 650);\n    return () => clearTimeout(t);\n  }, [switching, choice]);\n\n  useEffect(() => {\n    if (!retrying || !failed) return;\n    const t = setTimeout(() => {\n      setInvoices((all) => all.map((i) => (i.id === failed.id ? { ...i, status: \"paid\" } : i)));\n      setRecovered(failed);\n      setRetrying(false);\n    }, 900);\n    return () => clearTimeout(t);\n  }, [retrying, failed]);\n\n  useEffect(() => {\n    if (!recovered) return;\n    const t = setTimeout(() => setRecovered(null), 2800);\n    return () => clearTimeout(t);\n  }, [recovered]);\n\n  const banner = failed ? { key: \"failed\" as const, invoice: failed } : recovered ? { key: \"recovered\" as const, invoice: recovered } : null;\n\n  return (\n    <>\n      <Collapse show={Boolean(banner)}>\n        {banner && (\n          <div className=\"pt-8\">\n            <Alert variant={banner.key === \"failed\" ? \"error\" : \"success\"}>\n              {banner.key === \"failed\" ? <AlertTriangleIcon /> : <CheckIcon />}\n              <AlertTitle>\n                {banner.key === \"failed\" ? `The ${banner.invoice.date.replace(/, \\d{4}$/, \"\")} payment didn't go through` : \"Payment received\"}\n              </AlertTitle>\n              <AlertDescription>\n                <p className=\"text-pretty\">\n                  {banner.key === \"failed\" ? (\n                    <>\n                      <span className=\"tabular-nums\">{formatCents(banner.invoice.amount)}</span> on the card ending{\" \"}\n                      <span className=\"tabular-nums\">{card.last4}</span> was declined.\n                    </>\n                  ) : (\n                    <>\n                      <span className=\"font-mono\">{banner.invoice.id}</span> is paid. A receipt is on its way to {card.email ?? \"your billing email\"}.\n                    </>\n                  )}\n                </p>\n              </AlertDescription>\n              {banner.key === \"failed\" && (\n                <AlertAction>\n                  <Button className={press} loading={retrying} onClick={() => setRetrying(true)} size=\"sm\" variant=\"outline\">\n                    Retry payment\n                  </Button>\n                </AlertAction>\n              )}\n            </Alert>\n          </div>\n        )}\n      </Collapse>\n\n      <Section title=\"Plan\">\n        <Rows>\n          <div className=\"flex flex-wrap items-center gap-x-4 gap-y-3 px-4 py-4\">\n            <div className=\"min-w-0 flex-1 basis-44\">\n              <p className=\"flex items-center gap-2\">\n                <span className=\"font-semibold text-base tracking-tight\">{plan.name}</span>\n                <Badge size=\"sm\" variant=\"secondary\">\n                  Current\n                </Badge>\n              </p>\n              <p className=\"mt-0.5 text-muted-foreground text-xs\">\n                <RollingNumber format={formatMoney} value={plan.price} /> per seat / month · {plan.blurb}\n              </p>\n            </div>\n            {!picking && (\n              <Button\n                className={press}\n                onClick={() => {\n                  setChoice(plans[Math.min(plans.length - 1, plans.findIndex((p) => p.id === planId) + 1)].id);\n                  setPicking(true);\n                }}\n                size=\"sm\"\n                variant=\"outline\"\n              >\n                Change plan\n              </Button>\n            )}\n          </div>\n          <Collapse show={picking}>\n            <div className=\"flex flex-col gap-3 bg-muted/30 p-4\">\n              <div aria-label=\"Choose a plan\" className=\"grid gap-2 sm:grid-cols-3\" role=\"radiogroup\">\n                {plans.map((p) => {\n                  const on = choice === p.id;\n                  return (\n                    <button\n                      aria-checked={on}\n                      className={cn(\n                        \"relative flex cursor-pointer flex-col items-start gap-1 rounded-lg border bg-background p-3 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n                        press,\n                        !on && \"hover:bg-accent/60\",\n                      )}\n                      key={p.id}\n                      onClick={() => setChoice(p.id)}\n                      role=\"radio\"\n                      type=\"button\"\n                    >\n                      {on && (\n                        <motion.span\n                          className=\"absolute -inset-px rounded-lg border-2 border-foreground\"\n                          layoutId={`${pickerId}-ring`}\n                          transition={reduce ? { duration: 0 } : spring}\n                        />\n                      )}\n                      <span className=\"flex w-full items-center justify-between gap-2 font-medium text-sm\">\n                        {p.name}\n                        {p.id === planId && <span className=\"font-normal text-muted-foreground text-xs\">Current</span>}\n                      </span>\n                      <span className=\"font-medium text-sm tabular-nums\">\n                        ${p.price}\n                        <span className=\"font-normal text-muted-foreground text-xs\"> / seat</span>\n                      </span>\n                      <span className=\"text-pretty text-muted-foreground text-xs\">{p.blurb}</span>\n                    </button>\n                  );\n                })}\n              </div>\n              <div className=\"flex justify-end gap-2\">\n                <Button className={press} disabled={switching} onClick={() => setPicking(false)} size=\"sm\" variant=\"ghost\">\n                  Cancel\n                </Button>\n                <Button className={cn(press, \"min-w-32\")} disabled={choice === planId} loading={switching} onClick={() => setSwitching(true)} size=\"sm\">\n                  Switch to {plans.find((p) => p.id === choice)?.name}\n                </Button>\n              </div>\n            </div>\n          </Collapse>\n          <Row\n            help={\n              <>\n                {seats} seats × <RollingNumber format={formatMoney} value={plan.price} />, charged {renewsOn}\n              </>\n            }\n            label=\"Next invoice\"\n          >\n            <span className=\"font-medium text-sm\">\n              <RollingNumber format={formatCents} value={plan.price * seats} />\n            </span>\n          </Row>\n        </Rows>\n      </Section>\n\n      <Section\n        description={\n          <>\n            Resets {renewsOn}, <span className=\"tabular-nums\">{daysLeft}</span> days from now.\n          </>\n        }\n        title=\"Usage this cycle\"\n      >\n        <Rows>\n          {usage.map((u) => (\n            <UsageRow item={u} key={u.label} shown={hasOpened || reduce} />\n          ))}\n          {runs?.projected !== undefined && (\n            <div className=\"grid grid-cols-2 divide-x bg-muted/30\">\n              <div className=\"px-4 py-3\">\n                <p className=\"text-muted-foreground text-xs\">Projected by {renewsOn}</p>\n                <p className=\"mt-0.5 font-medium text-sm tabular-nums\">\n                  {formatInt(runs.projected)} <span className=\"font-normal text-muted-foreground text-xs\">runs</span>\n                </p>\n              </div>\n              <div className=\"px-4 py-3\">\n                <p className=\"text-muted-foreground text-xs\">Estimated overage</p>\n                <p className={cn(\"mt-0.5 font-medium text-sm tabular-nums\", overRuns > 0 && \"text-warning-foreground\")}>\n                  {formatCents((overRuns / 1000) * overagePer1k)}\n                  <span className=\"font-normal text-muted-foreground text-xs\"> at ${overagePer1k} / 1k</span>\n                </p>\n              </div>\n            </div>\n          )}\n        </Rows>\n      </Section>\n\n      <Section title=\"Payment method\">\n        <Rows>\n          <div className=\"flex items-center gap-3 px-4 py-3.5\">\n            <span className=\"flex h-8 w-11 shrink-0 items-center justify-center rounded-md border bg-muted/50\">\n              <CreditCardIcon className=\"size-4 text-muted-foreground\" />\n            </span>\n            <div className=\"min-w-0 flex-1\">\n              <p className=\"truncate font-medium text-sm\">\n                {card.brand ?? \"Card\"} ending <span className=\"tabular-nums\">{card.last4}</span>\n              </p>\n              <p className=\"truncate text-muted-foreground text-xs\">\n                Expires <span className=\"tabular-nums\">{card.expires}</span> · {card.holder}\n              </p>\n            </div>\n            <Button className={press} size=\"sm\" variant=\"outline\">\n              Replace\n            </Button>\n          </div>\n          {card.email && (\n            <Row help={card.email} label=\"Billing email\">\n              <Button className={press} size=\"sm\" variant=\"outline\">\n                Edit\n              </Button>\n            </Row>\n          )}\n        </Rows>\n      </Section>\n\n      <Section description={card.email ? `Sent to ${card.email} when they're issued.` : undefined} title=\"Invoices\">\n        <Rows>\n          <TableHeadRow className=\"sm:grid-cols-[minmax(0,1fr)_7rem_4.5rem_5rem_2rem]\">\n            <span>Invoice</span>\n            <span>Date</span>\n            <span>Status</span>\n            <span className=\"text-right\">Amount</span>\n            <span className=\"sr-only\">Download</span>\n          </TableHeadRow>\n          {invoices.length === 0 && (\n            <p className=\"px-4 py-10 text-center text-muted-foreground text-xs\">No invoices yet. The first one arrives on {renewsOn}.</p>\n          )}\n          {invoices.map((inv) => (\n            <div\n              className=\"grid grid-cols-[minmax(0,1fr)_auto_auto_2rem] items-center gap-3 px-4 py-2.5 sm:grid-cols-[minmax(0,1fr)_7rem_4.5rem_5rem_2rem] sm:gap-4\"\n              key={inv.id}\n            >\n              <div className=\"min-w-0\">\n                <p className=\"truncate font-mono text-xs\">{inv.id}</p>\n                <p className=\"truncate text-muted-foreground text-xs sm:hidden\">{inv.date}</p>\n              </div>\n              <span className=\"hidden text-muted-foreground text-sm sm:block\">{inv.date}</span>\n              <span>\n                <Swap id={inv.status}>\n                  <Badge variant={invoiceBadge[inv.status].variant}>{invoiceBadge[inv.status].label}</Badge>\n                </Swap>\n              </span>\n              <span className=\"text-right text-sm tabular-nums\">{formatCents(inv.amount)}</span>\n              <Button aria-label={`Download ${inv.id}`} size=\"icon-sm\" variant=\"ghost\">\n                <DownloadIcon />\n              </Button>\n            </div>\n          ))}\n        </Rows>\n      </Section>\n    </>\n  );\n}\n\nexport function SettingsAndPlans({\n  className,\n  defaultTab = \"workspace\",\n  workspace = { name: \"Ridgeline\", slug: \"ridgeline\", region: \"eu-central\" },\n  members = defaultMembers,\n  apiKeys = defaultKeys,\n  plans = defaultPlans,\n  currentPlan = \"team\",\n  renewsOn = \"Nov 14\",\n  usage = defaultUsage,\n  invoices = defaultInvoices,\n  cycleDaysLeft = 18,\n  overagePer1k = 4,\n  card = { brand: \"Visa\", last4: \"4417\", expires: \"09/28\", holder: \"Ada Lindqvist\", email: \"billing@ridgeline.app\" },\n  domain = \"ridgeline.app\",\n  onNavigate,\n}: SettingsAndPlansProps) {\n  const [tab, setTab] = useState<SettingsTab>(defaultTab);\n  const [saved, setSaved] = useState(workspace);\n  const [draft, setDraft] = useState(workspace);\n  const [saving, setSaving] = useState(false);\n  const [justSaved, setJustSaved] = useState(false);\n  const scrollRef = useRef<HTMLDivElement>(null);\n  const reduce = useReducedMotionAfterMount();\n  const seatLimit = usage.find((u) => u.label === \"Seats\")?.limit ?? 10;\n  const copy = tabCopy[tab];\n  const errors = workspaceErrors(draft);\n  const blocker = errors.name ?? errors.slug;\n  const dirty = draft.name !== saved.name || draft.slug !== saved.slug || draft.region !== saved.region;\n  const barVisible = tab === \"workspace\" && (dirty || justSaved);\n\n  useEffect(() => {\n    if (!saving) return;\n    const t = setTimeout(() => {\n      setSaving(false);\n      setSaved(draft);\n      setJustSaved(true);\n    }, 600);\n    return () => clearTimeout(t);\n  }, [saving, draft]);\n\n  useEffect(() => {\n    if (!justSaved) return;\n    const t = setTimeout(() => setJustSaved(false), 1600);\n    return () => clearTimeout(t);\n  }, [justSaved]);\n\n  const select = (id: SettingsSectionId) => {\n    onNavigate?.(id);\n    const next = tabForNav[id];\n    if (!next || next === tab) return;\n    setTab(next);\n    scrollRef.current?.parentElement?.scrollTo({ top: 0 });\n  };\n\n  return (\n    <RidgelineShell active={navForTab[tab]} className={className} onNavigate={select}>\n      <div className=\"relative flex min-h-full flex-col\" ref={scrollRef}>\n        <div className=\"mx-auto w-full max-w-2xl flex-1 px-6 pt-10 pb-24 md:px-10\">\n          <Swap id={tab}>\n            <h1 className=\"text-balance font-semibold text-2xl tracking-tight\">{copy.title}</h1>\n            <p className=\"mt-1 text-pretty text-muted-foreground text-sm\">{copy.description}</p>\n          </Swap>\n          {tabOrder.map((t) => (\n            <motion.div\n              animate={tab === t ? { opacity: 1, y: 0 } : { opacity: 0, y: reduce ? 0 : 6 }}\n              className={cn(tab !== t && \"hidden\")}\n              initial={false}\n              key={t}\n              role=\"region\"\n              aria-label={tabCopy[t].title}\n              transition={{ duration: 0.2, ease: easeOut }}\n            >\n              {t === \"workspace\" && <WorkspacePanel domain={domain} draft={draft} savedSlug={saved.slug} setDraft={setDraft} />}\n              {t === \"members\" && <MembersPanel initial={members} seatLimit={seatLimit} />}\n              {t === \"keys\" && <KeysPanel initial={apiKeys} />}\n              {t === \"billing\" && (\n                <BillingPanel\n                  active={tab === \"billing\"}\n                  card={card}\n                  current={currentPlan}\n                  daysLeft={cycleDaysLeft}\n                  invoices={invoices}\n                  overagePer1k={overagePer1k}\n                  plans={plans}\n                  renewsOn={renewsOn}\n                  seats={members.length}\n                  usage={usage}\n                />\n              )}\n            </motion.div>\n          ))}\n        </div>\n        <AnimatePresence>\n          {barVisible && (\n            <motion.div\n              animate={{ opacity: 1, y: 0 }}\n              className=\"pointer-events-none sticky bottom-4 z-20 -mt-16 flex justify-center px-4 md:px-6\"\n              exit={{ opacity: 0, y: reduce ? 0 : 16 }}\n              initial={{ opacity: 0, y: reduce ? 0 : 24 }}\n              transition={reduce ? { duration: 0.15 } : { type: \"spring\", stiffness: 480, damping: 34 }}\n            >\n              <div className=\"pointer-events-auto flex min-h-12 w-full max-w-xl items-center gap-2 rounded-xl border bg-popover py-2 ps-4 pe-2 shadow-lg/5\">\n                <AnimatePresence initial={false} mode=\"popLayout\">\n                  {justSaved && !dirty ? (\n                    <motion.span\n                      animate={{ opacity: 1, y: 0 }}\n                      aria-live=\"polite\"\n                      className=\"flex min-h-8 flex-1 items-center gap-2 font-medium text-sm\"\n                      exit={{ opacity: 0, y: reduce ? 0 : -6 }}\n                      initial={{ opacity: 0, y: reduce ? 0 : 6 }}\n                      key=\"saved\"\n                      transition={{ duration: 0.18, ease: easeOut }}\n                    >\n                      <CheckIcon className=\"size-4 text-success-foreground\" />\n                      Workspace saved\n                    </motion.span>\n                  ) : (\n                    <motion.div\n                      animate={{ opacity: 1, y: 0 }}\n                      className=\"flex min-w-0 flex-1 items-center gap-2\"\n                      exit={{ opacity: 0, y: reduce ? 0 : -6 }}\n                      initial={{ opacity: 0, y: reduce ? 0 : 6 }}\n                      key=\"dirty\"\n                      transition={{ duration: 0.18, ease: easeOut }}\n                    >\n                      <span aria-live=\"polite\" className=\"flex min-w-0 flex-1 flex-col\">\n                        <span className=\"truncate font-medium text-sm\">\n                          <span className=\"sm:hidden\">Unsaved changes</span>\n                          <span className=\"hidden sm:inline\">You have unsaved changes</span>\n                        </span>\n                        {blocker && !saving && <span className=\"truncate text-warning-foreground text-xs\">{blocker}</span>}\n                      </span>\n                      <Button className={press} disabled={saving} onClick={() => setDraft(saved)} size=\"sm\" variant=\"ghost\">\n                        Discard\n                      </Button>\n                      <Button className={cn(press, \"min-w-14\")} disabled={Boolean(blocker)} loading={saving} onClick={() => setSaving(true)} size=\"sm\">\n                        Save\n                      </Button>\n                    </motion.div>\n                  )}\n                </AnimatePresence>\n              </div>\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n    </RidgelineShell>\n  );\n}\n"
    }
  ]
}