{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "agenda",
  "type": "registry:ui",
  "title": "Agenda",
  "description": "The running order of a session. `Agenda` is the presenter's console: the item that is on, a clock that counts down and then counts over, the presenter's notes, how far the session has drifted from the plan and when it will end at this pace, and 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/agenda.tsx",
      "target": "components/ui/games/agenda.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport { Check, ChevronLeft, ChevronRight, Pause, Play, Plus } from 'lucide-react';\n\n// @interlace/agenda v1.1.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/agenda\n// What changed since: https://ds.interlace.tools/c/agenda#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — Agenda and AgendaNow\n *\n * The running order of a session. `Agenda` is the presenter's console: the\n * item that is on, a clock that counts down and then counts over, the\n * presenter's notes, how far the session has drifted from the plan and when\n * it will end at this pace, and the controls. `AgendaNow` is the room's\n * view of the same state: what is on, the time left and what comes next.\n *\n * ## Flow map\n *\n * | Phase    | Presenter (`Agenda`)                  | Room (`AgendaNow`)       |\n * | -------- | ------------------------------------- | ------------------------ |\n * | before   | the plan, Start                       | \"Starting soon\", first item |\n * | running  | clock, notes, Back, Pause, +1 min, Next | item, time left, next  |\n * | paused   | clock stopped, Resume                 | item, \"Paused\"           |\n * | over     | clock counts over in the warning tone | item, time left reads 0  |\n * | finished | how each item ran against the plan    | \"That's all\"             |\n *\n * ## Anatomy\n *\n *   Agenda                       (section — data-slot=\"agenda\", data-phase)\n *     ├─ div                     (data-slot=\"agenda-now\": eyebrow, title, clock role=\"timer\")\n *     ├─ div aria-hidden         (data-slot=\"agenda-bar\": the item's time, emptying)\n *     ├─ p                       (data-slot=\"agenda-pace\": drift and the end time)\n *     ├─ div                     (data-slot=\"agenda-notes\": presenter notes)\n *     ├─ div                     (data-slot=\"agenda-controls\")\n *     ├─ ol                      (data-slot=\"agenda-list\": aria-current=\"step\" on the item that is on)\n *     └─ span sr-only aria-live  (data-slot=\"agenda-announce\")\n *   AgendaNow                    (div — data-slot=\"agenda-now-screen\", data-phase)\n *\n * ## State\n *\n * Controlled. Keep `AgendaState` where the room's state lives, pass it in,\n * and apply every event `onEvent` sends with `applyAgendaEvent`. Because\n * the state is timestamps, a refreshed tab or a late screen shows the right\n * clock at once. The clock ticks on whole seconds with timers, not an\n * animation loop, and stops while paused or finished. `frozenAt` freezes it at\n * one moment, for a recap, a print view or a test.\n *\n * ## Keyboard\n *\n * Every control is a button. With `shortcuts`, a presentation remote works\n * too: Page Down or Right moves on, Page Up or Left goes back, `p` pauses\n * and resumes, unless focus is in a text field.\n *\n * ## Motion\n *\n * The bar empties in one linear animation to the item's end (transform).\n * On moving on, the new item's title rises in (200ms). Under reduced motion\n * the bar steps with the clock and nothing 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        | agenda / -now / -bar / -pace / -notes / -controls / -list |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                  |\n * | R8   | Enums, not booleans       | `size`                                             |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const               |\n * | R26  | A11y                      | role=\"timer\", aria-current=\"step\", sparse announcements, words with every tone |\n */\n\nimport * as React from 'react';\n\nimport { cn } from '@/lib/utils';\nimport { motionEase } from '@/lib/motion-token';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { Button } from '@/components/ui/button';\nimport {\n  agendaStatus,\n  formatClock,\n  type AgendaEvent,\n  type AgendaItem,\n  type AgendaState,\n  type AgendaStatus,\n} from '@/components/ui/games/agenda-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\ninterface AgendaLabels {\n  /** @default 'Now' */\n  now?: string;\n  /** @default 'Up next' */\n  next?: string;\n  /** @default 'Start' */\n  start?: string;\n  /** @default 'Next' */\n  forward?: string;\n  /** @default 'Finish' */\n  finish?: string;\n  /** @default 'Back' */\n  back?: string;\n  /** @default 'Pause' */\n  pause?: string;\n  /** @default 'Resume' */\n  resume?: string;\n  /** @default 'Add a minute' */\n  extend?: string;\n  /** @default 'Notes' */\n  notes?: string;\n  /** @default 'Running order' */\n  list?: string;\n  /** The clock's name. @default 'Time left' */\n  clock?: string;\n  /** @default (t) => `${t} over` */\n  over?: (time: string) => string;\n  /** @default 'Paused' */\n  paused?: string;\n  /** @default 'Starting soon' */\n  before?: string;\n  /** @default \"That's all\" */\n  finished?: string;\n  /** @default (m) => `${m} min` */\n  minutes?: (m: number) => string;\n  /**\n   * The pace line. `drift` is whole minutes, positive when behind.\n   * @default English: 'On plan', '3 min behind plan', '2 min ahead of plan', then '. Ends around {time}.'\n   */\n  pace?: (r: { drift: number; endsAt: string | null }) => string;\n  /** Spoken when an item starts. @default (title) => `Now: ${title}` */\n  started?: (title: string) => string;\n  /** Spoken a minute before the end. @default (title) => `One minute left on ${title}` */\n  oneMinute?: (title: string) => string;\n  /** Spoken when time is up. @default (title) => `Time is up on ${title}` */\n  timeUp?: (title: string) => string;\n}\n\nconst PACE: NonNullable<AgendaLabels['pace']> = ({ drift, endsAt }) => {\n  const where = drift === 0 ? 'On plan' : drift > 0 ? `${drift} min behind plan` : `${-drift} min ahead of plan`;\n  return endsAt ? `${where}. Ends around ${endsAt}.` : `${where}.`;\n};\n\n/** The clock for a state, re-read on each whole second while it runs. */\nfunction useAgendaClock(\n  items: readonly AgendaItem[],\n  state: AgendaState,\n  frozen?: number,\n  clock: () => number = Date.now,\n): AgendaStatus {\n  const read = React.useRef(clock);\n  read.current = clock;\n  const [now, setNow] = React.useState(() => clock());\n  const ticking = frozen === undefined && state.current >= 0 && state.current < items.length && state.pausedAt === null;\n  React.useEffect(() => {\n    setNow(read.current());\n    if (!ticking || state.startedAt === null) return;\n    const startedAt = state.startedAt;\n    let timer: ReturnType<typeof setTimeout>;\n    const tick = () => {\n      const t = read.current();\n      setNow(t);\n      const into = (t - startedAt) % 1000;\n      timer = setTimeout(tick, 1000 - into + 5);\n    };\n    timer = setTimeout(tick, 1000 - ((read.current() - startedAt) % 1000) + 5);\n    return () => clearTimeout(timer);\n  }, [ticking, state.startedAt]);\n  return agendaStatus(items, state, frozen ?? (ticking ? now : (state.pausedAt ?? now)));\n}\n\nfunction useAnnouncements(status: AgendaStatus, labels: AgendaLabels | undefined): string {\n  const [text, setText] = React.useState('');\n  const said = React.useRef(new Set<string>());\n  const id = status.item?.id;\n  const title = status.item?.title ?? '';\n  const first = React.useRef(true);\n  React.useEffect(() => {\n    if (first.current) {\n      // A refresh or a late join does not announce what is already on.\n      first.current = false;\n      return;\n    }\n    if (id) setText((labels?.started ?? ((t: string) => `Now: ${t}`))(title));\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [id]);\n  const left = status.leftMs;\n  const live = status.phase === 'running' || status.phase === 'over';\n  React.useEffect(() => {\n    if (!id || !live) return;\n    const oneMinute = `${id}:1`;\n    const up = `${id}:0`;\n    if (left <= 0 && !said.current.has(up)) {\n      said.current.add(up);\n      setText((labels?.timeUp ?? ((t: string) => `Time is up on ${t}`))(title));\n    } else if (left > 0 && left <= 60_000 && status.plannedMs > 60_000 && !said.current.has(oneMinute)) {\n      said.current.add(oneMinute);\n      setText((labels?.oneMinute ?? ((t: string) => `One minute left on ${t}`))(title));\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [id, live, left <= 0, left <= 60_000]);\n  return text;\n}\n\nfunction AgendaBar({ status, reduced, frozen }: { status: AgendaStatus; reduced: boolean; frozen: boolean }) {\n  const ref = React.useRef<HTMLSpanElement>(null);\n  const fraction = status.plannedMs > 0 ? Math.min(1, Math.max(0, status.leftMs / status.plannedMs)) : 0;\n  const running = status.phase === 'running' && !frozen;\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el || !running || reduced || typeof el.animate !== 'function') return;\n    const anim = el.animate([{ transform: `scaleX(${fraction})` }, { transform: 'scaleX(0)' }], {\n      duration: Math.max(0, status.leftMs),\n      easing: 'linear',\n      fill: 'forwards',\n    });\n    return () => anim.cancel();\n    // Restart only when the item, the pause state or an extension changes.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [status.item?.id, running, status.plannedMs, reduced]);\n  return (\n    <div aria-hidden data-slot=\"agenda-bar\" className=\"bg-muted h-1.5 overflow-hidden rounded-full\">\n      <span\n        ref={ref}\n        className={cn(\n          'block h-full origin-left rounded-full rtl:origin-right',\n          status.phase === 'over' ? 'bg-destructive' : 'bg-primary',\n        )}\n        style={{ transform: `scaleX(${fraction})` }}\n      />\n    </div>\n  );\n}\n\nfunction Rise({ id, reduced, children }: { id: string | undefined; reduced: boolean; children: React.ReactNode }) {\n  const ref = React.useRef<HTMLSpanElement>(null);\n  const first = React.useRef(true);\n  React.useEffect(() => {\n    if (first.current) {\n      first.current = false;\n      return;\n    }\n    const el = ref.current;\n    if (!el || reduced || typeof el.animate !== 'function') return;\n    el.animate(\n      [\n        { transform: 'translateY(0.5em)', opacity: 0 },\n        { transform: 'translateY(0)', opacity: 1 },\n      ],\n      {\n        duration: 200,\n        easing: motionEase(el, 'enter'),\n      },\n    );\n  }, [id, reduced]);\n  return (\n    <span ref={ref} className=\"block\">\n      {children}\n    </span>\n  );\n}\n\n// --- Agenda (presenter) ----------------------------------------------------------\n\ntype AgendaProps = Omit<React.ComponentProps<'section'>, 'children'> & {\n  items: readonly AgendaItem[];\n  state: AgendaState;\n  /** Every control sends one event. Apply it with `applyAgendaEvent`. */\n  onEvent: (event: AgendaEvent) => void;\n  /** Show the session at this moment and stop the clock: a recap, a print view, a test. */\n  frozenAt?: number;\n  /**\n   * The clock the presenter's events are stamped with and the countdown reads. A second screen passes the\n   * controlling window's clock (`useAgendaSync().now`) so both agree. @default Date.now\n   */\n  now?: () => number;\n  /** Presentation-remote keys (Page Up/Down, arrows, p). @default false */\n  shortcuts?: boolean;\n  locale?: string;\n  labels?: AgendaLabels;\n};\n\nfunction Agenda({\n  items,\n  state,\n  onEvent,\n  frozenAt,\n  now: clock = Date.now,\n  shortcuts = false,\n  locale,\n  labels,\n  className,\n  ...props\n}: AgendaProps) {\n  const reduced = useReducedMotion();\n  const status = useAgendaClock(items, state, frozenAt, clock);\n  const announce = useAnnouncements(status, labels);\n  const time = React.useMemo(() => new Intl.DateTimeFormat(locale, { timeStyle: 'short' }), [locale]);\n  const minutes = labels?.minutes ?? ((m: number) => `${m} min`);\n  const { phase, index } = status;\n  const isLast = index === items.length - 1;\n\n  const send = React.useRef(onEvent);\n  send.current = onEvent;\n  const where = React.useRef({ phase, index });\n  where.current = { phase, index };\n  const stamp = React.useRef(clock);\n  stamp.current = clock;\n\n  React.useEffect(() => {\n    if (!shortcuts) return;\n    const onKey = (e: KeyboardEvent) => {\n      const t = e.target as HTMLElement | null;\n      if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;\n      if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return;\n      const { phase: p, index: i } = where.current;\n      const at = stamp.current();\n      if (e.key === 'PageDown' || e.key === 'ArrowRight') {\n        e.preventDefault();\n        send.current(p === 'before' ? { type: 'start', at } : { type: 'next', from: i, at });\n      } else if (e.key === 'PageUp' || e.key === 'ArrowLeft') {\n        e.preventDefault();\n        send.current({ type: 'back', from: i, at });\n      } else if (e.key === 'p' && (p === 'running' || p === 'over' || p === 'paused')) {\n        send.current({ type: p === 'paused' ? 'resume' : 'pause', at });\n      }\n    };\n    document.addEventListener('keydown', onKey);\n    return () => document.removeEventListener('keydown', onKey);\n  }, [shortcuts]);\n\n  const drift = Math.round(status.driftMs / 60_000);\n  const over = phase === 'over';\n\n  return (\n    <section\n      data-slot=\"agenda\"\n      data-phase={phase}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-5', className)}\n      {...props}\n    >\n      <div data-slot=\"agenda-now\" className=\"flex flex-wrap items-end justify-between gap-x-6 gap-y-2\">\n        <div className=\"min-w-0\">\n          <p className=\"text-muted-foreground text-sm font-medium\">\n            {phase === 'before'\n              ? (labels?.before ?? 'Starting soon')\n              : phase === 'finished'\n                ? ''\n                : (labels?.now ?? 'Now')}\n          </p>\n          <p className=\"font-heading text-2xl font-semibold text-balance\">\n            <Rise id={status.item?.id} reduced={reduced}>\n              {phase === 'finished'\n                ? (labels?.finished ?? \"That's all\")\n                : (status.item?.title ?? status.next?.title ?? '')}\n            </Rise>\n          </p>\n        </div>\n        {status.item ? (\n          <div\n            role=\"timer\"\n            aria-label={labels?.clock ?? 'Time left'}\n            data-slot=\"agenda-clock\"\n            className={cn(\n              'grid justify-items-end text-4xl leading-none font-semibold tabular-nums',\n              over ? 'text-destructive' : 'text-foreground',\n            )}\n          >\n            <span>{over ? `+${formatClock(status.leftMs)}` : formatClock(status.leftMs)}</span>\n            <span className=\"mt-1 text-sm font-medium\">\n              {phase === 'paused'\n                ? (labels?.paused ?? 'Paused')\n                : over\n                  ? (labels?.over ?? ((t: string) => `${t} over`))(formatClock(status.leftMs))\n                  : minutes(Math.round(status.plannedMs / 60_000))}\n            </span>\n          </div>\n        ) : null}\n      </div>\n\n      {status.item ? <AgendaBar status={status} reduced={reduced} frozen={frozenAt !== undefined} /> : null}\n\n      {phase !== 'before' ? (\n        <p data-slot=\"agenda-pace\" className=\"text-muted-foreground text-sm\">\n          {(labels?.pace ?? PACE)({\n            drift,\n            endsAt: status.endsAt === null ? null : time.format(status.endsAt),\n          })}\n        </p>\n      ) : null}\n\n      {status.item?.notes ? (\n        <div data-slot=\"agenda-notes\" className=\"bg-muted/60 rounded-lg p-4\">\n          <p className=\"text-muted-foreground mb-1 text-xs font-medium\">{labels?.notes ?? 'Notes'}</p>\n          <p className=\"text-sm whitespace-pre-line\">{status.item.notes}</p>\n        </div>\n      ) : null}\n\n      <div data-slot=\"agenda-controls\" className=\"flex flex-wrap gap-2\">\n        {phase === 'before' ? (\n          <Button size=\"lg\" disabled={items.length === 0} onClick={() => onEvent({ type: 'start', at: clock() })}>\n            <Play aria-hidden />\n            {labels?.start ?? 'Start'}\n          </Button>\n        ) : (\n          <>\n            <Button\n              variant=\"outline\"\n              disabled={index < 1}\n              onClick={() => onEvent({ type: 'back', from: index, at: clock() })}\n            >\n              <ChevronLeft aria-hidden className=\"rtl:rotate-180\" />\n              {labels?.back ?? 'Back'}\n            </Button>\n            {phase !== 'finished' ? (\n              <>\n                <Button\n                  variant=\"outline\"\n                  onClick={() => onEvent({ type: phase === 'paused' ? 'resume' : 'pause', at: clock() })}\n                >\n                  {phase === 'paused' ? <Play aria-hidden /> : <Pause aria-hidden />}\n                  {phase === 'paused' ? (labels?.resume ?? 'Resume') : (labels?.pause ?? 'Pause')}\n                </Button>\n                <Button variant=\"outline\" onClick={() => onEvent({ type: 'extend', minutes: 1 })}>\n                  <Plus aria-hidden />\n                  {labels?.extend ?? 'Add a minute'}\n                </Button>\n                <Button className=\"ms-auto\" onClick={() => onEvent({ type: 'next', from: index, at: clock() })}>\n                  {isLast ? (labels?.finish ?? 'Finish') : (labels?.forward ?? 'Next')}\n                  <ChevronRight aria-hidden className=\"rtl:rotate-180\" />\n                </Button>\n              </>\n            ) : null}\n          </>\n        )}\n      </div>\n\n      <div>\n        <p className=\"text-muted-foreground mb-2 text-xs font-medium\">{labels?.list ?? 'Running order'}</p>\n        <ol data-slot=\"agenda-list\" className=\"grid gap-1\">\n          {items.map((it, i) => {\n            const done = i < index;\n            const on = i === index;\n            const spent = state.spent[it.id];\n            return (\n              <li\n                key={it.id}\n                aria-current={on ? 'step' : undefined}\n                data-state={done ? 'done' : on ? 'current' : 'upcoming'}\n                className={cn(\n                  'flex items-center gap-3 rounded-md px-3 py-2 text-sm motion-safe:transition-colors motion-safe:duration-(--duration-base)',\n                  on ? 'bg-primary/10 text-foreground font-medium' : done ? 'text-muted-foreground' : 'text-foreground',\n                )}\n              >\n                <span aria-hidden className=\"grid size-5 shrink-0 place-items-center\">\n                  {done ? (\n                    <Check className=\"size-4\" />\n                  ) : (\n                    <span className={cn('size-2 rounded-full', on ? 'bg-primary' : 'bg-foreground/30')} />\n                  )}\n                </span>\n                <span className=\"min-w-0 flex-1\">{it.title}</span>\n                <span className=\"text-muted-foreground tabular-nums\">\n                  {done && spent !== undefined ? formatClock(spent) : minutes(it.minutes + (state.extra[it.id] ?? 0))}\n                </span>\n              </li>\n            );\n          })}\n        </ol>\n      </div>\n\n      <span data-slot=\"agenda-announce\" aria-live=\"polite\" className=\"sr-only\">\n        {announce}\n      </span>\n    </section>\n  );\n}\nAgenda.displayName = 'Agenda';\n\n// --- AgendaNow (room) ------------------------------------------------------------\n\ntype AgendaNowProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  items: readonly AgendaItem[];\n  state: AgendaState;\n  /** Show the session at this moment and stop the clock. */\n  frozenAt?: number;\n  /** The clock the countdown reads. @default Date.now */\n  now?: () => number;\n  /** Hide the time left from the room. @default true */\n  showTime?: boolean;\n  /** `stage` for a shared screen. @default 'default' */\n  size?: 'default' | 'stage';\n  labels?: Pick<AgendaLabels, 'now' | 'next' | 'before' | 'finished' | 'paused' | 'clock'>;\n};\n\nfunction AgendaNow({\n  items,\n  state,\n  frozenAt,\n  now: clock = Date.now,\n  showTime = true,\n  size = 'default',\n  labels,\n  className,\n  ...props\n}: AgendaNowProps) {\n  const reduced = useReducedMotion();\n  const status = useAgendaClock(items, state, frozenAt, clock);\n  const { phase } = status;\n  const stage = size === 'stage';\n  const title =\n    phase === 'finished' ? (labels?.finished ?? \"That's all\") : (status.item?.title ?? status.next?.title ?? '');\n  const eyebrow =\n    phase === 'before' ? (labels?.before ?? 'Starting soon') : phase === 'finished' ? '' : (labels?.now ?? 'Now');\n  return (\n    <div\n      data-slot=\"agenda-now-screen\"\n      data-phase={phase}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-2', stage && 'gap-4', className)}\n      {...props}\n    >\n      {eyebrow ? (\n        <p className={cn('text-muted-foreground font-medium', stage ? 'text-lg' : 'text-sm')}>{eyebrow}</p>\n      ) : null}\n      <div className=\"flex flex-wrap items-baseline justify-between gap-x-6 gap-y-1\">\n        <p className={cn('font-heading font-semibold text-balance', stage ? 'text-h1' : 'text-2xl')}>\n          <Rise id={status.item?.id} reduced={reduced}>\n            {title}\n          </Rise>\n        </p>\n        {showTime && status.item ? (\n          <p\n            role=\"timer\"\n            aria-label={labels?.clock ?? 'Time left'}\n            className={cn('text-muted-foreground font-semibold tabular-nums', stage ? 'text-4xl' : 'text-xl')}\n          >\n            {phase === 'paused' ? (labels?.paused ?? 'Paused') : formatClock(Math.max(0, status.leftMs))}\n          </p>\n        ) : null}\n      </div>\n      {phase !== 'before' && status.next ? (\n        <p className={cn('text-muted-foreground', stage ? 'text-lg' : 'text-sm')}>\n          {labels?.next ?? 'Up next'}: <span className=\"text-foreground\">{status.next.title}</span>\n        </p>\n      ) : null}\n    </div>\n  );\n}\nAgendaNow.displayName = 'AgendaNow';\n\nexport { Agenda, AgendaNow };\nexport type { AgendaProps, AgendaNowProps, AgendaLabels };\n"
    },
    {
      "path": "registry/interlace-ui/games/agenda-model.ts",
      "target": "components/ui/games/agenda-model.ts",
      "type": "registry:ui",
      "content": "export interface AgendaItem {\n  id: string;\n  title: string;\n  /** Planned length, in minutes. */\n  minutes: number;\n  /** Presenter notes for this item. Never shown to the room. */\n  notes?: string;\n}\n\nexport interface AgendaState {\n  /** -1 before the start; `items.length` once finished. */\n  current: number;\n  /** When the current item began, ms, moved forward by any pause. */\n  startedAt: number | null;\n  /** Set while paused. */\n  pausedAt: number | null;\n  /** Minutes added to an item, by id. */\n  extra: Readonly<Record<string, number>>;\n  /** How long each finished item really ran, ms, by id. */\n  spent: Readonly<Record<string, number>>;\n}\n\nexport type AgendaEvent =\n  | { type: 'start'; at: number }\n  | { type: 'next'; from: number; at: number }\n  | { type: 'back'; from: number; at: number }\n  | { type: 'pause'; at: number }\n  | { type: 'resume'; at: number }\n  /** Adds minutes (or takes them away, down to zero extra) to the current item. */\n  | { type: 'extend'; minutes: number }\n  | { type: 'reset' };\n\nexport type AgendaPhase = 'before' | 'running' | 'paused' | 'over' | 'finished';\n\nexport interface AgendaStatus {\n  phase: AgendaPhase;\n  index: number;\n  item: AgendaItem | null;\n  next: AgendaItem | null;\n  /** The current item's length with any extension, ms. */\n  plannedMs: number;\n  elapsedMs: number;\n  /** Negative once the item runs over. */\n  leftMs: number;\n  /** Positive when behind the plan, negative when ahead, ms. */\n  driftMs: number;\n  /** When the session will end at this pace, ms; null before the start. */\n  endsAt: number | null;\n  /** Planned length of the whole session, ms, with extensions. */\n  totalMs: number;\n}\n\nconst MIN = 60_000;\n\nexport function createAgenda(): AgendaState {\n  return { current: -1, startedAt: null, pausedAt: null, extra: {}, spent: {} };\n}\n\nfunction plannedOf(item: AgendaItem, state: AgendaState): number {\n  return Math.max(0, item.minutes + (state.extra[item.id] ?? 0)) * MIN;\n}\n\nfunction elapsedOf(state: AgendaState, now: number): number {\n  if (state.startedAt === null) return 0;\n  return Math.max(0, (state.pausedAt ?? now) - state.startedAt);\n}\n\n/** Applies one event. Events that change nothing return the same state. */\nexport function applyAgendaEvent(items: readonly AgendaItem[], state: AgendaState, event: AgendaEvent): AgendaState {\n  const live = state.current >= 0 && state.current < items.length;\n  switch (event.type) {\n    case 'start':\n      if (state.current !== -1 || items.length === 0) return state;\n      return { ...state, current: 0, startedAt: event.at, pausedAt: null };\n    case 'next': {\n      if (!live || state.current !== event.from) return state;\n      const item = items[state.current] as AgendaItem;\n      const spent = { ...state.spent, [item.id]: elapsedOf(state, event.at) };\n      const to = state.current + 1;\n      if (to >= items.length) return { ...state, current: items.length, startedAt: null, pausedAt: null, spent };\n      return { ...state, current: to, startedAt: event.at, pausedAt: null, spent };\n    }\n    case 'back': {\n      // Works from the finished state too, to reopen the last item.\n      if (state.current !== event.from || state.current < 1 || state.current > items.length) return state;\n      const leaving = items[state.current];\n      const spent = leaving ? { ...state.spent, [leaving.id]: elapsedOf(state, event.at) } : { ...state.spent };\n      const prev = items[state.current - 1] as AgendaItem;\n      // The earlier item picks up where it stopped.\n      const { [prev.id]: before = 0, ...rest } = spent;\n      return { ...state, current: state.current - 1, startedAt: event.at - before, pausedAt: null, spent: rest };\n    }\n    case 'pause':\n      if (!live || state.pausedAt !== null) return state;\n      return { ...state, pausedAt: event.at };\n    case 'resume': {\n      if (!live || state.pausedAt === null || state.startedAt === null) return state;\n      return { ...state, startedAt: state.startedAt + (event.at - state.pausedAt), pausedAt: null };\n    }\n    case 'extend': {\n      if (!live) return state;\n      const id = (items[state.current] as AgendaItem).id;\n      const extra = Math.max(0, (state.extra[id] ?? 0) + event.minutes);\n      return { ...state, extra: { ...state.extra, [id]: extra } };\n    }\n    case 'reset':\n      return createAgenda();\n  }\n}\n\n/** Where the session is at `now`. */\nexport function agendaStatus(items: readonly AgendaItem[], state: AgendaState, now: number): AgendaStatus {\n  const totalMs = items.reduce((sum, it) => sum + plannedOf(it, state), 0);\n  const index = state.current;\n  const item = items[index] ?? null;\n  const base = { index, item, next: items[index + 1] ?? null, totalMs };\n\n  // Time over or under plan on items already finished.\n  let driftMs = 0;\n  for (const it of items) {\n    const spent = state.spent[it.id];\n    if (spent !== undefined) driftMs += spent - plannedOf(it, state);\n  }\n\n  if (index < 0) {\n    return {\n      ...base,\n      phase: 'before',\n      next: items[0] ?? null,\n      plannedMs: 0,\n      elapsedMs: 0,\n      leftMs: 0,\n      driftMs: 0,\n      endsAt: null,\n    };\n  }\n  if (!item) {\n    return { ...base, phase: 'finished', plannedMs: 0, elapsedMs: 0, leftMs: 0, driftMs, endsAt: null };\n  }\n\n  const plannedMs = plannedOf(item, state);\n  const elapsedMs = elapsedOf(state, now);\n  const leftMs = plannedMs - elapsedMs;\n  const overMs = Math.max(0, -leftMs);\n  const later = items.slice(index + 1).reduce((sum, it) => sum + plannedOf(it, state), 0);\n  const phase: AgendaPhase = state.pausedAt !== null ? 'paused' : leftMs < 0 ? 'over' : 'running';\n  return {\n    ...base,\n    phase,\n    plannedMs,\n    elapsedMs,\n    leftMs,\n    driftMs: driftMs + overMs,\n    endsAt: now + Math.max(0, leftMs) + later,\n  };\n}\n\n/** `m:ss` for a length of time (its absolute value), rounded up to the second. */\nexport function formatClock(ms: number): string {\n  const s = Math.ceil(Math.abs(ms) / 1000);\n  const m = Math.floor(s / 60);\n  return `${m}:${String(s % 60).padStart(2, '0')}`;\n}\n\n/**\n * @interlace/ui — agenda-model\n *\n * The running order of a session, and where the presenter is in it. Each\n * item has planned minutes; the state records when the current item began,\n * pauses, extensions and how long finished items really took. Everything is\n * a timestamp, so a refreshed presenter tab, a second device, or a shared\n * screen that joins late all read the same clock from the same state.\n *\n * ## Events\n *\n * `next` and `back` name the item they move from (`from`), so an event that\n * arrives twice after a reconnect moves once, not twice. `pause` while\n * paused, `resume` while running and `start` once started change nothing.\n *\n * ## Status\n *\n * `agendaStatus(items, state, now)` says which item is on, how long is left\n * (negative once it runs over), how far the whole session has drifted from\n * the plan, and when it will end at this pace.\n */\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.1.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/agenda\n\nInstalled to `components/ui/games/agenda.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/agenda';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/agenda\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
