{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "team-chat",
  "type": "registry:block",
  "title": "Team Chat",
  "description": "Channels and DMs with grouped messages, reactions that roll their counts, and threads that open in a side panel; send something and a teammate starts typing back.",
  "categories": [
    "screen",
    "Comms"
  ],
  "dependencies": [
    "motion",
    "lucide-react"
  ],
  "registryDependencies": [
    "utils",
    "https://coss.com/ui/r/avatar.json",
    "https://coss.com/ui/r/button.json",
    "https://coss.com/ui/r/kbd.json",
    "https://coss.com/ui/r/popover.json",
    "https://coss.com/ui/r/tooltip.json"
  ],
  "files": [
    {
      "path": "registry/devl/team-chat.tsx",
      "type": "registry:component",
      "content": "\"use client\";\n\nimport { AnimatePresence, LayoutGroup, MotionConfig, motion } from \"motion/react\";\nimport {\n  ArrowLeftIcon,\n  AtSignIcon,\n  BellOffIcon,\n  BoldIcon,\n  BookmarkIcon,\n  CornerDownLeftIcon,\n  ChevronDownIcon,\n  CodeIcon,\n  FileTextIcon,\n  HashIcon,\n  ItalicIcon,\n  LockIcon,\n  MenuIcon,\n  MessageSquareTextIcon,\n  MessagesSquareIcon,\n  PaperclipIcon,\n  PinIcon,\n  PlusIcon,\n  SearchIcon,\n  SendHorizontalIcon,\n  SmilePlusIcon,\n  UsersIcon,\n  XIcon,\n} from \"lucide-react\";\nimport {\n  Fragment,\n  type KeyboardEvent,\n  type RefObject,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { Avatar, AvatarFallback } from \"@/components/ui/avatar\";\nimport { Button } from \"@/components/ui/button\";\nimport { Kbd } from \"@/components/ui/kbd\";\nimport { Popover, PopoverPopup, PopoverTrigger } from \"@/components/ui/popover\";\nimport { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from \"@/components/ui/tooltip\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ChatTone = \"blue\" | \"orange\" | \"teal\" | \"violet\" | \"rose\" | \"amber\" | \"emerald\" | \"sky\";\n\nexport interface ChatPerson {\n  id: string;\n  name: string;\n  tone: ChatTone;\n  title?: string;\n  presence?: \"active\" | \"away\" | \"offline\";\n}\n\nexport interface ChatReaction {\n  emoji: string;\n  people: string[];\n}\n\nexport interface ChatReply {\n  id: string;\n  author: string;\n  time: string;\n  text: string;\n  reactions?: ChatReaction[];\n  saved?: boolean;\n}\n\nexport interface ChatMessage extends ChatReply {\n  day: string;\n  replies?: ChatReply[];\n  file?: { name: string; size: string; pages?: number };\n}\n\nexport interface ChatChannel {\n  id: string;\n  name: string;\n  kind: \"channel\" | \"dm\";\n  with?: string;\n  topic?: string;\n  private?: boolean;\n  unread?: number;\n  mentions?: number;\n  muted?: boolean;\n  members?: number;\n  pinned?: string[];\n  messages: ChatMessage[];\n}\n\nexport interface TeamChatProps {\n  workspace?: string;\n  me?: string;\n  people?: ChatPerson[];\n  channels?: ChatChannel[];\n  className?: string;\n}\n\nconst avatarTone: Record<ChatTone, string> = {\n  blue: \"bg-blue-500/14 text-blue-700 dark:text-blue-300\",\n  orange: \"bg-orange-500/14 text-orange-700 dark:text-orange-300\",\n  teal: \"bg-teal-500/16 text-teal-700 dark:text-teal-300\",\n  violet: \"bg-violet-500/16 text-violet-700 dark:text-violet-300\",\n  rose: \"bg-rose-500/14 text-rose-700 dark:text-rose-300\",\n  amber: \"bg-amber-500/18 text-amber-800 dark:text-amber-300\",\n  emerald: \"bg-emerald-500/16 text-emerald-700 dark:text-emerald-300\",\n  sky: \"bg-sky-500/16 text-sky-700 dark:text-sky-300\",\n};\n\nconst spring = { type: \"spring\", stiffness: 520, damping: 42 } as const;\nconst panelSpring = { type: \"spring\", stiffness: 420, damping: 40 } as const;\nconst ease = [0.23, 1, 0.32, 1] as const;\n\nconst initials = (name: string) =>\n  name\n    .split(\" \")\n    .map((p) => p[0])\n    .slice(0, 2)\n    .join(\"\")\n    .toUpperCase();\n\nconst defaultPeople: ChatPerson[] = [\n  { id: \"maya\", name: \"Maya Okafor\", tone: \"teal\", title: \"Head of Product\", presence: \"active\" },\n  { id: \"priya\", name: \"Priya Raman\", tone: \"violet\", title: \"Product Designer\", presence: \"active\" },\n  { id: \"jonas\", name: \"Jonas Weber\", tone: \"blue\", title: \"Growth\", presence: \"active\" },\n  { id: \"leo\", name: \"Leo Marchetti\", tone: \"rose\", title: \"Mobile\", presence: \"away\" },\n  { id: \"sam\", name: \"Sam Whitfield\", tone: \"amber\", title: \"Platform\", presence: \"active\" },\n  { id: \"ana\", name: \"Ana Sousa\", tone: \"orange\", title: \"Research\", presence: \"offline\" },\n];\n\nconst defaultChannels: ChatChannel[] = [\n  {\n    id: \"design\",\n    name: \"design\",\n    kind: \"channel\",\n    topic: \"Crit Thursdays 2pm · onboarding v3 in review\",\n    members: 14,\n    pinned: [\"d1\", \"d6\"],\n    messages: [\n      {\n        id: \"d0\",\n        day: \"Yesterday\",\n        author: \"ana\",\n        time: \"4:48 PM\",\n        text: \"Synthesis from the five beta teams is in the research folder. Short version: nobody reads step 4.\",\n        reactions: [{ emoji: \"😅\", people: [\"priya\", \"leo\"] }],\n      },\n      {\n        id: \"d1\",\n        day: \"Today\",\n        author: \"priya\",\n        time: \"9:12 AM\",\n        text: \"Onboarding v3 is up for crit at 2pm. Biggest change: we ask for the team name last, after people have seen their first project.\",\n        file: { name: \"onboarding-v3.pdf\", size: \"2.4 MB\", pages: 18 },\n        reactions: [\n          { emoji: \"🔥\", people: [\"jonas\", \"leo\", \"sam\"] },\n          { emoji: \"👀\", people: [\"ana\", \"maya\"] },\n        ],\n        replies: [\n          { id: \"r1\", author: \"jonas\", time: \"9:20 AM\", text: \"Love that it ends on their first project instead of a form.\" },\n          { id: \"r2\", author: \"ana\", time: \"9:31 AM\", text: \"Can we test step 4 with the beta teams before we lock it?\" },\n          { id: \"r3\", author: \"priya\", time: \"9:40 AM\", text: \"@Ana yes, booked three sessions for Tuesday.\", reactions: [{ emoji: \"🙌\", people: [\"ana\"] }] },\n          { id: \"r4\", author: \"leo\", time: \"10:15 AM\", text: \"I'll bring the mobile prototype so we test both.\" },\n        ],\n      },\n      {\n        id: \"d2\",\n        day: \"Today\",\n        author: \"leo\",\n        time: \"9:24 AM\",\n        text: \"The empty project state on step 3 is so much calmer. Can we reuse it in the mobile app?\",\n        reactions: [{ emoji: \"👍\", people: [\"priya\", \"maya\"] }],\n      },\n      { id: \"d3\", day: \"Today\", author: \"leo\", time: \"9:25 AM\", text: \"Also, the progress dots feel small on phones. 6px is hard to read at arm's length.\" },\n      {\n        id: \"d4\",\n        day: \"Today\",\n        author: \"jonas\",\n        time: \"10:02 AM\",\n        text: \"From the pricing side: if team name comes last, can we still show the plan picker before invites? I need it for the Starter experiment.\",\n        replies: [\n          { id: \"r1\", author: \"priya\", time: \"10:06 AM\", text: \"Yes, plan picker stays on step 2.\" },\n          { id: \"r2\", author: \"jonas\", time: \"10:07 AM\", text: \"Perfect, thank you.\" },\n        ],\n      },\n      {\n        id: \"d5\",\n        day: \"Today\",\n        author: \"maya\",\n        time: \"10:05 AM\",\n        text: \"@Jonas plan picker stays where it is. Priya and I walked the whole flow yesterday.\",\n      },\n      {\n        id: \"d6\",\n        day: \"Today\",\n        author: \"sam\",\n        time: \"10:41 AM\",\n        text: \"Shipped the `ease-out-quint` token to the design system. Every transition in the app is under 250ms now.\",\n        reactions: [\n          { emoji: \"🎉\", people: [\"priya\", \"leo\", \"jonas\", \"ana\"] },\n          { emoji: \"⚡\", people: [\"maya\"] },\n        ],\n      },\n    ],\n  },\n  {\n    id: \"eng-platform\",\n    name: \"eng-platform\",\n    kind: \"channel\",\n    topic: \"Queue, webhooks, deploys · on-call: Sam\",\n    members: 9,\n    unread: 3,\n    messages: [\n      { id: \"e1\", day: \"Today\", author: \"sam\", time: \"8:02 AM\", text: \"Webhook backlog is back to zero. Postmortem draft is in the doc, comments open until Monday.\" },\n      { id: \"e2\", day: \"Today\", author: \"sam\", time: \"8:03 AM\", text: \"Three follow-ups: poison-message handling, consumer lag alert at 2 minutes, and a replay tool.\", saved: true },\n      {\n        id: \"e3\",\n        day: \"Today\",\n        author: \"jonas\",\n        time: \"9:50 AM\",\n        text: \"Does the replay tool cover the Oct 21 window? Two customers asked.\",\n        reactions: [{ emoji: \"👍\", people: [\"maya\"] }],\n      },\n    ],\n  },\n  {\n    id: \"launches\",\n    name: \"launches\",\n    kind: \"channel\",\n    topic: \"What's shipping and when\",\n    members: 32,\n    mentions: 1,\n    messages: [\n      { id: \"l1\", day: \"Today\", author: \"jonas\", time: \"11:02 AM\", text: \"@Maya can you sign off the Starter pricing copy before 3pm? Release notes go out at 4.\" },\n    ],\n  },\n  {\n    id: \"research\",\n    name: \"research\",\n    kind: \"channel\",\n    private: true,\n    members: 5,\n    topic: \"Interview notes and synthesis\",\n    messages: [{ id: \"x1\", day: \"Yesterday\", author: \"ana\", time: \"3:10 PM\", text: \"Uploaded the last two interview recordings.\" }],\n  },\n  {\n    id: \"random\",\n    name: \"random\",\n    kind: \"channel\",\n    muted: true,\n    members: 41,\n    topic: \"Dogs, lunch, and the office plant\",\n    messages: [{ id: \"z1\", day: \"Today\", author: \"leo\", time: \"8:30 AM\", text: \"Someone watered the fern twice again. It's thriving out of spite.\" }],\n  },\n  {\n    id: \"dm-priya\",\n    name: \"Priya Raman\",\n    kind: \"dm\",\n    with: \"priya\",\n    messages: [\n      { id: \"p1\", day: \"Today\", author: \"priya\", time: \"8:55 AM\", text: \"Do you have 10 minutes before crit? I want a second pair of eyes on step 4.\" },\n    ],\n  },\n  {\n    id: \"dm-sam\",\n    name: \"Sam Whitfield\",\n    kind: \"dm\",\n    with: \"sam\",\n    unread: 1,\n    messages: [{ id: \"s1\", day: \"Today\", author: \"sam\", time: \"10:58 AM\", text: \"Heads up: deploy freeze starts Thursday 6pm for the board demo.\" }],\n  },\n  {\n    id: \"dm-leo\",\n    name: \"Leo Marchetti\",\n    kind: \"dm\",\n    with: \"leo\",\n    messages: [{ id: \"o1\", day: \"Yesterday\", author: \"leo\", time: \"6:12 PM\", text: \"Venue options for Lisbon are in your email.\" }],\n  },\n];\n\nconst emojiChoices = [\"👍\", \"🔥\", \"🎉\", \"👀\", \"🙌\", \"😅\", \"✅\", \"❤️\"];\n\nconst autoReplies: Record<string, { author: string; text: string }> = {\n  design: { author: \"priya\", text: \"Good call. Adding it to the crit doc so we don't lose it.\" },\n  \"eng-platform\": { author: \"sam\", text: \"On it. I'll post an update here after standup.\" },\n  launches: { author: \"jonas\", text: \"Thanks! Locking the copy now.\" },\n};\n\nconst fileExt = (name: string) => name.split(\".\").pop()?.toUpperCase() ?? \"File\";\n\nfunction fileSize(bytes: number) {\n  if (bytes < 1024) return `${bytes} B`;\n  if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;\n  return `${(bytes / 1024 / 1024).toFixed(1)} MB`;\n}\n\nfunction isTyping(e: KeyboardEvent) {\n  const t = e.target as HTMLElement;\n  return t.tagName === \"INPUT\" || t.tagName === \"TEXTAREA\" || t.isContentEditable;\n}\n\nfunction RichText({ text, people, me }: { text: string; people: ChatPerson[]; me: string }) {\n  const parts = text.split(/(`[^`]+`|\\*\\*[^*]+\\*\\*|\\b_[^_]+_\\b|@\\w+)/g);\n  return (\n    <>\n      {parts.map((part, i) => {\n        if (part.startsWith(\"`\") && part.endsWith(\"`\") && part.length > 2) {\n          return (\n            <code className=\"rounded-md border bg-muted px-1 py-px font-mono text-[0.8125rem]\" key={i}>\n              {part.slice(1, -1)}\n            </code>\n          );\n        }\n        if (part.startsWith(\"**\") && part.endsWith(\"**\") && part.length > 4) {\n          return (\n            <strong className=\"font-semibold\" key={i}>\n              {part.slice(2, -2)}\n            </strong>\n          );\n        }\n        if (part.startsWith(\"_\") && part.endsWith(\"_\") && part.length > 2) {\n          return (\n            <em key={i}>\n              {part.slice(1, -1)}\n            </em>\n          );\n        }\n        if (part.startsWith(\"@\")) {\n          const who = people.find((p) => p.name.split(\" \")[0].toLowerCase() === part.slice(1).toLowerCase());\n          if (who) {\n            const isMe = who.id === me;\n            return (\n              <span\n                className={cn(\n                  \"rounded px-0.5 font-medium\",\n                  isMe ? \"bg-warning/16 text-warning-foreground\" : \"bg-info/10 text-info-foreground\",\n                )}\n                key={i}\n              >\n                {part}\n              </span>\n            );\n          }\n        }\n        return <Fragment key={i}>{part}</Fragment>;\n      })}\n    </>\n  );\n}\n\nfunction PersonAvatar({ person, size = \"size-9\", presence }: { person?: ChatPerson; size?: string; presence?: boolean }) {\n  if (!person) return null;\n  const tiny = size === \"size-5\" || size === \"size-6\";\n  const tinyText = size === \"size-5\" ? \"text-[9px]\" : \"text-[10px]\";\n  return (\n    <span className=\"relative inline-flex shrink-0\">\n      <Avatar className={cn(size, tiny ? \"rounded-md\" : \"rounded-lg\")}>\n        <AvatarFallback className={cn(\"font-medium\", tiny ? cn(\"rounded-md\", tinyText) : \"rounded-lg text-xs\", avatarTone[person.tone])}>\n          {initials(person.name)}\n        </AvatarFallback>\n      </Avatar>\n      {presence && (\n        <span\n          className={cn(\n            \"absolute -right-0.5 -bottom-0.5 size-2 rounded-full ring-2 ring-sidebar\",\n            person.presence === \"active\" ? \"bg-success\" : person.presence === \"away\" ? \"bg-warning\" : \"border border-muted-foreground/60 bg-sidebar\",\n          )}\n        />\n      )}\n    </span>\n  );\n}\n\nexport type ChatView = \"threads\" | \"mentions\" | \"saved\";\n\nconst slugify = (v: string) =>\n  v\n    .toLowerCase()\n    .trim()\n    .replace(/[^a-z0-9]+/g, \"-\")\n    .replace(/^-+|-+$/g, \"\")\n    .slice(0, 40);\n\nfunction NavPill() {\n  return (\n    <motion.span\n      className=\"absolute inset-0 rounded-lg bg-accent\"\n      layoutId=\"chat-channel-pill\"\n      transition={spring}\n    />\n  );\n}\n\nfunction ChannelNav({\n  workspace,\n  channels,\n  people,\n  active,\n  view,\n  viewCounts,\n  onSelect,\n  onView,\n  onCreateChannel,\n  onJump,\n  onClose,\n}: {\n  workspace: string;\n  channels: ChatChannel[];\n  people: ChatPerson[];\n  active: string;\n  view: ChatView | null;\n  viewCounts: Record<ChatView, number>;\n  onSelect: (id: string) => void;\n  onView: (v: ChatView) => void;\n  onCreateChannel: (name: string) => void;\n  onJump: (mode: \"all\" | \"people\") => void;\n  onClose?: () => void;\n}) {\n  const [open, setOpen] = useState({ channel: true, dm: true });\n  const [creating, setCreating] = useState(false);\n  const [newName, setNewName] = useState(\"\");\n  const row =\n    \"group/row relative flex h-8 w-full cursor-pointer items-center gap-2 rounded-lg px-2.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring\";\n  const finishCreate = () => {\n    const name = slugify(newName);\n    if (name) onCreateChannel(name);\n    setCreating(false);\n    setNewName(\"\");\n  };\n  const section = (kind: \"channel\" | \"dm\", title: string) => (\n    <div className=\"mt-4\">\n      <div className=\"flex h-7 items-center ps-1.5 pe-1\">\n        <button\n          aria-expanded={open[kind]}\n          className=\"flex h-7 cursor-pointer items-center gap-1 rounded-md px-1 font-medium text-muted-foreground text-xs outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n          onClick={() => setOpen((o) => ({ ...o, [kind]: !o[kind] }))}\n          type=\"button\"\n        >\n          {title}\n          <ChevronDownIcon className={cn(\"size-3 transition-transform duration-200 ease-out\", !open[kind] && \"-rotate-90\")} />\n        </button>\n        <Button\n          aria-label={kind === \"channel\" ? \"Create a channel\" : \"New direct message\"}\n          className=\"ms-auto\"\n          onClick={() => {\n            setOpen((o) => ({ ...o, [kind]: true }));\n            if (kind === \"channel\") setCreating(true);\n            else onJump(\"people\");\n          }}\n          size=\"icon-xs\"\n          variant=\"ghost\"\n        >\n          <PlusIcon />\n        </Button>\n      </div>\n      <AnimatePresence initial={false}>\n        {open[kind] && (\n          <motion.ul\n            animate={{ height: \"auto\", opacity: 1 }}\n            className=\"-mx-1 flex flex-col gap-0.5 overflow-hidden px-1\"\n            exit={{ height: 0, opacity: 0 }}\n            initial={{ height: 0, opacity: 0 }}\n            transition={{ duration: 0.2, ease }}\n          >\n            {channels\n              .filter((c) => c.kind === kind)\n              .map((c) => {\n                const on = !view && c.id === active;\n                const loud = !c.muted && ((c.unread ?? 0) > 0 || (c.mentions ?? 0) > 0);\n                const person = c.with ? people.find((p) => p.id === c.with) : undefined;\n                return (\n                  <li key={c.id}>\n                    <button\n                      aria-current={on ? \"page\" : undefined}\n                      className={cn(\n                        row,\n                        on ? \"text-foreground\" : loud ? \"text-foreground\" : \"text-muted-foreground hover:text-foreground\",\n                        c.muted && !on && \"[&>svg]:opacity-60\",\n                      )}\n                      onClick={() => onSelect(c.id)}\n                      type=\"button\"\n                    >\n                      {on ? <NavPill /> : <span className=\"absolute inset-0 rounded-lg transition-colors group-hover/row:bg-accent\" />}\n                      {person ? (\n                        <span className=\"relative -ms-0.5\">\n                          <PersonAvatar person={person} presence size=\"size-6\" />\n                        </span>\n                      ) : c.private ? (\n                        <LockIcon className=\"relative size-3.5 shrink-0 opacity-70\" />\n                      ) : (\n                        <HashIcon className=\"relative size-3.5 shrink-0 opacity-70\" />\n                      )}\n                      <span className={cn(\"relative min-w-0 flex-1 truncate\", loud ? \"font-semibold\" : \"font-medium\")}>{c.name}</span>\n                      {c.muted && <BellOffIcon aria-label=\"Muted\" className=\"relative size-3 shrink-0\" />}\n                      {c.mentions ? (\n                        <span className=\"relative flex h-4.5 min-w-4.5 items-center justify-center rounded-full bg-red-600 px-1 font-semibold text-[11px] text-white tabular-nums\">\n                          {c.mentions}\n                        </span>\n                      ) : c.unread && kind === \"dm\" ? (\n                        <span className=\"relative flex h-4.5 min-w-4.5 items-center justify-center rounded-full bg-foreground px-1 font-semibold text-[11px] text-background tabular-nums\">\n                          {c.unread}\n                        </span>\n                      ) : null}\n                    </button>\n                  </li>\n                );\n              })}\n            {kind === \"channel\" && creating && (\n              <li>\n                <label className=\"flex h-8 items-center gap-2 rounded-lg border bg-background px-2.5 shadow-xs/5 focus-within:border-ring/60 focus-within:ring-3 focus-within:ring-ring/16 dark:bg-input/32\">\n                  <HashIcon className=\"size-3.5 shrink-0 text-muted-foreground\" />\n                  <input\n                    aria-label=\"New channel name\"\n                    autoFocus\n                    className=\"min-w-0 flex-1 bg-transparent font-medium outline-none placeholder:font-normal placeholder:text-muted-foreground\"\n                    onBlur={finishCreate}\n                    onChange={(e) => setNewName(e.target.value)}\n                    onKeyDown={(e) => {\n                      e.stopPropagation();\n                      if (e.key === \"Enter\") finishCreate();\n                      if (e.key === \"Escape\") {\n                        setNewName(\"\");\n                        setCreating(false);\n                      }\n                    }}\n                    placeholder=\"new-channel\"\n                    value={newName}\n                  />\n                  <CornerDownLeftIcon className=\"size-3.5 shrink-0 text-muted-foreground\" />\n                </label>\n              </li>\n            )}\n          </motion.ul>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n\n  const views: { id: ChatView; label: string; icon: typeof AtSignIcon }[] = [\n    { id: \"threads\", label: \"Threads\", icon: MessagesSquareIcon },\n    { id: \"mentions\", label: \"Mentions\", icon: AtSignIcon },\n    { id: \"saved\", label: \"Saved\", icon: BookmarkIcon },\n  ];\n\n  return (\n    <div className=\"flex h-full min-h-0 flex-col\">\n      <div className=\"flex items-center gap-2 px-3 pt-3 pb-2\">\n        <span className=\"flex size-7 shrink-0 items-center justify-center rounded-lg bg-teal-600 font-semibold text-[11px] text-white\">\n          {initials(workspace)}\n        </span>\n        <div className=\"min-w-0 flex-1 leading-tight\">\n          <div className=\"truncate font-medium\">{workspace}</div>\n          <div className=\"flex items-center gap-1 text-muted-foreground text-xs\">\n            <span className=\"size-1.5 rounded-full bg-success\" />\n            {people.filter((p) => p.presence === \"active\").length} online\n          </div>\n        </div>\n        {onClose && (\n          <Button aria-label=\"Close channels\" onClick={onClose} size=\"icon-sm\" variant=\"ghost\">\n            <XIcon />\n          </Button>\n        )}\n      </div>\n      <div className=\"px-2 pb-1\">\n        <button\n          className=\"flex h-8 w-full cursor-pointer items-center gap-2 rounded-lg border bg-background px-2.5 text-muted-foreground shadow-xs/5 outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring dark:bg-input/32\"\n          onClick={() => onJump(\"all\")}\n          type=\"button\"\n        >\n          <SearchIcon className=\"size-4\" />\n          <span className=\"flex-1 text-left\">Jump to…</span>\n          <Kbd>⌘K</Kbd>\n        </button>\n      </div>\n      <nav aria-label=\"Conversations\" className=\"min-h-0 flex-1 overflow-y-auto px-2 pb-3 [scrollbar-width:thin]\">\n        <LayoutGroup id=\"chat-nav\">\n          <div className=\"mt-2 flex flex-col gap-0.5\">\n            {views.map((v) => {\n              const on = view === v.id;\n              const n = viewCounts[v.id];\n              return (\n                <button\n                  aria-current={on ? \"page\" : undefined}\n                  className={cn(row, on ? \"text-foreground\" : \"text-muted-foreground hover:text-foreground\")}\n                  key={v.id}\n                  onClick={() => onView(v.id)}\n                  type=\"button\"\n                >\n                  {on ? <NavPill /> : <span className=\"absolute inset-0 rounded-lg transition-colors group-hover/row:bg-accent\" />}\n                  <v.icon className=\"relative size-4\" />\n                  <span className=\"relative flex-1 font-medium\">{v.label}</span>\n                  {n > 0 && <span className=\"relative text-muted-foreground text-xs tabular-nums\">{n}</span>}\n                </button>\n              );\n            })}\n          </div>\n          {section(\"channel\", \"Channels\")}\n          {section(\"dm\", \"Direct messages\")}\n        </LayoutGroup>\n      </nav>\n    </div>\n  );\n}\n\nfunction Reactions({\n  reactions,\n  me,\n  people,\n  onToggle,\n}: {\n  reactions: ChatReaction[];\n  me: string;\n  people: ChatPerson[];\n  onToggle: (emoji: string) => void;\n}) {\n  if (!reactions.length) return null;\n  return (\n    <div className=\"mt-1.5 flex flex-wrap gap-1\">\n      <AnimatePresence initial={false} mode=\"popLayout\">\n        {reactions.map((r) => {\n          const mine = r.people.includes(me);\n          const names = r.people.map((id) => (id === me ? \"You\" : (people.find((p) => p.id === id)?.name.split(\" \")[0] ?? id)));\n          return (\n            <motion.button\n              animate={{ opacity: 1, scale: 1 }}\n              aria-label={`${r.emoji} ${r.people.length}, ${names.join(\", \")}`}\n              aria-pressed={mine}\n              className={cn(\n                \"flex h-6 cursor-pointer items-center gap-1 rounded-full border px-2 text-xs outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring active:scale-95\",\n                mine ? \"border-info/40 bg-info/10 text-info-foreground\" : \"bg-background hover:border-foreground/20 dark:bg-input/32\",\n              )}\n              exit={{ opacity: 0, scale: 0.9 }}\n              initial={{ opacity: 0, scale: 0.9 }}\n              key={r.emoji}\n              layout\n              onClick={() => onToggle(r.emoji)}\n              title={names.join(\", \")}\n              transition={spring}\n              type=\"button\"\n            >\n              <span className=\"text-[13px] leading-none\">{r.emoji}</span>\n              <span className=\"relative inline-flex h-4 overflow-hidden font-medium tabular-nums\">\n                <AnimatePresence initial={false} mode=\"popLayout\">\n                  <motion.span\n                    animate={{ y: 0, opacity: 1 }}\n                    exit={{ y: -10, opacity: 0 }}\n                    initial={{ y: 10, opacity: 0 }}\n                    key={r.people.length}\n                    transition={{ duration: 0.18, ease }}\n                  >\n                    {r.people.length}\n                  </motion.span>\n                </AnimatePresence>\n              </span>\n            </motion.button>\n          );\n        })}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nfunction EmojiPicker({ onPick, className }: { onPick: (emoji: string) => void; className?: string }) {\n  const [open, setOpen] = useState(false);\n  return (\n    <Popover onOpenChange={setOpen} open={open}>\n      <PopoverTrigger\n        aria-label=\"Add reaction\"\n        className={cn(\n          \"flex size-8 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring data-popup-open:bg-accent\",\n          className,\n        )}\n      >\n        <SmilePlusIcon className=\"size-4\" />\n      </PopoverTrigger>\n      <PopoverPopup align=\"end\" className=\"p-0\" side=\"top\" sideOffset={6}>\n        <div className=\"grid grid-cols-4 gap-0.5 p-1\">\n          {emojiChoices.map((e) => (\n            <button\n              aria-label={`React with ${e}`}\n              className=\"flex size-9 cursor-pointer items-center justify-center rounded-lg text-lg outline-none transition-[background-color,scale] duration-100 hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring active:scale-90\"\n              key={e}\n              onClick={() => {\n                onPick(e);\n                setOpen(false);\n              }}\n              type=\"button\"\n            >\n              {e}\n            </button>\n          ))}\n        </div>\n      </PopoverPopup>\n    </Popover>\n  );\n}\n\nfunction MessageRow({\n  message,\n  grouped,\n  people,\n  me,\n  inThread,\n  isNew,\n  onReact,\n  onSave,\n  onOpenThread,\n  threadOpen,\n  flash,\n}: {\n  message: ChatMessage | ChatReply;\n  grouped: boolean;\n  people: ChatPerson[];\n  me: string;\n  inThread?: boolean;\n  isNew?: boolean;\n  onReact: (emoji: string) => void;\n  onSave: () => void;\n  onOpenThread?: () => void;\n  threadOpen?: boolean;\n  flash?: boolean;\n}) {\n  const author = people.find((p) => p.id === message.author);\n  const full = message as ChatMessage;\n  const replies = !inThread ? full.replies : undefined;\n  const repliers = replies ? Array.from(new Set(replies.map((r) => r.author))).slice(0, 3) : [];\n  return (\n    <motion.div\n      animate={{ opacity: 1, y: 0 }}\n      className={cn(\n        \"group/msg relative flex gap-3 rounded-xl px-3 transition-colors duration-300 hover:bg-accent/50 focus-within:bg-accent/50\",\n        grouped ? \"py-0.5\" : \"pt-2 pb-1 [&:not(:first-child)]:mt-1.5\",\n        threadOpen && \"bg-info/6 hover:bg-info/8\",\n        message.saved && \"bg-warning/6 hover:bg-warning/8\",\n        flash && \"bg-warning/16 duration-0\",\n      )}\n      data-msg={message.id}\n      initial={isNew ? { opacity: 0, y: 8 } : false}\n      transition={spring}\n    >\n      <div className=\"w-9 shrink-0\">\n        {grouped ? (\n          <span className=\"block pt-0.5 text-right text-[10px] text-muted-foreground tabular-nums leading-5 opacity-0 group-hover/msg:opacity-100\">\n            {message.time.replace(/ (AM|PM)/, \"\")}\n          </span>\n        ) : (\n          <PersonAvatar person={author} />\n        )}\n      </div>\n      <div className=\"min-w-0 flex-1\">\n        {message.saved && (\n          <div className=\"flex items-center gap-1 pb-0.5 font-medium text-warning-foreground text-xs\">\n            <BookmarkIcon className=\"size-3 fill-current\" />\n            Saved for later\n          </div>\n        )}\n        {!grouped && (\n          <div className=\"flex items-baseline gap-2\">\n            <span className=\"font-semibold\">{author?.name}</span>\n            <span className=\"text-muted-foreground text-xs tabular-nums\">{message.time}</span>\n          </div>\n        )}\n        <p className=\"text-pretty leading-6 [overflow-wrap:anywhere]\">\n          <RichText me={me} people={people} text={message.text} />\n        </p>\n        {full.file && (\n          <div className=\"mt-2 flex w-full max-w-sm items-center gap-3 rounded-xl border bg-card p-2.5 shadow-xs/5\">\n            <span className=\"flex size-10 shrink-0 items-center justify-center rounded-lg bg-rose-500/12 text-rose-600 dark:text-rose-400\">\n              <FileTextIcon className=\"size-5\" />\n            </span>\n            <span className=\"min-w-0 flex-1 leading-tight\">\n              <span className=\"block truncate font-medium\">{full.file.name}</span>\n              <span className=\"mt-0.5 block text-muted-foreground text-xs tabular-nums\">\n                {[fileExt(full.file.name), full.file.pages ? `${full.file.pages} pages` : null, full.file.size].filter(Boolean).join(\" · \")}\n              </span>\n            </span>\n          </div>\n        )}\n        <Reactions me={me} onToggle={onReact} people={people} reactions={message.reactions ?? []} />\n        {replies && replies.length > 0 && onOpenThread && (\n          <button\n            className=\"group/thr -ms-1.5 mt-1 flex cursor-pointer items-center gap-2 rounded-lg py-1 ps-1.5 pe-2 text-left outline-none transition-colors hover:bg-background focus-visible:ring-2 focus-visible:ring-ring dark:hover:bg-accent\"\n            onClick={onOpenThread}\n            type=\"button\"\n          >\n            <span className=\"flex gap-0.5\">\n              {repliers.map((id) => {\n                const p = people.find((x) => x.id === id);\n                return p ? <PersonAvatar key={id} person={p} size=\"size-5\" /> : null;\n              })}\n            </span>\n            <span className=\"font-medium text-info-foreground text-xs\">\n              {replies.length} {replies.length === 1 ? \"reply\" : \"replies\"}\n            </span>\n            <span className=\"text-muted-foreground text-xs group-hover/thr:hidden\">Last reply {replies[replies.length - 1].time}</span>\n            <span className=\"hidden text-muted-foreground text-xs group-hover/thr:inline\">View thread</span>\n          </button>\n        )}\n      </div>\n\n      <div className=\"pointer-events-none absolute -top-3 right-3 z-10 flex items-center gap-0.5 rounded-lg border bg-popover p-0.5 opacity-0 shadow-xs/5 transition-opacity duration-100 group-hover/msg:pointer-events-auto group-hover/msg:opacity-100 group-focus-within/msg:pointer-events-auto group-focus-within/msg:opacity-100\">\n        {[\"✅\", \"👀\", \"🙌\"].map((e) => (\n          <button\n            aria-label={`React with ${e}`}\n            className=\"flex size-8 cursor-pointer items-center justify-center rounded-md text-sm outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring\"\n            key={e}\n            onClick={() => onReact(e)}\n            type=\"button\"\n          >\n            {e}\n          </button>\n        ))}\n        <span className=\"mx-0.5 h-4 w-px bg-border\" />\n        <EmojiPicker onPick={onReact} />\n        {!inThread && onOpenThread && (\n          <button\n            aria-label=\"Reply in thread\"\n            className=\"flex size-8 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n            onClick={onOpenThread}\n            type=\"button\"\n          >\n            <MessageSquareTextIcon className=\"size-4\" />\n          </button>\n        )}\n        <button\n          aria-label={message.saved ? \"Remove from saved\" : \"Save for later\"}\n          aria-pressed={!!message.saved}\n          className={cn(\n            \"flex size-8 cursor-pointer items-center justify-center rounded-md outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring\",\n            message.saved ? \"text-warning-foreground\" : \"text-muted-foreground hover:text-foreground\",\n          )}\n          onClick={onSave}\n          type=\"button\"\n        >\n          <BookmarkIcon className={cn(\"size-4\", message.saved && \"fill-current\")} />\n        </button>\n      </div>\n    </motion.div>\n  );\n}\n\nfunction Composer({\n  placeholder,\n  value,\n  onChange,\n  onSend,\n  inputRef,\n  compact,\n  file,\n  onFile,\n}: {\n  placeholder: string;\n  value: string;\n  onChange: (v: string) => void;\n  onSend: () => void;\n  inputRef?: RefObject<HTMLTextAreaElement | null>;\n  compact?: boolean;\n  file?: ChatMessage[\"file\"];\n  onFile?: (file: ChatMessage[\"file\"]) => void;\n}) {\n  const local = useRef<HTMLTextAreaElement>(null);\n  const ref = inputRef ?? local;\n  const fileInput = useRef<HTMLInputElement>(null);\n  const canSend = !!value.trim() || !!file;\n  const wrap = (left: string, right = left) => {\n    const el = ref.current;\n    if (!el) return;\n    const start = el.selectionStart;\n    const end = el.selectionEnd;\n    onChange(value.slice(0, start) + left + value.slice(start, end) + right + value.slice(end));\n    requestAnimationFrame(() => {\n      el.focus();\n      el.setSelectionRange(start + left.length, end + left.length);\n    });\n  };\n  useLayoutEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    el.style.height = \"0px\";\n    el.style.height = `${Math.min(el.scrollHeight, 160)}px`;\n  }, [value, ref]);\n  const tool =\n    \"flex size-8 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\";\n  return (\n    <div className=\"rounded-2xl border bg-card shadow-xs/5 transition-shadow focus-within:border-ring/60 focus-within:ring-3 focus-within:ring-ring/16\">\n      <textarea\n        aria-label={placeholder}\n        className=\"block w-full resize-none bg-transparent px-3.5 pt-3 pb-1 text-sm leading-6 outline-none placeholder:text-muted-foreground/70\"\n        onChange={(e) => onChange(e.target.value)}\n        onKeyDown={(e) => {\n          if (e.key === \"Enter\" && !e.shiftKey && !e.nativeEvent.isComposing) {\n            e.preventDefault();\n            onSend();\n          }\n          if ((e.metaKey || e.ctrlKey) && !compact) {\n            const k = e.key.toLowerCase();\n            if (k === \"b\" || k === \"i\" || k === \"e\") {\n              e.preventDefault();\n              wrap(k === \"b\" ? \"**\" : k === \"i\" ? \"_\" : \"`\");\n            }\n          }\n        }}\n        placeholder={placeholder}\n        ref={ref}\n        rows={1}\n        value={value}\n      />\n      {file && (\n        <div className=\"px-2.5 pb-1\">\n          <span className=\"inline-flex h-8 max-w-full items-center gap-2 rounded-lg border bg-background ps-2 pe-0.5 text-xs dark:bg-input/32\">\n            <FileTextIcon className=\"size-3.5 shrink-0 text-muted-foreground\" />\n            <span className=\"min-w-0 truncate font-medium\">{file.name}</span>\n            <span className=\"shrink-0 text-muted-foreground tabular-nums\">{file.size}</span>\n            <button\n              aria-label={`Remove ${file.name}`}\n              className=\"flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n              onClick={() => onFile?.(undefined)}\n              type=\"button\"\n            >\n              <XIcon className=\"size-3\" />\n            </button>\n          </span>\n        </div>\n      )}\n      <div className=\"flex items-center gap-0.5 px-2 pb-2\">\n        {!compact && (\n          <>\n            <button aria-label=\"Bold\" className={tool} onClick={() => wrap(\"**\")} title=\"Bold (⌘B)\" type=\"button\">\n              <BoldIcon className=\"size-4\" />\n            </button>\n            <button aria-label=\"Italic\" className={tool} onClick={() => wrap(\"_\")} title=\"Italic (⌘I)\" type=\"button\">\n              <ItalicIcon className=\"size-4\" />\n            </button>\n            <button aria-label=\"Code\" className={cn(tool, \"hidden @lg:flex\")} onClick={() => wrap(\"`\")} title=\"Code (⌘E)\" type=\"button\">\n              <CodeIcon className=\"size-4\" />\n            </button>\n            <span className=\"mx-1 h-4 w-px bg-border\" />\n          </>\n        )}\n        {onFile && (\n          <>\n            <input\n              aria-hidden\n              className=\"hidden\"\n              onChange={(e) => {\n                const f = e.target.files?.[0];\n                if (f) onFile({ name: f.name, size: fileSize(f.size) });\n                e.target.value = \"\";\n                ref.current?.focus();\n              }}\n              ref={fileInput}\n              tabIndex={-1}\n              type=\"file\"\n            />\n            <button aria-label=\"Attach a file\" className={tool} onClick={() => fileInput.current?.click()} type=\"button\">\n              <PaperclipIcon className=\"size-4\" />\n            </button>\n          </>\n        )}\n        <button\n          aria-label=\"Mention someone\"\n          className={tool}\n          onClick={() => {\n            onChange(`${value}${value && !value.endsWith(\" \") ? \" \" : \"\"}@`);\n            requestAnimationFrame(() => ref.current?.focus());\n          }}\n          type=\"button\"\n        >\n          <AtSignIcon className=\"size-4\" />\n        </button>\n        <div className=\"ms-auto flex items-center gap-2\">\n          <span className=\"hidden text-muted-foreground text-xs @xl:inline\">\n            <Kbd className=\"h-4 text-[10px]\">⇧↵</Kbd> new line\n          </span>\n          <Button\n            aria-label=\"Send message\"\n            className=\"transition-[box-shadow,scale,opacity] duration-150 ease-out active:scale-[0.97]\"\n            disabled={!canSend}\n            onClick={onSend}\n            size=\"icon-sm\"\n            variant={canSend ? \"default\" : \"ghost\"}\n          >\n            <SendHorizontalIcon />\n          </Button>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nfunction TypingIndicator({ name }: { name: string | null }) {\n  return (\n    <div aria-live=\"polite\" className=\"flex h-6 items-center gap-2 px-1 text-muted-foreground text-xs\">\n      <AnimatePresence>\n        {name && (\n          <motion.span\n            animate={{ opacity: 1, y: 0 }}\n            className=\"flex items-center gap-2\"\n            exit={{ opacity: 0, y: 2 }}\n            initial={{ opacity: 0, y: 2 }}\n            transition={{ duration: 0.18, ease }}\n          >\n            <span aria-hidden className=\"flex gap-0.5\">\n              {[0, 1, 2].map((i) => (\n                <motion.span\n                  animate={{ opacity: [0.3, 1, 0.3] }}\n                  className=\"size-1 rounded-full bg-current\"\n                  key={i}\n                  transition={{ duration: 1, repeat: Number.POSITIVE_INFINITY, delay: i * 0.15, ease: \"easeInOut\" }}\n                />\n              ))}\n            </span>\n            <span>\n              <span className=\"font-medium text-foreground\">{name}</span> is typing\n            </span>\n          </motion.span>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nfunction formatClock(minutes: number) {\n  const h = Math.floor(minutes / 60) % 24;\n  const m = minutes % 60;\n  return `${((h + 11) % 12) + 1}:${String(m).padStart(2, \"0\")} ${h >= 12 ? \"PM\" : \"AM\"}`;\n}\n\ntype ChatHit = { channel: ChatChannel; message: ChatMessage; reply?: ChatReply };\n\nfunction JumpPalette({\n  mode,\n  channels,\n  people,\n  me,\n  onChannel,\n  onPerson,\n  onClose,\n}: {\n  mode: \"all\" | \"people\";\n  channels: ChatChannel[];\n  people: ChatPerson[];\n  me: string;\n  onChannel: (id: string) => void;\n  onPerson: (id: string) => void;\n  onClose: () => void;\n}) {\n  const [query, setQuery] = useState(\"\");\n  const [index, setIndex] = useState(0);\n  const q = query.trim().toLowerCase();\n  const items = [\n    ...(mode === \"all\"\n      ? channels.filter((c) => c.kind === \"channel\").map((c) => ({ key: c.id, kind: \"channel\" as const, label: c.name, channel: c, person: undefined }))\n      : []),\n    ...people\n      .filter((p) => p.id !== me)\n      .map((p) => ({ key: `p:${p.id}`, kind: \"person\" as const, label: p.name, channel: channels.find((c) => c.with === p.id), person: p })),\n  ].filter((i) => !q || i.label.toLowerCase().includes(q));\n  const current = Math.min(index, Math.max(0, items.length - 1));\n  const pick = (i: (typeof items)[number] | undefined) => {\n    if (!i) return;\n    if (i.person) onPerson(i.person.id);\n    else onChannel(i.key);\n  };\n  return (\n    <div className=\"absolute inset-0 z-50 flex justify-center px-4 pt-16\">\n      <motion.div\n        animate={{ opacity: 1 }}\n        aria-hidden\n        className=\"absolute inset-0 bg-black/24\"\n        exit={{ opacity: 0 }}\n        initial={{ opacity: 0 }}\n        onClick={onClose}\n        transition={{ duration: 0.15 }}\n      />\n      <motion.div\n        animate={{ opacity: 1, scale: 1, y: 0 }}\n        aria-label={mode === \"people\" ? \"New direct message\" : \"Jump to a conversation\"}\n        aria-modal=\"true\"\n        className=\"relative flex h-fit max-h-[420px] w-full max-w-md origin-top flex-col overflow-hidden rounded-2xl border bg-popover shadow-lg/10\"\n        exit={{ opacity: 0, scale: 0.98, y: -4 }}\n        initial={{ opacity: 0, scale: 0.97, y: -6 }}\n        onKeyDown={(e) => {\n          e.stopPropagation();\n          if (e.key === \"Escape\") onClose();\n          else if (e.key === \"ArrowDown\") {\n            e.preventDefault();\n            setIndex((current + 1) % Math.max(1, items.length));\n          } else if (e.key === \"ArrowUp\") {\n            e.preventDefault();\n            setIndex((current - 1 + items.length) % Math.max(1, items.length));\n          } else if (e.key === \"Enter\") {\n            e.preventDefault();\n            pick(items[current]);\n          }\n        }}\n        role=\"dialog\"\n        transition={{ duration: 0.16, ease }}\n      >\n        <label className=\"flex h-12 shrink-0 items-center gap-2.5 border-b px-4\">\n          <SearchIcon className=\"size-4 shrink-0 text-muted-foreground\" />\n          <input\n            aria-activedescendant={items[current] ? `jump-${items[current].key}` : undefined}\n            aria-controls=\"jump-list\"\n            aria-label={mode === \"people\" ? \"Find a person\" : \"Find a channel or person\"}\n            autoFocus\n            className=\"min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground\"\n            onChange={(e) => {\n              setQuery(e.target.value);\n              setIndex(0);\n            }}\n            placeholder={mode === \"people\" ? \"Message someone…\" : \"Jump to a channel or person…\"}\n            role=\"combobox\"\n            aria-expanded\n            value={query}\n          />\n          <Kbd>Esc</Kbd>\n        </label>\n        <div className=\"min-h-0 overflow-y-auto p-1.5 [scrollbar-width:thin]\" id=\"jump-list\" role=\"listbox\">\n          {items.length === 0 ? (\n            <p className=\"px-3 py-6 text-center text-muted-foreground text-xs\">Nobody or nothing called “{query}”.</p>\n          ) : (\n            items.map((i, n) => (\n              <div\n                aria-selected={n === current}\n                className={cn(\n                  \"flex h-9 cursor-pointer items-center gap-2.5 rounded-lg px-2.5\",\n                  n === current ? \"bg-accent text-foreground\" : \"text-muted-foreground\",\n                )}\n                id={`jump-${i.key}`}\n                key={i.key}\n                onClick={() => pick(i)}\n                onMouseMove={() => n !== current && setIndex(n)}\n                role=\"option\"\n                tabIndex={-1}\n              >\n                {i.person ? (\n                  <PersonAvatar person={i.person} presence size=\"size-6\" />\n                ) : i.channel?.private ? (\n                  <LockIcon className=\"size-3.5 shrink-0\" />\n                ) : (\n                  <HashIcon className=\"size-3.5 shrink-0\" />\n                )}\n                <span className=\"min-w-0 flex-1 truncate font-medium text-foreground\">{i.label}</span>\n                {i.person?.title && <span className=\"truncate text-xs\">{i.person.title}</span>}\n                {!i.person && i.channel?.members ? <span className=\"text-xs tabular-nums\">{i.channel.members} members</span> : null}\n              </div>\n            ))\n          )}\n        </div>\n      </motion.div>\n    </div>\n  );\n}\n\nconst viewMeta: Record<ChatView, { title: string; icon: typeof AtSignIcon; empty: string }> = {\n  threads: { title: \"Threads\", icon: MessagesSquareIcon, empty: \"Threads you follow show up here when someone replies.\" },\n  mentions: { title: \"Mentions\", icon: AtSignIcon, empty: \"When someone @mentions you, it lands here.\" },\n  saved: { title: \"Saved\", icon: BookmarkIcon, empty: \"Hover a message and press the bookmark to keep it here for later.\" },\n};\n\nfunction ViewList({\n  view,\n  hits,\n  people,\n  me,\n  onOpen,\n  onMenu,\n}: {\n  view: ChatView;\n  hits: ChatHit[];\n  people: ChatPerson[];\n  me: string;\n  onOpen: (hit: ChatHit) => void;\n  onMenu: () => void;\n}) {\n  const meta = viewMeta[view];\n  return (\n    <section aria-label={meta.title} className=\"flex min-w-0 flex-1 flex-col\">\n      <header className=\"flex h-13 shrink-0 items-center gap-2 border-b px-3 @lg:px-4\">\n        <Button aria-label=\"Open channels\" className=\"@4xl:hidden\" onClick={onMenu} size=\"icon-sm\" variant=\"ghost\">\n          <MenuIcon />\n        </Button>\n        <meta.icon className=\"size-4 text-muted-foreground\" />\n        <h2 className=\"font-semibold\">{meta.title}</h2>\n        <span className=\"text-muted-foreground text-xs tabular-nums\">{hits.length}</span>\n      </header>\n      <div className=\"min-h-0 flex-1 overflow-y-auto px-1 py-2 @lg:px-2 [scrollbar-width:thin]\">\n        {hits.length === 0 ? (\n          <div className=\"flex h-full flex-col items-center justify-center px-8 pb-10 text-center\">\n            <span className=\"flex size-10 items-center justify-center rounded-xl border bg-card text-muted-foreground shadow-xs/5\">\n              <meta.icon className=\"size-5\" />\n            </span>\n            <p className=\"mt-3 font-medium\">Nothing here yet</p>\n            <p className=\"mt-1 max-w-64 text-pretty text-muted-foreground text-xs\">{meta.empty}</p>\n          </div>\n        ) : (\n          <ul className=\"flex flex-col gap-0.5\">\n            {hits.map((h) => {\n              const m = h.reply ?? h.message;\n              const author = people.find((p) => p.id === m.author);\n              const replies = h.message.replies ?? [];\n              return (\n                <li key={`${h.channel.id}:${h.message.id}:${h.reply?.id ?? \"\"}`}>\n                  <button\n                    className=\"flex w-full cursor-pointer gap-3 rounded-xl px-3 py-2.5 text-left outline-none transition-colors hover:bg-accent/50 focus-visible:ring-2 focus-visible:ring-ring\"\n                    onClick={() => onOpen(h)}\n                    type=\"button\"\n                  >\n                    <PersonAvatar person={author} />\n                    <span className=\"min-w-0 flex-1\">\n                      <span className=\"flex items-baseline gap-2\">\n                        <span className=\"truncate font-semibold\">{author?.name}</span>\n                        <span className=\"shrink-0 text-muted-foreground text-xs tabular-nums\">{m.time}</span>\n                        <span className=\"ms-auto flex shrink-0 items-center gap-1 text-muted-foreground text-xs\">\n                          {h.channel.kind === \"dm\" ? h.channel.name : `#${h.channel.name}`}\n                          {h.reply && \" · thread\"}\n                        </span>\n                      </span>\n                      <span className=\"line-clamp-2 text-pretty leading-6\">\n                        <RichText me={me} people={people} text={m.text} />\n                      </span>\n                      {view === \"threads\" && replies.length > 0 && (\n                        <span className=\"mt-0.5 block font-medium text-info-foreground text-xs\">\n                          {replies.length} {replies.length === 1 ? \"reply\" : \"replies\"}\n                          <span className=\"font-normal text-muted-foreground\"> · last {replies[replies.length - 1].time}</span>\n                        </span>\n                      )}\n                    </span>\n                  </button>\n                </li>\n              );\n            })}\n          </ul>\n        )}\n      </div>\n    </section>\n  );\n}\n\nconst headerBtn =\n  \"flex h-7 cursor-pointer items-center gap-1.5 rounded-lg border px-2 text-muted-foreground text-xs outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring data-popup-open:bg-accent data-popup-open:text-foreground\";\n\nexport function TeamChat({\n  workspace = \"Kestrel\",\n  me = \"maya\",\n  people = defaultPeople,\n  channels: initialChannels = defaultChannels,\n  className,\n}: TeamChatProps) {\n  const [channels, setChannels] = useState(initialChannels);\n  const [active, setActive] = useState(initialChannels[0]?.id ?? \"\");\n  const [view, setView] = useState<ChatView | null>(null);\n  const [threadId, setThreadId] = useState<string | null>(null);\n  const [drawer, setDrawer] = useState(false);\n  const [jump, setJump] = useState<\"all\" | \"people\" | null>(null);\n  const [search, setSearch] = useState<string | null>(null);\n  const [pinsOpen, setPinsOpen] = useState(false);\n  const [drafts, setDrafts] = useState<Record<string, string>>({});\n  const [files, setFiles] = useState<Record<string, ChatMessage[\"file\"]>>({});\n  const [typing, setTyping] = useState<{ channel: string; name: string } | null>(null);\n  const [fresh, setFresh] = useState<Set<string>>(() => new Set());\n  const [unreadFrom, setUnreadFrom] = useState<Record<string, string>>({});\n  const [flash, setFlash] = useState<string | null>(null);\n  const rootRef = useRef<HTMLDivElement>(null);\n  const scrollRef = useRef<HTMLDivElement>(null);\n  const threadScrollRef = useRef<HTMLDivElement>(null);\n  const composerRef = useRef<HTMLTextAreaElement>(null);\n  const threadComposerRef = useRef<HTMLTextAreaElement>(null);\n  const searchRef = useRef<HTMLInputElement>(null);\n  const timers = useRef<number[]>([]);\n  const clock = useRef(11 * 60 + 14);\n  const nowTime = () => formatClock(++clock.current);\n\n  useEffect(() => () => timers.current.forEach((t) => window.clearTimeout(t)), []);\n\n  const channel = channels.find((c) => c.id === active) ?? channels[0];\n  const thread = view ? null : (channel.messages.find((m) => m.id === threadId) ?? null);\n  const dmPerson = channel.with ? people.find((p) => p.id === channel.with) : undefined;\n  const meName = people.find((p) => p.id === me)?.name.split(\" \")[0] ?? me;\n\n  const hits = useMemo(() => {\n    const mention = new RegExp(`@${meName}\\\\b`, \"i\");\n    const out: Record<ChatView, ChatHit[]> = { threads: [], mentions: [], saved: [] };\n    for (const c of channels) {\n      for (const m of c.messages) {\n        if (m.replies?.length) out.threads.push({ channel: c, message: m });\n        if (mention.test(m.text)) out.mentions.push({ channel: c, message: m });\n        if (m.saved) out.saved.push({ channel: c, message: m });\n        for (const r of m.replies ?? []) {\n          if (mention.test(r.text)) out.mentions.push({ channel: c, message: m, reply: r });\n          if (r.saved) out.saved.push({ channel: c, message: m, reply: r });\n        }\n      }\n    }\n    return out;\n  }, [channels, meName]);\n\n  const q = search?.trim().toLowerCase() ?? \"\";\n  const shown = q ? channel.messages.filter((m) => m.text.toLowerCase().includes(q)) : channel.messages;\n\n  const count = channel.messages.length;\n  const atBottom = useRef(true);\n  useLayoutEffect(() => {\n    const el = scrollRef.current;\n    if (el) el.scrollTop = el.scrollHeight;\n    atBottom.current = true;\n  }, [active, count, view, q]);\n  useEffect(() => {\n    const el = scrollRef.current;\n    if (!el) return;\n    const ro = new ResizeObserver(() => {\n      if (atBottom.current) el.scrollTop = el.scrollHeight;\n    });\n    ro.observe(el);\n    if (el.firstElementChild) ro.observe(el.firstElementChild);\n    return () => ro.disconnect();\n  }, [active, view]);\n  useLayoutEffect(() => {\n    if (!flash) return;\n    const box = scrollRef.current;\n    const target = box?.querySelector<HTMLElement>(`[data-msg=\"${flash}\"]`);\n    if (box && target) {\n      const offset = target.getBoundingClientRect().top - box.getBoundingClientRect().top;\n      box.scrollTo({ top: box.scrollTop + offset - (box.clientHeight - target.offsetHeight) / 2 });\n    }\n    const t = window.setTimeout(() => setFlash(null), 1400);\n    return () => window.clearTimeout(t);\n  }, [flash]);\n  const threadCount = thread?.replies?.length ?? 0;\n  const shownThread = useRef<string | null>(null);\n  useLayoutEffect(() => {\n    const el = threadScrollRef.current;\n    if (!el) return;\n    el.scrollTop = shownThread.current === threadId ? el.scrollHeight : 0;\n    shownThread.current = threadId;\n  }, [threadId, threadCount]);\n\n  const updateChannel = (id: string, fn: (c: ChatChannel) => ChatChannel) =>\n    setChannels((cs) => cs.map((c) => (c.id === id ? fn(c) : c)));\n\n  const select = (id: string) => {\n    const target = channels.find((c) => c.id === id);\n    if (target?.unread && target.messages.length >= target.unread) {\n      const first = target.messages[target.messages.length - target.unread];\n      setUnreadFrom((u) => ({ ...u, [id]: first.id }));\n    }\n    updateChannel(id, (c) => ({ ...c, unread: 0, mentions: 0 }));\n    setActive(id);\n    setView(null);\n    setSearch(null);\n    setThreadId(null);\n    setDrawer(false);\n  };\n\n  const closeJump = () => {\n    setJump(null);\n    requestAnimationFrame(() => composerRef.current?.focus({ preventScroll: true }));\n  };\n\n  const openDm = (personId: string) => {\n    const existing = channels.find((c) => c.with === personId);\n    if (existing) select(existing.id);\n    else {\n      const p = people.find((x) => x.id === personId);\n      const id = `dm-${personId}`;\n      setChannels((cs) => [...cs, { id, name: p?.name ?? personId, kind: \"dm\", with: personId, messages: [] }]);\n      setActive(id);\n      setView(null);\n      setSearch(null);\n      setThreadId(null);\n      setDrawer(false);\n    }\n    closeJump();\n  };\n\n  const createChannel = (name: string) => {\n    if (channels.some((c) => c.id === name)) return select(name);\n    setChannels((cs) => {\n      const firstDm = cs.findIndex((c) => c.kind === \"dm\");\n      const next: ChatChannel = { id: name, name, kind: \"channel\", members: 1, messages: [] };\n      return firstDm < 0 ? [...cs, next] : [...cs.slice(0, firstDm), next, ...cs.slice(firstDm)];\n    });\n    setActive(name);\n    setView(null);\n    setSearch(null);\n    setThreadId(null);\n    setDrawer(false);\n    requestAnimationFrame(() => composerRef.current?.focus({ preventScroll: true }));\n  };\n\n  const toggleReaction = (reactions: ChatReaction[] | undefined, emoji: string): ChatReaction[] => {\n    const list = reactions ?? [];\n    const hit = list.find((r) => r.emoji === emoji);\n    if (!hit) return [...list, { emoji, people: [me] }];\n    const who = hit.people.includes(me) ? hit.people.filter((p) => p !== me) : [...hit.people, me];\n    return who.length ? list.map((r) => (r.emoji === emoji ? { ...r, people: who } : r)) : list.filter((r) => r.emoji !== emoji);\n  };\n\n  const editMessage = (msgId: string, fn: (m: ChatMessage) => ChatMessage) =>\n    updateChannel(channel.id, (c) => ({ ...c, messages: c.messages.map((m) => (m.id === msgId ? fn(m) : m)) }));\n\n  const editReply = (msgId: string, replyId: string, fn: (r: ChatReply) => ChatReply) =>\n    editMessage(msgId, (m) => ({ ...m, replies: m.replies?.map((r) => (r.id === replyId ? fn(r) : r)) }));\n\n  const markFresh = (id: string) => setFresh((f) => new Set(f).add(id));\n\n  const send = () => {\n    const text = (drafts[channel.id] ?? \"\").trim();\n    const file = files[channel.id];\n    if (!text && !file) return;\n    const id = `m${Date.now()}`;\n    const chId = channel.id;\n    updateChannel(chId, (c) => ({ ...c, messages: [...c.messages, { id, day: \"Today\", author: me, time: nowTime(), text, file }] }));\n    markFresh(id);\n    setDrafts((d) => ({ ...d, [chId]: \"\" }));\n    setFiles((f) => ({ ...f, [chId]: undefined }));\n    setSearch(null);\n    const auto = autoReplies[chId] ?? (channel.with ? { author: channel.with, text: \"Sounds good, talk soon.\" } : null);\n    if (auto && !typing) {\n      const who = people.find((p) => p.id === auto.author);\n      timers.current.push(\n        window.setTimeout(() => setTyping({ channel: chId, name: who?.name.split(\" \")[0] ?? \"Someone\" }), 900),\n        window.setTimeout(() => {\n          const rid = `m${Date.now()}`;\n          setTyping(null);\n          updateChannel(chId, (c) => ({ ...c, messages: [...c.messages, { id: rid, day: \"Today\", author: auto.author, time: nowTime(), text: auto.text }] }));\n          markFresh(rid);\n        }, 2600),\n      );\n    }\n  };\n\n  const sendReply = () => {\n    if (!thread) return;\n    const key = `thread:${thread.id}`;\n    const text = (drafts[key] ?? \"\").trim();\n    if (!text) return;\n    const id = `r${Date.now()}`;\n    editMessage(thread.id, (m) => ({ ...m, replies: [...(m.replies ?? []), { id, author: me, time: nowTime(), text }] }));\n    markFresh(id);\n    setDrafts((d) => ({ ...d, [key]: \"\" }));\n  };\n\n  const openThread = (id: string) => {\n    setThreadId(id);\n    requestAnimationFrame(() => threadComposerRef.current?.focus({ preventScroll: true }));\n  };\n\n  const openHit = (h: ChatHit) => {\n    select(h.channel.id);\n    if (h.reply || view === \"threads\") openThread(h.message.id);\n    else setFlash(h.message.id);\n  };\n\n  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n    if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"k\") {\n      e.preventDefault();\n      setDrawer(false);\n      setJump(\"all\");\n      return;\n    }\n    if (e.key === \"Escape\") {\n      if (drawer) setDrawer(false);\n      else if (threadId) {\n        setThreadId(null);\n        composerRef.current?.focus({ preventScroll: true });\n      }\n      return;\n    }\n    if (e.altKey && (e.key === \"ArrowDown\" || e.key === \"ArrowUp\")) {\n      e.preventDefault();\n      const idx = view ? -1 : channels.findIndex((c) => c.id === active);\n      const next = channels[(idx + (e.key === \"ArrowDown\" ? 1 : -1) + channels.length) % channels.length];\n      select(next.id);\n      return;\n    }\n    if (isTyping(e) || e.metaKey || e.ctrlKey || e.altKey || view) return;\n    if (e.key.length === 1 && /\\S/.test(e.key)) composerRef.current?.focus({ preventScroll: true });\n  };\n\n  const typingHere = typing?.channel === channel.id ? typing.name : null;\n  const marker = q ? undefined : unreadFrom[channel.id];\n  const pinned = (channel.pinned ?? []).map((id) => channel.messages.find((m) => m.id === id)).filter((m): m is ChatMessage => !!m);\n\n  const navProps = {\n    workspace,\n    channels,\n    people,\n    active,\n    view,\n    viewCounts: { threads: 0, mentions: hits.mentions.length, saved: hits.saved.length },\n    onSelect: select,\n    onView: (v: ChatView) => {\n      setView(v);\n      setThreadId(null);\n      setSearch(null);\n      setDrawer(false);\n    },\n    onCreateChannel: createChannel,\n    onJump: (mode: \"all\" | \"people\") => {\n      setDrawer(false);\n      setJump(mode);\n    },\n  };\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <TooltipProvider delay={500}>\n        <div\n          className={cn(\n            \"@container relative isolate flex h-[760px] w-full overflow-hidden bg-sidebar text-foreground text-sm outline-none\",\n            className,\n          )}\n          onKeyDown={onKeyDown}\n          ref={rootRef}\n          tabIndex={-1}\n        >\n          <aside aria-label=\"Channels\" className=\"hidden w-60 shrink-0 @4xl:block\">\n            <ChannelNav {...navProps} />\n          </aside>\n\n          <AnimatePresence>\n            {drawer && (\n              <>\n                <motion.div\n                  animate={{ opacity: 1 }}\n                  aria-hidden\n                  className=\"absolute inset-0 z-40 bg-black/32 @4xl:hidden\"\n                  exit={{ opacity: 0 }}\n                  initial={{ opacity: 0 }}\n                  onClick={() => setDrawer(false)}\n                  transition={{ duration: 0.2 }}\n                />\n                <motion.div\n                  animate={{ x: 0 }}\n                  aria-label=\"Channels\"\n                  aria-modal=\"true\"\n                  className=\"absolute inset-y-2 left-2 z-50 w-[264px] max-w-[calc(100%-3rem)] overflow-hidden rounded-2xl border bg-sidebar shadow-lg/10 @4xl:hidden\"\n                  exit={{ x: \"-110%\" }}\n                  initial={{ x: \"-110%\" }}\n                  role=\"dialog\"\n                  transition={panelSpring}\n                >\n                  <ChannelNav {...navProps} onClose={() => setDrawer(false)} />\n                </motion.div>\n              </>\n            )}\n          </AnimatePresence>\n\n          <AnimatePresence>\n            {jump && (\n              <JumpPalette\n                channels={channels}\n                key={jump}\n                me={me}\n                mode={jump}\n                onChannel={(id) => {\n                  select(id);\n                  closeJump();\n                }}\n                onClose={closeJump}\n                onPerson={openDm}\n                people={people}\n              />\n            )}\n          </AnimatePresence>\n\n          <main className=\"relative flex min-w-0 flex-1 overflow-hidden bg-background @4xl:my-2 @4xl:me-2 @4xl:rounded-2xl @4xl:border @4xl:shadow-xs/5\">\n            {view ? (\n              <ViewList hits={hits[view]} me={me} onMenu={() => setDrawer(true)} onOpen={openHit} people={people} view={view} />\n            ) : (\n              <section aria-label={channel.kind === \"dm\" ? channel.name : `#${channel.name}`} className=\"flex min-w-0 flex-1 flex-col\">\n                <header className=\"flex h-13 shrink-0 items-center gap-1.5 border-b px-3 @lg:px-4\">\n                  <Button aria-label=\"Open channels\" className=\"@4xl:hidden\" onClick={() => setDrawer(true)} size=\"icon-sm\" variant=\"ghost\">\n                    <MenuIcon />\n                  </Button>\n                  {dmPerson ? (\n                    <PersonAvatar person={dmPerson} size=\"size-6\" />\n                  ) : channel.private ? (\n                    <LockIcon className=\"size-4 shrink-0 text-muted-foreground\" />\n                  ) : (\n                    <HashIcon className=\"size-4 shrink-0 text-muted-foreground\" />\n                  )}\n                  <div className=\"ms-0.5 flex min-w-0 flex-1 items-baseline gap-2\">\n                    <h2 className=\"truncate font-semibold\">{channel.name}</h2>\n                    {channel.topic && <span className=\"hidden truncate text-muted-foreground text-xs @2xl:block\">{channel.topic}</span>}\n                    {dmPerson?.title && <span className=\"hidden truncate text-muted-foreground text-xs @2xl:block\">{dmPerson.title}</span>}\n                  </div>\n                  {channel.members ? (\n                    <Popover>\n                      <PopoverTrigger aria-label={`${channel.members} members`} className={cn(headerBtn, \"me-1 hidden @md:flex\")}>\n                        <UsersIcon className=\"size-3.5\" />\n                        <span className=\"tabular-nums\">{channel.members}</span>\n                      </PopoverTrigger>\n                      <PopoverPopup align=\"end\" className=\"w-64\">\n                        <div className=\"-mx-1 -my-1.5 flex flex-col gap-0.5\">\n                          <p className=\"px-1 pb-1.5 font-medium text-muted-foreground text-xs\">\n                            {channel.members} {channel.members === 1 ? \"member\" : \"members\"}\n                          </p>\n                          {(channel.members === 1 ? people.filter((p) => p.id === me) : people).map((p) => (\n                            <div className=\"flex h-9 items-center gap-2.5 px-1\" key={p.id}>\n                              <PersonAvatar person={p} presence size=\"size-6\" />\n                              <span className=\"min-w-0 flex-1 truncate font-medium\">\n                                {p.name}\n                                {p.id === me && <span className=\"font-normal text-muted-foreground\"> (you)</span>}\n                              </span>\n                              <span className=\"truncate text-muted-foreground text-xs\">{p.title}</span>\n                            </div>\n                          ))}\n                          {channel.members > people.length && (\n                            <p className=\"px-1 pt-1 text-muted-foreground text-xs tabular-nums\">and {channel.members - people.length} more</p>\n                          )}\n                        </div>\n                      </PopoverPopup>\n                    </Popover>\n                  ) : null}\n                  <Popover onOpenChange={setPinsOpen} open={pinsOpen}>\n                    <Tooltip>\n                      <TooltipTrigger\n                        render={<PopoverTrigger render={<Button aria-label=\"Pinned messages\" size=\"icon-sm\" variant=\"ghost\" />} />}\n                      >\n                        <PinIcon />\n                      </TooltipTrigger>\n                      <TooltipPopup>Pinned</TooltipPopup>\n                    </Tooltip>\n                    <PopoverPopup align=\"end\" className=\"w-80\">\n                      <div className=\"-mx-1 -my-1.5\">\n                        <p className=\"px-1 pb-1.5 font-medium text-muted-foreground text-xs\">Pinned in {dmPerson ? \"this conversation\" : `#${channel.name}`}</p>\n                        {pinned.length === 0 ? (\n                          <p className=\"px-1 py-3 text-pretty text-muted-foreground text-xs\">Nothing pinned yet. Pins keep decisions and links easy to find.</p>\n                        ) : (\n                          <div className=\"flex flex-col gap-0.5\">\n                            {pinned.map((m) => {\n                              const a = people.find((p) => p.id === m.author);\n                              return (\n                                <button\n                                  className=\"flex w-full cursor-pointer gap-2.5 rounded-lg p-1.5 text-left outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring\"\n                                  key={m.id}\n                                  onClick={() => {\n                                    setPinsOpen(false);\n                                    setSearch(null);\n                                    setFlash(m.id);\n                                  }}\n                                  type=\"button\"\n                                >\n                                  <PersonAvatar person={a} size=\"size-6\" />\n                                  <span className=\"min-w-0 flex-1\">\n                                    <span className=\"flex items-baseline gap-1.5 text-xs\">\n                                      <span className=\"font-semibold\">{a?.name}</span>\n                                      <span className=\"text-muted-foreground tabular-nums\">\n                                        {m.day} {m.time}\n                                      </span>\n                                    </span>\n                                    <span className=\"line-clamp-2 text-pretty text-xs leading-5\">\n                                      <RichText me={me} people={people} text={m.text} />\n                                    </span>\n                                  </span>\n                                </button>\n                              );\n                            })}\n                          </div>\n                        )}\n                      </div>\n                    </PopoverPopup>\n                  </Popover>\n                  <Tooltip>\n                    <TooltipTrigger\n                      render={\n                        <Button\n                          aria-label=\"Search in channel\"\n                          aria-pressed={search !== null}\n                          onClick={() => {\n                            if (search === null) {\n                              setSearch(\"\");\n                              requestAnimationFrame(() => searchRef.current?.focus());\n                            } else setSearch(null);\n                          }}\n                          size=\"icon-sm\"\n                          variant=\"ghost\"\n                        />\n                      }\n                    >\n                      <SearchIcon />\n                    </TooltipTrigger>\n                    <TooltipPopup>Search</TooltipPopup>\n                  </Tooltip>\n                </header>\n\n                {search !== null && (\n                  <div className=\"flex h-11 shrink-0 items-center gap-2 border-b px-4\">\n                    <SearchIcon className=\"size-4 shrink-0 text-muted-foreground\" />\n                    <input\n                      aria-label={`Search ${dmPerson ? dmPerson.name : `#${channel.name}`}`}\n                      className=\"min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-foreground\"\n                      onChange={(e) => setSearch(e.target.value)}\n                      onKeyDown={(e) => {\n                        if (e.key === \"Escape\") {\n                          e.stopPropagation();\n                          setSearch(null);\n                          composerRef.current?.focus({ preventScroll: true });\n                        }\n                      }}\n                      placeholder={`Search ${dmPerson ? dmPerson.name.split(\" \")[0] : `#${channel.name}`}`}\n                      ref={searchRef}\n                      value={search}\n                    />\n                    {q && (\n                      <span className=\"shrink-0 text-muted-foreground text-xs tabular-nums\">\n                        {shown.length} {shown.length === 1 ? \"result\" : \"results\"}\n                      </span>\n                    )}\n                    <Button aria-label=\"Close search\" onClick={() => setSearch(null)} size=\"icon-xs\" variant=\"ghost\">\n                      <XIcon />\n                    </Button>\n                  </div>\n                )}\n\n                <div\n                  className=\"min-h-0 flex-1 overflow-y-auto [scrollbar-width:thin]\"\n                  onScroll={(e) => {\n                    const el = e.currentTarget;\n                    atBottom.current = el.scrollHeight - el.scrollTop - el.clientHeight < 24;\n                  }}\n                  ref={scrollRef}\n                >\n                  <div className=\"flex min-h-full flex-col justify-end px-1 pt-6 pb-2 @lg:px-2\">\n                    {q && shown.length === 0 ? (\n                      <div className=\"flex flex-1 flex-col items-center justify-center pb-10 text-center\">\n                        <span className=\"flex size-10 items-center justify-center rounded-xl border bg-card text-muted-foreground shadow-xs/5\">\n                          <SearchIcon className=\"size-5\" />\n                        </span>\n                        <p className=\"mt-3 font-medium\">No messages match</p>\n                        <p className=\"mt-1 text-muted-foreground text-xs\">Nothing in {dmPerson ? \"this conversation\" : `#${channel.name}`} mentions “{search?.trim()}”.</p>\n                      </div>\n                    ) : (\n                      !q && (\n                        <div className=\"mb-4 px-3\">\n                          <span className=\"flex size-10 items-center justify-center rounded-xl border bg-card text-muted-foreground shadow-xs/5\">\n                            {dmPerson ? <PersonAvatar person={dmPerson} size=\"size-10\" /> : <HashIcon className=\"size-5\" />}\n                          </span>\n                          <h3 className=\"mt-3 font-heading font-semibold text-base\">{dmPerson ? dmPerson.name : `Welcome to #${channel.name}`}</h3>\n                          <p className=\"mt-0.5 text-pretty text-muted-foreground text-xs\">\n                            {dmPerson\n                              ? `This is the start of your conversation with ${dmPerson.name.split(\" \")[0]}.`\n                              : (channel.topic ?? \"You created this channel today. Say what it's for so people know when to use it.\")}\n                          </p>\n                        </div>\n                      )\n                    )}\n                    {shown.map((m, i) => {\n                      const prev = shown[i - 1];\n                      const newDay = !prev || prev.day !== m.day;\n                      const grouped = !q && !newDay && prev.author === m.author && !prev.replies?.length && marker !== m.id && !m.saved;\n                      return (\n                        <Fragment key={m.id}>\n                          {newDay && (\n                            <>\n                              <div aria-hidden className=\"mx-3 mt-4 h-px bg-border\" />\n                              <div className=\"pointer-events-none sticky top-2 z-10 -mt-[11px] mb-3 flex justify-center\" role=\"separator\">\n                                <span className=\"h-[22px] rounded-full border bg-background px-2.5 font-medium text-muted-foreground text-xs leading-5\">\n                                  {m.day}\n                                </span>\n                              </div>\n                            </>\n                          )}\n                          {marker === m.id && (\n                            <div className=\"relative my-2 flex items-center\" role=\"separator\">\n                              <span className=\"absolute inset-x-3 h-px bg-destructive/50\" />\n                              <span className=\"relative ms-auto me-3 rounded-full bg-background ps-2 font-semibold text-[11px] text-destructive-foreground\">\n                                New\n                              </span>\n                            </div>\n                          )}\n                          <MessageRow\n                            flash={flash === m.id}\n                            grouped={grouped}\n                            isNew={fresh.has(m.id)}\n                            me={me}\n                            message={m}\n                            onOpenThread={() => openThread(m.id)}\n                            onReact={(emoji) => editMessage(m.id, (x) => ({ ...x, reactions: toggleReaction(x.reactions, emoji) }))}\n                            onSave={() => editMessage(m.id, (x) => ({ ...x, saved: !x.saved }))}\n                            people={people}\n                            threadOpen={threadId === m.id}\n                          />\n                        </Fragment>\n                      );\n                    })}\n                  </div>\n                </div>\n\n                <div className=\"shrink-0 px-3 pb-3 @lg:px-4\">\n                  <TypingIndicator name={typingHere} />\n                  <Composer\n                    file={files[channel.id]}\n                    inputRef={composerRef}\n                    onChange={(v) => setDrafts((d) => ({ ...d, [channel.id]: v }))}\n                    onFile={(f) => setFiles((x) => ({ ...x, [channel.id]: f }))}\n                    onSend={send}\n                    placeholder={dmPerson ? `Message ${dmPerson.name.split(\" \")[0]}` : `Message #${channel.name}`}\n                    value={drafts[channel.id] ?? \"\"}\n                  />\n                </div>\n              </section>\n            )}\n\n            <AnimatePresence>\n              {thread && (\n                <motion.aside\n                  animate={{ x: 0, opacity: 1 }}\n                  aria-label=\"Thread\"\n                  className=\"absolute inset-0 z-30 flex flex-col border-s bg-background @5xl:static @5xl:z-auto @5xl:w-[380px] @5xl:shrink-0\"\n                  exit={{ x: 40, opacity: 0 }}\n                  initial={{ x: 40, opacity: 0 }}\n                  key=\"thread\"\n                  transition={{ duration: 0.22, ease }}\n                >\n                  <header className=\"flex h-13 shrink-0 items-center gap-2 border-b px-3\">\n                    <Button aria-label=\"Back to channel\" className=\"@5xl:hidden\" onClick={() => setThreadId(null)} size=\"icon-sm\" variant=\"ghost\">\n                      <ArrowLeftIcon />\n                    </Button>\n                    <div className=\"min-w-0 flex-1 leading-tight\">\n                      <div className=\"font-semibold\">Thread</div>\n                      <div className=\"truncate text-muted-foreground text-xs\">{dmPerson ? dmPerson.name : `#${channel.name}`}</div>\n                    </div>\n                    <span className=\"hidden text-muted-foreground text-xs @5xl:inline\">\n                      <Kbd>Esc</Kbd>\n                    </span>\n                    <Button aria-label=\"Close thread\" className=\"hidden @5xl:inline-flex\" onClick={() => setThreadId(null)} size=\"icon-sm\" variant=\"ghost\">\n                      <XIcon />\n                    </Button>\n                  </header>\n                  <div className=\"min-h-0 flex-1 overflow-y-auto px-1 py-3 [scrollbar-width:thin]\" ref={threadScrollRef}>\n                    <MessageRow\n                      grouped={false}\n                      inThread\n                      me={me}\n                      message={thread}\n                      onReact={(emoji) => editMessage(thread.id, (x) => ({ ...x, reactions: toggleReaction(x.reactions, emoji) }))}\n                      onSave={() => editMessage(thread.id, (x) => ({ ...x, saved: !x.saved }))}\n                      people={people}\n                    />\n                    <div className=\"relative my-3 flex items-center px-3\" role=\"separator\">\n                      <span className=\"pe-2 text-muted-foreground text-xs tabular-nums\">\n                        {threadCount} {threadCount === 1 ? \"reply\" : \"replies\"}\n                      </span>\n                      <span className=\"h-px flex-1 bg-border\" />\n                    </div>\n                    {(thread.replies ?? []).map((r, i, all) => (\n                      <MessageRow\n                        grouped={i > 0 && all[i - 1].author === r.author && !r.saved}\n                        inThread\n                        isNew={fresh.has(r.id)}\n                        key={r.id}\n                        me={me}\n                        message={r}\n                        onReact={(emoji) => editReply(thread.id, r.id, (x) => ({ ...x, reactions: toggleReaction(x.reactions, emoji) }))}\n                        onSave={() => editReply(thread.id, r.id, (x) => ({ ...x, saved: !x.saved }))}\n                        people={people}\n                      />\n                    ))}\n                  </div>\n                  <div className=\"shrink-0 px-3 pt-1 pb-3\">\n                    <Composer\n                      compact\n                      inputRef={threadComposerRef}\n                      onChange={(v) => setDrafts((d) => ({ ...d, [`thread:${thread.id}`]: v }))}\n                      onSend={sendReply}\n                      placeholder=\"Reply in thread\"\n                      value={drafts[`thread:${thread.id}`] ?? \"\"}\n                    />\n                  </div>\n                </motion.aside>\n              )}\n            </AnimatePresence>\n          </main>\n        </div>\n      </TooltipProvider>\n    </MotionConfig>\n  );\n}\n"
    }
  ]
}