{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "team-roles",
  "type": "registry:block",
  "title": "Members & Roles",
  "description": "Invite people, manage members and pending invites, and tune a role-by-permission matrix with a locked owner column, live head counts and a duplicate-to-customise role.",
  "categories": [
    "screen",
    "Settings"
  ],
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "utils",
    "https://coss.com/ui/r/alert-dialog.json",
    "https://coss.com/ui/r/avatar.json",
    "https://coss.com/ui/r/button.json",
    "https://coss.com/ui/r/input.json",
    "https://coss.com/ui/r/menu.json",
    "https://coss.com/ui/r/select.json"
  ],
  "files": [
    {
      "path": "registry/devl/team-roles.tsx",
      "type": "registry:component",
      "content": "\"use client\";\n\nimport {\n  ArrowLeftIcon,\n  BellIcon,\n  CheckIcon,\n  CopyIcon,\n  CreditCardIcon,\n  EllipsisIcon,\n  KeyRoundIcon,\n  LockIcon,\n  MailIcon,\n  PaletteIcon,\n  PlusIcon,\n  RotateCcwIcon,\n  SettingsIcon,\n  ShieldIcon,\n  UserIcon,\n  UserMinusIcon,\n  UsersIcon,\n  XIcon,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { type CSSProperties, type FormEvent, Fragment, type ReactNode, useEffect, useId, useRef, useState } from \"react\";\nimport { cn } from \"@/lib/utils\";\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 { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Menu, MenuItem, MenuPopup, MenuSeparator, MenuTrigger } from \"@/components/ui/menu\";\nimport { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from \"@/components/ui/select\";\n\nexport type SettingsSectionId =\n  | \"profile\"\n  | \"appearance\"\n  | \"notifications\"\n  | \"security\"\n  | \"general\"\n  | \"members\"\n  | \"billing\"\n  | \"developer\";\n\nexport type TeamHue = \"amber\" | \"rose\" | \"violet\" | \"teal\" | \"sky\" | \"emerald\" | \"indigo\" | \"orange\";\n\nexport interface TeamPermission {\n  id: string;\n  label: string;\n}\n\nexport interface TeamPermissionArea {\n  id: string;\n  name: string;\n  permissions: TeamPermission[];\n}\n\nexport interface TeamRole {\n  id: string;\n  name: string;\n  description: string;\n  locked?: boolean;\n  from?: string;\n  grants: string[];\n}\n\nexport interface TeamMember {\n  id: string;\n  name: string;\n  email: string;\n  roleId: string;\n  hue: TeamHue;\n  lastActive: string;\n}\n\nexport interface TeamInvite {\n  id: string;\n  email: string;\n  roleId: string;\n  invitedBy: string;\n  sent: string;\n}\n\nexport interface TeamRolesProps {\n  className?: string;\n  areas?: TeamPermissionArea[];\n  roles?: TeamRole[];\n  members?: TeamMember[];\n  invites?: TeamInvite[];\n  currentUserId?: string;\n  onNavigate?: (section: SettingsSectionId) => void;\n}\n\nconst easeOut = [0.23, 1, 0.32, 1] as const;\nconst spring = { type: \"spring\", stiffness: 500, damping: 40 } as const;\nconst press = \"transition-[color,background-color,box-shadow,scale] duration-150 ease-out active:scale-[0.97]\";\n\nconst avatarHues: Record<TeamHue, string> = {\n  amber: \"from-amber-300 to-orange-500\",\n  rose: \"from-rose-300 to-pink-500\",\n  violet: \"from-violet-400 to-indigo-500\",\n  teal: \"from-teal-300 to-emerald-500\",\n  sky: \"from-sky-300 to-blue-500\",\n  emerald: \"from-emerald-300 to-teal-600\",\n  indigo: \"from-indigo-400 to-violet-700\",\n  orange: \"from-orange-300 to-red-500\",\n};\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 defaultAreas: TeamPermissionArea[] = [\n  {\n    id: \"projects\",\n    name: \"Projects\",\n    permissions: [\n      { id: \"projects.view\", label: \"View projects\" },\n      { id: \"projects.edit\", label: \"Create and edit projects\" },\n      { id: \"projects.delete\", label: \"Delete projects\" },\n      { id: \"projects.access\", label: \"Manage project access\" },\n    ],\n  },\n  {\n    id: \"billing\",\n    name: \"Billing\",\n    permissions: [\n      { id: \"billing.view\", label: \"View invoices and usage\" },\n      { id: \"billing.manage\", label: \"Change plan and payment\" },\n    ],\n  },\n  {\n    id: \"members\",\n    name: \"Members\",\n    permissions: [\n      { id: \"members.invite\", label: \"Invite people\" },\n      { id: \"members.roles\", label: \"Change roles\" },\n      { id: \"members.remove\", label: \"Remove people\" },\n    ],\n  },\n  {\n    id: \"settings\",\n    name: \"Settings\",\n    permissions: [\n      { id: \"settings.edit\", label: \"Edit workspace settings\" },\n      { id: \"settings.keys\", label: \"Manage API keys\" },\n      { id: \"settings.audit\", label: \"Export the audit log\" },\n    ],\n  },\n];\n\nconst allPermissionIds = defaultAreas.flatMap((a) => a.permissions.map((p) => p.id));\n\nconst defaultRoles: TeamRole[] = [\n  { id: \"viewer\", name: \"Viewer\", description: \"Can look around, can’t change anything\", grants: [\"projects.view\", \"billing.view\"] },\n  {\n    id: \"member\",\n    name: \"Member\",\n    description: \"Creates and ships projects\",\n    grants: [\"projects.view\", \"projects.edit\", \"members.invite\", \"settings.keys\"],\n  },\n  {\n    id: \"admin\",\n    name: \"Admin\",\n    description: \"Everything except the plan and payment\",\n    grants: allPermissionIds.filter((id) => id !== \"billing.manage\"),\n  },\n  { id: \"owner\", name: \"Owner\", description: \"Full control of the workspace\", locked: true, grants: allPermissionIds },\n];\n\nconst defaultMembers: TeamMember[] = [\n  { id: \"m1\", name: \"Ada Lindqvist\", email: \"ada@ridgeline.app\", roleId: \"owner\", hue: \"violet\", lastActive: \"Now\" },\n  { id: \"m2\", name: \"Theo Marsh\", email: \"theo@ridgeline.app\", roleId: \"admin\", hue: \"sky\", lastActive: \"12 min ago\" },\n  { id: \"m3\", name: \"Priya Raman\", email: \"priya@ridgeline.app\", roleId: \"admin\", hue: \"teal\", lastActive: \"2 hours ago\" },\n  { id: \"m4\", name: \"Jonah Feld\", email: \"jonah@ridgeline.app\", roleId: \"member\", hue: \"amber\", lastActive: \"Yesterday\" },\n  { id: \"m5\", name: \"Inès Duarte\", email: \"ines@ridgeline.app\", roleId: \"member\", hue: \"rose\", lastActive: \"3 hours ago\" },\n  { id: \"m6\", name: \"Kofi Mensah\", email: \"kofi@ridgeline.app\", roleId: \"member\", hue: \"emerald\", lastActive: \"4 days ago\" },\n  { id: \"m7\", name: \"Sara Whitlock\", email: \"sara@ridgeline.app\", roleId: \"viewer\", hue: \"orange\", lastActive: \"Last week\" },\n  { id: \"m8\", name: \"Ren Takahashi\", email: \"ren@pinefold.co\", roleId: \"viewer\", hue: \"indigo\", lastActive: \"2 weeks ago\" },\n];\n\nconst defaultInvites: TeamInvite[] = [\n  { id: \"i1\", email: \"lucas@ridgeline.app\", roleId: \"member\", invitedBy: \"Theo\", sent: \"2 days ago\" },\n  { id: \"i2\", email: \"nadia@ordinal.studio\", roleId: \"viewer\", invitedBy: \"Ada\", sent: \"6 days ago\" },\n];\n\nfunction useReducedMotionAfterMount() {\n  const prefers = useReducedMotion();\n  const [mounted, setMounted] = useState(false);\n  useEffect(() => setMounted(true), []);\n  return mounted && Boolean(prefers);\n}\n\nfunction initials(name: string) {\n  return name\n    .split(/\\s+/)\n    .map((p) => p[0])\n    .join(\"\")\n    .slice(0, 2)\n    .toUpperCase();\n}\n\nfunction plural(n: number, one: string, many = `${one}s`) {\n  return `${n} ${n === 1 ? one : many}`;\n}\n\nfunction sameGrants(a: string[], b: string[]) {\n  return a.length === b.length && a.every((g) => b.includes(g));\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\nfunction PersonAvatar({ name, hue }: { name: string; hue: TeamHue }) {\n  return (\n    <Avatar className=\"size-8\">\n      <AvatarFallback className={cn(\"bg-gradient-to-br font-medium text-white text-xs\", avatarHues[hue])}>{initials(name)}</AvatarFallback>\n    </Avatar>\n  );\n}\n\nfunction RoleSelect({\n  roles,\n  value,\n  onChange,\n  label,\n  className,\n}: {\n  roles: TeamRole[];\n  value: string;\n  onChange: (id: string) => void;\n  label: string;\n  className?: string;\n}) {\n  const options = roles.filter((r) => !r.locked);\n  const items = options.map((r) => ({ value: r.id, label: r.name }));\n  return (\n    <Select items={items} onValueChange={(v) => v && onChange(v as string)} value={value}>\n      <SelectTrigger aria-label={label} className={cn(\"w-32 min-w-0\", className)} size=\"sm\">\n        <SelectValue />\n      </SelectTrigger>\n      <SelectPopup alignItemWithTrigger={false} className=\"w-64\">\n        {options.map((r) => (\n          <SelectItem className=\"items-start py-1.5 [&>span:first-child]:mt-0.5\" key={r.id} value={r.id}>\n            <span className=\"flex flex-col\">\n              <span className=\"font-medium\">{r.name}</span>\n              <span className=\"text-muted-foreground text-xs\">{r.description}</span>\n            </span>\n          </SelectItem>\n        ))}\n      </SelectPopup>\n    </Select>\n  );\n}\n\nfunction CheckCell({\n  checked,\n  locked,\n  changed,\n  label,\n  reduce,\n  onToggle,\n}: {\n  checked: boolean;\n  locked?: boolean;\n  changed?: boolean;\n  label: string;\n  reduce: boolean;\n  onToggle: () => void;\n}) {\n  return (\n    <button\n      aria-checked={checked}\n      aria-label={label}\n      className=\"group/cell flex size-9 items-center justify-center rounded-md outline-none disabled:cursor-not-allowed\"\n      disabled={locked}\n      onClick={onToggle}\n      role=\"checkbox\"\n      type=\"button\"\n    >\n      <span\n        className={cn(\n          \"relative flex size-[18px] items-center justify-center rounded-[calc(var(--radius)*0.5)] border transition-[background-color,border-color,scale] duration-150 ease-out group-focus-visible/cell:ring-2 group-focus-visible/cell:ring-ring group-focus-visible/cell:ring-offset-1 group-focus-visible/cell:ring-offset-card group-active/cell:scale-90\",\n          checked ? \"border-primary bg-primary text-primary-foreground\" : \"border-input bg-background group-hover/cell:border-foreground/40 dark:bg-input/32\",\n          locked && \"opacity-40\",\n        )}\n      >\n        <svg aria-hidden className=\"size-3\" fill=\"none\" viewBox=\"0 0 24 24\">\n          <motion.path\n            animate={{ pathLength: checked ? 1 : 0, opacity: checked ? 1 : 0 }}\n            d=\"M5 12.5 10 17.5 19 7\"\n            initial={false}\n            stroke=\"currentColor\"\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n            strokeWidth={3.5}\n            transition={reduce ? { duration: 0 } : { duration: 0.18, ease: easeOut }}\n          />\n        </svg>\n        {changed && <span className=\"absolute -top-1 -right-1 size-1.5 rounded-full bg-warning ring-2 ring-card\" />}\n      </span>\n    </button>\n  );\n}\n\nfunction RollingCount({ value, reduce }: { value: number; reduce: boolean }) {\n  return (\n    <span className=\"relative inline-flex overflow-hidden tabular-nums\">\n      <AnimatePresence initial={false} mode=\"popLayout\">\n        <motion.span\n          animate={{ y: 0, opacity: 1 }}\n          exit={reduce ? { opacity: 0 } : { y: -8, opacity: 0 }}\n          initial={reduce ? { opacity: 0 } : { y: 8, opacity: 0 }}\n          key={value}\n          transition={{ duration: 0.18, ease: easeOut }}\n        >\n          {value}\n        </motion.span>\n      </AnimatePresence>\n    </span>\n  );\n}\n\nfunction PermissionMatrix({\n  areas,\n  roles,\n  draft,\n  saved,\n  counts,\n  reduce,\n  onToggle,\n  onRename,\n  onRemove,\n}: {\n  areas: TeamPermissionArea[];\n  roles: TeamRole[];\n  draft: Record<string, string[]>;\n  saved: Record<string, string[]>;\n  counts: Record<string, number>;\n  reduce: boolean;\n  onToggle: (roleId: string, permissionId: string) => void;\n  onRename: (roleId: string, name: string) => void;\n  onRemove: (roleId: string) => void;\n}) {\n  const [hover, setHover] = useState<string | null>(null);\n  const gridStyle = { \"--cols\": roles.length } as CSSProperties;\n  const grid = \"grid grid-cols-[minmax(7.5rem,1fr)_repeat(var(--cols),3.5rem)] sm:grid-cols-[minmax(11rem,1fr)_repeat(var(--cols),4.75rem)]\";\n  const colBg = (id: string) => (hover === id ? \"bg-accent/50\" : \"\");\n\n  return (\n    <div className=\"mt-3 overflow-hidden rounded-xl border bg-card\">\n      <div className=\"overflow-x-auto [scrollbar-width:thin]\" onMouseLeave={() => setHover(null)}>\n        <div className=\"min-w-fit\" role=\"table\">\n          <div className={cn(grid, \"border-b\")} role=\"row\" style={gridStyle}>\n            <div className=\"sticky left-0 z-10 flex items-end bg-card px-4 pb-2.5 font-medium text-muted-foreground text-xs\" role=\"columnheader\">\n              Permission\n            </div>\n            {roles.map((r) => {\n              const changed = !sameGrants(draft[r.id] ?? [], saved[r.id] ?? []);\n              const count = counts[r.id] ?? 0;\n              return (\n                <motion.div\n                  animate={{ opacity: 1 }}\n                  className={cn(\"flex flex-col items-center justify-end gap-0.5 px-1 pt-3 pb-2.5 text-center transition-colors duration-150\", colBg(r.id))}\n                  initial={false}\n                  key={r.id}\n                  onMouseEnter={() => setHover(r.id)}\n                  role=\"columnheader\"\n                >\n                  {r.from ? (\n                    <input\n                      aria-label=\"Custom role name\"\n                      className=\"w-full min-w-0 rounded-sm bg-transparent text-center font-medium text-xs underline decoration-dotted decoration-muted-foreground/60 underline-offset-4 outline-none focus-visible:no-underline focus-visible:ring-2 focus-visible:ring-ring\"\n                      onBlur={(e) => !e.target.value.trim() && onRename(r.id, \"Custom\")}\n                      onChange={(e) => onRename(r.id, e.target.value)}\n                      value={r.name}\n                    />\n                  ) : (\n                    <span className=\"flex items-center gap-1 font-medium text-xs\">\n                      {r.locked && <LockIcon aria-label=\"Locked\" className=\"size-3 text-muted-foreground\" />}\n                      {r.name}\n                    </span>\n                  )}\n                  <span className=\"flex items-center gap-1 text-[11px] text-muted-foreground\">\n                    {changed && <span aria-label=\"Unsaved changes\" className=\"size-1.5 rounded-full bg-warning\" role=\"img\" />}\n                    <RollingCount reduce={reduce} value={count} /> {count === 1 ? \"person\" : \"people\"}\n                  </span>\n                </motion.div>\n              );\n            })}\n          </div>\n          {areas.map((area) => (\n            <Fragment key={area.id}>\n              <div className={cn(grid, \"border-b\")} role=\"row\" style={gridStyle}>\n                <div className=\"sticky left-0 z-10 bg-card px-4 pt-3.5 pb-1 font-medium text-muted-foreground text-xs\" role=\"rowheader\">\n                  {area.name}\n                </div>\n                {roles.map((r) => (\n                  <div className={cn(\"transition-colors duration-150\", colBg(r.id))} key={r.id} onMouseEnter={() => setHover(r.id)} role=\"cell\" />\n                ))}\n              </div>\n              {area.permissions.map((p) => (\n                <div className={cn(grid, \"border-b last:border-b-0\")} key={p.id} role=\"row\" style={gridStyle}>\n                  <div className=\"sticky left-0 z-10 flex items-center bg-card py-1.5 ps-4 pe-2 text-sm leading-snug\" role=\"rowheader\">\n                    {p.label}\n                  </div>\n                  {roles.map((r) => {\n                    const on = (draft[r.id] ?? []).includes(p.id);\n                    const diverges = r.from ? on !== (draft[r.from] ?? []).includes(p.id) : false;\n                    return (\n                      <div\n                        className={cn(\"flex items-center justify-center transition-colors duration-150\", colBg(r.id))}\n                        key={r.id}\n                        onMouseEnter={() => setHover(r.id)}\n                        role=\"cell\"\n                      >\n                        <CheckCell\n                          changed={diverges}\n                          checked={on}\n                          label={`${r.name}: ${p.label}`}\n                          locked={r.locked}\n                          onToggle={() => onToggle(r.id, p.id)}\n                          reduce={reduce}\n                        />\n                      </div>\n                    );\n                  })}\n                </div>\n              ))}\n            </Fragment>\n          ))}\n          {roles.some((r) => r.from) && (\n            <div className={cn(grid, \"border-t\")} role=\"row\" style={gridStyle}>\n              <div className=\"sticky left-0 z-10 bg-card\" role=\"cell\" />\n              {roles.map((r) => (\n                <div className={cn(\"flex justify-center py-1.5 transition-colors duration-150\", colBg(r.id))} key={r.id} onMouseEnter={() => setHover(r.id)} role=\"cell\">\n                  {r.from && (\n                    <Button aria-label={`Remove ${r.name} role`} className={press} onClick={() => onRemove(r.id)} size=\"icon-xs\" variant=\"ghost\">\n                      <XIcon />\n                    </Button>\n                  )}\n                </div>\n              ))}\n            </div>\n          )}\n        </div>\n      </div>\n    </div>\n  );\n}\n\nexport function TeamRoles({\n  className,\n  areas = defaultAreas,\n  roles: initialRoles = defaultRoles,\n  members: initialMembers = defaultMembers,\n  invites: initialInvites = defaultInvites,\n  currentUserId = \"m1\",\n  onNavigate,\n}: TeamRolesProps) {\n  const reduce = useReducedMotionAfterMount();\n  const id = useId();\n  const [roles, setRoles] = useState(initialRoles);\n  const [saved, setSaved] = useState<Record<string, string[]>>(() => Object.fromEntries(initialRoles.map((r) => [r.id, r.grants])));\n  const [draft, setDraft] = useState<Record<string, string[]>>(saved);\n  const [members, setMembers] = useState(initialMembers);\n  const [invites, setInvites] = useState(initialInvites);\n  const [email, setEmail] = useState(\"\");\n  const [inviteRole, setInviteRole] = useState(\"member\");\n  const [inviteError, setInviteError] = useState<string | null>(null);\n  const [resent, setResent] = useState<string[]>([]);\n  const [removing, setRemoving] = useState<TeamMember | null>(null);\n  const [removeOpen, setRemoveOpen] = useState(false);\n  const [notice, setNotice] = useState<{ key: number; text: ReactNode; undo?: () => void } | null>(null);\n  const [justSaved, setJustSaved] = useState(false);\n  const counter = useRef(0);\n  const savedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  useEffect(() => {\n    if (!notice) return;\n    const t = setTimeout(() => setNotice(null), 4000);\n    return () => clearTimeout(t);\n  }, [notice]);\n\n  useEffect(() => () => {\n    if (savedTimer.current) clearTimeout(savedTimer.current);\n  }, []);\n\n  const say = (text: ReactNode, undo?: () => void) => {\n    counter.current += 1;\n    setNotice({ key: counter.current, text, undo });\n  };\n\n  const counts = Object.fromEntries(roles.map((r) => [r.id, members.filter((m) => m.roleId === r.id).length]));\n  const changedRoles = roles.filter((r) => !sameGrants(draft[r.id] ?? [], saved[r.id] ?? []));\n  const affected = changedRoles.reduce((n, r) => n + (counts[r.id] ?? 0), 0);\n  const customRole = roles.find((r) => r.from);\n\n  const sendInvite = (e: FormEvent) => {\n    e.preventDefault();\n    const value = email.trim();\n    if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value)) {\n      setInviteError(\"Enter a full email address, like name@company.com.\");\n      return;\n    }\n    if (invites.some((i) => i.email === value) || members.some((m) => m.email === value)) {\n      setInviteError(\"That person is already here or invited.\");\n      return;\n    }\n    counter.current += 1;\n    setInvites((all) => [{ id: `new-${counter.current}`, email: value, roleId: inviteRole, invitedBy: \"Ada\", sent: \"just now\" }, ...all]);\n    setEmail(\"\");\n    say(\n      <>\n        Invite sent to <span className=\"font-medium\">{value}</span>\n      </>,\n    );\n  };\n\n  const toggle = (roleId: string, permissionId: string) =>\n    setDraft((d) => {\n      const current = d[roleId] ?? [];\n      return { ...d, [roleId]: current.includes(permissionId) ? current.filter((p) => p !== permissionId) : [...current, permissionId] };\n    });\n\n  const addCustom = () => {\n    counter.current += 1;\n    const rid = `custom-${counter.current}`;\n    const grants = [...(draft.member ?? [])];\n    setRoles((all) => {\n      const ownerIndex = all.findIndex((r) => r.locked);\n      const next = [...all];\n      next.splice(ownerIndex < 0 ? all.length : ownerIndex, 0, {\n        id: rid,\n        name: \"Contractor\",\n        description: \"Custom, based on Member\",\n        from: \"member\",\n        grants,\n      });\n      return next;\n    });\n    setSaved((s) => ({ ...s, [rid]: grants }));\n    setDraft((d) => ({ ...d, [rid]: grants }));\n  };\n\n  const removeCustom = (rid: string) => {\n    const role = roles.find((r) => r.id === rid);\n    const fallback = role?.from ?? \"viewer\";\n    const before = { roles, members, invites, saved, draft };\n    setRoles((all) => all.filter((r) => r.id !== rid));\n    setMembers((all) => all.map((m) => (m.roleId === rid ? { ...m, roleId: fallback } : m)));\n    setInvites((all) => all.map((i) => (i.roleId === rid ? { ...i, roleId: fallback } : i)));\n    setSaved(({ [rid]: _, ...rest }) => rest);\n    setDraft(({ [rid]: _, ...rest }) => rest);\n    say(\n      <>\n        <span className=\"font-medium\">{role?.name}</span> role removed\n      </>,\n      () => {\n        setRoles(before.roles);\n        setMembers(before.members);\n        setInvites(before.invites);\n        setSaved(before.saved);\n        setDraft(before.draft);\n      },\n    );\n  };\n\n  const save = () => {\n    setSaved(draft);\n    setRoles((all) => all.map((r) => ({ ...r, grants: draft[r.id] ?? r.grants })));\n    setJustSaved(true);\n    if (savedTimer.current) clearTimeout(savedTimer.current);\n    savedTimer.current = setTimeout(() => setJustSaved(false), 1600);\n  };\n\n  const fade = reduce ? { duration: 0 } : { duration: 0.22, ease: easeOut };\n  const bar = changedRoles.length > 0 ? \"dirty\" : justSaved ? \"saved\" : null;\n  const roleName = (rid: string) => roles.find((r) => r.id === rid)?.name ?? \"Viewer\";\n\n  return (\n    <RidgelineShell active=\"members\" className={className} onNavigate={onNavigate}>\n          <div className=\"mx-auto w-full max-w-2xl px-6 py-10 md:px-10\">\n            <h1 className=\"font-semibold text-2xl tracking-tight\">Members & roles</h1>\n            <p className=\"mt-1 text-muted-foreground text-sm\">Invite people to Ridgeline and decide what each role can do.</p>\n\n            <section className=\"mt-10\">\n              <h2 className=\"font-medium text-sm\">Invite people</h2>\n              <p className=\"text-muted-foreground text-sm\">They’ll get an email with a link that works for 7 days.</p>\n              <form className=\"mt-3 flex flex-col gap-2 rounded-xl border bg-card p-3 sm:flex-row sm:items-start\" onSubmit={sendInvite}>\n                <div className=\"flex min-w-0 flex-1 flex-col gap-1.5\">\n                  <Input\n                    aria-describedby={inviteError ? `${id}-invite-error` : undefined}\n                    aria-invalid={inviteError ? true : undefined}\n                    aria-label=\"Email address\"\n                    onChange={(e) => {\n                      setEmail(e.target.value);\n                      setInviteError(null);\n                    }}\n                    placeholder=\"name@company.com\"\n                    type=\"email\"\n                    value={email}\n                  />\n                  {inviteError && (\n                    <p className=\"px-0.5 text-destructive-foreground text-xs\" id={`${id}-invite-error`}>\n                      {inviteError}\n                    </p>\n                  )}\n                </div>\n                <div className=\"flex gap-2\">\n                  <RoleSelect className=\"flex-1 sm:w-32 sm:flex-none\" label=\"Role for new invite\" onChange={setInviteRole} roles={roles} value={inviteRole} />\n                  <Button className={press} disabled={!email.trim()} type=\"submit\">\n                    Invite\n                  </Button>\n                </div>\n              </form>\n            </section>\n\n            <section className=\"mt-10\">\n              <h2 className=\"font-medium text-sm\">Members</h2>\n              <p className=\"text-muted-foreground text-sm\">{plural(members.length, \"person\", \"people\")} in Ridgeline.</p>\n              <div className=\"mt-3 overflow-hidden rounded-xl border bg-card\">\n                <div className=\"hidden grid-cols-[minmax(0,1fr)_8rem_6.5rem_2rem] items-center gap-4 border-b px-4 py-2.5 font-medium text-muted-foreground text-xs sm:grid\">\n                  <span>Name</span>\n                  <span>Role</span>\n                  <span>Last active</span>\n                  <span className=\"sr-only\">Actions</span>\n                </div>\n                <ul>\n                  <AnimatePresence initial={false}>\n                    {members.map((m) => {\n                      const role = roles.find((r) => r.id === m.roleId);\n                      const you = m.id === currentUserId;\n                      return (\n                        <motion.li\n                          animate={{ opacity: 1, height: \"auto\" }}\n                          className=\"overflow-hidden border-b last:border-b-0\"\n                          exit={{ opacity: 0, height: 0 }}\n                          initial={{ opacity: 0, height: 0 }}\n                          key={m.id}\n                          transition={fade}\n                        >\n                          <div className=\"grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-2 px-4 py-3 sm:grid-cols-[minmax(0,1fr)_8rem_6.5rem_2rem]\">\n                            <div className=\"flex min-w-0 items-center gap-3\">\n                              <PersonAvatar hue={m.hue} name={m.name} />\n                              <div className=\"min-w-0\">\n                                <p className=\"truncate font-medium text-sm\">\n                                  {m.name}\n                                  {you && <span className=\"font-normal text-muted-foreground\"> (you)</span>}\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 flex items-center gap-3 ps-11 sm:col-start-auto sm:row-start-auto sm:ps-0\">\n                              {role?.locked ? (\n                                <span className=\"flex h-8 items-center gap-1.5 px-0.5 text-sm sm:h-7\">\n                                  {role.name}\n                                  <LockIcon className=\"size-3 text-muted-foreground\" />\n                                </span>\n                              ) : (\n                                <RoleSelect\n                                  className=\"w-32\"\n                                  label={`Role for ${m.name}`}\n                                  onChange={(rid) => setMembers((all) => all.map((x) => (x.id === m.id ? { ...x, roleId: rid } : x)))}\n                                  roles={roles}\n                                  value={m.roleId}\n                                />\n                              )}\n                              <span className=\"text-muted-foreground text-xs sm:hidden\">{m.lastActive}</span>\n                            </div>\n                            <span className=\"hidden text-muted-foreground text-sm sm:block\">\n                              {m.lastActive === \"Now\" ? (\n                                <span className=\"inline-flex items-center gap-1.5\">\n                                  <span className=\"size-1.5 rounded-full bg-success\" />\n                                  Now\n                                </span>\n                              ) : (\n                                m.lastActive\n                              )}\n                            </span>\n                            <Menu>\n                              <MenuTrigger\n                                render={\n                                  <Button\n                                    aria-label={`Actions for ${m.name}`}\n                                    className={cn(\"col-start-2 row-start-1 justify-self-end sm:col-start-auto sm:row-start-auto\", press)}\n                                    size=\"icon-sm\"\n                                    variant=\"ghost\"\n                                  />\n                                }\n                              >\n                                <EllipsisIcon />\n                              </MenuTrigger>\n                              <MenuPopup align=\"end\" className=\"w-52\">\n                                <MenuItem onClick={() => navigator.clipboard?.writeText(m.email).catch(() => {})}>\n                                  <CopyIcon />\n                                  Copy email\n                                </MenuItem>\n                                <MenuSeparator />\n                                <MenuItem\n                                  disabled={role?.locked || you}\n                                  onClick={() => {\n                                    setRemoving(m);\n                                    setRemoveOpen(true);\n                                  }}\n                                  variant=\"destructive\"\n                                >\n                                  <UserMinusIcon />\n                                  {role?.locked ? \"Owner can’t be removed\" : \"Remove from workspace\"}\n                                </MenuItem>\n                              </MenuPopup>\n                            </Menu>\n                          </div>\n                        </motion.li>\n                      );\n                    })}\n                  </AnimatePresence>\n                </ul>\n              </div>\n\n              <h3 className=\"mt-6 flex items-center gap-1.5 font-medium text-muted-foreground text-xs\">\n                Pending invites\n                <span className=\"tabular-nums\">{invites.length}</span>\n              </h3>\n              <div className=\"mt-2 overflow-hidden rounded-xl border bg-card\">\n                <ul>\n                  <AnimatePresence initial={false}>\n                    {invites.map((inv) => {\n                      const wasResent = resent.includes(inv.id);\n                      return (\n                        <motion.li\n                          animate={{ opacity: 1, height: \"auto\" }}\n                          className=\"overflow-hidden border-b last:border-b-0\"\n                          exit={{ opacity: 0, height: 0 }}\n                          initial={{ opacity: 0, height: 0 }}\n                          key={inv.id}\n                          transition={fade}\n                        >\n                          <div className=\"flex flex-wrap items-center gap-x-4 gap-y-2 px-4 py-3\">\n                            <div className=\"flex min-w-0 flex-1 basis-56 items-center gap-3\">\n                              <span className=\"flex size-8 shrink-0 items-center justify-center rounded-full border border-dashed text-muted-foreground\">\n                                <MailIcon className=\"size-3.5\" />\n                              </span>\n                              <div className=\"min-w-0\">\n                                <p className=\"truncate font-medium text-sm\">{inv.email}</p>\n                                <p className=\"truncate text-muted-foreground text-xs\">\n                                  {roleName(inv.roleId)} · {wasResent ? \"resent just now\" : `invited by ${inv.invitedBy} ${inv.sent}`}\n                                </p>\n                              </div>\n                            </div>\n                            <div className=\"ms-11 flex items-center gap-1.5 sm:ms-auto\">\n                              <Button\n                                className={cn(\"min-w-[5.5rem]\", press)}\n                                disabled={wasResent}\n                                onClick={() => setResent((r) => [...r, inv.id])}\n                                size=\"sm\"\n                                variant=\"outline\"\n                              >\n                                <AnimatePresence initial={false} mode=\"popLayout\">\n                                  <motion.span\n                                    animate={{ opacity: 1, scale: 1 }}\n                                    className=\"flex items-center gap-1.5\"\n                                    exit={{ opacity: 0, scale: 0.9 }}\n                                    initial={{ opacity: 0, scale: 0.9 }}\n                                    key={wasResent ? \"done\" : \"idle\"}\n                                    transition={{ duration: 0.15, ease: easeOut }}\n                                  >\n                                    {wasResent && <CheckIcon className=\"size-3.5\" />}\n                                    {wasResent ? \"Resent\" : \"Resend\"}\n                                  </motion.span>\n                                </AnimatePresence>\n                              </Button>\n                              <Button\n                                className={press}\n                                onClick={() => {\n                                  const before = invites;\n                                  setInvites((all) => all.filter((x) => x.id !== inv.id));\n                                  say(\n                                    <>\n                                      Invite for <span className=\"font-medium\">{inv.email}</span> revoked\n                                    </>,\n                                    () => setInvites(before),\n                                  );\n                                }}\n                                size=\"sm\"\n                                variant=\"ghost\"\n                              >\n                                Revoke\n                              </Button>\n                            </div>\n                          </div>\n                        </motion.li>\n                      );\n                    })}\n                  </AnimatePresence>\n                </ul>\n                {invites.length === 0 && <p className=\"px-4 py-6 text-center text-muted-foreground text-sm\">No invites waiting.</p>}\n              </div>\n            </section>\n\n            <section className=\"mt-10\">\n              <div className=\"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between sm:gap-4\">\n                <div className=\"min-w-0\">\n                  <h2 className=\"font-medium text-sm\">Roles</h2>\n                  <p className=\"text-pretty text-muted-foreground text-sm\">What each role can do. Owners can always do everything.</p>\n                </div>\n                <Button className={cn(\"shrink-0 self-start sm:self-auto\", press)} disabled={Boolean(customRole)} onClick={addCustom} size=\"sm\" variant=\"outline\">\n                  <CopyIcon />\n                  Duplicate Member\n                </Button>\n              </div>\n              <PermissionMatrix\n                areas={areas}\n                counts={counts}\n                draft={draft}\n                onRemove={removeCustom}\n                onRename={(rid, name) => setRoles((all) => all.map((r) => (r.id === rid ? { ...r, name } : r)))}\n                onToggle={toggle}\n                reduce={reduce}\n                roles={roles}\n                saved={saved}\n              />\n              <p className=\"mt-2 text-pretty text-muted-foreground text-xs\">\n                {customRole ? (\n                  <>\n                    <span className=\"me-1 inline-block size-1.5 -translate-y-px rounded-full bg-warning align-middle\" />\n                    marks where {customRole.name} differs from Member. Click its name to rename it.\n                  </>\n                ) : (\n                  \"Need something in between? Duplicate Member and adjust it.\"\n                )}\n              </p>\n            </section>\n\n            <div className=\"sticky bottom-4 z-20 mt-6 flex justify-center\">\n              <AnimatePresence initial={false} mode=\"popLayout\">\n                {bar ? (\n                  <motion.div\n                    animate={{ opacity: 1, y: 0 }}\n                    className=\"flex w-full items-center gap-3 rounded-xl border bg-popover py-2 ps-4 pe-2 shadow-lg/5\"\n                    exit={reduce ? { opacity: 0 } : { opacity: 0, y: 16 }}\n                    initial={reduce ? { opacity: 0 } : { opacity: 0, y: 16 }}\n                    role=\"status\"\n                    transition={reduce ? { duration: 0 } : spring}\n                  >\n                    {bar === \"dirty\" ? (\n                      <>\n                        <p className=\"min-w-0 flex-1 truncate text-sm\">\n                          <span className=\"sm:hidden\">Unsaved changes</span>\n                          <span className=\"hidden sm:inline\">You have unsaved changes</span>\n                          <span className=\"hidden text-muted-foreground sm:inline\">\n                            {\" \"}\n                            · {affected === 0 ? \"no one has these roles yet\" : `affects ${plural(affected, \"person\", \"people\")}`}\n                          </span>\n                        </p>\n                        <Button className={press} onClick={() => setDraft(saved)} size=\"sm\" variant=\"ghost\">\n                          Discard\n                        </Button>\n                        <Button className={press} onClick={save} size=\"sm\">\n                          Save\n                        </Button>\n                      </>\n                    ) : (\n                      <p className=\"flex h-8 items-center gap-2 text-sm sm:h-7\">\n                        <CheckIcon className=\"size-4 text-success-foreground\" />\n                        Roles saved\n                      </p>\n                    )}\n                  </motion.div>\n                ) : notice ? (\n              <motion.div\n                animate={{ opacity: 1, y: 0 }}\n                className=\"flex max-w-full items-center gap-3 rounded-xl border bg-popover py-1.5 ps-3.5 pe-1.5 text-sm shadow-lg/5\"\n                exit={reduce ? { opacity: 0 } : { opacity: 0, y: 8 }}\n                initial={reduce ? { opacity: 0 } : { opacity: 0, y: 8 }}\n                key={notice.key}\n                role=\"status\"\n                transition={{ duration: 0.2, ease: easeOut }}\n              >\n                <p className=\"min-w-0 truncate\">{notice.text}</p>\n                {notice.undo ? (\n                  <Button\n                    className={press}\n                    onClick={() => {\n                      notice.undo?.();\n                      setNotice(null);\n                    }}\n                    size=\"sm\"\n                    variant=\"ghost\"\n                  >\n                    <RotateCcwIcon />\n                    Undo\n                  </Button>\n                ) : (\n                  <CheckIcon className=\"me-2 size-4 shrink-0 text-success-foreground\" />\n                )}\n              </motion.div>\n                ) : null}\n              </AnimatePresence>\n            </div>\n          </div>\n\n      <AlertDialog onOpenChange={setRemoveOpen} open={removeOpen}>\n        <AlertDialogPopup>\n          <AlertDialogHeader>\n            <AlertDialogTitle>Remove {removing?.name}?</AlertDialogTitle>\n            <AlertDialogDescription>\n              They lose access to Ridgeline straight away. Projects they created stay where they are.\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                    say(\n                      <>\n                        <span className=\"font-medium\">{target.name}</span> removed\n                      </>,\n                    );\n                  }}\n                  variant=\"destructive\"\n                />\n              }\n            >\n              Remove\n            </AlertDialogClose>\n          </AlertDialogFooter>\n        </AlertDialogPopup>\n      </AlertDialog>\n    </RidgelineShell>\n  );\n}\n"
    }
  ]
}