{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "team-board",
  "type": "registry:ui",
  "title": "Team Board",
  "description": "Team mode for a live room. The host sets up teams, balances them (or moves a player by hand), and everyone sees whose team they are on and how the teams score. The rules are `games/team-model`; the teams ride in the room (`RoomState.shared`), so a phone…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "games",
    "game"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/button.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/input.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/team-board.tsx",
      "target": "components/ui/games/team-board.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/team-board v1.5.1 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/team-board\n// What changed since: https://ds.interlace.tools/c/team-board#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — TeamBoard, TeamScoreboard, TeamBadge\n *\n * Team mode for a live room. The host sets up teams, balances them (or moves a player by hand),\n * and everyone sees whose team they are on and how the teams score. The rules are\n * `games/team-model`; the teams ride in the room (`RoomState.shared`), so a phone that joins late\n * or reconnects shows its team at once and no message can put an old assignment back.\n *\n * ## Anatomy\n *\n *   TeamBoard                      (section — data-slot=\"team-board\", data-state=empty|ready)\n *     ├─ div                       (data-slot=\"team-board-setup\": team count + make teams, before any)\n *     ├─ div role=\"group\"          (data-slot=\"team-board-actions\": shuffle, even out by score)\n *     ├─ ul                        (data-slot=\"team-board-teams\")\n *     │   └─ li × n                (data-slot=\"team-board-team\", data-team-id, data-mark)\n *     │       ├─ h3 + Input        (data-slot=\"team-board-name\": rename on blur or Enter)\n *     │       └─ ul > li × m       (data-slot=\"team-board-member\": name, away, and a \"move to\" select)\n *     ├─ section                   (data-slot=\"team-board-unassigned\": players with no team yet)\n *     └─ span aria-live            (data-slot=\"team-board-announce\")\n *\n *   TeamScoreboard                 (section — data-slot=\"team-scoreboard\")\n *     ├─ ol > li × n               (data-slot=\"team-scoreboard-row\": rank, mark, name, points, bar)\n *     └─ span aria-live            (data-slot=\"team-scoreboard-announce\": who leads, when it changes)\n *\n *   TeamBadge                      (div role=\"status\" — data-slot=\"team-badge\", data-state=none|team)\n *\n * ## Colour is never alone\n *\n * A team's colour is a `--team-N` token (retune them in your brand layer); each team also has a\n * letter (A, B, C…) and its name, so teams are told apart without seeing colour.\n *\n * ## Keyboard and screen readers\n *\n * Moving a player is a native `<select>` on each member, so there is no drag to do and it works\n * with a keyboard, a switch and a screen reader. The scoreboard is an ordered list and says in\n * words when the leader changes; a phone says when its player moves to another team.\n *\n * ## Motion\n *\n * The scoreboard bars grow with a transition (clamped to none under reduced motion by the page\n * preflight and by `useReducedMotion` here). Nothing else moves.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                                   |\n * | ---- | ------------------------- | ---------------------------------------------------- |\n * | R4   | Extends native el         | `section` / `div` props                              |\n * | R6   | data-slot per part        | team-board-*, team-scoreboard-*, team-badge         |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                    |\n * | R8   | Enums, not booleans       | `by`                                                 |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                 |\n * | R25  | Client component          | the board reacts to the room                         |\n * | R26  | A11y                      | lists, labelled selects, sparse live regions         |\n */\n\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport type { RoomHostEvent, RoomPlayer, RoomState } from '@/components/ui/games/room-model';\nimport type { Random } from '@/components/ui/games/group-model';\nimport {\n  autoBalance,\n  createTeams,\n  MAX_TEAMS,\n  membersOf,\n  moveToTeam,\n  placeNewcomers,\n  readTeams,\n  renameTeam,\n  teamColor,\n  teamMark,\n  teamOf,\n  teamsEvent,\n  teamStandings,\n  unassigned,\n  type TeamStanding,\n  type TeamsState,\n} from '@/components/ui/games/team-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\nconst SELECT =\n  'border-input bg-background text-foreground h-control-sm max-w-full min-w-0 rounded-lg border ps-2 pe-1 text-sm focus-visible:outline-hidden focus-visible:border-ring focus-visible:ring-ring focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\n/** A team's colour as a custom property, so a class can paint with it (`bg-(--team)`). */\nconst teamStyle = (index: number) => ({ '--team': teamColor(index) }) as React.CSSProperties;\n\n// --- TeamBoard ------------------------------------------------------------------\n\nexport interface TeamBoardLabels {\n  /** Names the board. @default 'Teams' */\n  name?: string;\n  /** @default 'Number of teams' */\n  count?: string;\n  /** @default 'Make teams' */\n  make?: string;\n  /** Shown before any teams are made. @default 'No teams yet. Choose how many and make them.' */\n  empty?: string;\n  /** Names the buttons that change the teams. @default 'Team actions' */\n  actions?: string;\n  /** @default 'Shuffle teams' */\n  shuffle?: string;\n  /** @default 'Even out by score' */\n  evenOut?: string;\n  /** @default 'Remove teams' */\n  clear?: string;\n  /** @default (mark) => `Team ${mark}` */\n  team?: (mark: string) => string;\n  /** @default (team) => `Name for ${team}` */\n  rename?: (team: string) => string;\n  /** @default (n) => n === 1 ? '1 player' : `${n} players` */\n  size?: (n: number) => string;\n  /** @default (player) => `Move ${player} to` */\n  move?: (player: string) => string;\n  /** The \"no team\" option. @default 'No team' */\n  none?: string;\n  /** @default 'away' */\n  away?: string;\n  /** @default 'No team yet' */\n  unassigned?: string;\n  /** Said when players are put on teams. @default (n) => `${n} players placed on teams` */\n  placed?: (n: number) => string;\n}\n\ntype TeamBoardProps = Omit<React.ComponentProps<'section'>, 'children'> & {\n  room: RoomState;\n  /** `send` from the host's `useRoom`. */\n  send: (event: RoomHostEvent) => void;\n  /** Teams to offer first in the setup. @default 2 */\n  defaultTeams?: number;\n  /** Put players who join after the teams are made on the smallest team. @default true */\n  autoPlace?: boolean;\n  /** @default Math.random. Pass `seededRandom(n)` for a split you can repeat. */\n  random?: Random;\n  labels?: TeamBoardLabels;\n};\n\nconst SIZE = (n: number) => (n === 1 ? '1 player' : `${n} players`);\n\nfunction TeamBoard({\n  room,\n  send,\n  defaultTeams = 2,\n  autoPlace = true,\n  random,\n  labels,\n  className,\n  ...props\n}: TeamBoardProps) {\n  const L = labels ?? {};\n  const teams = readTeams(room);\n  const [count, setCount] = React.useState(() => Math.min(MAX_TEAMS, Math.max(2, defaultTeams)));\n  const [announce, setAnnounce] = React.useState('');\n  const countId = React.useId();\n  const latest = React.useRef({ send, random });\n  latest.current = { send, random };\n\n  const write = React.useCallback((next: TeamsState | null) => latest.current.send(teamsEvent(next)), []);\n\n  // Someone who joined after the teams were made goes to the smallest team.\n  React.useEffect(() => {\n    if (!autoPlace || !teams) return;\n    const next = placeNewcomers(teams, room.players);\n    if (next !== teams) write(next);\n  }, [autoPlace, teams, room.players, write]);\n\n  const balance = (scored: boolean) => {\n    const base = teams ?? createTeams(count);\n    const next = autoBalance(base, room.players, {\n      scores: scored ? room.scores : undefined,\n      random: latest.current.random,\n    });\n    write(next);\n    setAnnounce((L.placed ?? ((n: number) => `${n} players placed on teams`))(room.players.length));\n  };\n\n  const loose = teams ? unassigned(teams, room.players) : [];\n\n  return (\n    <section\n      aria-label={L.name ?? 'Teams'}\n      data-slot=\"team-board\"\n      data-state={teams ? 'ready' : 'empty'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('@container flex flex-col gap-5', className)}\n      {...props}\n    >\n      {teams ? null : (\n        <div data-slot=\"team-board-setup\" className=\"flex flex-wrap items-end gap-3\">\n          <p className=\"text-muted-foreground basis-full text-sm\">\n            {L.empty ?? 'No teams yet. Choose how many and make them.'}\n          </p>\n          <div className=\"flex flex-col gap-1.5\">\n            <label htmlFor={countId} className=\"text-sm font-medium\">\n              {L.count ?? 'Number of teams'}\n            </label>\n            <select\n              id={countId}\n              data-slot=\"team-board-count\"\n              className={SELECT}\n              value={count}\n              onChange={(e) => setCount(Number(e.target.value))}\n            >\n              {Array.from({ length: MAX_TEAMS - 1 }, (_, i) => i + 2).map((n) => (\n                <option key={n} value={n}>\n                  {n}\n                </option>\n              ))}\n            </select>\n          </div>\n          <Button data-slot=\"team-board-make\" type=\"button\" onClick={() => balance(false)}>\n            {L.make ?? 'Make teams'}\n          </Button>\n        </div>\n      )}\n\n      {teams ? (\n        <div role=\"group\" aria-label={L.actions ?? 'Team actions'} data-slot=\"team-board-actions\" className=\"flex flex-wrap gap-2\">\n          <Button data-slot=\"team-board-shuffle\" type=\"button\" variant=\"outline\" onClick={() => balance(false)}>\n            {L.shuffle ?? 'Shuffle teams'}\n          </Button>\n          <Button data-slot=\"team-board-even\" type=\"button\" variant=\"outline\" onClick={() => balance(true)}>\n            {L.evenOut ?? 'Even out by score'}\n          </Button>\n          <Button data-slot=\"team-board-clear\" type=\"button\" variant=\"ghost\" onClick={() => write(null)}>\n            {L.clear ?? 'Remove teams'}\n          </Button>\n        </div>\n      ) : null}\n\n      {teams ? (\n        <ul data-slot=\"team-board-teams\" className=\"grid list-none gap-4 p-0 @2xl:grid-cols-2 @5xl:grid-cols-3\">\n          {teams.teams.map((team, index) => {\n            const people = membersOf(teams, team.id, room.players);\n            const mark = teamMark(index);\n            return (\n              <li\n                key={team.id}\n                data-slot=\"team-board-team\"\n                data-team-id={team.id}\n                data-mark={mark}\n                style={teamStyle(index)}\n                className=\"bg-card text-card-foreground border-border flex min-w-0 flex-col gap-3 rounded-xl border border-s-4 border-s-(--team) p-4\"\n              >\n                <div className=\"flex min-w-0 items-center gap-2\">\n                  <span\n                    aria-hidden\n                    className=\"border-border bg-background grid size-7 shrink-0 place-items-center rounded-full border-2 border-(--team) text-sm font-semibold\"\n                  >\n                    {mark}\n                  </span>\n                  <RenameField\n                    key={team.name}\n                    label={(L.rename ?? ((n: string) => `Name for ${n}`))(team.name)}\n                    value={team.name}\n                    onCommit={(name) => write(renameTeam(teams, team.id, name))}\n                  />\n                </div>\n                <p className=\"text-muted-foreground text-xs tabular-nums\">{(L.size ?? SIZE)(people.length)}</p>\n                <ul className=\"flex list-none flex-col gap-1.5 p-0\">\n                  {people.map((p) => (\n                    <MemberRow key={p.id} player={p} teams={teams} labels={L} onMove={(to) => write(moveToTeam(teams, p.id, to))} />\n                  ))}\n                </ul>\n              </li>\n            );\n          })}\n        </ul>\n      ) : null}\n\n      {teams && loose.length ? (\n        <section data-slot=\"team-board-unassigned\" aria-label={L.unassigned ?? 'No team yet'} className=\"flex flex-col gap-2\">\n          <h3 className=\"text-sm font-semibold\">{L.unassigned ?? 'No team yet'}</h3>\n          <ul className=\"flex list-none flex-col gap-1.5 p-0\">\n            {loose.map((p) => (\n              <MemberRow key={p.id} player={p} teams={teams} labels={L} onMove={(to) => write(moveToTeam(teams, p.id, to))} />\n            ))}\n          </ul>\n        </section>\n      ) : null}\n\n      <span data-slot=\"team-board-announce\" aria-live=\"polite\" className=\"sr-only\">\n        {announce}\n      </span>\n    </section>\n  );\n}\nTeamBoard.displayName = 'TeamBoard';\n\n/** A team's name as a field: the new name is kept on blur or Enter, and Escape puts the old one back. */\nfunction RenameField({ label, value, onCommit }: { label: string; value: string; onCommit: (name: string) => void }) {\n  const [draft, setDraft] = React.useState(value);\n  return (\n    <Input\n      data-slot=\"team-board-name\"\n      aria-label={label}\n      value={draft}\n      maxLength={24}\n      className=\"min-w-0 font-semibold\"\n      onChange={(e) => setDraft(e.target.value)}\n      onBlur={() => draft !== value && onCommit(draft)}\n      onKeyDown={(e) => {\n        if (e.key === 'Enter') (e.target as HTMLInputElement).blur();\n        if (e.key === 'Escape') setDraft(value);\n      }}\n    />\n  );\n}\n\nfunction MemberRow({\n  player,\n  teams,\n  labels,\n  onMove,\n}: {\n  player: RoomPlayer;\n  teams: TeamsState;\n  labels: TeamBoardLabels;\n  onMove: (teamId: string | null) => void;\n}) {\n  const current = teamOf(teams, player.id)?.id ?? '';\n  return (\n    <li\n      data-slot=\"team-board-member\"\n      data-player-id={player.id}\n      data-away={player.connected ? undefined : ''}\n      className=\"flex min-w-0 items-center justify-between gap-2\"\n    >\n      <span className={cn('min-w-0 truncate text-sm', !player.connected && 'text-muted-foreground')}>\n        {player.name}\n        {player.connected ? null : <span className=\"ms-1.5 text-xs\">{labels.away ?? 'away'}</span>}\n      </span>\n      <select\n        data-slot=\"team-board-move\"\n        aria-label={(labels.move ?? ((n: string) => `Move ${n} to`))(player.name)}\n        className={SELECT}\n        value={current}\n        onChange={(e) => onMove(e.target.value || null)}\n      >\n        <option value=\"\">{labels.none ?? 'No team'}</option>\n        {teams.teams.map((t, i) => (\n          <option key={t.id} value={t.id}>\n            {teamMark(i)} · {t.name}\n          </option>\n        ))}\n      </select>\n    </li>\n  );\n}\n\n// --- TeamScoreboard -------------------------------------------------------------\n\nexport interface TeamScoreboardLabels {\n  /** Names the board. @default 'Team scores' */\n  name?: string;\n  /** @default (n) => n === 1 ? '1 player' : `${n} players` */\n  size?: (n: number) => string;\n  /** The points figure's unit, spoken. @default (n, by) => by === 'average' ? `${n} per player` : `${n} points` */\n  points?: (n: number, by: 'average' | 'total') => string;\n  /** What a round added. @default (n) => `+${n}` */\n  gained?: (n: number) => string;\n  /** @default (name) => `${name} leads` */\n  leads?: (name: string) => string;\n  /** Said when two or more share the lead. @default (names) => `${names.join(' and ')} are level` */\n  level?: (names: string[]) => string;\n  /** Shown before any teams. @default 'No teams yet.' */\n  empty?: string;\n}\n\ntype TeamScoreboardProps = Omit<React.ComponentProps<'section'>, 'children'> & {\n  room: Pick<RoomState, 'shared' | 'players' | 'scores' | 'lastPoints'>;\n  /** What ranks: `average` is fair when teams differ in size by one. @default 'average' */\n  by?: 'average' | 'total';\n  /** The viewer's player id, to mark their team. */\n  selfId?: string;\n  /** For the numbers. @default the page's language */\n  locale?: string;\n  labels?: TeamScoreboardLabels;\n};\n\nfunction TeamScoreboard({ room, by = 'average', selfId, locale, labels, className, ...props }: TeamScoreboardProps) {\n  const L = labels ?? {};\n  const fmt = React.useMemo(() => new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }), [locale]);\n  const reduced = useReducedMotion();\n  const teams = readTeams(room);\n  const rows: TeamStanding[] = teams ? teamStandings(teams, room, by) : [];\n  const top = rows.length ? Math.max(...rows.map((r) => (by === 'total' ? r.total : r.average))) : 0;\n  const mine = teams && selfId ? teamOf(teams, selfId)?.id : undefined;\n  const leaders = rows.filter((r) => r.rank === 1);\n  const said = React.useRef<string | null>(null);\n  const [announce, setAnnounce] = React.useState('');\n\n  // Say who leads, only when it changes (and never on the first look).\n  const leadKey = leaders.map((r) => r.id).join(',');\n  const leadWords = leaders.length > 1\n    ? (L.level ?? ((names: string[]) => `${names.join(' and ')} are level`))(leaders.map((r) => r.name))\n    : leaders[0]\n      ? (L.leads ?? ((name: string) => `${name} leads`))(leaders[0].name)\n      : '';\n  React.useEffect(() => {\n    const before = said.current;\n    said.current = leadKey;\n    if (before !== null && before !== leadKey && leadKey && top > 0) setAnnounce(leadWords);\n  }, [leadKey, leadWords, top]);\n\n  return (\n    <section\n      aria-label={L.name ?? 'Team scores'}\n      data-slot=\"team-scoreboard\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('flex flex-col gap-3', className)}\n      {...props}\n    >\n      {rows.length ? (\n        <ol data-slot=\"team-scoreboard-list\" className=\"flex list-none flex-col gap-3 p-0\">\n          {rows.map((r) => {\n            const value = by === 'total' ? r.total : r.average;\n            return (\n              <li\n                key={r.id}\n                data-slot=\"team-scoreboard-row\"\n                data-team-id={r.id}\n                data-rank={r.rank}\n                data-mine={r.id === mine ? '' : undefined}\n                style={teamStyle(r.index)}\n                className=\"grid grid-cols-[auto_1fr_auto] items-center gap-x-3 gap-y-1.5\"\n              >\n                <span className=\"text-muted-foreground w-6 text-sm font-semibold tabular-nums\">\n                  {r.rank}\n                  <span className=\"sr-only\">{r.tied ? ' (tied)' : ''}</span>\n                </span>\n                <span className=\"flex min-w-0 items-center gap-2 text-sm\">\n                  <span aria-hidden className=\"border-border bg-background grid size-6 shrink-0 place-items-center rounded-full border-2 border-(--team) text-xs font-semibold\">\n                    {teamMark(r.index)}\n                  </span>\n                  <span className={cn('truncate', r.id === mine && 'font-semibold')}>{r.name}</span>\n                  <span className=\"text-muted-foreground shrink-0 text-xs\">{(L.size ?? SIZE)(r.size)}</span>\n                </span>\n                <span className=\"text-end text-sm font-semibold tabular-nums\">\n                  <span aria-hidden>{fmt.format(value)}</span>\n                  <span className=\"sr-only\">{(L.points ?? ((n: number, b) => (b === 'average' ? `${n} per player` : `${n} points`)))(value, by)}</span>\n                  {r.gained > 0 ? (\n                    <span className=\"text-muted-foreground ms-1.5 text-xs font-medium\">{(L.gained ?? ((n: number) => `+${n}`))(r.gained)}</span>\n                  ) : null}\n                </span>\n                <span aria-hidden className=\"bg-muted col-span-3 block h-2 overflow-hidden rounded-full\">\n                  <span\n                    data-slot=\"team-scoreboard-bar\"\n                    className={cn(\n                      'block h-full origin-left rounded-full bg-(--team) rtl:origin-right',\n                      reduced ? '' : 'transition-[width] duration-(--duration-slow) ease-enter',\n                    )}\n                    style={{ width: `${top > 0 ? Math.max(2, Math.round((value / top) * 100)) : 0}%` }}\n                  />\n                </span>\n              </li>\n            );\n          })}\n        </ol>\n      ) : (\n        <p data-slot=\"team-scoreboard-empty\" className=\"text-muted-foreground\">\n          {L.empty ?? 'No teams yet.'}\n        </p>\n      )}\n      <span data-slot=\"team-scoreboard-announce\" aria-live=\"polite\" className=\"sr-only\">\n        {announce}\n      </span>\n    </section>\n  );\n}\nTeamScoreboard.displayName = 'TeamScoreboard';\n\n// --- TeamBadge ------------------------------------------------------------------\n\nexport interface TeamBadgeLabels {\n  /** @default (team) => `You are on ${team}` */\n  on?: (team: string) => string;\n  /** @default 'Waiting for a team' */\n  none?: string;\n  /** @default (mark) => `Team ${mark}` */\n  mark?: (mark: string) => string;\n}\n\ntype TeamBadgeProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  room: Pick<RoomState, 'shared' | 'players'> | null;\n  /** The viewer's player id. */\n  selfId: string;\n  labels?: TeamBadgeLabels;\n};\n\nfunction TeamBadge({ room, selfId, labels, className, ...props }: TeamBadgeProps) {\n  const L = labels ?? {};\n  const teams = readTeams(room);\n  const team = teams ? teamOf(teams, selfId) : null;\n  const index = teams && team ? teams.teams.findIndex((t) => t.id === team.id) : 0;\n  return (\n    <div\n      role=\"status\"\n      data-slot=\"team-badge\"\n      data-state={team ? 'team' : 'none'}\n      data-team-id={team?.id}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      style={team ? teamStyle(index) : undefined}\n      className={cn(\n        'bg-card text-card-foreground border-border flex items-center gap-3 rounded-xl border border-s-4 p-4',\n        team ? 'border-s-(--team)' : 'border-dashed',\n        className,\n      )}\n      {...props}\n    >\n      {team ? (\n        <>\n          <span\n            aria-hidden\n            className=\"border-border bg-background grid size-9 shrink-0 place-items-center rounded-full border-2 border-(--team) text-base font-semibold\"\n          >\n            {teamMark(index)}\n          </span>\n          <span className=\"min-w-0 text-lg font-semibold break-words\">{(L.on ?? ((n: string) => `You are on ${n}`))(team.name)}</span>\n        </>\n      ) : (\n        <span className=\"text-muted-foreground\">{L.none ?? 'Waiting for a team'}</span>\n      )}\n    </div>\n  );\n}\nTeamBadge.displayName = 'TeamBadge';\n\nexport { TeamBadge, TeamBoard, TeamScoreboard };\nexport type { TeamBadgeProps, TeamBoardProps, TeamScoreboardProps };\n"
    },
    {
      "path": "registry/interlace-ui/games/group-model.ts",
      "target": "components/ui/games/group-model.ts",
      "type": "registry:ui",
      "content": "export type Random = () => number;\n\n/**\n * A repeatable random source (mulberry32): the same seed gives the same run. For tests, and for a\n * host that wants a split it can reproduce.\n */\nexport function seededRandom(seed: number): Random {\n  let a = seed >>> 0;\n  return () => {\n    a = (a + 0x6d2b79f5) >>> 0;\n    let t = a;\n    t = Math.imul(t ^ (t >>> 15), t | 1);\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\n/** A shuffled copy (Fisher-Yates). A `random` that returns 1 or more is held below 1. */\nexport function shuffled<T>(items: readonly T[], random: Random = Math.random): T[] {\n  const out = items.slice();\n  for (let i = out.length - 1; i > 0; i--) {\n    const j = Math.min(i, Math.floor(random() * (i + 1)));\n    [out[i], out[j]] = [out[j] as T, out[i] as T];\n  }\n  return out;\n}\n\n/**\n * Deals `items` into `groups` piles, first to last then back (1 2 3 3 2 1 …), so when the items\n * are sorted best first every pile gets its share of the best, and no pile is more than one\n * larger than another.\n */\nexport function snakeDeal<T>(items: readonly T[], groups: number): T[][] {\n  const piles: T[][] = Array.from({ length: groups }, () => []);\n  items.forEach((item, i) => {\n    const pos = i % groups;\n    (piles[Math.floor(i / groups) % 2 === 0 ? pos : groups - 1 - pos] as T[]).push(item);\n  });\n  return piles;\n}\n\n/** The index of the smallest size, the first on a tie. -1 for no sizes. */\nexport function smallestIndex(sizes: readonly number[]): number {\n  let best = -1;\n  sizes.forEach((size, i) => {\n    if (best === -1 || size < (sizes[best] as number)) best = i;\n  });\n  return best;\n}\n\n/** Clamps a count to a whole number in [min, max]; NaN falls to `min`. */\nexport function clampCount(value: number, min: number, max: number): number {\n  return Math.min(max, Math.max(min, Math.floor(Number.isFinite(value) ? value : min)));\n}\n\n/** True for a plain JSON object (not null, not an array). */\nexport const isRecord = (v: unknown): v is Record<string, unknown> =>\n  typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/** An id read from untrusted data: a short word of letters, digits, `_` and `-`. */\nexport const isId = (v: unknown): v is string => typeof v === 'string' && /^[\\w-]{1,64}$/.test(v);\n\n/**\n * @interlace/ui — games/group-model\n *\n * The small, pure helpers every way of splitting a room shares (teams, breakout groups, pairs):\n * a shuffle that takes its random source, a fair deal, and a seeded random for tests and replays.\n * Nothing here knows about a room.\n */\n\n/** A float in [0, 1), like `Math.random`. */\n"
    },
    {
      "path": "registry/interlace-ui/games/leaderboard-model.ts",
      "target": "components/ui/games/leaderboard-model.ts",
      "type": "registry:ui",
      "content": "export interface LeaderboardEntry {\n  /** Stable id: a player or a group. */\n  id: string;\n  /** What the board shows. */\n  name: string;\n  score: number;\n  /** Breaks ties on score: lower first (time taken, say). Equal or missing values share a rank. */\n  tiebreak?: number;\n}\n\nexport interface RankedEntry extends LeaderboardEntry {\n  /** 1-based; ties share a rank and the next rank skips (1, 2, 2, 4). */\n  rank: number;\n  /** True when another entry has the same rank. */\n  tied: boolean;\n}\n\nexport interface RankOptions {\n  /** `desc` when a higher score wins. @default 'desc' */\n  order?: 'desc' | 'asc';\n  /** Below this many entries the board is hidden. @default 1 */\n  minPlayers?: number;\n  /** Rows to show from the top. @default all */\n  limit?: number;\n  /** The viewing player's id: their row is kept even outside `limit`. */\n  currentId?: string;\n}\n\nexport interface RankedBoard {\n  /** False while fewer than `minPlayers` have played. */\n  visible: boolean;\n  /** Entries counted. */\n  players: number;\n  /** The top rows, within `limit`. Empty while hidden. */\n  top: RankedEntry[];\n  /** The viewing player's row when it falls outside `top`. */\n  current?: RankedEntry;\n}\n\n/** Rank every entry. */\nexport function rankEntries(entries: readonly LeaderboardEntry[], order: 'desc' | 'asc' = 'desc'): RankedEntry[] {\n  const sign = order === 'desc' ? -1 : 1;\n  // An id counts once: a repeated message must not add a row, and the latest report wins.\n  const sorted = [...new Map(entries.map((e) => [e.id, e])).values()]\n    .sort(\n      (a, b) =>\n        sign * (a.score - b.score) || (a.tiebreak ?? Infinity) - (b.tiebreak ?? Infinity) || a.name.localeCompare(b.name),\n    );\n  const same = (a: LeaderboardEntry, b: LeaderboardEntry) => a.score === b.score && (a.tiebreak ?? null) === (b.tiebreak ?? null);\n  const ranked: RankedEntry[] = [];\n  sorted.forEach((entry, i) => {\n    const prev = sorted[i - 1];\n    const rank = prev && same(prev, entry) ? (ranked[i - 1] as RankedEntry).rank : i + 1;\n    ranked.push({ ...entry, rank, tied: false });\n  });\n  for (let i = 0; i < ranked.length; i++) {\n    const r = ranked[i] as RankedEntry;\n    r.tied = ranked[i - 1]?.rank === r.rank || ranked[i + 1]?.rank === r.rank;\n  }\n  return ranked;\n}\n\n/** The board as a page shows it: hidden below the minimum, top rows, and the viewer's own row. */\nexport function buildBoard(entries: readonly LeaderboardEntry[], options: RankOptions = {}): RankedBoard {\n  const { order = 'desc', minPlayers = 1, limit, currentId } = options;\n  const ranked = rankEntries(entries, order);\n  const players = ranked.length;\n  if (players < Math.max(1, minPlayers)) return { visible: false, players, top: [] };\n  const top = limit === undefined ? ranked : ranked.slice(0, limit);\n  const mine = currentId === undefined ? undefined : ranked.find((e) => e.id === currentId);\n  const current = mine && !top.includes(mine) ? mine : undefined;\n  return { visible: true, players, top, current };\n}\n\n/**\n * @interlace/ui — games/leaderboard-model\n *\n * Ranking for a group's board: ties share a rank (1, 2, 2, 4), the board\n * stays hidden until enough people have played, and the player's own row is\n * found even when it falls outside the top rows. Pure, so the server that\n * stores scores ranks them the same way.\n *\n * ## Why a minimum\n *\n * A board of two people tells each of them exactly what the other scored.\n * `minPlayers` keeps a small group's scores private until there are enough\n * of them to stand in a crowd.\n */\n"
    },
    {
      "path": "registry/interlace-ui/games/room-model.ts",
      "target": "components/ui/games/room-model.ts",
      "type": "registry:ui",
      "content": "import { rankEntries, type RankedEntry } from '@/components/ui/games/leaderboard-model';\n\n/**\n * @interlace/ui — games/room-model\n *\n * The pure core of a live room: one host on a big screen, players on their\n * phones, a join code, a lobby, rounds and a podium. Every client runs the\n * same reducer, so the host's screen and every phone agree on what happens,\n * and a server can replay a room from its events.\n *\n * The host is the authority. Players send intents (join, leave, answer); the\n * host applies them with `applyRoomEvent`, which refuses anything the sender\n * may not do, and sends the new state to everyone. How messages travel is a\n * `RoomTransport`: two functions, so any realtime service fits behind it. The\n * kit ships an in-memory hub (tests, demos, one screen) and a\n * BroadcastChannel transport (tabs on one device); a WebSocket or hosted\n * realtime adapter is a few lines in the app.\n *\n * Time is always a timestamp in ms from the host's clock (`startsAt`,\n * `endsAt`), so a phone that joins late counts down to the same moment.\n */\n\n// --- Join codes -----------------------------------------------------------------\n\n/** Letters and digits no one misreads: no 0/O, 1/I/L, or U/V. */\nexport const JOIN_CODE_ALPHABET = '23456789ABCDEFGHJKMNPQRSTWXYZ';\n\nexport interface JoinCodeOptions {\n  /** @default 6 */\n  length?: number;\n  /** @default JOIN_CODE_ALPHABET. Pass '0123456789' for a numeric PIN. */\n  alphabet?: string;\n}\n\n/**\n * A new join code. Leave `random` out to draw from `crypto.getRandomValues`\n * without bias (rejection sampling on a bit mask); pass a function returning\n * a float in [0, 1) for seeded tests. The alphabet holds at most 256 characters.\n */\nexport function makeJoinCode(options: JoinCodeOptions = {}, random?: () => number): string {\n  const { length = 6, alphabet = JOIN_CODE_ALPHABET } = options;\n  const n = alphabet.length;\n  if (n < 1 || n > 256) throw new RangeError('A join code alphabet holds 1 to 256 characters.');\n  const crypto = (globalThis as { crypto?: Crypto }).crypto;\n  let code = '';\n  if (!random && crypto?.getRandomValues) {\n    const mask = 2 ** Math.ceil(Math.log2(n)) - 1;\n    while (code.length < length) {\n      for (const byte of crypto.getRandomValues(new Uint8Array(length * 2))) {\n        const index = byte & mask;\n        if (index < n && code.length < length) code += alphabet[index];\n      }\n    }\n    return code;\n  }\n  const pick = random ?? Math.random;\n  for (let i = 0; i < length; i++) code += alphabet[Math.min(n - 1, Math.floor(pick() * n))];\n  return code;\n}\n\n/**\n * What someone typed, as a code: upper case, spaces and dashes dropped.\n * Returns null when it has the wrong length or a character outside the\n * alphabet, so the field can say so before anything is sent.\n */\nexport function normalizeJoinCode(input: string, options: JoinCodeOptions = {}): string | null {\n  const { length = 6, alphabet = JOIN_CODE_ALPHABET } = options;\n  const code = input.toUpperCase().replace(/[\\s\\-–—.]/g, '');\n  if (code.length !== length) return null;\n  for (const ch of code) if (!alphabet.includes(ch)) return null;\n  return code;\n}\n\n/** A code in groups for reading aloud and on a big screen: \"K7Q 4MZ\". */\nexport function formatJoinCode(code: string, group = 3): string {\n  if (group <= 0) return code;\n  const parts: string[] = [];\n  for (let i = 0; i < code.length; i += group) parts.push(code.slice(i, i + group));\n  return parts.join(' ');\n}\n\n// --- State ----------------------------------------------------------------------\n\nexport type RoomPhase = 'lobby' | 'countdown' | 'question' | 'reveal' | 'podium' | 'closed';\n\nexport interface RoomPlayer {\n  id: string;\n  name: string;\n  /** False after `leave`; the player keeps their score and can come back. */\n  connected: boolean;\n}\n\nexport interface RoomState {\n  code: string;\n  hostId: string;\n  phase: RoomPhase;\n  /** No new players while locked. Players already in can still reconnect. */\n  locked: boolean;\n  /**\n   * When the join code stops letting new players in, in ms (host clock), or\n   * null for a code that lasts as long as the room. Players already in can\n   * still reconnect after it.\n   */\n  codeExpiresAt: number | null;\n  /** In the order they joined. */\n  players: RoomPlayer[];\n  /** Players the host removed; they cannot join again with the same id. */\n  removed: string[];\n  /** 0 in the lobby, then 1, 2, 3… */\n  round: number;\n  /** How many rounds the game has, when known. */\n  rounds: number | null;\n  /** When the countdown ends, in ms (host clock). */\n  startsAt: number | null;\n  /** When the current question closes, in ms (host clock). null: no clock. */\n  endsAt: number | null;\n  /**\n   * What the current round asks, as the host sent it with `question`: whatever\n   * the game needs (a prompt and its choices, a number to guess). Every phone\n   * and a player who joins late see the same round. null in the lobby.\n   * Keep the answer out of it until `reveal`.\n   */\n  prompt: unknown;\n  /** The round's answer, as the host sent it with `reveal`. null until then. */\n  solution: unknown;\n  /** Total points per player id. */\n  scores: Record<string, number>;\n  /** This round's answers per player id. Cleared when a new round starts. */\n  answers: Record<string, RoomAnswer>;\n  /** Points each player won in the last revealed round. */\n  lastPoints: Record<string, number>;\n  /**\n   * Room-wide extras the host shares with every screen, by name: team assignments, breakout\n   * groups, pairs (see `team-model`, `breakout-model`, `pair-model`). They ride in the room, so\n   * they inherit its guarantees: the newest `seq` wins, a late joiner and a phone that reconnects\n   * get them with the state, and a host that restores the room (`restoreRoom`) restores them.\n   * Written by the host's `share` event; read with `readShared`, which treats them as untrusted.\n   * Absent until the first `share`.\n   */\n  shared?: Record<string, unknown>;\n  /**\n   * The ids of each player's most recent `submit` events, so a message the network delivers twice\n   * (or a player's own resend) is applied once, and a player can see theirs was taken.\n   */\n  acked?: Record<string, string[]>;\n  /** Bumped on every change, so a client keeps only the newest state. */\n  seq: number;\n}\n\nexport interface RoomAnswer {\n  value: unknown;\n  /**\n   * When it reached the host, in ms (host clock). `useRoom` stamps it on\n   * arrival, so a player cannot claim an earlier answer than they gave.\n   */\n  at: number;\n}\n\n/** Why an activity refuses a move. */\nexport type ActivityRefusal = 'not-host' | 'wrong-phase' | 'full' | 'rate-limited' | 'bad-action';\n\nexport interface ActivityContext {\n  /** Who made the move: a player's id, or the host's. */\n  playerId: string;\n  /** True when the host made it. */\n  host: boolean;\n  /** When it arrived, in ms (host clock). */\n  at: number;\n  /** Everyone in the room now. */\n  players: readonly RoomPlayer[];\n}\n\n/**\n * An activity's rule: its slice of `RoomState.shared` (anything, or null before it starts: read it\n * as untrusted), one move, and who made it. Returns the new slice (null removes it) or why not.\n * Pure: the host runs it to decide and again to apply, so it must give the same answer twice.\n */\nexport type ActivityReducer = (\n  slice: unknown,\n  action: unknown,\n  ctx: ActivityContext,\n) => { slice: unknown } | { refuse: ActivityRefusal };\n\nexport interface RoomSettings {\n  /** The activities this room runs, by the key of their slice. */\n  activities?: Record<string, ActivityReducer>;\n  /** The most players the room takes. @default 200 */\n  maxPlayers?: number;\n  /** The longest name, in characters. @default 24 */\n  maxNameLength?: number;\n}\n\nexport function createRoom(init: {\n  code: string;\n  hostId: string;\n  rounds?: number | null;\n  /** When the code stops admitting new players, in ms (host clock). */\n  codeExpiresAt?: number | null;\n}): RoomState {\n  return {\n    code: init.code,\n    hostId: init.hostId,\n    phase: 'lobby',\n    locked: false,\n    codeExpiresAt: init.codeExpiresAt ?? null,\n    players: [],\n    removed: [],\n    round: 0,\n    rounds: init.rounds ?? null,\n    startsAt: null,\n    endsAt: null,\n    prompt: null,\n    solution: null,\n    scores: {},\n    answers: {},\n    lastPoints: {},\n    seq: 0,\n  };\n}\n\n// --- Events ---------------------------------------------------------------------\n\n/** Events a player sends about themselves. */\nexport type RoomPlayerEvent =\n  | {\n      type: 'join';\n      playerId: string;\n      name: string;\n      /**\n       * When the join arrived, in ms. `useRoom` stamps it with the host's clock,\n       * so an expired code cannot be beaten by a phone with its clock set back;\n       * code that calls `applyRoomEvent` directly must stamp it too. While the\n       * room has an expiry, an unstamped new join is refused as `expired`.\n       */\n      at?: number;\n    }\n  | { type: 'leave'; playerId: string }\n  /**\n   * A player's move in an activity that takes input from everyone (a question, a vote, a reaction, a\n   * raised hand, a spot on a line). `key` names the activity (`RoomState.shared[key]`), `action` is\n   * what it takes, and `id` is unique per move: the host applies a move once however often it\n   * arrives. The host may send one too (`playerId` its own id), for what only it may do. Which\n   * moves an activity allows is its reducer's rule (`RoomSettings.activities`).\n   */\n  | {\n      type: 'submit';\n      playerId: string;\n      id: string;\n      key: string;\n      action: unknown;\n      /**\n       * When it arrived, in ms (host clock). `useRoom` stamps it; code that calls `applyRoomEvent`\n       * directly must too. A `submit` without it is refused.\n       */\n      at?: number;\n      /** Send it again until the host's state shows it. @default true. Off for moves that go stale (a reaction). */\n      retry?: boolean;\n    }\n  | {\n      type: 'answer';\n      playerId: string;\n      value: unknown;\n      /**\n       * When the answer arrived. `useRoom` replaces it with the host's clock on\n       * receipt; code that calls `applyRoomEvent` directly must do the same\n       * rather than trust the sender's value.\n       */\n      at: number;\n    };\n\n/** Events only the host sends. */\nexport type RoomHostEvent =\n  | { type: 'lock'; locked: boolean }\n  /** Moves the code's expiry: later to let latecomers in, null for no expiry. */\n  | { type: 'extend-code'; expiresAt: number | null }\n  | { type: 'remove'; playerId: string }\n  /** Starts the countdown to the first round (or the next one). */\n  | { type: 'countdown'; startsAt: number }\n  /** Opens a round. `endsAt` null for no clock. `prompt`: what the round asks (see `RoomState.prompt`). */\n  | { type: 'question'; endsAt: number | null; prompt?: unknown }\n  /** Closes the round and adds each player's points. `solution`: the round's answer, for every screen. */\n  | { type: 'reveal'; points: Record<string, number>; solution?: unknown }\n  | { type: 'podium' }\n  | { type: 'close' }\n  /** Back to the lobby with the same players, scores at zero and the room open again. */\n  | { type: 'restart' }\n  /** Sets one named extra for every screen (`RoomState.shared`); `value` null removes it. */\n  | { type: 'share'; key: string; value: unknown };\n\nexport type RoomEvent = RoomPlayerEvent | RoomHostEvent;\n\nexport type RoomRejection =\n  | 'not-host'\n  | 'not-you'\n  | 'closed'\n  | 'locked'\n  | 'expired'\n  | 'full'\n  | 'removed'\n  | 'name-empty'\n  | 'name-taken'\n  | 'wrong-phase'\n  | 'already-answered'\n  | 'unknown-player'\n  /** A `share` with a key that is not a short lowercase name, or a value that is not JSON or too big. */\n  | 'bad-share'\n  /** A `submit` for an activity this room does not run. */\n  | 'unknown-activity'\n  /** A `submit` the activity cannot take (nonsense, or not allowed now). */\n  | 'bad-action'\n  /** A `submit` with an id the host already applied: said nothing to, never counted twice. */\n  | 'duplicate'\n  /** Too many moves too fast from this player, or from the room. */\n  | 'rate-limited';\n\nconst HOST_EVENTS = new Set<RoomEvent['type']>([\n  'lock',\n  'extend-code',\n  'remove',\n  'countdown',\n  'question',\n  'reveal',\n  'podium',\n  'close',\n  'restart',\n  'share',\n]);\n\n/** Names of `shared` entries: lowercase, digits and dashes, so no key can be `__proto__`. */\nconst SHARE_KEY = /^[a-z][a-z0-9-]{0,31}$/;\n/** The most a room's extras may weigh as JSON, in characters: every state message carries them. */\nexport const MAX_SHARED_SIZE = 60_000;\n\n/** Which phases each host step may follow. */\nconst NEXT: Partial<Record<RoomEvent['type'], readonly RoomPhase[]>> = {\n  countdown: ['lobby', 'reveal'],\n  question: ['countdown', 'reveal'],\n  reveal: ['question'],\n  podium: ['reveal', 'question'],\n  restart: ['podium', 'reveal', 'question', 'countdown', 'lobby'],\n};\n\n/**\n * True when a join at `at` (host clock) comes after the code stopped admitting new players.\n * Fails closed: when the room has an expiry, a join without a finite `at` (missing, NaN, null) counts as expired, so a server\n * that forgets to stamp joins cannot let people in late. Stamp `join.at` with the host clock.\n */\nexport function codeExpired(state: Pick<RoomState, 'codeExpiresAt'>, at: number | undefined): boolean {\n  if (state.codeExpiresAt === null) return false;\n  return !Number.isFinite(at) || (at as number) >= state.codeExpiresAt;\n}\n\n/** A display name, trimmed, inner spaces collapsed, and cut to `max` characters. */\nexport function cleanName(name: string, max = 24): string {\n  return Array.from(name.trim().replace(/\\s+/g, ' ')).slice(0, max).join('').trim();\n}\n\nconst sameName = (a: string, b: string) => a.localeCompare(b, undefined, { sensitivity: 'base' }) === 0;\n\n/** How many ids of a player's `submit` moves the room remembers. */\nexport const ACK_KEEP = 16;\n\ntype SubmitEvent = Extract<RoomEvent, { type: 'submit' }>;\n\n/** What a `submit` would do, or why it may not: the same call decides and applies. */\nfunction runSubmit(\n  state: RoomState,\n  event: SubmitEvent,\n  settings: RoomSettings,\n): { slice: unknown } | { refuse: RoomRejection } {\n  if (event.playerId !== state.hostId && !state.players.some((p) => p.id === event.playerId))\n    return { refuse: 'unknown-player' };\n  if (typeof event.id !== 'string' || !event.id || event.id.length > 64 || !Number.isFinite(event.at))\n    return { refuse: 'bad-action' };\n  if (Object.hasOwn(state.acked ?? {}, event.playerId) && (state.acked as Record<string, string[]>)[event.playerId]!.includes(event.id))\n    return { refuse: 'duplicate' };\n  const reducer = SHARE_KEY.test(event.key) && settings.activities && Object.hasOwn(settings.activities, event.key) ? settings.activities[event.key] : undefined;\n  if (!reducer) return { refuse: 'unknown-activity' };\n  const slice = state.shared && Object.hasOwn(state.shared, event.key) ? state.shared[event.key] : null;\n  let result: ReturnType<ActivityReducer>;\n  try {\n    result = reducer(slice, event.action, { playerId: event.playerId, host: event.playerId === state.hostId, at: event.at as number, players: state.players });\n  } catch {\n    return { refuse: 'bad-action' };\n  }\n  if ('refuse' in result) return result;\n  const json = JSON.stringify(result.slice ?? null);\n  return json === undefined || json.length > MAX_SHARED_SIZE ? { refuse: 'full' } : result;\n}\n\nfunction rejectSubmit(state: RoomState, event: SubmitEvent, settings: RoomSettings): RoomRejection | null {\n  const result = runSubmit(state, event, settings);\n  return 'refuse' in result ? result.refuse : null;\n}\n\n/**\n * Why `from` may not apply `event` to `state`, or null when they may. The\n * host's own id may send any event; a player may send only their own.\n */\nexport function rejectRoomEvent(\n  state: RoomState,\n  event: RoomEvent,\n  from: string,\n  settings: RoomSettings = {},\n): RoomRejection | null {\n  const isHost = from === state.hostId;\n  if (HOST_EVENTS.has(event.type)) {\n    if (!isHost) return 'not-host';\n  } else if (!isHost && (event as RoomPlayerEvent).playerId !== from) {\n    return 'not-you';\n  }\n  if (state.phase === 'closed') return 'closed';\n\n  const allowed = NEXT[event.type];\n  if (allowed && !allowed.includes(state.phase)) return 'wrong-phase';\n\n  switch (event.type) {\n    case 'join': {\n      if (state.removed.includes(event.playerId)) return 'removed';\n      const name = cleanName(event.name, settings.maxNameLength);\n      if (!name) return 'name-empty';\n      const known = state.players.find((p) => p.id === event.playerId);\n      if (state.players.some((p) => p.id !== event.playerId && sameName(p.name, name))) return 'name-taken';\n      if (known) return null; // a reconnect, even when locked\n      if (state.locked) return 'locked';\n      if (codeExpired(state, event.at)) return 'expired';\n      if (state.players.length >= (settings.maxPlayers ?? 200)) return 'full';\n      return null;\n    }\n    case 'leave':\n      return state.players.some((p) => p.id === event.playerId) ? null : 'unknown-player';\n    case 'answer':\n      if (state.phase !== 'question') return 'wrong-phase';\n      if (!state.players.some((p) => p.id === event.playerId)) return 'unknown-player';\n      if (Object.hasOwn(state.answers, event.playerId)) return 'already-answered';\n      return null;\n    case 'remove':\n      return state.players.some((p) => p.id === event.playerId) ? null : 'unknown-player';\n    case 'submit':\n      return rejectSubmit(state, event, settings);\n    case 'share': {\n      if (!SHARE_KEY.test(event.key)) return 'bad-share';\n      const json = JSON.stringify(event.value);\n      return json === undefined || json.length > MAX_SHARED_SIZE ? 'bad-share' : null;\n    }\n    default:\n      return null;\n  }\n}\n\n/**\n * The room after `event` from `from`. Returns the same object when the\n * event is refused (see `rejectRoomEvent`), so `next === state` means\n * nothing happened.\n */\nexport function applyRoomEvent(\n  state: RoomState,\n  event: RoomEvent,\n  from: string,\n  settings: RoomSettings = {},\n): RoomState {\n  if (rejectRoomEvent(state, event, from, settings)) return state;\n  const next = (patch: Partial<RoomState>): RoomState => ({\n    ...state,\n    ...patch,\n    seq: state.seq + 1,\n  });\n\n  switch (event.type) {\n    case 'join': {\n      const name = cleanName(event.name, settings.maxNameLength);\n      const known = state.players.some((p) => p.id === event.playerId);\n      return next({\n        players: known\n          ? state.players.map((p) => (p.id === event.playerId ? { ...p, name, connected: true } : p))\n          : [...state.players, { id: event.playerId, name, connected: true }],\n        scores: known ? state.scores : { ...state.scores, [event.playerId]: 0 },\n      });\n    }\n    case 'leave':\n      return next({\n        players: state.players.map((p) => (p.id === event.playerId ? { ...p, connected: false } : p)),\n      });\n    case 'answer':\n      return next({\n        answers: {\n          ...state.answers,\n          [event.playerId]: { value: event.value, at: event.at },\n        },\n      });\n    case 'lock':\n      return next({ locked: event.locked });\n    case 'extend-code':\n      return next({ codeExpiresAt: event.expiresAt });\n    case 'remove': {\n      const { [event.playerId]: _score, ...scores } = state.scores;\n      const { [event.playerId]: _answer, ...answers } = state.answers;\n      const { [event.playerId]: _acks, ...acked } = state.acked ?? {};\n      return next({\n        acked,\n        players: state.players.filter((p) => p.id !== event.playerId),\n        removed: [...state.removed, event.playerId],\n        scores,\n        answers,\n      });\n    }\n    case 'countdown':\n      return next({\n        phase: 'countdown',\n        startsAt: event.startsAt,\n        endsAt: null,\n      });\n    case 'question':\n      return next({\n        phase: 'question',\n        round: state.round + 1,\n        endsAt: event.endsAt,\n        prompt: event.prompt ?? null,\n        solution: null,\n        answers: {},\n        lastPoints: {},\n      });\n    case 'reveal': {\n      // Own keys only, and `fromEntries` below: an id of `__proto__` is data, not the prototype setter.\n      const won = (id: string) => (Object.hasOwn(event.points, id) && Number.isFinite(event.points[id]) ? event.points[id]! : 0);\n      const lastPoints: Record<string, number> = Object.fromEntries(state.players.map((p) => [p.id, won(p.id)]));\n      const scores: Record<string, number> = Object.fromEntries([\n        ...Object.entries(state.scores),\n        ...state.players.map((p) => [p.id, (Object.hasOwn(state.scores, p.id) ? state.scores[p.id]! : 0) + won(p.id)] as const),\n      ]);\n      return next({ phase: 'reveal', scores, lastPoints, endsAt: null, solution: event.solution ?? null });\n    }\n    case 'podium':\n      return next({ phase: 'podium', endsAt: null });\n    case 'close':\n      return next({\n        phase: 'closed',\n        locked: true,\n        startsAt: null,\n        endsAt: null,\n      });\n    case 'submit': {\n      const result = runSubmit(state, event, settings) as { slice: unknown };\n      const { [event.key]: _old, ...rest } = state.shared ?? {};\n      const mine = Object.hasOwn(state.acked ?? {}, event.playerId) ? (state.acked as Record<string, string[]>)[event.playerId]! : [];\n      return next({\n        shared: result.slice === null ? rest : { ...rest, [event.key]: result.slice },\n        acked: { ...state.acked, [event.playerId]: [...mine, event.id].slice(-ACK_KEEP) },\n      });\n    }\n    case 'share': {\n      const { [event.key]: _old, ...rest } = state.shared ?? {};\n      return next({ shared: event.value === null ? rest : { ...rest, [event.key]: event.value } });\n    }\n    case 'restart':\n      return next({\n        phase: 'lobby',\n        locked: false,\n        round: 0,\n        startsAt: null,\n        endsAt: null,\n        prompt: null,\n        solution: null,\n        answers: {},\n        lastPoints: {},\n        scores: Object.fromEntries(state.players.map((p) => [p.id, 0])),\n      });\n  }\n}\n\n// --- Guessing codes -------------------------------------------------------------\n\n/*\n * Stops people guessing their way into a room. Every wrong code counts\n * against where it came from (a network, a device, whatever key your server\n * trusts) and against the room as a whole; past either limit, more tries are\n * refused until the window moves on. A six-character code from\n * `makeJoinCode` has about 600 million values, so five tries per source and\n * thirty per room leave a guesser nowhere, while a person who mistyped twice\n * is never stopped. Pure and serialisable: keep the state wherever the code\n * is checked (a server, an edge function, the host), call `checkJoinAttempt`\n * before comparing the code and `recordJoinAttempt` after.\n */\n\nexport interface JoinGuardOptions {\n  /** Wrong tries one source may make in the window. @default 5 */\n  perSource?: number;\n  /** Wrong tries the whole room accepts in the window, across sources. @default 30 */\n  total?: number;\n  /** How far back wrong tries count, in ms. @default 10 minutes */\n  windowMs?: number;\n}\n\nexport interface JoinGuardState {\n  /** Wrong tries, oldest first. */\n  failures: { source: string; at: number }[];\n}\n\nexport type JoinGuardVerdict =\n  | { allowed: true; left: number }\n  | {\n      allowed: false;\n      /** `source`: this source used its tries. `room`: the room stopped taking guesses. */\n      reason: 'source' | 'room';\n      /** When the oldest counted try leaves the window and one more is allowed, in ms. */\n      retryAt: number;\n    };\n\nconst DEFAULTS = { perSource: 5, total: 30, windowMs: 10 * 60_000 };\n\nconst settings = (o: JoinGuardOptions) => ({\n  perSource: Math.max(1, Math.floor(o.perSource ?? DEFAULTS.perSource)),\n  total: Math.max(1, Math.floor(o.total ?? DEFAULTS.total)),\n  windowMs: Math.max(1, o.windowMs ?? DEFAULTS.windowMs),\n});\n\nexport function createJoinGuard(): JoinGuardState {\n  return { failures: [] };\n}\n\n/** Drops wrong tries older than the window. */\nexport function pruneJoinGuard(state: JoinGuardState, now: number, options: JoinGuardOptions = {}): JoinGuardState {\n  const { windowMs } = settings(options);\n  const failures = state.failures.filter((f) => now - f.at < windowMs);\n  return failures.length === state.failures.length ? state : { failures };\n}\n\n/** May `source` try a code now? Ask before comparing the code, so a blocked source learns nothing. */\nexport function checkJoinAttempt(\n  state: JoinGuardState,\n  source: string,\n  now: number,\n  options: JoinGuardOptions = {},\n): JoinGuardVerdict {\n  const { perSource, total, windowMs } = settings(options);\n  const recent = pruneJoinGuard(state, now, options).failures;\n  const mine = recent.filter((f) => f.source === source);\n  if (recent.length >= total) {\n    return { allowed: false, reason: 'room', retryAt: recent[recent.length - total]!.at + windowMs };\n  }\n  if (mine.length >= perSource) {\n    return { allowed: false, reason: 'source', retryAt: mine[mine.length - perSource]!.at + windowMs };\n  }\n  return { allowed: true, left: Math.min(perSource - mine.length, total - recent.length) };\n}\n\n/** The guard after a try: a wrong code is counted, a right one changes nothing. */\nexport function recordJoinAttempt(\n  state: JoinGuardState,\n  source: string,\n  correct: boolean,\n  now: number,\n  options: JoinGuardOptions = {},\n): JoinGuardState {\n  const pruned = pruneJoinGuard(state, now, options);\n  return correct ? pruned : { failures: [...pruned.failures, { source, at: now }] };\n}\n\n// --- Reading the state ----------------------------------------------------------\n\n/**\n * How far the host's clock is ahead of this one, in ms, from `{ at, local }` pairs: the host's\n * send time and this client's receive time. A message can only arrive after it was sent, so each\n * `at - local` is a lower bound on the true offset and the largest is the closest. Pass the recent\n * samples only, so a host whose clock is reset is followed. 0 with no samples.\n */\nexport function clockOffset(samples: readonly { at: number; local: number }[]): number {\n  let best = -Infinity;\n  for (const s of samples) if (Number.isFinite(s.at) && Number.isFinite(s.local)) best = Math.max(best, s.at - s.local);\n  return best === -Infinity ? 0 : best;\n}\n\n/** Players still connected. */\nexport function connectedPlayers(state: RoomState): RoomPlayer[] {\n  return state.players.filter((p) => p.connected);\n}\n\n/** How many connected players have answered this round, of how many. */\nexport function answerProgress(state: RoomState): {\n  answered: number;\n  total: number;\n} {\n  const live = connectedPlayers(state);\n  return {\n    answered: live.filter((p) => Object.hasOwn(state.answers, p.id)).length,\n    total: live.length,\n  };\n}\n\n/** Everyone in the room by score, ties sharing a rank (the leaderboard's ranking). */\nexport function roomStandings(state: RoomState): RankedEntry[] {\n  return rankEntries(\n    state.players.map((p) => ({\n      id: p.id,\n      name: p.name,\n      score: state.scores[p.id] ?? 0,\n    })),\n  );\n}\n\n/**\n * One named extra from `RoomState.shared`, read as untrusted: `decode` gets whatever is there\n * (anything, from an older version of the app or a bad client) and returns the value or null.\n * Null too when it is absent, or when `decode` throws, so a screen shows \"nothing set\" rather\n * than breaking.\n */\nexport function readShared<T>(\n  state: Pick<RoomState, 'shared'> | null | undefined,\n  key: string,\n  decode: (raw: unknown) => T | null,\n): T | null {\n  const shared = state?.shared;\n  if (!shared || !Object.hasOwn(shared, key)) return null;\n  try {\n    return decode(shared[key]);\n  } catch {\n    return null;\n  }\n}\n\n// --- Keeping a room across a refresh -------------------------------------------------\n\n/**\n * How far `restoreRoom` moves `seq` ahead. A host that restores a save written just before its\n * last few changes would otherwise send states the phones already hold newer ones of, and every\n * phone would ignore them.\n */\nexport const RESTORE_SEQ_JUMP = 1_000;\n\nconst PHASES: readonly RoomPhase[] = ['lobby', 'countdown', 'question', 'reveal', 'podium', 'closed'];\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\nconst isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);\nconst nullableNum = (v: unknown): number | null | undefined => (v === null ? null : isNum(v) ? v : undefined);\nconst isCount = (v: unknown): v is number => isNum(v) && Number.isInteger(v) && v >= 0;\n\n/** A record read from JSON, as plain own properties (a `__proto__` key stays data), values checked. */\nfunction cleanRecord<T>(raw: unknown, ok: (v: unknown) => T | undefined): Record<string, T> {\n  const out: [string, T][] = [];\n  if (isRecord(raw)) {\n    for (const [k, v] of Object.entries(raw)) {\n      const value = ok(v);\n      if (value !== undefined) out.push([k, value]);\n    }\n  }\n  return Object.fromEntries(out);\n}\n\n/** The room as text, to keep in `localStorage` or on a server, so a host that refreshes can go on. */\nexport function serializeRoom(state: RoomState): string {\n  return JSON.stringify(state);\n}\n\n/**\n * The room from text written by `serializeRoom`, or null when it is not one (absent, damaged, from\n * another host). Everything is checked and rebuilt, never trusted. Nobody is known to be here yet:\n * each player comes back `away`, and a phone that is still open says so by itself (it sees itself\n * away and joins again), so the host never shows someone present who left while it was down.\n * Scores, answers, rounds, clocks and the room's extras are kept, and `seq` moves ahead by\n * `RESTORE_SEQ_JUMP` so phones take the restored state as the newest.\n *\n * Pass `hostId` to refuse a room saved by someone else.\n */\nexport function restoreRoom(text: string | null | undefined, options: { hostId?: string } = {}): RoomState | null {\n  if (!text) return null;\n  let raw: unknown;\n  try {\n    raw = JSON.parse(text);\n  } catch {\n    return null;\n  }\n  if (!isRecord(raw)) return null;\n  const { code, hostId, phase, players, seq, round } = raw;\n  if (typeof code !== 'string' || !code || typeof hostId !== 'string' || !hostId) return null;\n  if (options.hostId !== undefined && hostId !== options.hostId) return null;\n  if (!PHASES.includes(phase as RoomPhase) || !Array.isArray(players) || !isCount(seq) || !isCount(round)) return null;\n  const seen = new Set<string>();\n  const kept: RoomPlayer[] = [];\n  for (const p of players) {\n    if (!isRecord(p) || typeof p.id !== 'string' || typeof p.name !== 'string') return null;\n    if (seen.has(p.id)) continue;\n    seen.add(p.id);\n    kept.push({ id: p.id, name: p.name, connected: false });\n  }\n  const rounds = raw.rounds === null || raw.rounds === undefined ? null : isCount(raw.rounds) ? raw.rounds : undefined;\n  const startsAt = nullableNum(raw.startsAt ?? null);\n  const endsAt = nullableNum(raw.endsAt ?? null);\n  const codeExpiresAt = nullableNum(raw.codeExpiresAt ?? null);\n  if (rounds === undefined || startsAt === undefined || endsAt === undefined || codeExpiresAt === undefined) return null;\n  const num = (v: unknown) => (isNum(v) ? v : undefined);\n  const answer = (v: unknown) => (isRecord(v) && isNum(v.at) ? { value: v.value, at: v.at } : undefined);\n  const state: RoomState = {\n    code,\n    hostId,\n    phase: phase as RoomPhase,\n    locked: raw.locked === true,\n    codeExpiresAt,\n    players: kept,\n    removed: Array.isArray(raw.removed) ? raw.removed.filter((id): id is string => typeof id === 'string') : [],\n    round,\n    rounds,\n    startsAt,\n    endsAt,\n    prompt: raw.prompt ?? null,\n    solution: raw.solution ?? null,\n    scores: cleanRecord(raw.scores, num),\n    answers: cleanRecord(raw.answers, answer),\n    lastPoints: cleanRecord(raw.lastPoints, num),\n    seq: seq + RESTORE_SEQ_JUMP,\n  };\n  const acked = cleanRecord(raw.acked, (v) =>\n    Array.isArray(v) ? v.filter((id): id is string => typeof id === 'string' && id.length > 0 && id.length <= 64).slice(-ACK_KEEP) : undefined,\n  );\n  if (Object.keys(acked).length) state.acked = acked;\n  if (isRecord(raw.shared)) state.shared = Object.fromEntries(Object.entries(raw.shared).filter(([k]) => SHARE_KEY.test(k)));\n  return state;\n}\n\n/** Where a host keeps its room between page loads. `Storage` fits (`localStorage`, `sessionStorage`). */\nexport interface RoomStorage {\n  getItem(key: string): string | null;\n  setItem(key: string, value: string): void;\n  removeItem(key: string): void;\n}\n\n/**\n * A room kept in `storage` under `key`. Storage that is missing, full or blocked (a private window,\n * a storage-less embed) never throws: `load` finds nothing and `save` does nothing, and the room\n * carries on in memory. Call `save` after every change, `clear` when the game ends.\n */\nexport function createRoomStore(\n  storage: RoomStorage | null | undefined,\n  key: string,\n  options: { hostId?: string } = {},\n): { load(): RoomState | null; save(state: RoomState): void; clear(): void } {\n  return {\n    load() {\n      try {\n        return restoreRoom(storage?.getItem(key), options);\n      } catch {\n        return null;\n      }\n    },\n    save(state) {\n      try {\n        storage?.setItem(key, serializeRoom(state));\n      } catch {\n        /* a full or blocked store must not stop the game */\n      }\n    },\n    clear() {\n      try {\n        storage?.removeItem(key);\n      } catch {\n        /* nothing to clear */\n      }\n    },\n  };\n}\n\n// --- Transport ------------------------------------------------------------------\n\n/** What travels between the host and the players. */\nexport type RoomMessage =\n  /** A player asks the host to apply an event. */\n  | { kind: 'intent'; from: string; event: RoomEvent }\n  /** The host's room, after every change. */\n  | {\n      kind: 'state';\n      state: RoomState;\n      /** The host's clock when it sent this, in ms. Phones use it to read deadlines on the host's time. */\n      at?: number;\n    }\n  /** A client that just arrived asks for the current state. */\n  | { kind: 'hello'; from: string }\n  /** The host refused a player's intent, and why. */\n  | {\n      kind: 'rejected';\n      to: string;\n      event: RoomEvent['type'];\n      reason: RoomRejection;\n      /** For a refused `submit`: its id, so the player stops sending that move. */\n      id?: string;\n    };\n\n/**\n * How a room talks. `send` reaches every other client in the room (not the\n * sender); `subscribe` returns an unsubscribe. Wrap any realtime service in\n * these two functions.\n */\nexport interface RoomTransport<M = RoomMessage> {\n  send(message: M): void;\n  subscribe(listener: (message: M) => void): () => void;\n  /** Optional: release the connection. */\n  close?(): void;\n}\n\n/**\n * An in-memory room: every `connect()` is a client, and messages arrive on\n * the next microtask, like a network would deliver them. For tests, demos\n * and a host and players on one screen.\n */\nexport function createMemoryRoomHub<M = RoomMessage>(): { connect(): RoomTransport<M> } {\n  const clients = new Set<(message: M) => void>();\n  return {\n    connect() {\n      const own = new Set<(message: M) => void>();\n      const deliver = (message: M) => own.forEach((l) => l(message));\n      clients.add(deliver);\n      return {\n        send(message) {\n          const copy = JSON.parse(JSON.stringify(message)) as M;\n          queueMicrotask(() => clients.forEach((c) => c !== deliver && c(copy)));\n        },\n        subscribe(listener) {\n          own.add(listener);\n          return () => own.delete(listener);\n        },\n        close() {\n          clients.delete(deliver);\n          own.clear();\n        },\n      };\n    },\n  };\n}\n\n/**\n * A transport over `BroadcastChannel`: every tab of the same site on this\n * device that opens the same `name` is in the room. Null where the browser\n * has no BroadcastChannel.\n */\nexport function createBroadcastRoomTransport<M = RoomMessage>(name: string): RoomTransport<M> | null {\n  if (typeof BroadcastChannel === 'undefined') return null;\n  const channel = new BroadcastChannel(name);\n  return {\n    send: (message) => channel.postMessage(message),\n    subscribe(listener) {\n      const handle = (e: MessageEvent<M>) => listener(e.data);\n      channel.addEventListener('message', handle);\n      return () => channel.removeEventListener('message', handle);\n    },\n    close: () => channel.close(),\n  };\n}\n"
    },
    {
      "path": "registry/interlace-ui/games/team-model.ts",
      "target": "components/ui/games/team-model.ts",
      "type": "registry:ui",
      "content": "import { cleanName, readShared, rejectRoomEvent, type RoomHostEvent, type RoomPlayer, type RoomState } from '@/components/ui/games/room-model';\n\n/**\n * @interlace/ui — games/team-model\n *\n * Teams for a live room: who is on which team, a fair automatic split, a move by hand, and each\n * team's score from the room's own player scores. Pure, so the host and a server run the same\n * rules.\n *\n * The teams live in the room (`RoomState.shared.teams`, written with a `share` event), so a phone\n * that joins late or reconnects gets them with the room state, the newest `seq` wins whatever\n * order messages arrive in, and a host that restores the room restores its teams. Everything\n * read back goes through `readTeams`, which treats the data as untrusted and drops anyone who is\n * no longer in the room.\n *\n * A team's colour is its place in the list: `teamColor(i)` is a `--team-N` token (five of them; a\n * sixth team reuses the first colour), and `teamMark(i)` is the letter that goes with it, so\n * colour is never the only way to tell teams apart.\n */\n\nimport { rankEntries } from '@/components/ui/games/leaderboard-model';\nimport { clampCount, isId, isRecord, shuffled, snakeDeal, smallestIndex, type Random } from '@/components/ui/games/group-model';\n\n/** The key in `RoomState.shared`. */\nexport const TEAMS_KEY = 'teams';\n/** The most teams a room has. */\nexport const MAX_TEAMS = 12;\n/** How many `--team-N` colour tokens there are. */\nexport const TEAM_COLORS = 5;\nconst MAX_NAME = 24;\n\nexport interface Team {\n  /** `t1`, `t2`, … Stable: renaming a team or adding one never changes another's id. */\n  id: string;\n  name: string;\n}\n\nexport interface TeamsState {\n  /** In order. A team's colour and mark come from its place. */\n  teams: Team[];\n  /** Team id per player id. A player with no entry is not on a team yet. */\n  members: Record<string, string>;\n}\n\n/** `count` empty teams (2 to `MAX_TEAMS`), named from `names`, then \"Team 3\", \"Team 4\"… */\nexport function createTeams(count: number, names: readonly string[] = []): TeamsState {\n  const n = clampCount(count, 2, MAX_TEAMS);\n  return {\n    teams: Array.from({ length: n }, (_, i) => ({\n      id: `t${i + 1}`,\n      name: cleanName(names[i] ?? '', MAX_NAME) || `Team ${i + 1}`,\n    })),\n    members: {},\n  };\n}\n\n/** Teams from untrusted data (a `share` value), or null when it is not teams. */\nexport function decodeTeams(raw: unknown): TeamsState | null {\n  if (!isRecord(raw) || !Array.isArray(raw.teams)) return null;\n  if (raw.teams.length < 2 || raw.teams.length > MAX_TEAMS) return null;\n  const teams: Team[] = [];\n  for (const t of raw.teams) {\n    if (!isRecord(t) || !isId(t.id) || typeof t.name !== 'string') return null;\n    if (teams.some((x) => x.id === t.id)) return null;\n    teams.push({ id: t.id, name: cleanName(t.name, MAX_NAME) || `Team ${teams.length + 1}` });\n  }\n  const members = Object.entries(isRecord(raw.members) ? raw.members : {}).filter(\n    ([id, team]) => id !== '__proto__' && typeof team === 'string' && teams.some((t) => t.id === team),\n  ) as [string, string][];\n  return { teams, members: Object.fromEntries(members) };\n}\n\n/** The room's teams, with anyone no longer in the room dropped; null when none are set. */\nexport function readTeams(room: Pick<RoomState, 'shared' | 'players'> | null | undefined): TeamsState | null {\n  const teams = readShared(room, TEAMS_KEY, decodeTeams);\n  if (!teams || !room) return teams;\n  const here = new Set(room.players.map((p) => p.id));\n  return { ...teams, members: Object.fromEntries(Object.entries(teams.members).filter(([id]) => here.has(id))) };\n}\n\n/** The host event that sets the teams for every screen, or clears them with null. */\nexport function teamsEvent(teams: TeamsState | null): RoomHostEvent {\n  return { type: 'share', key: TEAMS_KEY, value: teams };\n}\n\n/** Whether the room would take these teams (the size limit on `shared` is the only way not). */\nexport function teamsFit(room: RoomState, teams: TeamsState): boolean {\n  return rejectRoomEvent(room, teamsEvent(teams), room.hostId) === null;\n}\n\n/** The index of a team in the list, or -1. Its colour and mark come from it. */\nexport function teamIndex(teams: TeamsState, teamId: string): number {\n  return teams.teams.findIndex((t) => t.id === teamId);\n}\n\n/** The team a player is on, or null. */\nexport function teamOf(teams: TeamsState, playerId: string): Team | null {\n  const id = Object.hasOwn(teams.members, playerId) ? teams.members[playerId] : undefined;\n  return teams.teams.find((t) => t.id === id) ?? null;\n}\n\n/** A team's players, in the order they joined the room. */\nexport function membersOf(teams: TeamsState, teamId: string, players: readonly RoomPlayer[]): RoomPlayer[] {\n  return players.filter((p) => Object.hasOwn(teams.members, p.id) && teams.members[p.id] === teamId);\n}\n\n/** Players on no team yet, in the order they joined. */\nexport function unassigned(teams: TeamsState, players: readonly RoomPlayer[]): RoomPlayer[] {\n  return players.filter((p) => !teamOf(teams, p.id));\n}\n\n/** The `var()` of a team's colour token: `var(--team-1)` … `var(--team-5)`, then round again. */\nexport function teamColor(index: number): string {\n  return `var(--team-${(Math.max(0, index) % TEAM_COLORS) + 1})`;\n}\n\n/** The letter that goes with a team's colour: A, B, C … (it repeats after Z, which no room reaches). */\nexport function teamMark(index: number): string {\n  return String.fromCharCode(65 + (Math.max(0, index) % 26));\n}\n\n/** Moves a player to a team, or off every team with null. The same object when nothing changes. */\nexport function moveToTeam(teams: TeamsState, playerId: string, teamId: string | null): TeamsState {\n  const now = teamOf(teams, playerId)?.id ?? null;\n  if (teamId === now) return teams;\n  if (teamId === null) {\n    const { [playerId]: _gone, ...members } = teams.members;\n    return { ...teams, members };\n  }\n  if (!teams.teams.some((t) => t.id === teamId)) return teams;\n  return { ...teams, members: { ...teams.members, [playerId]: teamId } };\n}\n\n/** Renames a team. The same object when the name is empty, unknown or unchanged. */\nexport function renameTeam(teams: TeamsState, teamId: string, name: string): TeamsState {\n  const clean = cleanName(name, MAX_NAME);\n  const team = teams.teams.find((t) => t.id === teamId);\n  if (!team || !clean || team.name === clean) return teams;\n  return { ...teams, teams: teams.teams.map((t) => (t === team ? { ...t, name: clean } : t)) };\n}\n\n/**\n * Changes the number of teams (2 to `MAX_TEAMS`). New teams are empty; the players of a team that\n * goes become unassigned (`placeNewcomers` or `autoBalance` then places them).\n */\nexport function resizeTeams(teams: TeamsState, count: number): TeamsState {\n  const n = clampCount(count, 2, MAX_TEAMS);\n  if (n === teams.teams.length) return teams;\n  const kept = teams.teams.slice(0, n);\n  const added = Array.from({ length: Math.max(0, n - kept.length) }, (_, i) => {\n    const place = kept.length + i + 1;\n    return { id: `t${nextNumber(teams.teams, place)}`, name: `Team ${place}` };\n  });\n  const all = [...kept, ...added];\n  return {\n    teams: all,\n    members: Object.fromEntries(Object.entries(teams.members).filter(([, id]) => all.some((t) => t.id === id))),\n  };\n}\n\n/** The lowest `tN` number at or above `from` that no team uses (a removed team's number is free again). */\nfunction nextNumber(teams: readonly Team[], from: number): number {\n  let n = from;\n  while (teams.some((t) => t.id === `t${n}`)) n++;\n  return n;\n}\n\n/** How many of `players` are on each team, in team order. */\nfunction sizes(teams: TeamsState, players: readonly RoomPlayer[]): number[] {\n  return teams.teams.map((t) => membersOf(teams, t.id, players).length);\n}\n\n/**\n * Puts every player with no team on the smallest one (the first on a tie), one by one. Call it\n * when someone joins late. The same object when everyone already has a team.\n */\nexport function placeNewcomers(teams: TeamsState, players: readonly RoomPlayer[]): TeamsState {\n  const loose = unassigned(teams, players);\n  if (!loose.length) return teams;\n  const count = sizes(teams, players);\n  const members = { ...teams.members };\n  for (const p of loose) {\n    const at = smallestIndex(count);\n    members[p.id] = (teams.teams[at] as Team).id;\n    count[at] = (count[at] as number) + 1;\n  }\n  return { ...teams, members };\n}\n\nexport interface BalanceOptions {\n  /** Points so far per player id. Strong players are spread across teams instead of piling onto one. */\n  scores?: Record<string, number>;\n  /** @default Math.random. Pass `seededRandom(n)` for a split you can repeat. */\n  random?: Random;\n}\n\n/**\n * Splits every player across the teams so sizes differ by at most one. Players are shuffled, then\n * ordered by score (best first) and dealt 1 2 3 3 2 1 …, so with scores the teams start level and\n * without them it is a fair random split. Everyone is placed again, whoever was where.\n */\nexport function autoBalance(teams: TeamsState, players: readonly RoomPlayer[], options: BalanceOptions = {}): TeamsState {\n  const { scores = {}, random } = options;\n  const score = (id: string) => (Object.hasOwn(scores, id) && Number.isFinite(scores[id]) ? (scores[id] as number) : 0);\n  const order = shuffled(players, random)\n    .sort((a, b) => score(b.id) - score(a.id))\n    .map((p) => p.id);\n  const piles = snakeDeal(order, teams.teams.length);\n  const members: Record<string, string> = {};\n  piles.forEach((ids, i) => ids.forEach((id) => (members[id] = (teams.teams[i] as Team).id)));\n  return { ...teams, members };\n}\n\nexport interface TeamStanding {\n  id: string;\n  name: string;\n  /** The team's place in the list: its colour and mark. */\n  index: number;\n  /** 1-based; ties share a rank. */\n  rank: number;\n  tied: boolean;\n  /** Players on the team. */\n  size: number;\n  /** The players' points added up. */\n  total: number;\n  /** `total` per player, to one decimal; 0 for an empty team. */\n  average: number;\n  /** Points the team's players won in the last revealed round. */\n  gained: number;\n}\n\n/**\n * Each team's score from the room's player scores, best first. `by` decides what ranks:\n * `average` (default) is fair when teams differ in size by one; `total` rewards a bigger team.\n */\nexport function teamStandings(\n  teams: TeamsState,\n  room: Pick<RoomState, 'players' | 'scores' | 'lastPoints'>,\n  by: 'average' | 'total' = 'average',\n): TeamStanding[] {\n  const sum = (ids: RoomPlayer[], from: Record<string, number>) =>\n    ids.reduce((acc, p) => acc + (Object.hasOwn(from, p.id) ? (from[p.id] as number) : 0), 0);\n  const rows = teams.teams.map((t, index) => {\n    const people = membersOf(teams, t.id, room.players);\n    const total = sum(people, room.scores);\n    const average = people.length ? Math.round((total / people.length) * 10) / 10 : 0;\n    return { id: t.id, name: t.name, index, size: people.length, total, average, gained: sum(people, room.lastPoints) };\n  });\n  const ranked = rankEntries(rows.map((r) => ({ id: r.id, name: r.name, score: by === 'total' ? r.total : r.average })));\n  return ranked.map((r) => ({\n    ...(rows.find((x) => x.id === r.id) as (typeof rows)[number]),\n    rank: r.rank,\n    tied: r.tied,\n  }));\n}\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.5.1",
    "since": "2.0.0"
  },
  "docs": "## @interlace/team-board\n\nInstalled to `components/ui/games/team-board.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/team-board';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/team-board\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
