{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "snake-404",
  "title": "Snake 404",
  "description": "Dot-matrix 404 where every dot is food: a Nokia-style snake eats the digits, then they come back. Arrow keys, WASD, or a swipe take over.",
  "files": [
    {
      "path": "registry/snake-404/snake-404.tsx",
      "content": "\"use client\"\n\nimport { useEffect, useRef, useState } from \"react\"\nimport { cn } from \"@/lib/utils\"\n\nexport type Snake404Theme = \"light\" | \"dark\" | \"auto\"\n\nexport type Snake404Options = {\n  /** Digits drawn as food. Default `\"404\"`. Anything but 0–9 is dropped. */\n  code?: string\n  /** Snake and food ink (hex). Default follows theme, or LCD ink. */\n  color?: string\n  /** Grid cell in CSS px. Default `12` */\n  cellSize?: number\n  /** Cells per second. Default `14` */\n  speed?: number\n  /** Longest the snake grows. Default `32` */\n  maxLength?: number\n  /** Faint unlit cells behind the field. Default `true` */\n  grid?: boolean\n  /** Paint a green Nokia LCD behind the field. Default `false` */\n  lcd?: boolean\n  /** Arrow keys, WASD, or swipes take over the snake. Default `true` */\n  playable?: boolean\n  /** Pellets eaten, top left. Default `true` */\n  score?: boolean\n  /** Glide between cells. Off steps cell by cell. Default `true` */\n  smooth?: boolean\n  /**\n   * Palette mode. Default `auto` follows shadcn / next-themes\n   * (`html.dark` class).\n   */\n  theme?: Snake404Theme\n  /** After each pellet: how many are left, out of how many. */\n  onEat?: (left: number, total: number) => void\n  /** The last pellet is gone; the digits come back shortly after. */\n  onClear?: () => void\n  /** A player took over (`true`) or handed back to autopilot (`false`). */\n  onPlayChange?: (playing: boolean) => void\n}\n\n/** 0 right, 1 down, 2 left, 3 up */\nexport type Snake404Direction = 0 | 1 | 2 | 3\n\nexport type Snake404Instance = {\n  setOptions: (options: Partial<Snake404Options>) => void\n  /** Steer as the player. Takes over from autopilot. */\n  steer: (direction: Snake404Direction) => void\n  destroy: () => void\n}\n\n/** Near-black ink on paper */\nexport const LIGHT_COLOR = \"#18181B\"\n/** Near-white ink on slate */\nexport const DARK_COLOR = \"#E4E4E7\"\n/** Nokia 3310 screen */\nexport const LCD_SCREEN = \"#C7F0D8\"\n/** Nokia 3310 pixels */\nexport const LCD_INK = \"#43523D\"\n\nconst START_LENGTH = 4\nconst ENTER_DELAY_MS = 700\nconst REFILL_DELAY_MS = 900\nconst REFILL_MS = 700\nconst POP_MS = 240\nconst DEATH_MS = 1300\nconst BLINK_MS = 150\nconst BLINKS = 6\nconst MAX_QUEUE = 3\nconst SWIPE_PX = 24\n\nconst DX = [1, 0, -1, 0] as const\nconst DY = [0, 1, 0, -1] as const\n\n/** 6×7 bold digits, `#` is food. */\nconst DIGITS: Record<string, readonly string[]> = {\n  \"0\": [\".####.\", \"##..##\", \"##..##\", \"##..##\", \"##..##\", \"##..##\", \".####.\"],\n  \"1\": [\"..##..\", \".###..\", \"..##..\", \"..##..\", \"..##..\", \"..##..\", \".####.\"],\n  \"2\": [\".####.\", \"##..##\", \"....##\", \"..###.\", \".##...\", \"##....\", \"######\"],\n  \"3\": [\".####.\", \"##..##\", \"....##\", \"..###.\", \"....##\", \"##..##\", \".####.\"],\n  \"4\": [\"##..##\", \"##..##\", \"##..##\", \"######\", \"....##\", \"....##\", \"....##\"],\n  \"5\": [\"######\", \"##....\", \"#####.\", \"....##\", \"....##\", \"##..##\", \".####.\"],\n  \"6\": [\".####.\", \"##....\", \"#####.\", \"##..##\", \"##..##\", \"##..##\", \".####.\"],\n  \"7\": [\"######\", \"....##\", \"...##.\", \"..##..\", \"..##..\", \"..##..\", \"..##..\"],\n  \"8\": [\".####.\", \"##..##\", \"##..##\", \".####.\", \"##..##\", \"##..##\", \".####.\"],\n  \"9\": [\".####.\", \"##..##\", \"##..##\", \".#####\", \"....##\", \"....##\", \".####.\"],\n}\nconst DIGIT_W = 6\nconst DIGIT_H = 7\nconst DIGIT_GAP = 2\n\n/** 3×5 score digits, one row per string. */\nconst SCORE_DIGITS = [\n  \"111101101101111\",\n  \"010110010010111\",\n  \"111001111100111\",\n  \"111001111001111\",\n  \"101101111001001\",\n  \"111100111001111\",\n  \"111100111101111\",\n  \"111001001001001\",\n  \"111101111101111\",\n  \"111101111001111\",\n] as const\n\nconst BAYER4 = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5] as const\n\n/** Resolves shadcn / next-themes dark mode (`attribute=\"class\"` → `html.dark`). */\nexport function isDarkTheme(): boolean {\n  if (typeof document === \"undefined\") return false\n  const root = document.documentElement\n  if (root.classList.contains(\"dark\")) return true\n  if (root.classList.contains(\"light\")) return false\n  const dataTheme = root.getAttribute(\"data-theme\")\n  if (dataTheme === \"dark\") return true\n  if (dataTheme === \"light\") return false\n  return window.matchMedia(\"(prefers-color-scheme: dark)\").matches\n}\n\nexport function resolveDark(theme: Snake404Theme): boolean {\n  if (theme === \"dark\") return true\n  if (theme === \"light\") return false\n  return isDarkTheme()\n}\n\n/** Digits of `code` that have a glyph, `\"404\"` when none do. */\nexport function codeDigits(code: string | undefined): string {\n  const digits = (code ?? \"\").replace(/[^0-9]/g, \"\").slice(0, 6)\n  return digits || \"404\"\n}\n\nfunction easeOutBack(t: number) {\n  const c = 1.70158\n  const u = t - 1\n  return 1 + (c + 1) * u * u * u + c * u * u\n}\n\nconst KEYS: Record<string, Snake404Direction> = {\n  ArrowRight: 0,\n  ArrowDown: 1,\n  ArrowLeft: 2,\n  ArrowUp: 3,\n  d: 0,\n  s: 1,\n  a: 2,\n  w: 3,\n  D: 0,\n  S: 1,\n  A: 2,\n  W: 3,\n}\n\ntype Phase = \"wait\" | \"run\" | \"dead\"\n\nexport function createSnake404(\n  wrap: HTMLElement,\n  canvas: HTMLCanvasElement,\n  initial: Snake404Options = {}\n): Snake404Instance | null {\n  let options: Snake404Options = {\n    code: \"404\",\n    cellSize: 12,\n    speed: 14,\n    maxLength: 32,\n    grid: true,\n    lcd: false,\n    playable: true,\n    score: true,\n    smooth: true,\n    theme: \"auto\",\n    ...initial,\n  }\n\n  const ctx = canvas.getContext(\"2d\", { alpha: true })\n  if (!ctx) return null\n\n  let reduce = false\n  let dark = resolveDark(options.theme ?? \"auto\")\n  let visible = true\n  let running = true\n  let raf = 0\n  let lastNow = performance.now()\n\n  let cssW = 0\n  let cssH = 0\n  let dpr = 1\n  let cell = 12\n  let cols = 0\n  let rows = 0\n  let ox = 0\n  let oy = 0\n  let builtKey = \"\"\n\n  // Field\n  let food = new Uint8Array(0)\n  let born = new Float64Array(0)\n  let glyph: number[] = []\n  let remaining = 0\n  let refillAt = 0\n\n  // Snake, head first. Cells may sit off the grid while it slides in.\n  let bx: number[] = []\n  let by: number[] = []\n  let fed: boolean[] = []\n  let occ = new Uint8Array(0)\n  let dir: Snake404Direction = 0\n  let nextX = 0\n  let nextY = 0\n  let growing = false\n  let phase: Phase = \"wait\"\n  let enterAt = 0\n  let deadAt = 0\n  let acc = 0\n  let score = 0\n\n  let playing = false\n  let queue: Snake404Direction[] = []\n\n  // Search scratch, reused every step.\n  let seen = new Uint32Array(0)\n  let dist = new Int32Array(0)\n  let bfs = new Int32Array(0)\n  let stamp = 0\n\n  // Unlit LCD cells, drawn once per layout and ink.\n  const ghost = document.createElement(\"canvas\")\n  let ghostKey = \"\"\n\n  const inkOf = () =>\n    options.color ?? (options.lcd ? LCD_INK : dark ? DARK_COLOR : LIGHT_COLOR)\n\n  const inGrid = (x: number, y: number) =>\n    x >= 0 && y >= 0 && x < cols && y < rows\n\n  const tailCell = () => {\n    const i = bx.length - 1\n    return inGrid(bx[i]!, by[i]!) ? by[i]! * cols + bx[i]! : -1\n  }\n\n  /** Free next step: empty, or the tail cell that moves out this step. */\n  const passable = (x: number, y: number, freeTail: number) => {\n    if (!inGrid(x, y)) return false\n    const i = y * cols + x\n    return occ[i] === 0 || (i === freeTail && occ[i] === 1)\n  }\n\n  const nextStamp = () => {\n    stamp++\n    if (stamp === 0xffffffff) {\n      seen.fill(0)\n      stamp = 1\n    }\n    return stamp\n  }\n\n  /** Cells reachable from `start`, stopping once it passes `cap`. */\n  const flood = (start: number, freeTail: number, cap: number) => {\n    const s = nextStamp()\n    // The head moves to `start`, so the old head cell stays blocked.\n    seen[start] = s\n    bfs[0] = start\n    let head = 0\n    let tail = 1\n    while (head < tail) {\n      const c = bfs[head++]!\n      const x = c % cols\n      const y = (c / cols) | 0\n      for (let d = 0; d < 4; d++) {\n        const nx = x + DX[d]!\n        const ny = y + DY[d]!\n        if (!passable(nx, ny, freeTail)) continue\n        const n = ny * cols + nx\n        if (seen[n] === s) continue\n        seen[n] = s\n        bfs[tail++] = n\n        if (tail > cap) return tail\n      }\n    }\n    return tail\n  }\n\n  const visibleFood = (i: number, now: number) => food[i] === 1 && born[i]! <= now\n\n  /** Autopilot: shortest way to the nearest pellet that will not trap it. */\n  const autopilot = (freeTail: number, now: number): Snake404Direction => {\n    const hx = bx[0]!\n    const hy = by[0]!\n    if (!inGrid(hx, hy)) return dir\n    const head = hy * cols + hx\n    const order = [dir, (dir + 3) % 4, (dir + 1) % 4] as Snake404Direction[]\n    const len = bx.length\n\n    // Nearest pellet by path length.\n    let target = -1\n    if (remaining > 0) {\n      const s = nextStamp()\n      seen[head] = s\n      bfs[0] = head\n      let qh = 0\n      let qt = 1\n      search: while (qh < qt) {\n        const c = bfs[qh++]!\n        const x = c % cols\n        const y = (c / cols) | 0\n        for (const d of order) {\n          const nx = x + DX[d]!\n          const ny = y + DY[d]!\n          if (!passable(nx, ny, freeTail)) continue\n          const n = ny * cols + nx\n          if (seen[n] === s) continue\n          seen[n] = s\n          if (visibleFood(n, now)) {\n            target = n\n            break search\n          }\n          bfs[qt++] = n\n        }\n      }\n    }\n\n    let pick = -1\n    if (target >= 0) {\n      // Distances back from the pellet; step to the neighbor closest to it,\n      // keeping straight on ties so paths turn once instead of zigzagging.\n      const s = nextStamp()\n      seen[target] = s\n      dist[target] = 0\n      bfs[0] = target\n      let qh = 0\n      let qt = 1\n      while (qh < qt) {\n        const c = bfs[qh++]!\n        const x = c % cols\n        const y = (c / cols) | 0\n        for (let d = 0; d < 4; d++) {\n          const nx = x + DX[d]!\n          const ny = y + DY[d]!\n          if (!passable(nx, ny, freeTail)) continue\n          const n = ny * cols + nx\n          if (seen[n] === s) continue\n          seen[n] = s\n          dist[n] = dist[c]! + 1\n          bfs[qt++] = n\n        }\n      }\n      let best = Infinity\n      for (const d of order) {\n        const nx = hx + DX[d]!\n        const ny = hy + DY[d]!\n        if (!passable(nx, ny, freeTail)) continue\n        const n = ny * cols + nx\n        if (seen[n] !== s) continue\n        if (dist[n]! < best) {\n          best = dist[n]!\n          pick = d\n        }\n      }\n      if (pick >= 0) {\n        const n = (hy + DY[pick]!) * cols + hx + DX[pick]!\n        if (flood(n, freeTail, len) < len) pick = -1\n      }\n    }\n    if (pick >= 0) return pick as Snake404Direction\n\n    // No safe pellet: wander, mostly straight, away from walls and itself.\n    const cap = len * 2 + 8\n    let bestArea = -1\n    let bestDir = dir\n    const ahead = (d: number) =>\n      passable(hx + DX[d]! * 2, hy + DY[d]! * 2, freeTail) ? 1 : 0\n    const wander =\n      Math.random() < 0.08 ? [order[1]!, order[2]!, order[0]!] : order\n    for (const d of wander) {\n      const nx = hx + DX[d]!\n      const ny = hy + DY[d]!\n      if (!passable(nx, ny, freeTail)) continue\n      const area = flood(ny * cols + nx, freeTail, cap) * 2 + ahead(d)\n      if (area > bestArea) {\n        bestArea = area\n        bestDir = d\n      }\n    }\n    return bestDir\n  }\n\n  const die = (now: number) => {\n    phase = \"dead\"\n    deadAt = now\n    queue = []\n    if (playing) {\n      playing = false\n      options.onPlayChange?.(false)\n    }\n  }\n\n  /** Decide the move for the step now starting. */\n  const plan = (now: number) => {\n    const last = bx.length - 1\n    growing = fed[last]! && bx.length < Math.max(START_LENGTH, options.maxLength ?? 32)\n    const freeTail = growing ? -1 : tailCell()\n    let d = dir\n    if (playing) {\n      if (queue.length) d = queue.shift()!\n    } else {\n      d = autopilot(freeTail, now)\n    }\n    const nx = bx[0]! + DX[d]!\n    const ny = by[0]! + DY[d]!\n    if (!passable(nx, ny, freeTail)) {\n      die(now)\n      return\n    }\n    dir = d\n    nextX = nx\n    nextY = ny\n  }\n\n  /** Finish the step: the tail follows, the head lands and maybe eats. */\n  const commit = (now: number) => {\n    const last = bx.length - 1\n    if (growing) {\n      // The bulge reached the tail; the tail holds and the snake is longer.\n      fed[last] = false\n    } else {\n      if (inGrid(bx[last]!, by[last]!)) {\n        const t = by[last]! * cols + bx[last]!\n        occ[t] = occ[t]! - 1\n      }\n      bx.pop()\n      by.pop()\n      fed.pop()\n    }\n    bx.unshift(nextX)\n    by.unshift(nextY)\n    const i = nextY * cols + nextX\n    occ[i] = occ[i]! + 1\n    const ate = food[i] === 1\n    fed.unshift(ate)\n    if (ate) {\n      food[i] = 0\n      remaining--\n      score++\n      options.onEat?.(remaining, glyph.length)\n      if (remaining === 0) {\n        refillAt = now + REFILL_DELAY_MS\n        options.onClear?.()\n      }\n    }\n  }\n\n  const spawn = (now: number) => {\n    const row = Math.floor(rows / 2)\n    // Slide in from the left edge; reduced motion parks it on screen.\n    const onScreen = reduce\n    bx = []\n    by = []\n    fed = []\n    occ.fill(0)\n    for (let k = 0; k < START_LENGTH; k++) {\n      const x = onScreen ? START_LENGTH - k : -1 - k\n      bx.push(x)\n      by.push(row)\n      fed.push(false)\n      if (inGrid(x, row)) occ[row * cols + x] = 1\n    }\n    dir = 0\n    nextX = bx[0]! + 1\n    nextY = row\n    growing = false\n    acc = 0\n    score = 0\n    queue = []\n    phase = onScreen ? \"run\" : \"wait\"\n    enterAt = now + ENTER_DELAY_MS\n  }\n\n  const refill = (now: number) => {\n    const span = Math.max(1, cols + rows)\n    for (const i of glyph) {\n      if (food[i] === 1) continue\n      const x = i % cols\n      const y = (i / cols) | 0\n      food[i] = 1\n      born[i] =\n        now + ((x + y) / span) * REFILL_MS * 2 + (BAYER4[(y & 3) * 4 + (x & 3)]! / 16) * 140\n      remaining++\n    }\n  }\n\n  const layout = (now: number) => {\n    cell = Math.max(4, Math.round(options.cellSize ?? 12))\n    cols = Math.max(1, Math.floor(cssW / cell))\n    rows = Math.max(1, Math.floor(cssH / cell))\n    ox = Math.floor((cssW - cols * cell) / 2)\n    oy = Math.floor((cssH - rows * cell) / 2)\n    const n = cols * rows\n    food = new Uint8Array(n)\n    born = new Float64Array(n)\n    occ = new Uint8Array(n)\n    seen = new Uint32Array(n)\n    dist = new Int32Array(n)\n    bfs = new Int32Array(n + 4)\n    stamp = 0\n    glyph = []\n    remaining = 0\n    refillAt = 0\n\n    const digits = codeDigits(options.code)\n    const bw = digits.length * DIGIT_W + (digits.length - 1) * DIGIT_GAP\n    const k = Math.max(\n      1,\n      Math.floor(Math.min((cols * 0.74) / bw, (rows * 0.5) / DIGIT_H))\n    )\n    const gx0 = Math.floor((cols - bw * k) / 2)\n    const gy0 = Math.floor((rows - DIGIT_H * k) / 2)\n    for (let di = 0; di < digits.length; di++) {\n      const bitmap = DIGITS[digits[di]!]!\n      const left = gx0 + di * (DIGIT_W + DIGIT_GAP) * k\n      for (let r = 0; r < DIGIT_H; r++) {\n        for (let c = 0; c < DIGIT_W; c++) {\n          if (bitmap[r]![c] !== \"#\") continue\n          for (let sy = 0; sy < k; sy++) {\n            for (let sx = 0; sx < k; sx++) {\n              const x = left + c * k + sx\n              const y = gy0 + r * k + sy\n              if (!inGrid(x, y)) continue\n              const i = y * cols + x\n              food[i] = 1\n              glyph.push(i)\n              remaining++\n            }\n          }\n        }\n      }\n    }\n    if (playing) {\n      playing = false\n      options.onPlayChange?.(false)\n    }\n    spawn(now)\n  }\n\n  /** Returns whether the backing store changed (which clears the canvas). */\n  const resize = () => {\n    dpr = Math.min(window.devicePixelRatio || 1, 2)\n    const w = wrap.clientWidth\n    const h = wrap.clientHeight\n    if (w <= 0 || h <= 0) return false\n    cssW = w\n    cssH = h\n    const width = Math.max(1, Math.floor(w * dpr))\n    const height = Math.max(1, Math.floor(h * dpr))\n    const changed = width !== canvas.width || height !== canvas.height\n    if (changed) {\n      canvas.width = width\n      canvas.height = height\n    }\n    canvas.style.width = `${w}px`\n    canvas.style.height = `${h}px`\n    const c = Math.max(4, Math.round(options.cellSize ?? 12))\n    const key = `${Math.floor(w / c)}x${Math.floor(h / c)}:${c}:${codeDigits(options.code)}`\n    if (key !== builtKey) {\n      builtKey = key\n      layout(performance.now())\n    }\n    return changed\n  }\n\n  const drawGhost = (ink: string) => {\n    const key = `${canvas.width}x${canvas.height}:${cols}x${rows}:${cell}:${ink}:${options.lcd}:${dark}`\n    if (key === ghostKey) return\n    ghostKey = key\n    ghost.width = canvas.width\n    ghost.height = canvas.height\n    const g = ghost.getContext(\"2d\")\n    if (!g) return\n    g.setTransform(dpr, 0, 0, dpr, 0, 0)\n    g.clearRect(0, 0, cssW, cssH)\n    g.fillStyle = ink\n    g.globalAlpha = options.lcd ? 0.07 : dark ? 0.05 : 0.035\n    const inset = Math.max(1, Math.round(cell * 0.16))\n    const size = cell - inset * 2\n    for (let y = 0; y < rows; y++) {\n      for (let x = 0; x < cols; x++) {\n        g.fillRect(ox + x * cell + inset, oy + y * cell + inset, size, size)\n      }\n    }\n  }\n\n  const draw = (now: number, p: number) => {\n    const ink = inkOf()\n    ctx.setTransform(dpr, 0, 0, dpr, 0, 0)\n    ctx.clearRect(0, 0, cssW, cssH)\n    if (options.lcd) {\n      ctx.fillStyle = LCD_SCREEN\n      ctx.fillRect(0, 0, cssW, cssH)\n    }\n    if (options.grid) {\n      drawGhost(ink)\n      ctx.drawImage(ghost, 0, 0, cssW, cssH)\n    }\n\n    ctx.fillStyle = ink\n\n    // Food: one pellet per lit cell, popping in after a refill.\n    const inset = Math.max(1, Math.round(cell * 0.16))\n    const pellet = cell - inset * 2\n    for (const i of glyph) {\n      if (food[i] !== 1) continue\n      const t = (now - born[i]!) / POP_MS\n      if (t < 0) continue\n      const x = ox + (i % cols) * cell\n      const y = oy + ((i / cols) | 0) * cell\n      if (t >= 1) {\n        ctx.fillRect(x + inset, y + inset, pellet, pellet)\n      } else {\n        const s = pellet * easeOutBack(t)\n        const o = (cell - s) / 2\n        ctx.fillRect(x + o, y + o, s, s)\n      }\n    }\n\n    // Snake.\n    const dead = phase === \"dead\"\n    const blink = Math.floor((now - deadAt) / BLINK_MS)\n    const shown = !dead || (blink < BLINKS && blink % 2 === 1)\n    if (shown && bx.length > 0) {\n      // Body as thick as a pellet; a meal swells it to nearly a full cell.\n      const th = pellet\n      const half = th / 2\n      const cx = (x: number) => ox + (x + 0.5) * cell\n      const cy = (y: number) => oy + (y + 0.5) * cell\n      const moving = phase === \"run\"\n      const t = moving ? p : 0\n      const last = bx.length - 1\n\n      const hx = cx(bx[0]! + (moving ? (nextX - bx[0]!) * t : 0))\n      const hy = cy(by[0]! + (moving ? (nextY - by[0]!) * t : 0))\n      const tailT = moving && !growing ? t : 0\n      const tx = cx(bx[last]! + (bx[Math.max(0, last - 1)]! - bx[last]!) * tailT)\n      const ty = cy(by[last]! + (by[Math.max(0, last - 1)]! - by[last]!) * tailT)\n\n      const band = (ax: number, ay: number, bx2: number, by2: number) => {\n        ctx.fillRect(\n          Math.min(ax, bx2) - half,\n          Math.min(ay, by2) - half,\n          Math.abs(ax - bx2) + th,\n          Math.abs(ay - by2) + th\n        )\n      }\n\n      let px = hx\n      let py = hy\n      for (let k = 0; k < last; k++) {\n        const qx = cx(bx[k]!)\n        const qy = cy(by[k]!)\n        band(px, py, qx, qy)\n        px = qx\n        py = qy\n      }\n      band(px, py, tx, ty)\n\n      // Swallowed pellets: a bulge that stays put while the body slides by.\n      const swell = cell - Math.max(1, Math.round(cell * 0.06)) * 2\n      for (let k = 1; k <= last; k++) {\n        if (!fed[k] || (k === last && !growing)) continue\n        ctx.fillRect(cx(bx[k]!) - swell / 2, cy(by[k]!) - swell / 2, swell, swell)\n      }\n\n      // Eye, and a mouth that opens when food is next.\n      const fx = DX[dir]!\n      const fy = DY[dir]!\n      const lx = fy\n      const ly = -fx\n      const cut = (x: number, y: number, w: number, h: number) => {\n        if (options.lcd) {\n          ctx.fillStyle = LCD_SCREEN\n          ctx.fillRect(x, y, w, h)\n          ctx.fillStyle = ink\n          return\n        }\n        ctx.globalCompositeOperation = \"destination-out\"\n        ctx.fillRect(x, y, w, h)\n        ctx.globalCompositeOperation = \"source-over\"\n      }\n      // The head is a full swell, so the eye and mouth have room.\n      ctx.fillRect(hx - swell / 2, hy - swell / 2, swell, swell)\n      const eye = Math.max(2, Math.round(cell * 0.2))\n      const ex = hx - fx * swell * 0.06 + lx * swell * 0.22\n      const ey = hy - fy * swell * 0.06 + ly * swell * 0.22\n      cut(ex - eye / 2, ey - eye / 2, eye, eye)\n      if (moving && inGrid(nextX, nextY) && visibleFood(nextY * cols + nextX, now)) {\n        const w = Math.max(2, Math.round(swell * 0.36))\n        const depth = Math.max(1, Math.round(swell * 0.3))\n        const mx = hx + fx * (swell / 2 - depth / 2)\n        const my = hy + fy * (swell / 2 - depth / 2)\n        const mw = fx !== 0 ? depth : w\n        const mh = fx !== 0 ? w : depth\n        cut(mx - mw / 2, my - mh / 2, mw, mh)\n      }\n    }\n\n    if (options.score) {\n      const dot = Math.max(2, Math.round(cell / 4))\n      const digits = String(score).padStart(4, \"0\")\n      const x0 = ox + cell\n      const y0 = oy + cell\n      ctx.globalAlpha = 0.6\n      for (let d = 0; d < digits.length; d++) {\n        const bits = SCORE_DIGITS[digits.charCodeAt(d) - 48]!\n        for (let b = 0; b < 15; b++) {\n          if (bits[b] !== \"1\") continue\n          ctx.fillRect(\n            x0 + d * dot * 4 + (b % 3) * dot,\n            y0 + Math.floor(b / 3) * dot,\n            dot,\n            dot\n          )\n        }\n      }\n      ctx.globalAlpha = 1\n    }\n  }\n\n  const tick = (now: number) => {\n    if (!running) return\n    const dt = Math.min(100, now - lastNow)\n    lastNow = now\n\n    if (refillAt && now >= refillAt) {\n      refillAt = 0\n      refill(now)\n    }\n    if (phase === \"wait\" && now >= enterAt && !reduce) phase = \"run\"\n    if (phase === \"dead\" && now - deadAt >= DEATH_MS) spawn(now)\n\n    const stepMs = 1000 / Math.max(1, options.speed ?? 14)\n    if (phase === \"run\" && (!reduce || playing)) {\n      acc += dt\n      while (acc >= stepMs && phase === \"run\") {\n        acc -= stepMs\n        commit(now)\n        plan(now)\n      }\n    }\n    const p = options.smooth ? Math.min(1, acc / stepMs) : 0\n    draw(now, p)\n\n    if (visible) raf = requestAnimationFrame(tick)\n  }\n\n  const start = () => {\n    cancelAnimationFrame(raf)\n    lastNow = performance.now()\n    raf = requestAnimationFrame(tick)\n  }\n\n  const steer = (d: Snake404Direction) => {\n    if (!options.playable || phase === \"dead\") return\n    if (!playing) {\n      playing = true\n      queue = []\n      options.onPlayChange?.(true)\n    }\n    if (phase === \"wait\") phase = \"run\"\n    const last = queue.length ? queue[queue.length - 1]! : dir\n    if (d === last || d === (last + 2) % 4) return\n    if (queue.length < MAX_QUEUE) queue.push(d)\n  }\n\n  const handBack = () => {\n    if (!playing) return\n    playing = false\n    queue = []\n    options.onPlayChange?.(false)\n  }\n\n  const mqReduce = window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n  reduce = mqReduce.matches\n  const onReduce = () => {\n    const was = reduce\n    reduce = mqReduce.matches\n    if (reduce !== was && !playing) spawn(performance.now())\n  }\n  mqReduce.addEventListener(\"change\", onReduce)\n\n  resize()\n  draw(performance.now(), 0)\n\n  const ro = new ResizeObserver(() => {\n    const changed = resize()\n    if (changed && running) draw(performance.now(), 0)\n  })\n  ro.observe(wrap)\n\n  const io = new IntersectionObserver(([entry]) => {\n    const was = visible\n    visible = entry?.isIntersecting ?? true\n    if (visible && !was) start()\n  })\n  io.observe(wrap)\n\n  const syncTheme = () => {\n    dark = resolveDark(options.theme ?? \"auto\")\n  }\n  const mo = new MutationObserver(syncTheme)\n  mo.observe(document.documentElement, {\n    attributes: true,\n    attributeFilter: [\"class\", \"data-theme\", \"style\"],\n  })\n  const mqDark = window.matchMedia(\"(prefers-color-scheme: dark)\")\n  mqDark.addEventListener(\"change\", syncTheme)\n\n  const onKey = (e: KeyboardEvent) => {\n    if (!options.playable || e.metaKey || e.ctrlKey || e.altKey) return\n    if (e.key === \"Escape\") {\n      if (playing) {\n        e.preventDefault()\n        handBack()\n      }\n      return\n    }\n    const d = KEYS[e.key]\n    if (d === undefined) return\n    e.preventDefault()\n    steer(d)\n  }\n\n  let swipe: { id: number; x: number; y: number } | null = null\n  const onDown = (e: PointerEvent) => {\n    if (!options.playable) return\n    swipe = { id: e.pointerId, x: e.clientX, y: e.clientY }\n  }\n  const onUp = (e: PointerEvent) => {\n    if (!swipe || swipe.id !== e.pointerId) return\n    const dx = e.clientX - swipe.x\n    const dy = e.clientY - swipe.y\n    swipe = null\n    if (Math.max(Math.abs(dx), Math.abs(dy)) < SWIPE_PX) return\n    if (Math.abs(dx) > Math.abs(dy)) steer(dx > 0 ? 0 : 2)\n    else steer(dy > 0 ? 1 : 3)\n  }\n  const onCancel = () => {\n    swipe = null\n  }\n\n  wrap.addEventListener(\"keydown\", onKey)\n  wrap.addEventListener(\"focusout\", handBack)\n  wrap.addEventListener(\"pointerdown\", onDown)\n  wrap.addEventListener(\"pointerup\", onUp)\n  wrap.addEventListener(\"pointercancel\", onCancel)\n\n  start()\n\n  return {\n    setOptions(next) {\n      const prev = options\n      options = { ...options, ...next }\n      if (\n        options.cellSize !== prev.cellSize ||\n        codeDigits(options.code) !== codeDigits(prev.code)\n      ) {\n        builtKey = \"\"\n        resize()\n      }\n      if (options.theme !== prev.theme) syncTheme()\n      if (!options.playable) handBack()\n      if (!visible) draw(performance.now(), 0)\n    },\n    steer,\n    destroy() {\n      running = false\n      cancelAnimationFrame(raf)\n      ro.disconnect()\n      io.disconnect()\n      mo.disconnect()\n      mqReduce.removeEventListener(\"change\", onReduce)\n      mqDark.removeEventListener(\"change\", syncTheme)\n      wrap.removeEventListener(\"keydown\", onKey)\n      wrap.removeEventListener(\"focusout\", handBack)\n      wrap.removeEventListener(\"pointerdown\", onDown)\n      wrap.removeEventListener(\"pointerup\", onUp)\n      wrap.removeEventListener(\"pointercancel\", onCancel)\n    },\n  }\n}\n\nexport type Snake404Props = Snake404Options & {\n  /** Accessible name. Default `\"<code>, page not found\"`. */\n  label?: string\n  className?: string\n}\n\n/**\n * A dot-matrix 404 where every dot is food. A Nokia-style snake eats its\n * way through the digits, then they come back. Click and use the arrow\n * keys, WASD, or swipe to play.\n */\nexport function Snake404({\n  code = \"404\",\n  color,\n  cellSize = 12,\n  speed = 14,\n  maxLength = 32,\n  grid = true,\n  lcd = false,\n  playable = true,\n  score = true,\n  smooth = true,\n  theme = \"auto\",\n  onEat,\n  onClear,\n  onPlayChange,\n  label,\n  className,\n}: Snake404Props) {\n  const wrapRef = useRef<HTMLDivElement>(null)\n  const canvasRef = useRef<HTMLCanvasElement>(null)\n  const instanceRef = useRef<Snake404Instance | null>(null)\n  const callbacksRef = useRef({ onEat, onClear, onPlayChange })\n  const [playing, setPlaying] = useState(false)\n\n  useEffect(() => {\n    callbacksRef.current = { onEat, onClear, onPlayChange }\n  }, [onEat, onClear, onPlayChange])\n\n  const options = {\n    code,\n    color,\n    cellSize,\n    speed,\n    maxLength,\n    grid,\n    lcd,\n    playable,\n    score,\n    smooth,\n    theme,\n  }\n\n  useEffect(() => {\n    const wrap = wrapRef.current\n    const canvas = canvasRef.current\n    if (!wrap || !canvas) return\n    instanceRef.current = createSnake404(wrap, canvas, {\n      ...options,\n      onEat: (left, total) => callbacksRef.current.onEat?.(left, total),\n      onClear: () => callbacksRef.current.onClear?.(),\n      onPlayChange: (next) => {\n        setPlaying(next)\n        callbacksRef.current.onPlayChange?.(next)\n      },\n    })\n    return () => {\n      instanceRef.current?.destroy()\n      instanceRef.current = null\n    }\n    // Engine reads live options via setOptions; mount once.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [])\n\n  useEffect(() => {\n    instanceRef.current?.setOptions(options)\n    // `options` is rebuilt every render; its fields are the real deps.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [\n    code,\n    color,\n    cellSize,\n    speed,\n    maxLength,\n    grid,\n    lcd,\n    playable,\n    score,\n    smooth,\n    theme,\n  ])\n\n  const name = label ?? `${codeDigits(code)}, page not found`\n\n  return (\n    <div\n      ref={wrapRef}\n      data-slot=\"snake-404\"\n      data-playing={playing || undefined}\n      role={playable ? \"application\" : \"img\"}\n      aria-roledescription={playable ? \"Snake game\" : undefined}\n      aria-label={\n        playable ? `${name}. Press an arrow key to steer the snake.` : name\n      }\n      tabIndex={playable ? 0 : undefined}\n      className={cn(\n        \"absolute inset-0 overflow-hidden outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset\",\n        playable && \"touch-none\",\n        className\n      )}\n    >\n      <canvas ref={canvasRef} className=\"absolute inset-0 size-full\" />\n    </div>\n  )\n}\n",
      "type": "registry:ui",
      "target": "components/ui/snake-404.tsx"
    }
  ],
  "type": "registry:ui"
}