{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "live-room",
  "type": "registry:ui",
  "title": "Live Room",
  "description": "A game night on one big screen and everyone's phones. The host opens a room and shows its JoinCode; players scan or type it and land in the lobby; the host starts, everyone sees the same countdown, plays the same rounds, and the night ends on a Podium. The…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "games",
    "game"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "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/motion-token.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/live-room.tsx",
      "target": "components/ui/games/live-room.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/live-room v1.6.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/live-room\n// What changed since: https://ds.interlace.tools/c/live-room#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — LiveRoom: useRoom and the LiveRoom flow (Lobby, Countdown, HostControls)\n *\n * A game night on one big screen and everyone's phones. The host opens a\n * room and shows its JoinCode; players scan or type it and land in the\n * lobby; the host starts, everyone sees the same countdown, plays the same\n * rounds, and the night ends on a Podium. The rules of the room live in\n * `room-model.ts` (pure), and the network is whatever `RoomTransport` the\n * app passes, so no realtime vendor is built in.\n *\n * ## Flow\n *\n * A flow (docs/philosophies/FLOW_PHILOSOPHY.md): one namespace, `LiveRoom`,\n * and the app holds the room through `useRoom`. Every phase of\n * `RoomPhase`, the part that shows it, and what moves it on:\n *\n * | Phase     | Host screen                                 | Player phone         | Leaves by (event)                        |\n * | --------- | ------------------------------------------- | -------------------- | ---------------------------------------- |\n * | lobby     | LiveRoom.Lobby with JoinCode                | LiveRoom.Lobby       | Start → `countdown`                      |\n * | countdown | LiveRoom.Countdown                          | LiveRoom.Countdown   | its deadline → `question`                |\n * | question  | LiveRoom.HostControls                       | AnswerPad, or Poll   | all answered or the clock → `reveal`     |\n * | reveal    | TallyBars, Standings, LiveRoom.HostControls | AnswerPad (revealed) | Next → `countdown`, or Podium → `podium` |\n * | podium    | Podium, LiveRoom.HostControls               | Podium               | Play again → `restart`, or End → `close` |\n * | closed    | the app's own end screen                    | the app's own screen | —                                        |\n *\n * AnswerPad, Poll, TallyBars, Standings and Podium are game components in their\n * own right, so the flow names them rather than wrapping them. The round's\n * prompt reaches the phones in `room.prompt` and its answer in\n * `room.solution` (see room-model), so AnswerPad never needs the answer early.\n *\n * ## Anatomy\n *\n *   useRoom({ transport, selfId, host? })  → { room, isHost, send }\n *\n *   LiveRoom.Lobby                 (section — data-slot=\"room-lobby\", data-count)\n *     ├─ div                       (data-slot=\"room-lobby-join\": your JoinCode, when given)\n *     ├─ h2                        (data-slot=\"room-lobby-count\": \"8 players\")\n *     ├─ ul                        (data-slot=\"room-lobby-players\")\n *     │   └─ li × n                (data-slot=\"room-lobby-player\", data-self, data-away)\n *     │       └─ Button?           (data-slot=\"room-lobby-remove\", host only)\n *     ├─ p                         (data-slot=\"room-lobby-empty\", before anyone joins)\n *     ├─ div                       (data-slot=\"room-lobby-actions\": host controls, or \"Waiting for the host\")\n *     └─ span aria-live            (data-slot=\"room-lobby-announce\": \"Dana joined\")\n *\n *   LiveRoom.Countdown             (div role=\"timer\" — data-slot=\"room-countdown\", data-state)\n *     ├─ span                      (data-slot=\"room-countdown-value\": 3, 2, 1, then \"Go\")\n *     └─ span aria-live            (data-slot=\"room-countdown-announce\")\n *\n *   LiveRoom.HostControls          (div role=\"group\" — data-slot=\"room-host-controls\", data-phase)\n *     ├─ p aria-live               (data-slot=\"room-host-status\": \"5 of 8 answered\")\n *     ├─ Button                    (data-slot=\"room-host-primary\": Start / Reveal / Next / Podium / Play again)\n *     ├─ Button                    (data-slot=\"room-host-lock\": lock or unlock)\n *     └─ Button                    (data-slot=\"room-host-end\")\n *\n * ## Who decides\n *\n * The host's `useRoom` holds the room. A player's `send` travels as an\n * intent; the host applies it only if the model allows it (no joining a\n * locked room, one answer a round, only the host starts) and sends the new\n * state to everyone, with `seq` so an old message never overwrites a new\n * one. A refused intent comes back to that player through `onRejected`.\n *\n * ## Time\n *\n * Deadlines are timestamps from the host's clock. Every state the host sends\n * carries its clock (`at`), and `useRoom` returns `now`: this device's clock\n * corrected to the host's. Pass it to `LiveRoom.Countdown`, `TimerRing` and\n * `useSecondsLeft`, and a phone whose clock is a minute off still shows the\n * host's deadline. Timing uses `setTimeout` to the next whole second, never\n * a frame loop.\n *\n * ## Delivery\n *\n * Networks drop messages. A player's join or answer is sent again every 3s\n * until the host's state shows it (5 tries at most); the host applies it\n * once, and a repeated or late answer gets no reply, since a reply would go\n * to every phone. The host's last state is the truth: a transport may send\n * it again when quiet so a phone that missed one catches up.\n *\n * ## Presence\n *\n * A player's page says it is away on `pagehide` and asks for the room again\n * when it is seen (a phone that slept missed messages). Shown away while\n * still here, it rejoins by itself under the same id and name, scores kept;\n * a player who sends `leave` stays out. Turn it off with `presence: false`.\n *\n * ## Motion\n *\n * A player's chip pops in when they join (scale only, 240ms);\n * each countdown number lands with a short scale (400ms). Under reduced\n * motion both are simply there. The words carry everything: joins and the\n * countdown are announced, sparsely.\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        | room-lobby-*, room-countdown-*, room-host-*          |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                    |\n * | R8   | Enums, not booleans       | `size`                                               |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                 |\n * | R25  | Client component          | the room runs in the browser                         |\n * | R26  | A11y                      | list of players; sparse live announcements; timer role |\n */\n\nimport { Lock, LockOpen, X } from 'lucide-react';\n\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { motionDuration, motionEase } from '@/lib/motion-token';\nimport { Button } from '@/components/ui/button';\nimport {\n  answerProgress,\n  applyRoomEvent,\n  clockOffset,\n  connectedPlayers,\n  rejectRoomEvent,\n  type RoomEvent,\n  type RoomHostEvent,\n  type RoomPlayer,\n  type RoomRejection,\n  type RoomSettings,\n  type RoomState,\n  type RoomTransport,\n} from '@/components/ui/games/room-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\n\n// --- useRoom --------------------------------------------------------------------\n\nexport interface UseRoomOptions {\n  /** How messages travel. null while connecting. */\n  transport: RoomTransport | null;\n  /** This client's id: the host's id for the host, the player's id for a player. */\n  selfId: string;\n  /** The room to start from, on the host only. Present = this client is the host. */\n  host?: RoomState;\n  /** A player only: accept states for this room code only. */\n  code?: string;\n  settings?: RoomSettings;\n  /** A player's intent (or the host's own event) was refused. */\n  onRejected?: (reason: RoomRejection, event: RoomEvent['type']) => void;\n  /** The host's clock, which stamps each answer and join as it arrives. @default Date.now */\n  now?: () => number;\n  /**\n   * A player only: say \"away\" when the page is closed or hidden for good (`pagehide`), and come\n   * back by itself when the page is seen again or the host shows this player away. A player who\n   * sends `leave` themselves stays out. @default true\n   */\n  presence?: boolean;\n}\n\nexport interface UseRoomResult {\n  /** The room as this client knows it. null on a player until the host answers. */\n  room: RoomState | null;\n  isHost: boolean;\n  /** Apply (host) or ask the host to apply (player). */\n  send: (event: RoomEvent) => void;\n  /**\n   * This client's clock, corrected to the host's: pass it as `now` to `LiveRoom.Countdown`,\n   * `TimerRing` and `useSecondsLeft`, so every phone shows the host's deadline, whatever its own\n   * clock says. On the host it is `now`.\n   */\n  now: () => number;\n}\n\nconst OFFSET_WINDOW_MS = 60_000;\nconst REJOIN_EVERY_MS = 3_000;\n/** A player's join or answer is sent again this often until the host's state shows it. */\nconst RESEND_EVERY_MS = 3_000;\nconst RESEND_TRIES = 5;\n\n/** True once `state` shows the player's `event` (or it can no longer count). */\nfunction settled(state: RoomState, event: RoomEvent, round: number): boolean {\n  if (event.type === 'join') return state.players.some((p) => p.id === event.playerId && p.connected);\n  if (event.type === 'answer')\n    return state.phase !== 'question' || state.round !== round || event.playerId in state.answers;\n  if (event.type === 'submit')\n    return !!state.acked && Object.hasOwn(state.acked, event.playerId) && state.acked[event.playerId]!.includes(event.id);\n  return true;\n}\n\nexport function useRoom({\n  transport,\n  selfId,\n  host,\n  code,\n  settings,\n  onRejected,\n  now = Date.now,\n  presence = true,\n}: UseRoomOptions): UseRoomResult {\n  const isHost = host !== undefined;\n  const [room, setRoom] = React.useState<RoomState | null>(host ?? null);\n  const roomRef = React.useRef<RoomState | null>(host ?? null);\n  const latest = React.useRef({ settings, onRejected, code, now });\n  latest.current = { settings, onRejected, code, now };\n  // A player's measure of the host's clock: recent (host send, local receive) pairs.\n  const samples = React.useRef<{ at: number; local: number }[]>([]);\n  const offset = React.useRef(0);\n  const leftOnPurpose = React.useRef(false);\n  const lastRejoin = React.useRef(-Infinity);\n  // A player's join, answer or submit moves, until the host's state shows each: networks drop messages.\n  const pending = React.useRef<{ event: RoomEvent; round: number; tries: number }[]>([]);\n  const [pendingTick, setPendingTick] = React.useState(0);\n\n  const apply = React.useCallback(\n    (event: RoomEvent, from: string) => {\n      const current = roomRef.current;\n      if (!current) return;\n      // The host's clock decides when a move arrived, never the sender's.\n      if (event.type === 'submit') event = { ...event, at: latest.current.now() };\n      const reason = rejectRoomEvent(current, event, from, latest.current.settings);\n      if (reason) {\n        if (from === selfId) latest.current.onRejected?.(reason, event.type);\n        // A refused answer (a repeat, or one that arrived after the reveal) gets no reply: it\n        // would go to every phone, and the state already tells the player what counted. Nor does\n        // a repeated move: the player's own resend, or the network's, already counted.\n        else if (event.type !== 'answer' && reason !== 'duplicate')\n          transport?.send({\n            kind: 'rejected',\n            to: from,\n            event: event.type,\n            reason,\n            ...(event.type === 'submit' ? { id: event.id } : {}),\n          });\n        return;\n      }\n      const next = applyRoomEvent(current, event, from, latest.current.settings);\n      roomRef.current = next;\n      setRoom(next);\n      transport?.send({ kind: 'state', state: next, at: latest.current.now() });\n    },\n    [transport, selfId],\n  );\n\n  React.useEffect(() => {\n    if (!transport) return;\n    const off = transport.subscribe((message) => {\n      if (isHost) {\n        if (message.kind === 'intent') {\n          // The host's clock decides when an answer or a join arrived, never the sender's.\n          const event = message.event;\n          apply(\n            event.type === 'answer' || event.type === 'join' ? { ...event, at: latest.current.now() } : event,\n            message.from,\n          );\n        } else if (message.kind === 'hello' && roomRef.current)\n          transport.send({ kind: 'state', state: roomRef.current, at: latest.current.now() });\n        return;\n      }\n      if (message.kind === 'state') {\n        const current = roomRef.current;\n        const want = latest.current.code;\n        if (want && message.state.code !== want) return;\n        if (typeof message.at === 'number') {\n          const local = Date.now();\n          samples.current = [\n            ...samples.current.filter((s) => local - s.local < OFFSET_WINDOW_MS),\n            { at: message.at, local },\n          ];\n          offset.current = clockOffset(samples.current);\n        }\n        // Shown away (the phone slept, or its leave crossed a reload): come back, unless we left.\n        const self = message.state.players.find((p) => p.id === selfId);\n        if (\n          presence &&\n          self &&\n          !self.connected &&\n          !leftOnPurpose.current &&\n          message.state.phase !== 'closed' &&\n          !message.state.removed.includes(selfId) &&\n          (typeof document === 'undefined' || document.visibilityState !== 'hidden') &&\n          Date.now() - lastRejoin.current > REJOIN_EVERY_MS\n        ) {\n          lastRejoin.current = Date.now();\n          transport.send({ kind: 'intent', from: selfId, event: { type: 'join', playerId: selfId, name: self.name } });\n        }\n        if (current && current.code === message.state.code && message.state.seq <= current.seq) return;\n        roomRef.current = message.state;\n        setRoom(message.state);\n        pending.current = pending.current.filter((w) => !settled(message.state, w.event, w.round));\n      } else if (message.kind === 'rejected' && message.to === selfId) {\n        pending.current = pending.current.filter(\n          (w) => !(w.event.type === message.event && (w.event.type !== 'submit' || message.id === undefined || w.event.id === message.id)),\n        );\n        latest.current.onRejected?.(message.reason, message.event);\n      }\n    });\n    if (isHost) {\n      if (roomRef.current) transport.send({ kind: 'state', state: roomRef.current, at: latest.current.now() });\n    } else {\n      transport.send({ kind: 'hello', from: selfId });\n    }\n    return off;\n  }, [transport, isHost, selfId, apply, presence]);\n\n  // A player's page: away when it is closed, and a fresh look at the room when it is seen again\n  // (a phone that slept missed messages; the answer may bring it back in, see above).\n  React.useEffect(() => {\n    if (isHost || !presence || !transport || typeof window === 'undefined') return;\n    const hide = (e: PageTransitionEvent) => {\n      // A page kept for back/forward is not gone; a closed one is.\n      if (e.persisted) return;\n      if (roomRef.current?.players.some((p) => p.id === selfId && p.connected))\n        transport.send({ kind: 'intent', from: selfId, event: { type: 'leave', playerId: selfId } });\n    };\n    const seen = () => {\n      if (document.visibilityState === 'visible') transport.send({ kind: 'hello', from: selfId });\n    };\n    window.addEventListener('pagehide', hide);\n    document.addEventListener('visibilitychange', seen);\n    return () => {\n      window.removeEventListener('pagehide', hide);\n      document.removeEventListener('visibilitychange', seen);\n    };\n  }, [isHost, presence, transport, selfId]);\n\n  const send = React.useCallback(\n    (event: RoomEvent) => {\n      if (isHost) apply(event, selfId);\n      else {\n        if (event.type === 'leave') leftOnPurpose.current = true;\n        else if (event.type === 'join') leftOnPurpose.current = false;\n        if (event.type === 'join' || event.type === 'answer' || (event.type === 'submit' && event.retry !== false)) {\n          const round = roomRef.current?.round ?? 0;\n          // A join or an answer replaces the last of its kind; every submit is its own move.\n          const rest = event.type === 'submit' ? pending.current : pending.current.filter((w) => w.event.type !== event.type);\n          pending.current = [...rest, { event, round, tries: 0 }];\n          setPendingTick((n) => n + 1);\n        }\n        transport?.send({ kind: 'intent', from: selfId, event });\n      }\n    },\n    [isHost, apply, selfId, transport],\n  );\n\n  // Send the moves still waiting again until the host's state shows them, a few times at most.\n  React.useEffect(() => {\n    if (isHost || !transport) return;\n    const timer = setInterval(() => {\n      const current = roomRef.current;\n      pending.current = pending.current.filter((w) => !(current && settled(current, w.event, w.round)) && w.tries < RESEND_TRIES);\n      if (!pending.current.length) return clearInterval(timer);\n      for (const wait of pending.current) {\n        wait.tries++;\n        transport.send({ kind: 'intent', from: selfId, event: wait.event });\n      }\n    }, RESEND_EVERY_MS);\n    return () => clearInterval(timer);\n  }, [isHost, transport, selfId, pendingTick]);\n\n  const corrected = React.useCallback(() => (isHost ? latest.current.now() : Date.now() + offset.current), [isHost]);\n\n  return { room, isHost, send, now: corrected };\n}\n\n/**\n * Whole seconds until `target` (a timestamp in ms), re-rendering at each\n * second boundary with `setTimeout`. null when there is no target.\n */\nexport function useSecondsLeft(target: number | null, now: () => number = Date.now): number | null {\n  const [, tick] = React.useReducer((n: number) => n + 1, 0);\n  const left = target === null ? null : Math.max(0, Math.ceil((target - now()) / 1000));\n  React.useEffect(() => {\n    if (target === null) return;\n    const ms = target - now();\n    if (ms <= 0) return;\n    const t = setTimeout(tick, ms % 1000 || 1000);\n    return () => clearTimeout(t);\n  });\n  return left;\n}\n\n// --- LiveRoomLobby ------------------------------------------------------------------\n\nexport interface LiveRoomLobbyLabels {\n  /** The heading. @default (n) => n === 1 ? '1 player' : `${n} players` */\n  count?: (n: number) => string;\n  /** @default 'Waiting for players to join.' */\n  empty?: string;\n  /** On the viewer's own chip. @default 'You' */\n  you?: string;\n  /** On a player who dropped out. @default 'away' */\n  away?: string;\n  /** @default (name) => `Remove ${name}` */\n  remove?: (name: string) => string;\n  /** @default (names) => names.length === 1 ? `${names[0]} joined` : `${names.length} players joined` */\n  joined?: (names: string[]) => string;\n  /** A player's view, where the host controls would be. @default 'You are in. Waiting for the host to start.' */\n  waiting?: string;\n  /** Names the player list. @default 'Players' */\n  list?: string;\n}\n\n/**\n * The lobby is a landmark named by its player count. With more than one lobby\n * on a page (a host screen beside a preview), give each its own `aria-label`,\n * which then names the landmark instead.\n */\ntype LiveRoomLobbyProps = Omit<React.ComponentProps<'section'>, 'children'> & {\n  players: readonly RoomPlayer[];\n  /** The viewer's id, to mark their chip. */\n  selfId?: string;\n  /** Your JoinCode (or any way in), shown beside the players. */\n  join?: React.ReactNode;\n  /** Host controls. Leave out on a player's screen to show `labels.waiting`. */\n  actions?: React.ReactNode;\n  /** Shows a remove button on each chip (host only). */\n  onRemove?: (playerId: string) => void;\n  /** Hide players who dropped out. @default false */\n  hideAway?: boolean;\n  labels?: LiveRoomLobbyLabels;\n};\n\nconst COUNT = (n: number) => (n === 1 ? '1 player' : `${n} players`);\nconst JOINED = (names: string[]) => (names.length === 1 ? `${names[0]} joined` : `${names.length} players joined`);\n\nfunction LiveRoomLobby({\n  players,\n  selfId,\n  join,\n  actions,\n  onRemove,\n  hideAway = false,\n  labels,\n  className,\n  ...props\n}: LiveRoomLobbyProps) {\n  const reduced = useReducedMotion();\n  const listRef = React.useRef<HTMLUListElement>(null);\n  const seen = React.useRef<Set<string> | null>(null);\n  const [announce, setAnnounce] = React.useState('');\n  const shown = hideAway ? players.filter((p) => p.connected) : players;\n  const live = players.filter((p) => p.connected).length;\n  const headingId = React.useId();\n\n  React.useEffect(() => {\n    const ids = new Set(players.map((p) => p.id));\n    const before = seen.current;\n    seen.current = ids;\n    if (!before) return; // first render: no entrance, no announcement\n    const fresh = players.filter((p) => !before.has(p.id));\n    if (!fresh.length) return;\n    setAnnounce((labels?.joined ?? JOINED)(fresh.map((p) => p.name)));\n    if (reduced) return;\n    const freshIds = new Set(fresh.map((p) => p.id));\n    const chips = listRef.current?.querySelectorAll<HTMLElement>('[data-player-id]') ?? [];\n    for (const el of chips) {\n      if (!freshIds.has(el.dataset.playerId ?? '')) continue;\n      if (typeof el.animate === 'function') {\n        el.animate(\n          // Scale only: a fading name would dip below text contrast mid-entrance.\n          [{ transform: 'scale(0.6)' }, { transform: 'scale(1)' }],\n          { duration: 240, easing: motionEase(el, 'enter') },\n        );\n      }\n    }\n  }, [players, reduced, labels]);\n\n  return (\n    <section\n      data-slot=\"room-lobby\"\n      data-count={live}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      aria-labelledby={props['aria-label'] ? undefined : headingId}\n      className={cn('@container', className)}\n      {...props}\n    >\n      <div className={cn('grid gap-8', join && '@3xl:grid-cols-[2fr_3fr] @3xl:items-start')}>\n        {join ? <div data-slot=\"room-lobby-join\">{join}</div> : null}\n        <div className=\"flex min-w-0 flex-col gap-4\">\n          <h2 id={headingId} data-slot=\"room-lobby-count\" className=\"text-2xl font-semibold tabular-nums\">\n            {(labels?.count ?? COUNT)(live)}\n          </h2>\n          {shown.length ? (\n            <ul\n              ref={listRef}\n              data-slot=\"room-lobby-players\"\n              aria-label={labels?.list ?? 'Players'}\n              className=\"flex flex-wrap gap-2\"\n            >\n              {shown.map((p) => {\n                const self = p.id === selfId;\n                return (\n                  <li\n                    key={p.id}\n                    data-slot=\"room-lobby-player\"\n                    data-player-id={p.id}\n                    data-self={self ? '' : undefined}\n                    data-away={p.connected ? undefined : ''}\n                    className={cn(\n                      'bg-card text-card-foreground inline-flex max-w-full min-w-0 items-center gap-1.5 rounded-full border py-1.5 ps-3.5 text-sm font-medium',\n                      onRemove ? 'pe-1' : 'pe-3.5',\n                      self ? 'border-primary' : 'border-border',\n                      !p.connected && 'text-muted-foreground border-dashed',\n                    )}\n                  >\n                    <span className=\"truncate\">{p.name}</span>\n                    {self ? (\n                      <span className=\"text-primary shrink-0 text-xs font-semibold\">{labels?.you ?? 'You'}</span>\n                    ) : null}\n                    {!p.connected ? <span className=\"shrink-0 text-xs\">{labels?.away ?? 'away'}</span> : null}\n                    {onRemove && !self ? (\n                      <Button\n                        data-slot=\"room-lobby-remove\"\n                        type=\"button\"\n                        variant=\"ghost\"\n                        size=\"icon-xs\"\n                        className=\"rounded-full\"\n                        aria-label={(labels?.remove ?? ((n: string) => `Remove ${n}`))(p.name)}\n                        onClick={() => onRemove(p.id)}\n                      >\n                        <X aria-hidden />\n                      </Button>\n                    ) : null}\n                  </li>\n                );\n              })}\n            </ul>\n          ) : (\n            <p data-slot=\"room-lobby-empty\" className=\"text-muted-foreground\">\n              {labels?.empty ?? 'Waiting for players to join.'}\n            </p>\n          )}\n          <div data-slot=\"room-lobby-actions\" className=\"pt-2\">\n            {actions ?? (\n              <p className=\"text-muted-foreground\">{labels?.waiting ?? 'You are in. Waiting for the host to start.'}</p>\n            )}\n          </div>\n        </div>\n      </div>\n      <span data-slot=\"room-lobby-announce\" aria-live=\"polite\" className=\"sr-only\">\n        {announce}\n      </span>\n    </section>\n  );\n}\nLiveRoomLobby.displayName = 'LiveRoom.Lobby';\n\n// --- LiveRoomCountdown --------------------------------------------------------------\n\nexport interface LiveRoomCountdownLabels {\n  /** Names the timer. @default 'Starting in' */\n  name?: string;\n  /** Spoken once, when the countdown appears. @default (s) => `Starting in ${s} seconds` */\n  starting?: (seconds: number) => string;\n  /** Shown and spoken at 0. @default 'Go' */\n  go?: string;\n}\n\ntype LiveRoomCountdownProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  /** When it reaches 0, in ms (host clock). null: idle. */\n  startsAt: number | null;\n  /** Your clock, corrected to the host's. @default Date.now */\n  now?: () => number;\n  /** Called once at 0. */\n  onDone?: () => void;\n  /** @default 'default' */\n  size?: 'default' | 'stage';\n  labels?: LiveRoomCountdownLabels;\n};\n\nconst COUNTDOWN_SIZE = {\n  default: 'size-28 text-5xl',\n  stage: 'size-44 text-7xl',\n} as const;\n\nfunction LiveRoomCountdown({\n  startsAt,\n  now = Date.now,\n  onDone,\n  size = 'default',\n  labels,\n  className,\n  ...props\n}: LiveRoomCountdownProps) {\n  const reduced = useReducedMotion();\n  const left = useSecondsLeft(startsAt, now);\n  const valueRef = React.useRef<HTMLSpanElement>(null);\n  const done = left === 0;\n  const fired = React.useRef<number | null>(null);\n  const [announce, setAnnounce] = React.useState('');\n  const go = labels?.go ?? 'Go';\n  const latest = React.useRef(onDone);\n  latest.current = onDone;\n\n  // Speak once on arrival and once at 0, never every second. The deps are\n  // `startsAt` alone on purpose: a new `now` or `labels` must not re-announce\n  // mid-countdown.\n  React.useEffect(() => {\n    if (startsAt === null) return;\n    const s = Math.max(0, Math.ceil((startsAt - now()) / 1000));\n    if (s > 0) setAnnounce((labels?.starting ?? ((n: number) => `Starting in ${n} seconds`))(s));\n  }, [startsAt]);\n\n  React.useEffect(() => {\n    if (!done || startsAt === null || fired.current === startsAt) return;\n    fired.current = startsAt;\n    setAnnounce(go);\n    latest.current?.();\n  }, [done, startsAt, go]);\n\n  React.useEffect(() => {\n    if (left === null || reduced) return;\n    const el = valueRef.current;\n    if (!el || typeof el.animate !== 'function') return;\n    el.animate(\n      // Scale only, like the chips: a fading number would dip below text contrast.\n      [{ transform: 'scale(1.5)' }, { transform: 'scale(1)' }],\n      { duration: motionDuration(el, 'slow'), easing: motionEase(el, 'enter') },\n    );\n  }, [left, reduced]);\n\n  return (\n    <div\n      role=\"timer\"\n      aria-label={labels?.name ?? 'Starting in'}\n      data-slot=\"room-countdown\"\n      data-state={startsAt === null ? 'idle' : done ? 'done' : 'running'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn(\n        'border-primary text-foreground grid place-items-center rounded-full border-4 font-semibold tabular-nums',\n        done && 'bg-primary text-primary-foreground',\n        COUNTDOWN_SIZE[size],\n        className,\n      )}\n      {...props}\n    >\n      <span ref={valueRef} data-slot=\"room-countdown-value\" className={cn('leading-none', done && 'text-[0.6em]')}>\n        {left === null ? '' : done ? go : left}\n      </span>\n      <span data-slot=\"room-countdown-announce\" aria-live=\"assertive\" className=\"sr-only\">\n        {announce}\n      </span>\n    </div>\n  );\n}\nLiveRoomCountdown.displayName = 'LiveRoom.Countdown';\n\n// --- LiveRoomHostControls -----------------------------------------------------------\n\nexport interface LiveRoomHostControlsLabels {\n  /** @default 'Host controls' */\n  group?: string;\n  /** @default 'Start' */\n  start?: string;\n  /** @default (min, n) => `Needs ${min} players to start. ${n} so far.` */\n  needMore?: (min: number, players: number) => string;\n  /** @default (n) => n === 1 ? '1 player is in.' : `${n} players are in.` */\n  ready?: (players: number) => string;\n  /** @default 'Starting…' */\n  starting?: string;\n  /** @default (a, t) => `${a} of ${t} answered` */\n  answered?: (answered: number, total: number) => string;\n  /** @default 'Reveal now' */\n  reveal?: string;\n  /** @default (round, rounds) => rounds ? `Round ${round} of ${rounds}` : `Round ${round}` */\n  round?: (round: number, rounds: number | null) => string;\n  /** @default 'Next round' */\n  next?: string;\n  /** @default 'Show the podium' */\n  podium?: string;\n  /** @default 'Play again' */\n  restart?: string;\n  /** @default 'Lock the room' */\n  lock?: string;\n  /** @default 'Unlock the room' */\n  unlock?: string;\n  /** @default 'End the game' */\n  end?: string;\n  /** @default 'The game has ended.' */\n  closed?: string;\n}\n\ntype LiveRoomHostControlsProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  room: RoomState;\n  /** `send` from the host's `useRoom`. */\n  send: (event: RoomHostEvent) => void;\n  /** Players needed to start. @default 1 */\n  minPlayers?: number;\n  /** Seconds of countdown before each round. @default 3 */\n  countdownSeconds?: number;\n  /** Seconds per round, or null for no clock. @default 20 */\n  roundSeconds?: number | null;\n  /** Points per player id for the round being revealed. @default () => ({}) */\n  score?: (room: RoomState) => Record<string, number>;\n  /**\n   * Move on by itself: open the round when the countdown ends, reveal when\n   * the clock runs out or everyone has answered. @default true\n   */\n  autoAdvance?: boolean;\n  /** @default Date.now */\n  now?: () => number;\n  labels?: LiveRoomHostControlsLabels;\n};\n\nconst NO_POINTS = () => ({});\n\nfunction LiveRoomHostControls({\n  room,\n  send,\n  minPlayers = 1,\n  countdownSeconds = 3,\n  roundSeconds = 20,\n  score = NO_POINTS,\n  autoAdvance = true,\n  now = Date.now,\n  labels,\n  className,\n  ...props\n}: LiveRoomHostControlsProps) {\n  const L = labels ?? {};\n  const live = connectedPlayers(room).length;\n  const { answered, total } = answerProgress(room);\n  const latest = React.useRef({ send, score, now, roundSeconds });\n  latest.current = { send, score, now, roundSeconds };\n\n  const openRound = React.useCallback(() => {\n    const { send: s, now: n, roundSeconds: r } = latest.current;\n    s({ type: 'question', endsAt: r === null ? null : n() + r * 1000 });\n  }, []);\n  const reveal = React.useCallback(() => {\n    latest.current.send({ type: 'reveal', points: latest.current.score(room) });\n  }, [room]);\n\n  // Countdown over → open the round. Clock out or all in → reveal.\n  React.useEffect(() => {\n    if (!autoAdvance) return;\n    const n = latest.current.now;\n    if (room.phase === 'countdown' && room.startsAt !== null) {\n      const t = setTimeout(openRound, Math.max(0, room.startsAt - n()));\n      return () => clearTimeout(t);\n    }\n    if (room.phase === 'question') {\n      if (total > 0 && answered >= total) {\n        const t = setTimeout(reveal, 600);\n        return () => clearTimeout(t);\n      }\n      if (room.endsAt !== null) {\n        const t = setTimeout(reveal, Math.max(0, room.endsAt - n()));\n        return () => clearTimeout(t);\n      }\n    }\n    return undefined;\n  }, [autoAdvance, room.phase, room.startsAt, room.endsAt, answered, total, openRound, reveal]);\n\n  const countdown = () => send({ type: 'countdown', startsAt: now() + countdownSeconds * 1000 });\n  const last = room.rounds !== null && room.round >= room.rounds;\n\n  let status: string;\n  let primary: {\n    label: string;\n    onClick: () => void;\n    disabled?: boolean;\n  } | null = null;\n  switch (room.phase) {\n    case 'lobby':\n      status =\n        live < minPlayers\n          ? (L.needMore ?? ((m: number, n: number) => `Needs ${m} players to start. ${n} so far.`))(minPlayers, live)\n          : (L.ready ?? ((n: number) => (n === 1 ? '1 player is in.' : `${n} players are in.`)))(live);\n      primary = {\n        label: L.start ?? 'Start',\n        onClick: countdown,\n        disabled: live < minPlayers,\n      };\n      break;\n    case 'countdown':\n      status = L.starting ?? 'Starting…';\n      break;\n    case 'question':\n      status = (L.answered ?? ((a: number, t: number) => `${a} of ${t} answered`))(answered, total);\n      primary = { label: L.reveal ?? 'Reveal now', onClick: reveal };\n      break;\n    case 'reveal':\n      status = (L.round ?? ((r: number, rs: number | null) => (rs ? `Round ${r} of ${rs}` : `Round ${r}`)))(\n        room.round,\n        room.rounds,\n      );\n      primary = last\n        ? {\n            label: L.podium ?? 'Show the podium',\n            onClick: () => send({ type: 'podium' }),\n          }\n        : { label: L.next ?? 'Next round', onClick: countdown };\n      break;\n    case 'podium':\n      status = (L.round ?? ((r: number, rs: number | null) => (rs ? `Round ${r} of ${rs}` : `Round ${r}`)))(\n        room.round,\n        room.rounds,\n      );\n      primary = {\n        label: L.restart ?? 'Play again',\n        onClick: () => send({ type: 'restart' }),\n      };\n      break;\n    default:\n      status = L.closed ?? 'The game has ended.';\n  }\n\n  return (\n    <div\n      role=\"group\"\n      aria-label={L.group ?? 'Host controls'}\n      data-slot=\"room-host-controls\"\n      data-phase={room.phase}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('flex flex-wrap items-center gap-3', className)}\n      {...props}\n    >\n      <p\n        data-slot=\"room-host-status\"\n        aria-live=\"polite\"\n        className=\"text-muted-foreground basis-full text-sm tabular-nums\"\n      >\n        {status}\n      </p>\n      {primary ? (\n        <Button\n          data-slot=\"room-host-primary\"\n          type=\"button\"\n          size=\"lg\"\n          disabled={primary.disabled}\n          onClick={primary.onClick}\n        >\n          {primary.label}\n        </Button>\n      ) : null}\n      {room.phase !== 'closed' ? (\n        <>\n          <Button\n            data-slot=\"room-host-lock\"\n            type=\"button\"\n            variant=\"outline\"\n            onClick={() => send({ type: 'lock', locked: !room.locked })}\n          >\n            {room.locked ? <Lock aria-hidden /> : <LockOpen aria-hidden />}\n            {room.locked ? (L.unlock ?? 'Unlock the room') : (L.lock ?? 'Lock the room')}\n          </Button>\n          <Button data-slot=\"room-host-end\" type=\"button\" variant=\"ghost\" onClick={() => send({ type: 'close' })}>\n            {L.end ?? 'End the game'}\n          </Button>\n        </>\n      ) : null}\n    </div>\n  );\n}\nLiveRoomHostControls.displayName = 'LiveRoom.HostControls';\n\n/**\n * The live room flow. One import; every part is `LiveRoom.<Part>`, named for\n * what it is on the screen. The hook, the labels and the props stay flat.\n */\nconst LiveRoom = {\n  Lobby: LiveRoomLobby,\n  Countdown: LiveRoomCountdown,\n  HostControls: LiveRoomHostControls,\n} as const;\n\nexport { LiveRoom };\nexport type { LiveRoomLobbyProps, LiveRoomCountdownProps, LiveRoomHostControlsProps };\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"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.6.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/live-room\n\nInstalled to `components/ui/games/live-room.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/live-room';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/live-room\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
