{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "code-review",
  "type": "registry:block",
  "title": "Code Review",
  "description": "A pull request review with a file tree, split or unified diffs with word-level highlights, inline threads you can reply to and resolve, Viewed checkboxes that fold files away, and an approve or request-changes panel.",
  "categories": [
    "screen",
    "Dev"
  ],
  "dependencies": [
    "motion",
    "lucide-react",
    "vitest"
  ],
  "registryDependencies": [
    "utils",
    "https://coss.com/ui/r/avatar.json",
    "https://coss.com/ui/r/badge.json",
    "https://coss.com/ui/r/button.json",
    "https://coss.com/ui/r/kbd.json"
  ],
  "files": [
    {
      "path": "registry/devl/code-review.tsx",
      "type": "registry:component",
      "content": "\"use client\";\n\nimport { AnimatePresence, MotionConfig, motion } from \"motion/react\";\nimport {\n  CheckIcon,\n  ChevronDownIcon,\n  ChevronRightIcon,\n  CircleCheckIcon,\n  FileCode2Icon,\n  FileDiffIcon,\n  FilePlus2Icon,\n  FolderIcon,\n  GitBranchIcon,\n  GitPullRequestIcon,\n  MessageSquareIcon,\n  PanelLeftIcon,\n  PlusIcon,\n  XIcon,\n} from \"lucide-react\";\nimport {\n  Fragment,\n  type KeyboardEvent,\n  type ReactNode,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { Avatar, AvatarFallback } from \"@/components/ui/avatar\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Kbd } from \"@/components/ui/kbd\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ReviewTone = \"blue\" | \"orange\" | \"teal\" | \"violet\" | \"rose\" | \"amber\" | \"emerald\" | \"sky\";\n\nexport interface ReviewPerson {\n  id: string;\n  name: string;\n  tone: ReviewTone;\n}\n\nexport interface DiffFile {\n  path: string;\n  status: \"added\" | \"modified\" | \"deleted\";\n  hunks: { header: string; oldStart: number; newStart: number; lines: string }[];\n}\n\nexport interface ReviewComment {\n  id: string;\n  author: string;\n  body: string;\n  time: string;\n}\n\nexport interface ReviewThread {\n  id: string;\n  file: string;\n  line: number;\n  side: \"new\" | \"old\";\n  resolved?: boolean;\n  comments: ReviewComment[];\n}\n\nexport interface CodeReviewProps {\n  title?: string;\n  number?: number;\n  author?: string;\n  base?: string;\n  head?: string;\n  me?: string;\n  people?: ReviewPerson[];\n  files?: DiffFile[];\n  threads?: ReviewThread[];\n  className?: string;\n}\n\nconst avatarTone: Record<ReviewTone, 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 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\nfunction PersonAvatar({ person, size = \"size-6\" }: { person?: ReviewPerson; size?: string }) {\n  if (!person) return null;\n  return (\n    <Avatar className={size}>\n      <AvatarFallback className={cn(\"font-medium text-[10px]\", avatarTone[person.tone])}>{initials(person.name)}</AvatarFallback>\n    </Avatar>\n  );\n}\n\nconst defaultPeople: ReviewPerson[] = [\n  { id: \"maya\", name: \"Maya Okafor\", tone: \"teal\" },\n  { id: \"sam\", name: \"Sam Whitfield\", tone: \"amber\" },\n  { id: \"leo\", name: \"Leo Marchetti\", tone: \"rose\" },\n  { id: \"jonas\", name: \"Jonas Weber\", tone: \"blue\" },\n];\n\nconst defaultFiles: DiffFile[] = [\n  {\n    path: \"src/queue/consumer.ts\",\n    status: \"modified\",\n    hunks: [\n      {\n        header: \"@@ -1,7 +1,8 @@\",\n        oldStart: 1,\n        newStart: 1,\n        lines: ` import { Queue, type Message } from \"./queue\";\n import { deliver } from \"../delivery\";\n-import { backoff } from \"./retry\";\n+import { backoff, MAX_ATTEMPTS } from \"./retry\";\n+import { deadLetter } from \"./dead-letter\";\n import { metrics } from \"../metrics\";\n\n const queue = new Queue(\"webhooks\");`,\n      },\n      {\n        header: \"@@ -38,15 +39,31 @@ export async function consume(batchSize = 50)\",\n        oldStart: 38,\n        newStart: 39,\n        lines: ` export async function consume(batchSize = 50) {\n   const messages = await queue.receive(batchSize);\n\n   for (const message of messages) {\n-    try {\n-      await deliver(message.body);\n-      await queue.ack(message);\n-    } catch (error) {\n-      await queue.retry(message, backoff(message.attempts));\n-    }\n+    await handle(message);\n   }\n\n   metrics.gauge(\"webhooks.lag\", await queue.lag());\n }\n+\n+async function handle(message: Message) {\n+  try {\n+    await deliver(message.body);\n+    await queue.ack(message);\n+  } catch (error) {\n+    if (message.attempts + 1 >= MAX_ATTEMPTS) {\n+      // Park it so one bad payload can't hold up the partition.\n+      await deadLetter.put(message, error);\n+      await queue.ack(message);\n+      metrics.increment(\"webhooks.dead_lettered\");\n+      return;\n+    }\n+    await queue.retry(message, backoff(message.attempts));\n+  }\n+}`,\n      },\n    ],\n  },\n  {\n    path: \"src/queue/dead-letter.ts\",\n    status: \"added\",\n    hunks: [\n      {\n        header: \"@@ -0,0 +1,35 @@\",\n        oldStart: 0,\n        newStart: 1,\n        lines: `+import { db } from \"../db\";\n+import type { Message } from \"./queue\";\n+\n+const RETENTION_DAYS = 7;\n+\n+export interface DeadLetter {\n+  id: string;\n+  endpointId: string;\n+  payload: unknown;\n+  error: string;\n+  attempts: number;\n+  parkedAt: Date;\n+}\n+\n+export const deadLetter = {\n+  async put(message: Message, error: unknown) {\n+    await db.insert(\"dead_letters\", {\n+      id: message.id,\n+      endpointId: message.endpointId,\n+      payload: message.body,\n+      error: String(error),\n+      attempts: message.attempts + 1,\n+      parkedAt: new Date(),\n+    });\n+  },\n+\n+  async replay(id: string) {\n+    const row = await db.take<DeadLetter>(\"dead_letters\", id);\n+    return row && queue.publish(row.payload, { endpointId: row.endpointId });\n+  },\n+\n+  async sweep() {\n+    await db.deleteOlderThan(\"dead_letters\", \"parkedAt\", RETENTION_DAYS);\n+  },\n+};`,\n      },\n    ],\n  },\n  {\n    path: \"src/queue/retry.ts\",\n    status: \"modified\",\n    hunks: [\n      {\n        header: \"@@ -1,11 +1,8 @@\",\n        oldStart: 1,\n        newStart: 1,\n        lines: `+export const MAX_ATTEMPTS = 3;\n const BASE_DELAY_MS = 1_000;\n-const MAX_DELAY_MS = 60_000;\n+const MAX_DELAY_MS = 30_000;\n\n export function backoff(attempt: number) {\n-  const delay = BASE_DELAY_MS * 2 ** attempt;\n-  if (delay > MAX_DELAY_MS) {\n-    return MAX_DELAY_MS;\n-  }\n-  return delay;\n+  const delay = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);\n+  return delay / 2 + Math.random() * (delay / 2);\n }`,\n      },\n    ],\n  },\n  {\n    path: \"test/consumer.test.ts\",\n    status: \"added\",\n    hunks: [\n      {\n        header: \"@@ -0,0 +1,26 @@\",\n        oldStart: 0,\n        newStart: 1,\n        lines: `+import { describe, expect, it } from \"vitest\";\n+import { consume } from \"../src/queue/consumer\";\n+import { fakeQueue, failingEndpoint } from \"./fixtures\";\n+\n+describe(\"consume\", () => {\n+  it(\"parks a message after three failed attempts\", async () => {\n+    const queue = fakeQueue([{ id: \"m1\", attempts: 2, body: \"{\" }]);\n+    failingEndpoint(\"ep_live_42\");\n+\n+    await consume();\n+\n+    expect(queue.deadLetters).toHaveLength(1);\n+    expect(queue.pending).toHaveLength(0);\n+  });\n+\n+  it(\"keeps delivering after a poison message\", async () => {\n+    const queue = fakeQueue([\n+      { id: \"bad\", attempts: 2, body: \"{\" },\n+      { id: \"ok\", attempts: 0, body: \"{}\" },\n+    ]);\n+\n+    await consume();\n+\n+    expect(queue.delivered).toContain(\"ok\");\n+  });\n+});`,\n      },\n    ],\n  },\n  {\n    path: \"docs/webhooks/retries.md\",\n    status: \"modified\",\n    hunks: [\n      {\n        header: \"@@ -12,9 +12,13 @@ ## Retries\",\n        oldStart: 12,\n        newStart: 12,\n        lines: ` ## Retries\n\n-Failed deliveries are retried with exponential backoff for up to 24 hours.\n+Failed deliveries are retried up to three times with exponential backoff\n+and jitter, capped at 30 seconds between attempts.\n+\n+After the third failure the event moves to the dead-letter queue, where it\n+stays for 7 days. You can replay it from the dashboard at any time.\n\n ## Ordering\n\n-Events for one endpoint are delivered in order.\n+Events for one endpoint are delivered in order, except for events that were\n+dead-lettered and replayed later.`,\n      },\n    ],\n  },\n];\n\nconst defaultThreads: ReviewThread[] = [\n  {\n    id: \"t1\",\n    file: \"src/queue/consumer.ts\",\n    line: 3,\n    side: \"new\",\n    comments: [\n      { id: \"c1\", author: \"leo\", body: \"Should `MAX_ATTEMPTS` come from the endpoint's retry policy? Ops will want to tune it for the noisy integrations.\", time: \"2h\" },\n      { id: \"c2\", author: \"sam\", body: \"Fair. I'd keep the constant as the default and read `endpoint.retryPolicy` in a follow-up, so this one stays small.\", time: \"1h\" },\n    ],\n  },\n  {\n    id: \"t2\",\n    file: \"src/queue/dead-letter.ts\",\n    line: 29,\n    side: \"new\",\n    comments: [{ id: \"c3\", author: \"leo\", body: \"`queue` isn't imported in this file, so `replay` will throw the first time someone clicks it.\", time: \"48m\" }],\n  },\n  {\n    id: \"t3\",\n    file: \"src/queue/retry.ts\",\n    line: 3,\n    side: \"new\",\n    resolved: true,\n    comments: [\n      { id: \"c4\", author: \"jonas\", body: \"30s cap feels low for endpoints that are down for a deploy.\", time: \"3h\" },\n      { id: \"c5\", author: \"sam\", body: \"It only applies to the three attempts now. Anything longer goes to the dead-letter queue.\", time: \"3h\" },\n    ],\n  },\n];\n\ninterface Line {\n  kind: \"ctx\" | \"add\" | \"del\";\n  text: string;\n  old?: number;\n  new?: number;\n}\n\nfunction parseHunk(h: DiffFile[\"hunks\"][number]): Line[] {\n  let o = h.oldStart;\n  let n = h.newStart;\n  return h.lines.split(\"\\n\").map((raw) => {\n    const sign = raw[0];\n    const text = raw.slice(1);\n    if (sign === \"+\") return { kind: \"add\", text, new: n++ };\n    if (sign === \"-\") return { kind: \"del\", text, old: o++ };\n    return { kind: \"ctx\", text, old: o++, new: n++ };\n  });\n}\n\ntype SplitRow = { left?: Line; right?: Line };\n\nfunction toSplit(lines: Line[]): SplitRow[] {\n  const rows: SplitRow[] = [];\n  let i = 0;\n  while (i < lines.length) {\n    const l = lines[i];\n    if (l.kind === \"ctx\") {\n      rows.push({ left: l, right: l });\n      i++;\n      continue;\n    }\n    const dels: Line[] = [];\n    const adds: Line[] = [];\n    while (i < lines.length && lines[i].kind === \"del\") dels.push(lines[i++]);\n    while (i < lines.length && lines[i].kind === \"add\") adds.push(lines[i++]);\n    for (let k = 0; k < Math.max(dels.length, adds.length); k++) rows.push({ left: dels[k], right: adds[k] });\n  }\n  return rows;\n}\n\nfunction pairs(lines: Line[]) {\n  const map = new Map<Line, Line>();\n  for (const row of toSplit(lines)) {\n    if (row.left?.kind === \"del\" && row.right?.kind === \"add\") {\n      map.set(row.left, row.right);\n      map.set(row.right, row.left);\n    }\n  }\n  return map;\n}\n\nfunction changedRange(a: string, b: string) {\n  let start = 0;\n  while (start < a.length && start < b.length && a[start] === b[start]) start++;\n  let end = 0;\n  while (end < a.length - start && end < b.length - start && a[a.length - 1 - end] === b[b.length - 1 - end]) end++;\n  return { start, endA: a.length - end, endB: b.length - end };\n}\n\nconst KEYWORDS =\n  /^(import|from|export|const|let|var|return|if|else|await|async|function|type|interface|new|throw|try|catch|for|of|in|true|false|null|undefined)$/;\n\nfunction highlight(text: string, md: boolean): ReactNode[] {\n  if (md) {\n    if (text.startsWith(\"#\")) return [<span className=\"font-semibold text-sky-800 dark:text-sky-300\" key=\"h\">{text}</span>];\n    return [text];\n  }\n  const out: ReactNode[] = [];\n  const re = /(\\/\\/.*$)|(\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'|`(?:[^`\\\\]|\\\\.)*`)|(\\b\\d[\\d_]*\\b)|([A-Za-z_$][\\w$]*)/g;\n  let last = 0;\n  let m: RegExpExecArray | null;\n  let k = 0;\n  // biome-ignore lint/suspicious/noAssignInExpressions: tokenizer loop\n  while ((m = re.exec(text))) {\n    if (m.index > last) out.push(text.slice(last, m.index));\n    const [tok] = m;\n    if (m[1]) out.push(<span className=\"text-muted-foreground italic\" key={k++}>{tok}</span>);\n    else if (m[2]) out.push(<span className=\"text-emerald-700 dark:text-emerald-300\" key={k++}>{tok}</span>);\n    else if (m[3]) out.push(<span className=\"text-amber-800 dark:text-amber-300\" key={k++}>{tok}</span>);\n    else if (KEYWORDS.test(tok)) out.push(<span className=\"text-violet-700 dark:text-violet-300\" key={k++}>{tok}</span>);\n    else if (/^[A-Z]/.test(tok)) out.push(<span className=\"text-sky-800 dark:text-sky-300\" key={k++}>{tok}</span>);\n    else if (text[re.lastIndex] === \"(\") out.push(<span className=\"text-blue-700 dark:text-blue-300\" key={k++}>{tok}</span>);\n    else out.push(tok);\n    last = re.lastIndex;\n  }\n  if (last < text.length) out.push(text.slice(last));\n  return out;\n}\n\nfunction CodeText({ line, partner, md }: { line: Line; partner?: Line; md: boolean }) {\n  if (!partner || line.kind === \"ctx\") return <>{highlight(line.text, md) as ReactNode}</>;\n  const r = line.kind === \"del\" ? changedRange(line.text, partner.text) : changedRange(partner.text, line.text);\n  const end = line.kind === \"del\" ? r.endA : r.endB;\n  if (end <= r.start) return <>{highlight(line.text, md) as ReactNode}</>;\n  return (\n    <>\n      {highlight(line.text.slice(0, r.start), md)}\n      <span className={cn(\"rounded-[calc(var(--radius)*0.3)]\", line.kind === \"del\" ? \"bg-destructive/22\" : \"bg-success/24\")}>{highlight(line.text.slice(r.start, end), md)}</span>\n      {highlight(line.text.slice(end), md)}\n    </>\n  );\n}\n\nfunction ThreadView({\n  thread,\n  people,\n  me,\n  onReply,\n  onResolve,\n}: {\n  thread: ReviewThread;\n  people: ReviewPerson[];\n  me: string;\n  onReply: (body: string) => void;\n  onResolve: (resolved: boolean) => void;\n}) {\n  const [draft, setDraft] = useState(\"\");\n  const [replying, setReplying] = useState(false);\n  const person = (id: string) => people.find((p) => p.id === id);\n  if (thread.resolved) {\n    const last = thread.comments[thread.comments.length - 1];\n    return (\n      <div className=\"mx-3 my-2 flex items-center gap-2 rounded-xl border border-dashed px-3 py-2 font-sans text-muted-foreground text-xs\">\n        <CircleCheckIcon className=\"size-3.5 text-success\" />\n        <span className=\"min-w-0 flex-1 truncate\">\n          Resolved · <span className=\"text-foreground\">{person(thread.comments[0].author)?.name.split(\" \")[0]}</span>: {thread.comments[0].body}\n        </span>\n        <span className=\"hidden @lg:inline\">{last.time}</span>\n        <button className=\"cursor-pointer rounded font-medium text-foreground outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring\" onClick={() => onResolve(false)} type=\"button\">\n          Reopen\n        </button>\n      </div>\n    );\n  }\n  return (\n    <motion.div\n      animate={{ opacity: 1, y: 0 }}\n      className=\"mx-3 my-2 max-w-2xl overflow-hidden rounded-xl border bg-card font-sans text-sm shadow-xs/5\"\n      initial={{ opacity: 0, y: -4 }}\n      transition={{ duration: 0.18, ease }}\n    >\n      <ul className=\"flex flex-col\">\n        {thread.comments.map((c, i) => {\n          const p = person(c.author);\n          return (\n            <li className={cn(\"flex gap-2.5 px-3 py-3\", i > 0 && \"border-t\")} key={c.id}>\n              <PersonAvatar person={p} />\n              <div className=\"min-w-0 flex-1\">\n                <div className=\"flex items-baseline gap-2 text-xs\">\n                  <span className=\"font-medium text-foreground\">{c.author === me ? \"You\" : p?.name}</span>\n                  <span className=\"text-muted-foreground\">{c.time}</span>\n                </div>\n                <p className=\"mt-1 text-pretty text-[13px] text-foreground/90 leading-5 [overflow-wrap:anywhere]\">\n                  {c.body.split(/(`[^`]+`)/g).map((part, j) =>\n                    part.startsWith(\"`\") ? (\n                      <code className=\"rounded-[calc(var(--radius)*0.5)] border bg-muted px-1 py-px font-mono text-[12px]\" key={j}>\n                        {part.slice(1, -1)}\n                      </code>\n                    ) : (\n                      <Fragment key={j}>{part}</Fragment>\n                    ),\n                  )}\n                </p>\n              </div>\n            </li>\n          );\n        })}\n      </ul>\n      <div className=\"border-t px-2 py-2\">\n        {replying ? (\n          <div className=\"flex flex-col gap-2\">\n            <textarea\n              aria-label=\"Reply\"\n              autoFocus\n              className=\"min-h-16 w-full resize-none rounded-lg border bg-background px-2.5 py-2 text-sm outline-none placeholder:text-muted-foreground/70 focus-visible:border-ring/60 focus-visible:ring-3 focus-visible:ring-ring/16 dark:bg-input/32\"\n              onChange={(e) => setDraft(e.target.value)}\n              onKeyDown={(e) => {\n                if (e.key === \"Enter\" && (e.metaKey || e.ctrlKey) && draft.trim()) {\n                  onReply(draft.trim());\n                  setDraft(\"\");\n                  setReplying(false);\n                }\n                if (e.key === \"Escape\") {\n                  e.stopPropagation();\n                  setReplying(false);\n                }\n              }}\n              placeholder=\"Reply…\"\n              value={draft}\n            />\n            <div className=\"flex justify-end gap-1.5\">\n              <Button onClick={() => setReplying(false)} size=\"xs\" variant=\"ghost\">\n                Cancel\n              </Button>\n              <Button\n                disabled={!draft.trim()}\n                onClick={() => {\n                  onReply(draft.trim());\n                  setDraft(\"\");\n                  setReplying(false);\n                }}\n                size=\"xs\"\n              >\n                Reply\n              </Button>\n            </div>\n          </div>\n        ) : (\n          <div className=\"flex items-center gap-2\">\n            <button\n              className=\"h-7 flex-1 cursor-text rounded-md border bg-background px-2.5 text-left text-[13px] text-muted-foreground outline-none transition-colors hover:border-foreground/20 focus-visible:ring-2 focus-visible:ring-ring dark:bg-input/32\"\n              onClick={() => setReplying(true)}\n              type=\"button\"\n            >\n              Reply…\n            </button>\n            <Button onClick={() => onResolve(true)} size=\"xs\" variant=\"outline\">\n              <CheckIcon />\n              Resolve\n            </Button>\n          </div>\n        )}\n      </div>\n    </motion.div>\n  );\n}\n\nfunction NewComment({ onCancel, onSubmit }: { onCancel: () => void; onSubmit: (body: string) => void }) {\n  const [draft, setDraft] = useState(\"\");\n  return (\n    <motion.div\n      animate={{ opacity: 1, y: 0 }}\n      className=\"mx-3 my-2 flex max-w-2xl flex-col gap-2 rounded-xl border bg-card p-2 font-sans shadow-xs/5\"\n      initial={{ opacity: 0, y: -4 }}\n      transition={{ duration: 0.18, ease }}\n    >\n      <textarea\n        aria-label=\"New comment\"\n        autoFocus\n        className=\"min-h-20 w-full resize-none rounded-lg border bg-background px-2.5 py-2 text-sm outline-none placeholder:text-muted-foreground/70 focus-visible:border-ring/60 focus-visible:ring-3 focus-visible:ring-ring/16 dark:bg-input/32\"\n        onChange={(e) => setDraft(e.target.value)}\n        onKeyDown={(e) => {\n          if (e.key === \"Enter\" && (e.metaKey || e.ctrlKey) && draft.trim()) onSubmit(draft.trim());\n          if (e.key === \"Escape\") {\n            e.stopPropagation();\n            onCancel();\n          }\n        }}\n        placeholder=\"Leave a comment on this line…\"\n        value={draft}\n      />\n      <div className=\"flex items-center justify-end gap-1.5\">\n        <span className=\"me-auto ps-1 text-muted-foreground text-xs\">\n          <Kbd className=\"h-4 text-[10px]\">⌘↵</Kbd> to post\n        </span>\n        <Button onClick={onCancel} size=\"xs\" variant=\"ghost\">\n          Cancel\n        </Button>\n        <Button disabled={!draft.trim()} onClick={() => onSubmit(draft.trim())} size=\"xs\">\n          Comment\n        </Button>\n      </div>\n    </motion.div>\n  );\n}\n\ninterface TreeNode {\n  name: string;\n  path: string;\n  children: TreeNode[];\n  file?: DiffFile;\n}\n\nfunction buildTree(files: DiffFile[]): TreeNode[] {\n  const root: TreeNode = { name: \"\", path: \"\", children: [] };\n  for (const f of files) {\n    const parts = f.path.split(\"/\");\n    let node = root;\n    parts.forEach((part, i) => {\n      const path = parts.slice(0, i + 1).join(\"/\");\n      let child = node.children.find((c) => c.name === part);\n      if (!child) {\n        child = { name: part, path, children: [], file: i === parts.length - 1 ? f : undefined };\n        node.children.push(child);\n      }\n      node = child;\n    });\n  }\n  const squash = (n: TreeNode): TreeNode => {\n    if (!n.file && n.children.length === 1 && !n.children[0].file) {\n      const c = n.children[0];\n      return squash({ ...c, name: `${n.name}/${c.name}` });\n    }\n    return { ...n, children: n.children.map(squash) };\n  };\n  return root.children.map(squash);\n}\n\nconst statusIcon = { added: FilePlus2Icon, modified: FileDiffIcon, deleted: FileCode2Icon };\n\nexport function CodeReview({\n  title = \"Park poison messages after three failed attempts\",\n  number = 482,\n  author = \"sam\",\n  base = \"main\",\n  head = \"sam/dead-letter-queue\",\n  me = \"maya\",\n  people = defaultPeople,\n  files = defaultFiles,\n  threads: initialThreads = defaultThreads,\n  className,\n}: CodeReviewProps) {\n  const [threads, setThreads] = useState(initialThreads);\n  const [viewed, setViewed] = useState<Set<string>>(() => new Set([\"docs/webhooks/retries.md\"]));\n  const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set([\"docs/webhooks/retries.md\"]));\n  const [split, setSplit] = useState(true);\n  const [narrow, setNarrow] = useState(false);\n  const [treeOpen, setTreeOpen] = useState(true);\n  const [activeFile, setActiveFile] = useState(files[0]?.path ?? \"\");\n  const [composer, setComposer] = useState<{ file: string; line: number; side: \"new\" | \"old\" } | null>(null);\n  const [reviewOpen, setReviewOpen] = useState(false);\n  const [verdict, setVerdict] = useState<\"comment\" | \"approve\" | \"changes\">(\"approve\");\n  const [summary, setSummary] = useState(\"\");\n  const [submitted, setSubmitted] = useState<null | \"comment\" | \"approve\" | \"changes\">(null);\n  const [toast, setToast] = useState<{ key: number; text: string } | null>(null);\n  const rootRef = useRef<HTMLDivElement>(null);\n  const scrollRef = useRef<HTMLDivElement>(null);\n  const fileRefs = useRef(new Map<string, HTMLElement>());\n  const person = (id: string) => people.find((p) => p.id === id);\n\n  useEffect(() => {\n    const el = rootRef.current;\n    if (!el) return;\n    let first = true;\n    const ro = new ResizeObserver(([e]) => {\n      const isNarrow = e.contentRect.width < 900;\n      setNarrow(isNarrow);\n      if (first && isNarrow) setTreeOpen(false);\n      first = false;\n    });\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n\n  useEffect(() => {\n    if (!toast) return;\n    const id = window.setTimeout(() => setToast(null), 2800);\n    return () => window.clearTimeout(id);\n  }, [toast]);\n\n  const parsed = useMemo(\n    () =>\n      files.map((f) => {\n        const hunks = f.hunks.map((h) => ({ header: h.header, lines: parseHunk(h) }));\n        const all = hunks.flatMap((h) => h.lines);\n        return {\n          file: f,\n          hunks,\n          adds: all.filter((l) => l.kind === \"add\").length,\n          dels: all.filter((l) => l.kind === \"del\").length,\n          pairs: pairs(all),\n        };\n      }),\n    [files],\n  );\n  const totals = parsed.reduce((a, p) => ({ adds: a.adds + p.adds, dels: a.dels + p.dels }), { adds: 0, dels: 0 });\n  const tree = useMemo(() => buildTree(files), [files]);\n  const showSplit = split && !narrow;\n  const openThreads = threads.filter((t) => !t.resolved).length;\n\n  const scrollToFile = (path: string) => {\n    const el = fileRefs.current.get(path);\n    const box = scrollRef.current;\n    if (el && box) box.scrollTop = el.offsetTop - 8;\n    setActiveFile(path);\n    if (narrow) setTreeOpen(false);\n  };\n\n  const onScroll = () => {\n    const box = scrollRef.current;\n    if (!box) return;\n    let current = files[0]?.path ?? \"\";\n    for (const f of files) {\n      const el = fileRefs.current.get(f.path);\n      if (el && el.offsetTop - 24 <= box.scrollTop) current = f.path;\n    }\n    if (current !== activeFile) setActiveFile(current);\n  };\n\n  const toggleViewed = (path: string) => {\n    const nowViewed = !viewed.has(path);\n    setViewed((v) => {\n      const next = new Set(v);\n      if (nowViewed) next.add(path);\n      else next.delete(path);\n      return next;\n    });\n    setCollapsed((c) => {\n      const next = new Set(c);\n      if (nowViewed) next.add(path);\n      else next.delete(path);\n      return next;\n    });\n  };\n\n  const toggleCollapsed = (path: string) =>\n    setCollapsed((c) => {\n      const next = new Set(c);\n      if (next.has(path)) next.delete(path);\n      else next.add(path);\n      return next;\n    });\n\n  const addComment = (file: string, line: number, side: \"new\" | \"old\", body: string) => {\n    setThreads((ts) => [...ts, { id: `t${Date.now()}`, file, line, side, comments: [{ id: `c${Date.now()}`, author: me, body, time: \"now\" }] }]);\n    setComposer(null);\n  };\n\n  const submitReview = () => {\n    setSubmitted(verdict);\n    setReviewOpen(false);\n    setToast({\n      key: Date.now(),\n      text: verdict === \"approve\" ? \"Approved. Sam can merge when ready.\" : verdict === \"changes\" ? \"Changes requested\" : \"Review submitted\",\n    });\n    setSummary(\"\");\n  };\n\n  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n    const t = e.target as HTMLElement;\n    if (e.key === \"Escape\") {\n      if (reviewOpen) setReviewOpen(false);\n      else if (composer) setComposer(null);\n      else if (narrow && treeOpen) setTreeOpen(false);\n      return;\n    }\n    if (t.tagName === \"INPUT\" || t.tagName === \"TEXTAREA\" || e.metaKey || e.ctrlKey || e.altKey) return;\n    const idx = files.findIndex((f) => f.path === activeFile);\n    const k = e.key.toLowerCase();\n    if (k === \"j\" || k === \"]\") {\n      e.preventDefault();\n      const next = files[Math.min(files.length - 1, idx + 1)];\n      if (next) scrollToFile(next.path);\n    } else if (k === \"k\" || k === \"[\") {\n      e.preventDefault();\n      const prev = files[Math.max(0, idx - 1)];\n      if (prev) scrollToFile(prev.path);\n    } else if (k === \"v\" && activeFile) {\n      e.preventDefault();\n      toggleViewed(activeFile);\n    } else if (k === \"s\") {\n      setSplit((s) => !s);\n    } else if (k === \"n\") {\n      const next = threads.find((th) => !th.resolved && files.findIndex((f) => f.path === th.file) > idx) ?? threads.find((th) => !th.resolved);\n      if (next) scrollToFile(next.file);\n    } else if (k === \"r\") {\n      e.preventDefault();\n      setReviewOpen(true);\n    }\n  };\n\n  const renderTree = (nodes: TreeNode[], depth = 0): ReactNode =>\n    nodes.map((n) => {\n      if (n.file) {\n        const p = parsed.find((x) => x.file.path === n.path);\n        const Icon = statusIcon[n.file.status];\n        const count = threads.filter((t) => t.file === n.path && !t.resolved).length;\n        const on = activeFile === n.path;\n        return (\n          <li key={n.path}>\n            <button\n              aria-current={on ? \"true\" : undefined}\n              className={cn(\n                \"flex h-7 w-full cursor-pointer items-center gap-2 rounded-md pe-2 text-left text-[13px] outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring\",\n                on ? \"bg-accent font-medium text-foreground\" : \"text-muted-foreground hover:bg-accent/60 hover:text-foreground\",\n              )}\n              onClick={() => scrollToFile(n.path)}\n              style={{ paddingInlineStart: 8 + depth * 14 }}\n              type=\"button\"\n            >\n              <Icon className={cn(\"size-3.5 shrink-0\", n.file.status === \"added\" ? \"text-success\" : \"text-warning\")} />\n              <span className={cn(\"min-w-0 flex-1 truncate\", viewed.has(n.path) && \"text-muted-foreground\")}>{n.name}</span>\n              {count > 0 && (\n                <span className=\"flex items-center gap-0.5 text-[11px] text-muted-foreground tabular-nums\">\n                  <MessageSquareIcon className=\"size-3\" />\n                  {count}\n                </span>\n              )}\n              {viewed.has(n.path) ? (\n                <CheckIcon aria-label=\"Viewed\" className=\"size-3.5 text-success\" />\n              ) : (\n                <span className=\"font-mono text-[10px] tabular-nums\">\n                  <span className=\"text-success-foreground\">+{p?.adds}</span>\n                  {p && p.dels > 0 && <span className=\"ms-1 text-destructive-foreground\">−{p.dels}</span>}\n                </span>\n              )}\n            </button>\n          </li>\n        );\n      }\n      return (\n        <li key={n.path}>\n          <div className=\"flex h-7 items-center gap-1.5 text-muted-foreground text-xs\" style={{ paddingInlineStart: 8 + depth * 14 }}>\n            <FolderIcon className=\"size-3.5\" />\n            <span className=\"truncate font-mono\">{n.name}</span>\n          </div>\n          <ul className=\"flex flex-col gap-0.5\">{renderTree(n.children, depth + 1)}</ul>\n        </li>\n      );\n    });\n\n  const lineNo = \"w-10 shrink-0 select-none px-1.5 text-right text-muted-foreground tabular-nums\";\n\n  const gutterButton = (file: string, line: number, side: \"new\" | \"old\") => (\n    <button\n      aria-label={`Comment on line ${line}`}\n      className=\"group/gutter absolute inset-y-0 left-0 z-10 w-10 cursor-pointer outline-none\"\n      onClick={() => setComposer({ file, line, side })}\n      type=\"button\"\n    >\n      <span className=\"absolute top-0.5 left-1 flex size-4 items-center justify-center rounded bg-info text-white opacity-0 transition-[opacity,scale] duration-100 ease-out group-hover/line:opacity-100 group-focus-visible/gutter:opacity-100 group-focus-visible/gutter:ring-2 group-focus-visible/gutter:ring-ring group-active/gutter:scale-90\">\n        <PlusIcon className=\"size-3\" strokeWidth={3} />\n      </span>\n    </button>\n  );\n\n  const threadsAt = (file: string, line: Line, which: \"left\" | \"right\" | \"both\") => {\n    const out: ReviewThread[] = [];\n    for (const t of threads) {\n      if (t.file !== file) continue;\n      if (t.side === \"new\" && line.new === t.line && which !== \"left\") out.push(t);\n      else if (t.side === \"old\" && line.old === t.line && line.kind === \"del\" && which !== \"right\") out.push(t);\n    }\n    return out;\n  };\n\n  const extras = (file: string, line: Line, which: \"left\" | \"right\" | \"both\", split = false) => {\n    const ts = threadsAt(file, line, which);\n    const showComposer =\n      composer &&\n      composer.file === file &&\n      ((composer.side === \"new\" && line.new === composer.line && which !== \"left\") ||\n        (composer.side === \"old\" && line.old === composer.line && line.kind === \"del\" && which !== \"right\"));\n    if (!ts.length && !showComposer) return null;\n    return (\n      <div className={cn(\"border-y bg-muted/30 py-1\", split && \"@4xl:grid @4xl:grid-cols-2\")}>\n        <div className={cn(\"min-w-0\", split && which !== \"left\" && \"@4xl:col-start-2\")}>\n        {ts.map((t) => (\n          <ThreadView\n            key={t.id}\n            me={me}\n            onReply={(body) =>\n              setThreads((all) => all.map((x) => (x.id === t.id ? { ...x, comments: [...x.comments, { id: `c${Date.now()}`, author: me, body, time: \"now\" }] } : x)))\n            }\n            onResolve={(resolved) => setThreads((all) => all.map((x) => (x.id === t.id ? { ...x, resolved } : x)))}\n            people={people}\n            thread={t}\n          />\n        ))}\n        {showComposer && composer && (\n          <NewComment onCancel={() => setComposer(null)} onSubmit={(body) => addComment(composer.file, composer.line, composer.side, body)} />\n        )}\n        </div>\n      </div>\n    );\n  };\n\n  const rowTone = (kind?: Line[\"kind\"]) =>\n    kind === \"add\" ? \"bg-success/8 dark:bg-success/10\" : kind === \"del\" ? \"bg-destructive/8 dark:bg-destructive/10\" : \"\";\n  const numTone = (kind?: Line[\"kind\"]) =>\n    kind === \"add\"\n      ? \"bg-success/14 text-success-foreground/80 shadow-[inset_2px_0_0_var(--color-success)] dark:bg-success/16\"\n      : kind === \"del\"\n        ? \"bg-destructive/14 text-destructive-foreground/80 shadow-[inset_2px_0_0_var(--color-destructive)] dark:bg-destructive/16\"\n        : \"\";\n\n  const reviewLabel = submitted === \"approve\" ? \"Approved\" : submitted === \"changes\" ? \"Changes requested\" : submitted === \"comment\" ? \"Reviewed\" : \"Review\";\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div\n        className={cn(\"@container relative isolate flex h-[760px] w-full flex-col overflow-hidden bg-background text-foreground text-sm outline-none\", className)}\n        onKeyDown={onKeyDown}\n        ref={rootRef}\n        tabIndex={-1}\n      >\n        <header className=\"shrink-0 border-b px-4 pt-4 pb-3 @3xl:px-5\">\n          <div className=\"flex items-start gap-3\">\n            <div className=\"min-w-0 flex-1\">\n              <h1 className=\"text-balance font-heading font-semibold text-lg leading-snug tracking-tight\">\n                {title} <span className=\"font-normal text-muted-foreground\">#{number}</span>\n              </h1>\n              <div className=\"mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1.5 text-muted-foreground text-xs\">\n                <Badge className=\"gap-1\" variant=\"success\">\n                  <GitPullRequestIcon />\n                  Open\n                </Badge>\n                <span className=\"flex items-center gap-1.5\">\n                  <PersonAvatar person={person(author)} size=\"size-4\" />\n                  <span className=\"font-medium text-foreground\">{person(author)?.name}</span>\n                </span>\n                <span className=\"hidden @lg:inline\">wants to merge 4 commits into</span>\n                <span className=\"flex min-w-0 items-center gap-1 font-mono\">\n                  <span className=\"rounded-md bg-muted px-1.5 py-0.5 text-foreground\">{base}</span>\n                  <span>←</span>\n                  <span className=\"flex min-w-0 items-center gap-1 truncate rounded-md bg-muted px-1.5 py-0.5 text-foreground\">\n                    <GitBranchIcon className=\"size-3 shrink-0\" />\n                    <span className=\"truncate\">{head}</span>\n                  </span>\n                </span>\n              </div>\n            </div>\n            <div className=\"flex shrink-0 items-center gap-2\">\n              <div className=\"hidden items-center gap-1.5 rounded-lg border px-2 py-1 text-xs @2xl:flex\">\n                <CircleCheckIcon className=\"size-3.5 text-success\" />\n                <span className=\"tabular-nums\">12/12 checks</span>\n              </div>\n              <div className=\"hidden -space-x-1 @xl:flex\">\n                {[\"leo\", \"jonas\"].map((id) => (\n                  <span className=\"rounded-full ring-2 ring-background\" key={id} title={person(id)?.name}>\n                    <PersonAvatar person={person(id)} />\n                  </span>\n                ))}\n              </div>\n              <Button\n                className={cn(\"transition-[box-shadow,scale] duration-150 ease-out active:scale-[0.97]\", submitted === \"approve\" && \"bg-success hover:bg-success/90 border-success text-white\")}\n                onClick={() => setReviewOpen((o) => !o)}\n                size=\"sm\"\n                variant={submitted === \"changes\" ? \"destructive-outline\" : \"default\"}\n              >\n                {submitted === \"approve\" && <CheckIcon />}\n                {reviewLabel}\n                <ChevronDownIcon className={cn(\"transition-transform duration-200\", reviewOpen && \"rotate-180\")} />\n              </Button>\n            </div>\n          </div>\n        </header>\n\n        <div className=\"flex h-11 shrink-0 items-center gap-2 border-b px-3 @3xl:px-4\">\n          <Button aria-label={treeOpen ? \"Hide file tree\" : \"Show file tree\"} aria-pressed={treeOpen} onClick={() => setTreeOpen((o) => !o)} size=\"icon-sm\" variant=\"ghost\">\n            <PanelLeftIcon />\n          </Button>\n          <span className=\"font-medium\">Files changed</span>\n          <span className=\"text-muted-foreground text-xs tabular-nums\">{files.length}</span>\n          <span className=\"font-mono text-xs tabular-nums\">\n            <span className=\"text-success-foreground\">+{totals.adds}</span> <span className=\"text-destructive-foreground\">−{totals.dels}</span>\n          </span>\n          <div className=\"ms-auto flex items-center gap-3\">\n            <span className=\"hidden items-center gap-2 text-muted-foreground text-xs @xl:flex\">\n              <span className=\"tabular-nums\">\n                {viewed.size} of {files.length} viewed\n              </span>\n              <span className=\"h-1 w-16 overflow-hidden rounded-full bg-muted\">\n                <motion.span\n                  animate={{ scaleX: viewed.size / files.length }}\n                  className=\"block h-full origin-left rounded-full bg-success\"\n                  initial={false}\n                  transition={{ type: \"spring\", stiffness: 300, damping: 34 }}\n                />\n              </span>\n            </span>\n            {openThreads > 0 && (\n              <span className=\"hidden items-center gap-1 text-muted-foreground text-xs @md:flex\">\n                <MessageSquareIcon className=\"size-3.5\" />\n                <span className=\"tabular-nums\">{openThreads} open</span>\n              </span>\n            )}\n            {!narrow && (\n              <div aria-label=\"Diff layout\" className=\"flex rounded-lg bg-muted p-0.5\" role=\"group\">\n                {[\n                  { id: true, label: \"Split\" },\n                  { id: false, label: \"Unified\" },\n                ].map((o) => (\n                  <button\n                    aria-pressed={split === o.id}\n                    className={cn(\n                      \"relative h-6 cursor-pointer rounded-md px-2 font-medium text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n                      split === o.id ? \"text-foreground\" : \"text-muted-foreground hover:text-foreground\",\n                    )}\n                    key={o.label}\n                    onClick={() => setSplit(o.id)}\n                    type=\"button\"\n                  >\n                    {split === o.id && (\n                      <motion.span className=\"absolute inset-0 rounded-md bg-background shadow-xs/5 dark:bg-accent\" layoutId=\"diff-layout\" transition={{ type: \"spring\", stiffness: 520, damping: 42 }} />\n                    )}\n                    <span className=\"relative\">{o.label}</span>\n                  </button>\n                ))}\n              </div>\n            )}\n          </div>\n        </div>\n\n        <div className=\"relative flex min-h-0 flex-1\">\n          <AnimatePresence initial={false}>\n            {treeOpen && (\n              <motion.aside\n                animate={narrow ? { x: 0, opacity: 1 } : { width: 256, opacity: 1 }}\n                aria-label=\"Changed files\"\n                className={cn(\n                  \"flex shrink-0 flex-col overflow-hidden bg-sidebar\",\n                  narrow ? \"absolute inset-y-0 left-0 z-30 w-[272px] max-w-[85%] border-e shadow-lg/10\" : \"border-e\",\n                )}\n                exit={narrow ? { x: \"-100%\", opacity: 1 } : { width: 0, opacity: 0 }}\n                initial={narrow ? { x: \"-100%\", opacity: 1 } : { width: 0, opacity: 0 }}\n                transition={{ duration: 0.22, ease }}\n              >\n                <div className=\"w-64 min-w-64 flex-1 overflow-y-auto p-2 [scrollbar-width:thin]\">\n                  <ul className=\"flex flex-col gap-0.5\">{renderTree(tree)}</ul>\n                </div>\n                <div className=\"flex w-64 flex-col gap-1.5 border-t px-3 py-2.5 text-muted-foreground text-xs\">\n                  <div className=\"flex items-center gap-1.5\">\n                    <Kbd>J</Kbd>\n                    <Kbd>K</Kbd> files\n                    <Kbd className=\"ms-2\">V</Kbd> viewed\n                  </div>\n                  <div className=\"flex items-center gap-1.5\">\n                    <Kbd>N</Kbd> next thread\n                    <Kbd className=\"ms-2\">R</Kbd> review\n                  </div>\n                </div>\n              </motion.aside>\n            )}\n          </AnimatePresence>\n          <AnimatePresence>\n            {narrow && treeOpen && (\n              <motion.div\n                animate={{ opacity: 1 }}\n                aria-hidden\n                className=\"absolute inset-0 z-20 bg-black/24\"\n                exit={{ opacity: 0 }}\n                initial={{ opacity: 0 }}\n                onClick={() => setTreeOpen(false)}\n              />\n            )}\n          </AnimatePresence>\n\n          <div className=\"min-w-0 flex-1 overflow-y-auto bg-muted/30 [scrollbar-width:thin]\" onScroll={onScroll} ref={scrollRef}>\n            <div className=\"flex flex-col gap-3 p-3 @3xl:p-4\">\n              {parsed.map(({ file, hunks, adds, dels, pairs: pairMap }) => {\n                const isViewed = viewed.has(file.path);\n                const isCollapsed = collapsed.has(file.path);\n                const md = file.path.endsWith(\".md\");\n                return (\n                  <section\n                    aria-label={file.path}\n                    className=\"overflow-clip rounded-xl border bg-card shadow-xs/5\"\n                    key={file.path}\n                    ref={(el) => {\n                      if (el) fileRefs.current.set(file.path, el);\n                      else fileRefs.current.delete(file.path);\n                    }}\n                  >\n                    <div className={cn(\"sticky top-0 z-10 flex h-10 items-center gap-2 bg-card ps-1.5 pe-2\", !isCollapsed && \"border-b\")}>\n                      <button\n                        aria-expanded={!isCollapsed}\n                        aria-label={isCollapsed ? `Expand ${file.path}` : `Collapse ${file.path}`}\n                        className=\"flex size-7 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring\"\n                        onClick={() => toggleCollapsed(file.path)}\n                        type=\"button\"\n                      >\n                        <ChevronRightIcon className={cn(\"size-4 transition-transform duration-200 ease-out\", !isCollapsed && \"rotate-90\")} />\n                      </button>\n                      <span className=\"min-w-0 flex-1 truncate font-mono text-xs\">\n                        <span className=\"text-muted-foreground\">{file.path.split(\"/\").slice(0, -1).join(\"/\")}/</span>\n                        <span className=\"font-medium text-foreground\">{file.path.split(\"/\").pop()}</span>\n                      </span>\n                      {file.status === \"added\" && (\n                        <Badge className=\"hidden @md:inline-flex\" variant=\"success\">\n                          New\n                        </Badge>\n                      )}\n                      <span className=\"hidden font-mono text-xs tabular-nums @md:inline\">\n                        <span className=\"text-success-foreground\">+{adds}</span>\n                        {dels > 0 && <span className=\"ms-1 text-destructive-foreground\">−{dels}</span>}\n                      </span>\n                      <label className=\"flex h-7 cursor-pointer items-center gap-1.5 rounded-md border px-2 text-muted-foreground text-xs focus-within:ring-2 focus-within:ring-ring transition-colors hover:text-foreground has-checked:border-success/40 has-checked:bg-success/8 has-checked:text-success-foreground\">\n                        <input checked={isViewed} className=\"sr-only\" onChange={() => toggleViewed(file.path)} type=\"checkbox\" />\n                        <span className={cn(\"flex size-3.5 items-center justify-center rounded-[calc(var(--radius)*0.4)] border transition-colors\", isViewed ? \"border-success bg-success text-white\" : \"border-muted-foreground/50\")}>\n                          {isViewed && <CheckIcon className=\"size-2.5\" strokeWidth={3} />}\n                        </span>\n                        Viewed\n                      </label>\n                    </div>\n                    <AnimatePresence initial={false}>\n                      {!isCollapsed && (\n                        <motion.div\n                          animate={{ height: \"auto\", opacity: 1 }}\n                          className=\"overflow-hidden\"\n                          exit={{ height: 0, opacity: 0 }}\n                          initial={{ height: 0, opacity: 0 }}\n                          transition={{ duration: 0.22, ease }}\n                        >\n                          <div className=\"font-mono text-[12px] leading-5\">\n                            {hunks.map((h, hi) => (\n                              <Fragment key={h.header}>\n                                <div className=\"flex items-center gap-2 bg-info/6 px-3 py-1 text-info-foreground dark:bg-info/10\">\n                                  {hi > 0 && <span className=\"text-[11px]\">⋯</span>}\n                                  <span className=\"truncate\">{h.header}</span>\n                                </div>\n                                {showSplit\n                                  ? toSplit(h.lines).map((row, ri) => {\n                                      const key = `${ri}-${row.left?.old ?? \"\"}-${row.right?.new ?? \"\"}`;\n                                      const leftExtras = row.left && row.left.kind === \"del\" ? extras(file.path, row.left, \"left\", true) : null;\n                                      const rightExtras = row.right ? extras(file.path, row.right, row.right.kind === \"ctx\" ? \"both\" : \"right\", true) : null;\n                                      return (\n                                        <Fragment key={key}>\n                                          <div className=\"grid grid-cols-2\">\n                                            <div className={cn(\"group/line relative flex border-e\", rowTone(row.left?.kind), !row.left && \"bg-muted/40\")}>\n                                              {row.left && (\n                                                <>\n                                                  <span className={cn(lineNo, numTone(row.left.kind))}>{row.left.old}</span>\n                                                  <span className=\"w-4 shrink-0 select-none text-center text-muted-foreground/70\">{row.left.kind === \"del\" ? \"−\" : \"\"}</span>\n                                                  <span className=\"min-w-0 flex-1 whitespace-pre-wrap pe-3 [overflow-wrap:anywhere]\">\n                                                    <CodeText line={row.left} md={md} partner={pairMap.get(row.left)} />\n                                                  </span>\n                                                  {row.left.kind === \"del\" && row.left.old && gutterButton(file.path, row.left.old, \"old\")}\n                                                </>\n                                              )}\n                                            </div>\n                                            <div className={cn(\"group/line relative flex\", rowTone(row.right?.kind === \"ctx\" ? undefined : row.right?.kind), !row.right && \"bg-muted/40\")}>\n                                              {row.right && (\n                                                <>\n                                                  <span className={cn(lineNo, numTone(row.right.kind === \"ctx\" ? undefined : row.right.kind))}>{row.right.new}</span>\n                                                  <span className=\"w-4 shrink-0 select-none text-center text-muted-foreground/70\">{row.right.kind === \"add\" ? \"+\" : \"\"}</span>\n                                                  <span className=\"min-w-0 flex-1 whitespace-pre-wrap pe-3 [overflow-wrap:anywhere]\">\n                                                    <CodeText line={row.right} md={md} partner={pairMap.get(row.right)} />\n                                                  </span>\n                                                  {row.right.new && gutterButton(file.path, row.right.new, \"new\")}\n                                                </>\n                                              )}\n                                            </div>\n                                          </div>\n                                          {leftExtras}\n                                          {rightExtras}\n                                        </Fragment>\n                                      );\n                                    })\n                                  : h.lines.map((l, li) => (\n                                      <Fragment key={`${li}-${l.old ?? \"\"}-${l.new ?? \"\"}`}>\n                                        <div className={cn(\"group/line relative flex\", rowTone(l.kind))}>\n                                          <span className={cn(lineNo, \"hidden @md:block\", numTone(l.kind))}>{l.old ?? \"\"}</span>\n                                          <span className={cn(lineNo, \"hidden @md:block\", numTone(l.kind))}>{l.new ?? \"\"}</span>\n                                          <span className={cn(lineNo, \"@md:hidden\", numTone(l.kind))}>{l.new ?? l.old}</span>\n                                          <span className=\"w-4 shrink-0 select-none text-center text-muted-foreground/70\">\n                                            {l.kind === \"add\" ? \"+\" : l.kind === \"del\" ? \"−\" : \"\"}\n                                          </span>\n                                          <span className=\"min-w-0 flex-1 whitespace-pre-wrap pe-3 [overflow-wrap:anywhere]\">\n                                            <CodeText line={l} md={md} partner={pairMap.get(l)} />\n                                          </span>\n                                          {(l.new ?? l.old) !== undefined && gutterButton(file.path, (l.new ?? l.old) as number, l.new ? \"new\" : \"old\")}\n                                        </div>\n                                        {extras(file.path, l, \"both\")}\n                                      </Fragment>\n                                    ))}\n                              </Fragment>\n                            ))}\n                          </div>\n                        </motion.div>\n                      )}\n                    </AnimatePresence>\n                  </section>\n                );\n              })}\n              <p className=\"py-4 text-center text-muted-foreground text-xs\">\n                That's every file. Press <Kbd>R</Kbd> to finish your review.\n              </p>\n            </div>\n          </div>\n        </div>\n\n        <AnimatePresence>\n          {reviewOpen && (\n            <motion.div\n              animate={{ opacity: 1, scale: 1, y: 0 }}\n              aria-label=\"Finish your review\"\n              className=\"absolute top-16 right-3 left-3 z-40 origin-top-right rounded-2xl border bg-popover p-3 shadow-lg/10 @xl:left-auto @xl:w-[380px]\"\n              exit={{ opacity: 0, scale: 0.97, y: -4 }}\n              initial={{ opacity: 0, scale: 0.97, y: -4 }}\n              role=\"dialog\"\n              transition={{ duration: 0.16, ease }}\n            >\n              <div className=\"flex items-center justify-between\">\n                <h2 className=\"font-medium\">Finish your review</h2>\n                <Button aria-label=\"Close\" onClick={() => setReviewOpen(false)} size=\"icon-xs\" variant=\"ghost\">\n                  <XIcon />\n                </Button>\n              </div>\n              <textarea\n                aria-label=\"Review summary\"\n                autoFocus\n                className=\"mt-2 min-h-20 w-full resize-none rounded-lg border bg-background px-2.5 py-2 text-sm outline-none placeholder:text-muted-foreground/70 focus-visible:border-ring/60 focus-visible:ring-3 focus-visible:ring-ring/16 dark:bg-input/32\"\n                onChange={(e) => setSummary(e.target.value)}\n                onKeyDown={(e) => {\n                  if (e.key === \"Enter\" && (e.metaKey || e.ctrlKey)) submitReview();\n                }}\n                placeholder=\"Leave a summary (optional)\"\n                value={summary}\n              />\n              <div aria-label=\"Verdict\" className=\"mt-2 flex flex-col gap-1\" role=\"radiogroup\">\n                {(\n                  [\n                    { id: \"comment\", label: \"Comment\", note: \"General feedback, no verdict.\" },\n                    { id: \"approve\", label: \"Approve\", note: \"Good to merge as it is.\" },\n                    { id: \"changes\", label: \"Request changes\", note: \"Needs another pass before merging.\" },\n                  ] as const\n                ).map((o) => (\n                  <button\n                    aria-checked={verdict === o.id}\n                    className={cn(\n                      \"flex cursor-pointer items-start gap-2.5 rounded-xl border px-3 py-2 text-left outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring\",\n                      verdict === o.id ? \"border-foreground/20 bg-accent\" : \"border-transparent hover:bg-accent/50\",\n                    )}\n                    key={o.id}\n                    onClick={() => setVerdict(o.id)}\n                    role=\"radio\"\n                    type=\"button\"\n                  >\n                    <span className={cn(\"mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full border\", verdict === o.id ? \"border-primary\" : \"border-muted-foreground/50\")}>\n                      {verdict === o.id && <motion.span className=\"size-2 rounded-full bg-primary\" layoutId=\"verdict-dot\" transition={{ type: \"spring\", stiffness: 600, damping: 40 }} />}\n                    </span>\n                    <span className=\"min-w-0\">\n                      <span className=\"block font-medium\">{o.label}</span>\n                      <span className=\"block text-muted-foreground text-xs\">{o.note}</span>\n                    </span>\n                  </button>\n                ))}\n              </div>\n              <div className=\"mt-3 flex items-center gap-2\">\n                <span className=\"text-muted-foreground text-xs\">\n                  {openThreads} open {openThreads === 1 ? \"thread\" : \"threads\"}\n                </span>\n                <Button\n                  className=\"ms-auto transition-[box-shadow,scale] duration-150 ease-out active:scale-[0.97]\"\n                  onClick={submitReview}\n                  size=\"sm\"\n                  variant={verdict === \"changes\" ? \"destructive\" : \"default\"}\n                >\n                  Submit review\n                </Button>\n              </div>\n            </motion.div>\n          )}\n        </AnimatePresence>\n\n        <div aria-live=\"polite\" className=\"pointer-events-none absolute inset-x-0 bottom-4 z-40 flex justify-center px-4\">\n          <AnimatePresence mode=\"popLayout\">\n            {toast && (\n              <motion.div\n                animate={{ opacity: 1, y: 0, scale: 1 }}\n                className=\"flex h-9 items-center gap-2 rounded-full border bg-popover px-4 text-sm shadow-lg/10\"\n                exit={{ opacity: 0, y: 6, scale: 0.98 }}\n                initial={{ opacity: 0, y: 8, scale: 0.98 }}\n                key={toast.key}\n                transition={{ duration: 0.2, ease }}\n              >\n                {submitted === \"approve\" && <CircleCheckIcon className=\"size-4 text-success\" />}\n                {toast.text}\n              </motion.div>\n            )}\n          </AnimatePresence>\n        </div>\n      </div>\n    </MotionConfig>\n  );\n}\n"
    }
  ]
}