# Integrate `Pathfinder` from Motion Garden

You are helping me add the **Pathfinder** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** Pathfinder
- **Category:** Power-User Systems
- **Summary:** A pathfinding visualizer on a grid. Watch A*, Dijkstra, breadth-first or greedy search spread through a maze, then draw the path it found. Drag to draw or erase walls, or drag the start and the goal to move them. The path updates while you draw. Left alone, it builds a new maze, solves it and starts over.
- **Reference:** https://motion-garden.netlify.app/components/pathfinder
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
# Pathfinder needs no npm packages
```

## Files to create

3 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/pathfinder/pathfinder.tsx`

```tsx
"use client";

import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  useSyncExternalStore,
  type ReactNode,
} from "react";
import { useAnimationLoop, type Metrics } from "@/hooks/use-animation-loop";
import {
  generate,
  Search,
  type Maze,
  type PathfinderAlgorithm,
  type PathfinderMaze,
} from "./pathfinder-engine";

export type { PathfinderAlgorithm, PathfinderMaze } from "./pathfinder-engine";

export interface PathfinderProps {
  algorithm?: PathfinderAlgorithm;
  maze?: PathfinderMaze;
  diagonal?: boolean;
  speed?: number;
  cellSize?: number;
  autoplay?: boolean;
  searchColor?: string;
  pathColor?: string;
  boardColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

type Phase = "carve" | "search" | "trace" | "hold" | "fade" | "idle";
type Action = "new" | "run" | "clear";
type Rgb = [number, number, number];

interface Drag {
  id: number;
  kind: "start" | "goal" | "wall";
  value: number;
  last: number;
}

const CARVE_MIN = 1;
const CARVE_MAX = 1.4;
const TRACE = 0.45;
const HOLD = 1.6;
const FADE = 0.35;

const CHROME_MIN_HEIGHT = 280;
const CHROME_MIN_WIDTH = 260;
const PAD = 8;
const BAND_TOP = 40;
const BAND_BOTTOM = 46;

const LABELS: Record<PathfinderAlgorithm, string> = {
  astar: "A*",
  dijkstra: "Dijkstra",
  bfs: "BFS",
  greedy: "Greedy",
};

const REDUCED_QUERY = "(prefers-reduced-motion: reduce)";
const subscribeReduced = (onChange: () => void) => {
  const mq = window.matchMedia(REDUCED_QUERY);
  mq.addEventListener("change", onChange);
  return () => mq.removeEventListener("change", onChange);
};
const readReduced = () => window.matchMedia(REDUCED_QUERY).matches;
const readReducedOnServer = () => false;

export default function Pathfinder({
  algorithm = "astar",
  maze = "backtracker",
  diagonal = false,
  speed = 1,
  cellSize = 18,
  autoplay = true,
  searchColor = "#a855f7",
  pathColor = "#f0abfc",
  boardColor = "#0d0b12",
  paused = false,
  reducedMotion = false,
  className = "",
}: PathfinderProps) {
  const wrapRef = useRef<HTMLDivElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const exploredRef = useRef<HTMLSpanElement>(null);
  const stepsRef = useRef<HTMLSpanElement>(null);
  const announceRef = useRef<HTMLParagraphElement>(null);
  const drawRef = useRef<((dt: number) => void | false) | null>(null);
  const measureRef = useRef<((m: Metrics) => void) | null>(null);
  const actRef = useRef<((action: Action) => void) | null>(null);
  const [chrome, setChrome] = useState(false);

  const osReduced = useSyncExternalStore(subscribeReduced, readReduced, readReducedOnServer);
  const reduce = reducedMotion || osReduced;

  const live = useRef({
    algorithm,
    maze,
    diagonal,
    speed,
    cellSize,
    autoplay,
    searchColor,
    pathColor,
    boardColor,
    paused,
    reduce,
  });
  useLayoutEffect(() => {
    live.current = {
      algorithm,
      maze,
      diagonal,
      speed,
      cellSize,
      autoplay,
      searchColor,
      pathColor,
      boardColor,
      paused,
      reduce,
    };
  });

  const loop = useAnimationLoop({
    target: wrapRef,
    halted: paused || reduce,
    dpr: "auto",
    resizeDebounceMs: 120,
    onResize: (m) => measureRef.current?.(m),
    onFrame: ({ dt }) => (drawRef.current ? drawRef.current(dt) : false),
  });

  useEffect(() => {
    const wrap = wrapRef.current;
    const canvas = canvasRef.current;
    if (!wrap || !canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    let width = 0;
    let height = 0;
    let dpr = 1;
    let cols = 0;
    let rows = 0;
    let cs = 0;
    let ox = 0;
    let oy = 0;
    let ready = false;
    let gridLines = new Path2D();

    let walls: Uint8Array = new Uint8Array(0);
    let shown: Uint8Array = new Uint8Array(0);
    let build: Maze | null = null;
    let next: Maze | null = null;
    let revealed = 0;
    let start = 0;
    let goal = 0;
    let turn = -1;
    let edited = false;

    let search: Search | null = null;
    let budget = 0;
    let clock = 0;
    let path: Int32Array = new Int32Array(0);
    let pathLength = 0;
    let progress = 0;

    let phase: Phase = "idle";
    let t = 0;
    let carveFor = CARVE_MIN;
    let announceRun = false;

    let cursor = 0;
    let focused = false;
    let keyboard = false;
    let drag: Drag | null = null;
    let pointerLook = "";

    const initial = live.current;
    const applied = {
      algorithm: initial.algorithm,
      diagonal: initial.diagonal,
      maze: initial.maze,
      autoplay: initial.autoplay,
      reduce: initial.reduce,
    };

    const cycling = () => {
      const l = live.current;
      return l.autoplay && !edited && !l.reduce;
    };
    const still = () => live.current.paused || live.current.reduce;
    const rate = () => Math.max(0.05, live.current.speed) * Math.max(60, (cols * rows) / 3.2);

    const pal = {
      key: "",
      board: "",
      wall: "",
      lip: "",
      grid: "",
      age: ["", "", ""],
      glow: ["", "", ""],
      front: "",
      path: "",
      core: "",
      ink: "",
      halo: "",
    };
    const palette = () => {
      const l = live.current;
      const key = `${l.boardColor}|${l.searchColor}|${l.pathColor}`;
      if (key === pal.key) return pal;
      const board = toRgb(ctx, l.boardColor, [13, 11, 18]);
      const seek = toRgb(ctx, l.searchColor, [168, 85, 247]);
      const route = toRgb(ctx, l.pathColor, [240, 171, 252]);
      const dark = luminance(board) < 0.5;
      pal.key = key;
      pal.board = rgba(board, 1);
      pal.wall = rgba(mix(board, dark ? [255, 255, 255] : [0, 0, 0], dark ? 0.1 : 0.13), 1);
      pal.lip = dark
        ? rgba(mix(board, [255, 255, 255], 0.2), 1)
        : rgba(mix(board, [255, 255, 255], 0.55), 1);
      pal.grid = dark ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.06)";
      pal.age = [rgba(seek, 0.66), rgba(seek, 0.42), rgba(seek, 0.25)];
      const spark = dark
        ? mix([255, 255, 255], seek, 0.28)
        : mix(mix(board, [0, 0, 0], 0.7), seek, 0.28);
      pal.glow = [rgba(spark, 0.55), rgba(spark, 0.32), rgba(spark, 0.17)];
      pal.front = dark
        ? rgba(mix(seek, [255, 255, 255], 0.5), 0.92)
        : rgba(mix(seek, [0, 0, 0], 0.25), 0.92);
      pal.path = rgba(route, 1);
      pal.core = rgba(mix(route, [255, 255, 255], 0.65), 0.95);
      pal.ink = dark ? "rgba(255,255,255,0.96)" : "rgba(18,16,24,0.92)";
      pal.halo = rgba(board, 0.72);
      return pal;
    };

    const cx = (cell: number) => ox + ((cell % cols) + 0.5) * cs;
    const cy = (cell: number) => oy + (Math.floor(cell / cols) + 0.5) * cs;
    const lengthOf = (route: Int32Array) => {
      let total = 0;
      for (let i = 1; i < route.length; i++) {
        const a = route[i - 1];
        const b = route[i];
        total += a % cols !== b % cols && Math.floor(a / cols) !== Math.floor(b / cols) ? Math.SQRT2 : 1;
      }
      return total;
    };

    const fresh = (): Maze => {
      turn++;
      const seed = (Math.imul(turn + 1, 0x9e3779b1) ^ 0x5eed) >>> 0;
      return generate(cols, rows, live.current.maze, seed, turn);
    };

    const adopt = (m: Maze) => {
      build = m;
      walls = m.walls.slice();
      start = m.start;
      goal = m.goal;
      search = null;
      path = new Int32Array(0);
      pathLength = 0;
      progress = 0;
    };

    const say = (message: string) => {
      const el = announceRef.current;
      if (!el) return;
      el.textContent = el.textContent === message ? message + String.fromCharCode(160) : message;
    };

    const finishSearch = () => {
      const s = search;
      path = s && s.found ? s.path() : new Int32Array(0);
      pathLength = lengthOf(path);
      if (announceRun && s) {
        announceRun = false;
        say(
          s.found
            ? `Path found: ${path.length - 1} steps, ${s.visited} cells explored.`
            : `No path found. ${s.visited} cells explored.`,
        );
      }
    };

    const solveNow = () => {
      const l = live.current;
      search = new Search(walls, cols, rows, start, goal, l.algorithm, l.diagonal).solve();
      budget = 0;
      clock = Infinity;
      finishSearch();
      progress = search.found ? 1 : 0;
    };

    const startSearch = () => {
      const l = live.current;
      search = new Search(walls, cols, rows, start, goal, l.algorithm, l.diagonal);
      budget = 0;
      clock = 0;
      path = new Int32Array(0);
      pathLength = 0;
      progress = 0;
      phase = "search";
      t = 0;
    };

    const beginCarve = (m: Maze) => {
      adopt(m);
      shown = new Uint8Array(cols * rows).fill(m.solid ? 1 : 0);
      revealed = 0;
      carveFor = CARVE_MIN + (CARVE_MAX - CARVE_MIN) * Math.min(1, m.order.length / 1200);
      phase = "carve";
      t = 0;
    };

    const settle = (m: Maze) => {
      next = null;
      adopt(m);
      solveNow();
      phase = cycling() ? "hold" : "idle";
      t = 0;
    };

    const beginFade = () => {
      next = fresh();
      if (phase === "fade") return;
      phase = "fade";
      t = 0;
    };

    const completeBuild = () => {
      if (phase === "carve" && build) revealed = build.order.length;
      next = null;
    };

    const beginEdit = () => {
      completeBuild();
      edited = true;
      announceRun = false;
      phase = "idle";
      t = 0;
    };

    const newMaze = () => {
      edited = false;
      announceRun = false;
      if (still()) settle(fresh());
      else beginFade();
    };

    const run = () => {
      completeBuild();
      announceRun = true;
      if (still()) {
        solveNow();
        phase = cycling() ? "hold" : "idle";
        t = 0;
      } else {
        startSearch();
      }
    };

    const clear = () => {
      beginEdit();
      walls.fill(0);
      solveNow();
    };

    const restart = () => {
      next = null;
      shown = new Uint8Array(cols * rows);
      cursor = (rows >> 1) * cols + (cols >> 1);
      const m = fresh();
      if (still() || !live.current.autoplay) settle(m);
      else beginCarve(m);
    };

    const refit = (pc: number, pr: number, pw: Uint8Array, ps: number, pg: number, pcur: number) => {
      const n = cols * rows;
      const nw = new Uint8Array(n);
      const dx = Math.floor((cols - pc) / 2);
      const dy = Math.floor((rows - pr) / 2);
      for (let y = 0; y < rows; y++) {
        const sy = y - dy;
        if (sy < 0 || sy >= pr) continue;
        for (let x = 0; x < cols; x++) {
          const sx = x - dx;
          if (sx >= 0 && sx < pc) nw[y * cols + x] = pw[sy * pc + sx];
        }
      }
      const carry = (cell: number) => {
        const x = Math.min(cols - 1, Math.max(0, (cell % pc) + dx));
        const y = Math.min(rows - 1, Math.max(0, Math.floor(cell / pc) + dy));
        return y * cols + x;
      };
      walls = nw;
      start = carry(ps);
      goal = carry(pg);
      if (goal === start) goal = start + 1 < n ? start + 1 : start - 1;
      walls[start] = 0;
      walls[goal] = 0;
      cursor = carry(pcur);
      build = null;
      next = null;
      shown = new Uint8Array(n);
      solveNow();
      phase = "idle";
      t = 0;
    };

    const syncProps = () => {
      const l = live.current;
      if (l.reduce !== applied.reduce) {
        applied.reduce = l.reduce;
        if (l.reduce) {
          if (phase !== "idle") {
            completeBuild();
            if (!search || !search.done) solveNow();
            else {
              clock = Infinity;
              progress = search.found ? 1 : 0;
            }
            phase = "idle";
            t = 0;
          }
        } else if (cycling() && phase === "idle") {
          phase = "hold";
          t = HOLD;
        }
      }
      if (l.autoplay !== applied.autoplay) {
        applied.autoplay = l.autoplay;
        edited = false;
        if (l.autoplay && !l.reduce && phase === "idle") {
          phase = "hold";
          t = HOLD;
        }
      }
      if (l.maze !== applied.maze) {
        applied.maze = l.maze;
        if (!edited) newMaze();
      }
      if (l.algorithm !== applied.algorithm || l.diagonal !== applied.diagonal) {
        applied.algorithm = l.algorithm;
        applied.diagonal = l.diagonal;
        if (phase === "carve" || phase === "fade") {
        } else if (phase === "idle" || still()) {
          solveNow();
          if (phase !== "idle") {
            phase = cycling() ? "hold" : "idle";
            t = 0;
          }
        } else {
          startSearch();
        }
      }
    };

    const advance = (dt: number) => {
      switch (phase) {
        case "carve": {
          t += dt;
          if (!build) {
            phase = "idle";
            break;
          }
          const total = build.order.length;
          const k = t >= carveFor ? total : Math.floor((total * t) / carveFor);
          while (revealed < k) {
            const cell = build.order[revealed++];
            shown[cell] = build.walls[cell];
          }
          if (t >= carveFor) startSearch();
          break;
        }
        case "search": {
          const s = search;
          if (!s) {
            phase = "idle";
            break;
          }
          const r = rate();
          budget += r * dt;
          clock += r * dt;
          const n = Math.floor(budget);
          if (n > 0) {
            s.step(n);
            budget -= n;
          }
          if (s.done) {
            finishSearch();
            phase = s.found ? "trace" : "hold";
            t = 0;
          }
          break;
        }
        case "trace": {
          t += dt;
          clock += rate() * dt;
          const k = Math.min(1, t / TRACE);
          progress = 1 - (1 - k) * (1 - k) * (1 - k);
          if (t >= TRACE) {
            progress = 1;
            phase = "hold";
            t = 0;
          }
          break;
        }
        case "hold": {
          t += dt;
          clock += rate() * dt;
          if (t >= HOLD) {
            if (cycling()) beginFade();
            else {
              clock = Infinity;
              phase = "idle";
              t = 0;
            }
          }
          break;
        }
        case "fade": {
          t += dt;
          if (t >= FADE) {
            const m = next;
            next = null;
            if (m) beginCarve(m);
            else phase = "idle";
          }
          break;
        }
        default:
          break;
      }
    };

    const drawWalls = (P: typeof pal, src: Uint8Array) => {
      const body = new Path2D();
      const lip = new Path2D();
      for (let y = 0; y < rows; y++) {
        const row = y * cols;
        let x = 0;
        while (x < cols) {
          if (!src[row + x]) {
            x++;
            continue;
          }
          const x0 = x;
          while (x < cols && src[row + x]) x++;
          body.rect(ox + x0 * cs, oy + y * cs, (x - x0) * cs, cs);
        }
        x = 0;
        while (x < cols) {
          const i = row + x;
          if (!src[i] || (y > 0 && src[i - cols])) {
            x++;
            continue;
          }
          const x0 = x;
          x++;
          while (x < cols && src[row + x] && !(y > 0 && src[row + x - cols])) x++;
          lip.rect(ox + x0 * cs, oy + y * cs, (x - x0) * cs, 1);
        }
      }
      ctx.fillStyle = P.wall;
      ctx.fill(body);
      ctx.fillStyle = P.lip;
      ctx.fill(lip);
    };

    const drawExplored = (P: typeof pal, s: Search) => {
      const { state, closedAt } = s;
      const r = rate();
      const hot = r * 0.16;
      const warm = r * 0.55;
      const layers = [new Path2D(), new Path2D(), new Path2D()];
      for (let y = 0; y < rows; y++) {
        const row = y * cols;
        let x = 0;
        while (x < cols) {
          const i = row + x;
          if (state[i] !== 2) {
            x++;
            continue;
          }
          const age = clock - closedAt[i];
          const b = age < hot ? 0 : age < warm ? 1 : 2;
          const x0 = x;
          x++;
          while (x < cols) {
            const j = row + x;
            if (state[j] !== 2) break;
            const a = clock - closedAt[j];
            if ((a < hot ? 0 : a < warm ? 1 : 2) !== b) break;
            x++;
          }
          layers[b].rect(ox + x0 * cs, oy + y * cs, (x - x0) * cs, cs);
        }
      }
      for (let b = 2; b >= 0; b--) {
        ctx.fillStyle = P.age[b];
        ctx.fill(layers[b]);
      }
      const inset = Math.max(1, Math.round(cs * 0.31));
      const side = cs - inset * 2;
      if (side <= 0) return;
      const front = new Path2D();
      let any = false;
      for (let i = 0; i < state.length; i++) {
        if (state[i] !== 1) continue;
        front.rect(ox + (i % cols) * cs + inset, oy + Math.floor(i / cols) * cs + inset, side, side);
        any = true;
      }
      if (any) {
        ctx.fillStyle = P.front;
        ctx.fill(front);
      }
    };

    const drawCarveGlow = (P: typeof pal) => {
      if (!build || revealed === 0 || revealed >= build.order.length) return;
      const span = Math.min(42, Math.max(3, Math.ceil((build.order.length * 0.14) / carveFor)));
      const from = Math.max(0, revealed - span);
      const layers = [new Path2D(), new Path2D(), new Path2D()];
      for (let i = from; i < revealed; i++) {
        const cell = build.order[i];
        const b = Math.min(2, Math.floor(((revealed - 1 - i) / span) * 3));
        layers[b].rect(ox + (cell % cols) * cs, oy + Math.floor(cell / cols) * cs, cs, cs);
      }
      for (let b = 2; b >= 0; b--) {
        ctx.fillStyle = P.glow[b];
        ctx.fill(layers[b]);
      }
    };

    const drawPath = (P: typeof pal, glow: number) => {
      if (path.length < 2 || progress <= 0) return;
      let left = progress * pathLength;
      let px = cx(path[0]);
      let py = cy(path[0]);
      let tipX = px;
      let tipY = py;
      ctx.beginPath();
      ctx.moveTo(px, py);
      for (let i = 1; i < path.length; i++) {
        const nx = cx(path[i]);
        const ny = cy(path[i]);
        const seg = nx !== px && ny !== py ? Math.SQRT2 : 1;
        if (left >= seg) {
          ctx.lineTo(nx, ny);
          left -= seg;
          tipX = nx;
          tipY = ny;
        } else {
          const f = left / seg;
          tipX = px + (nx - px) * f;
          tipY = py + (ny - py) * f;
          ctx.lineTo(tipX, tipY);
          break;
        }
        px = nx;
        py = ny;
      }
      ctx.lineJoin = "round";
      ctx.lineCap = "round";
      ctx.lineWidth = cs * 0.32;
      ctx.strokeStyle = P.path;
      ctx.shadowColor = P.path;
      ctx.shadowBlur = cs * 0.75 * glow * dpr;
      ctx.stroke();
      ctx.shadowBlur = 0;
      ctx.shadowColor = "transparent";
      ctx.lineWidth = Math.max(1, cs * 0.09);
      ctx.strokeStyle = P.core;
      ctx.stroke();
      if (progress < 1) {
        ctx.fillStyle = P.ink;
        ctx.beginPath();
        ctx.arc(tipX, tipY, cs * 0.17, 0, Math.PI * 2);
        ctx.fill();
      }
    };

    const drawMarker = (P: typeof pal, cell: number, isGoal: boolean, alpha: number) => {
      if (alpha <= 0) return;
      const x = cx(cell);
      const y = cy(cell);
      ctx.globalAlpha = alpha;
      ctx.fillStyle = P.halo;
      ctx.beginPath();
      ctx.arc(x, y, cs * 0.45, 0, Math.PI * 2);
      ctx.fill();
      ctx.fillStyle = P.ink;
      ctx.strokeStyle = P.ink;
      ctx.beginPath();
      if (isGoal) {
        ctx.lineWidth = Math.max(1.25, cs * 0.1);
        ctx.arc(x, y, cs * 0.27, 0, Math.PI * 2);
        ctx.stroke();
        ctx.beginPath();
        ctx.arc(x, y, cs * 0.09, 0, Math.PI * 2);
        ctx.fill();
      } else {
        ctx.arc(x, y, cs * 0.27, 0, Math.PI * 2);
        ctx.fill();
      }
      ctx.globalAlpha = 1;
    };

    const drawGrid = (P: typeof pal) => {
      ctx.strokeStyle = P.grid;
      ctx.lineWidth = 1;
      ctx.stroke(gridLines);
    };

    const drawScene = (P: typeof pal) => {
      ctx.fillStyle = P.board;
      ctx.fillRect(0, 0, width, height);
      if (!ready) return;
      const carving = phase === "carve";
      if (search && !carving) drawExplored(P, search);
      drawGrid(P);
      drawWalls(P, carving ? shown : walls);
      if (carving) drawCarveGlow(P);
      const pulse = phase === "hold" ? 0.5 - 0.5 * Math.cos((t / HOLD) * Math.PI * 4) : 0;
      drawPath(P, 1 + 0.8 * pulse);
      const alpha = carving ? Math.min(1, t / 0.3) : 1;
      drawMarker(P, start, false, alpha);
      drawMarker(P, goal, true, alpha);
    };

    const drawBaseOver = (P: typeof pal, m: Maze, alpha: number) => {
      if (alpha <= 0) return;
      ctx.globalAlpha = alpha;
      const gw = cols * cs;
      const gh = rows * cs;
      if (m.solid) {
        const around = new Path2D();
        around.rect(0, 0, width, height);
        around.rect(ox, oy, gw, gh);
        ctx.fillStyle = P.board;
        ctx.fill(around, "evenodd");
        ctx.fillStyle = P.lip;
        ctx.fillRect(ox, oy, gw, 1);
        ctx.fillStyle = P.wall;
        ctx.fillRect(ox, oy + 1, gw, gh - 1);
      } else {
        ctx.fillStyle = P.board;
        ctx.fillRect(0, 0, width, height);
        drawGrid(P);
      }
      ctx.globalAlpha = 1;
    };

    const drawCursor = () => {
      if (!focused || !keyboard || !ready) return;
      const x = ox + (cursor % cols) * cs;
      const y = oy + Math.floor(cursor / cols) * cs;
      ctx.strokeStyle = "rgba(255,255,255,0.92)";
      ctx.lineWidth = 1.5;
      ctx.strokeRect(x + 1.25, y + 1.25, cs - 2.5, cs - 2.5);
      ctx.strokeStyle = "rgba(0,0,0,0.55)";
      ctx.lineWidth = 1;
      ctx.strokeRect(x + 2.5, y + 2.5, cs - 5, cs - 5);
    };

    const render = () => {
      const P = palette();
      drawScene(P);
      if (phase === "fade" && next) {
        const k = Math.min(1, t / FADE);
        drawBaseOver(P, next, k * k * (3 - 2 * k));
      }
      drawCursor();
    };

    const hud = () => {
      const explored = exploredRef.current;
      const steps = stepsRef.current;
      if (!explored || !steps) return;
      const s = phase === "carve" ? null : search;
      const e = s ? String(s.visited) : "0";
      const p = !s || !s.done ? "…" : s.found ? String(path.length - 1) : "none";
      if (explored.textContent !== e) explored.textContent = e;
      if (steps.textContent !== p) steps.textContent = p;
    };

    drawRef.current = (dt) => {
      if (!ready) return false;
      syncProps();
      advance(dt);
      render();
      hud();
      return phase === "idle" ? false : undefined;
    };

    measureRef.current = ({ width: w, height: h, dpr: d, bufferWidth, bufferHeight }) => {
      if (w <= 0 || h <= 0) return;
      width = w;
      height = h;
      dpr = d;
      if (canvas.width !== bufferWidth) canvas.width = bufferWidth;
      if (canvas.height !== bufferHeight) canvas.height = bufferHeight;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

      const withChrome = h >= CHROME_MIN_HEIGHT && w >= CHROME_MIN_WIDTH;
      setChrome(withChrome);
      const top = withChrome ? BAND_TOP : PAD;
      const bottom = withChrome ? BAND_BOTTOM : PAD;
      const availW = w - PAD * 2;
      const availH = h - top - bottom;
      let size = Math.max(4, Math.round(live.current.cellSize));
      let c = Math.floor(availW / size);
      let r = Math.floor(availH / size);
      if (c < 5 || r < 5) {
        size = Math.max(4, Math.floor(Math.min(availW, availH) / 5));
        c = Math.floor(availW / size);
        r = Math.floor(availH / size);
      }
      if (c % 2 === 0) c--;
      if (r % 2 === 0) r--;
      if (c < 3 || r < 3) {
        ready = false;
        return;
      }

      ox = PAD + Math.floor((availW - c * size) / 2);
      oy = top + Math.floor((availH - r * size) / 2);
      wrap.style.setProperty("--pf-x", `${ox}px`);
      wrap.style.setProperty("--pf-top", `${oy}px`);
      wrap.style.setProperty("--pf-bottom", `${h - oy - r * size}px`);

      const changed = c !== cols || r !== rows || size !== cs;
      const pc = cols;
      const pr = rows;
      cols = c;
      rows = r;
      cs = size;

      gridLines = new Path2D();
      for (let x = 0; x <= cols; x++) {
        const at = ox + x * cs + (x === cols ? -0.5 : 0.5);
        gridLines.moveTo(at, oy);
        gridLines.lineTo(at, oy + rows * cs);
      }
      for (let y = 0; y <= rows; y++) {
        const at = oy + y * cs + (y === rows ? -0.5 : 0.5);
        gridLines.moveTo(ox, at);
        gridLines.lineTo(ox + cols * cs, at);
      }

      if (ready && !changed) return;
      if (edited && pc > 0 && walls.length === pc * pr) refit(pc, pr, walls, start, goal, cursor);
      else restart();
      ready = true;
    };

    const cellAt = (e: PointerEvent, clamp: boolean) => {
      const box = canvas.getBoundingClientRect();
      const sx = box.width > 0 ? width / box.width : 1;
      const sy = box.height > 0 ? height / box.height : 1;
      let x = Math.floor(((e.clientX - box.left) * sx - ox) / cs);
      let y = Math.floor(((e.clientY - box.top) * sy - oy) / cs);
      if (clamp) {
        x = Math.min(cols - 1, Math.max(0, x));
        y = Math.min(rows - 1, Math.max(0, y));
      } else if (x < 0 || y < 0 || x >= cols || y >= rows) {
        return -1;
      }
      return y * cols + x;
    };

    const look = (value: string) => {
      if (value === pointerLook) return;
      pointerLook = value;
      canvas.style.cursor = value;
    };

    const onDown = (e: PointerEvent) => {
      if (!ready || drag) return;
      if (e.pointerType === "mouse" && e.button !== 0) return;
      const cell = cellAt(e, false);
      if (cell < 0) return;
      keyboard = false;
      try {
        canvas.setPointerCapture(e.pointerId);
      } catch {
      }
      beginEdit();
      if (cell === start || cell === goal) {
        drag = { id: e.pointerId, kind: cell === start ? "start" : "goal", value: 0, last: cell };
        look("grabbing");
      } else {
        const value = walls[cell] ? 0 : 1;
        drag = { id: e.pointerId, kind: "wall", value, last: cell };
        walls[cell] = value;
      }
      solveNow();
      loop.paint();
    };

    const onMove = (e: PointerEvent) => {
      if (!ready) return;
      if (!drag || e.pointerId !== drag.id) {
        if (drag || e.pointerType !== "mouse") return;
        const cell = cellAt(e, false);
        look(cell < 0 ? "" : cell === start || cell === goal ? "grab" : "crosshair");
        return;
      }
      const cell = cellAt(e, true);
      if (cell === drag.last) return;
      let changed = false;
      if (drag.kind === "wall") {
        const value = drag.value;
        trace(drag.last, cell, cols, (c) => {
          if (c === start || c === goal || walls[c] === value) return;
          walls[c] = value;
          changed = true;
        });
      } else if (!walls[cell] && cell !== start && cell !== goal) {
        if (drag.kind === "start") start = cell;
        else goal = cell;
        changed = true;
      }
      drag.last = cell;
      if (changed) {
        solveNow();
        loop.paint();
      }
    };

    const onUp = (e: PointerEvent) => {
      if (!drag || e.pointerId !== drag.id) return;
      if (canvas.hasPointerCapture(e.pointerId)) canvas.releasePointerCapture(e.pointerId);
      drag = null;
      look("");
      loop.paint();
    };

    const onMenu = (e: Event) => e.preventDefault();

    const moveCursor = (x: number, y: number) => {
      cursor = Math.min(rows - 1, Math.max(0, y)) * cols + Math.min(cols - 1, Math.max(0, x));
    };

    const place = (isGoal: boolean) => {
      if (cursor === (isGoal ? start : goal)) return;
      beginEdit();
      walls[cursor] = 0;
      if (isGoal) goal = cursor;
      else start = cursor;
      solveNow();
    };

    const onKey = (e: KeyboardEvent) => {
      if (e.target !== wrap || !ready) return;
      if (e.altKey || e.ctrlKey || e.metaKey) return;
      const x = cursor % cols;
      const y = Math.floor(cursor / cols);
      const by = e.shiftKey ? 5 : 1;
      switch (e.key) {
        case "ArrowLeft":
          moveCursor(x - by, y);
          break;
        case "ArrowRight":
          moveCursor(x + by, y);
          break;
        case "ArrowUp":
          moveCursor(x, y - by);
          break;
        case "ArrowDown":
          moveCursor(x, y + by);
          break;
        case " ":
        case "Spacebar":
          if (!e.repeat && cursor !== start && cursor !== goal) {
            beginEdit();
            walls[cursor] = walls[cursor] ? 0 : 1;
            solveNow();
          }
          break;
        case "s":
        case "S":
          if (!e.repeat) place(false);
          break;
        case "g":
        case "G":
          if (!e.repeat) place(true);
          break;
        case "Enter":
          if (!e.repeat) run();
          break;
        case "m":
        case "M":
          if (!e.repeat) newMaze();
          break;
        case "c":
        case "C":
          if (!e.repeat) clear();
          break;
        default:
          return;
      }
      e.preventDefault();
      keyboard = true;
      loop.paint();
    };

    const onFocus = () => {
      focused = true;
      try {
        keyboard = wrap.matches(":focus-visible");
      } catch {
        keyboard = false;
      }
      loop.paint();
    };

    const onBlur = () => {
      focused = false;
      keyboard = false;
      loop.paint();
    };

    actRef.current = (action) => {
      if (!ready) return;
      if (action === "new") newMaze();
      else if (action === "run") run();
      else clear();
      loop.paint();
    };

    canvas.addEventListener("pointerdown", onDown);
    canvas.addEventListener("pointermove", onMove);
    canvas.addEventListener("pointerup", onUp);
    canvas.addEventListener("pointercancel", onUp);
    canvas.addEventListener("lostpointercapture", onUp);
    canvas.addEventListener("contextmenu", onMenu);
    wrap.addEventListener("keydown", onKey);
    wrap.addEventListener("focus", onFocus);
    wrap.addEventListener("blur", onBlur);

    loop.resize();
    loop.start();

    return () => {
      drawRef.current = null;
      measureRef.current = null;
      actRef.current = null;
      canvas.removeEventListener("pointerdown", onDown);
      canvas.removeEventListener("pointermove", onMove);
      canvas.removeEventListener("pointerup", onUp);
      canvas.removeEventListener("pointercancel", onUp);
      canvas.removeEventListener("lostpointercapture", onUp);
      canvas.removeEventListener("contextmenu", onMenu);
      wrap.removeEventListener("keydown", onKey);
      wrap.removeEventListener("focus", onFocus);
      wrap.removeEventListener("blur", onBlur);
    };
  }, [loop]);

  useEffect(() => {
    loop.start();
  }, [paused, reduce, autoplay, algorithm, maze, diagonal, loop]);

  useEffect(() => {
    loop.paint();
  }, [searchColor, pathColor, boardColor, chrome, loop]);

  useEffect(() => {
    loop.resize();
  }, [cellSize, loop]);

  return (
    <div className={`relative flex h-full w-full flex-col overflow-hidden ${className}`.trim()}>
      <div
        ref={wrapRef}
        tabIndex={0}
        role="application"
        aria-roledescription="pathfinding grid"
        aria-label="Pathfinding grid. Arrow keys move the cursor, and Shift moves it five cells. Space adds or removes a wall. S sets the start and G sets the goal. Enter runs the search, M builds a new maze and C clears the board."
        className="@container relative min-h-0 flex-1 touch-none select-none outline-none focus-visible:outline-2 focus-visible:-outline-offset-2"
        style={{ backgroundColor: boardColor, outlineColor: searchColor }}
      >
        <canvas ref={canvasRef} aria-hidden="true" className="absolute inset-0 block size-full" />
        {chrome && (
          <>
            <div
              aria-hidden="true"
              className="pointer-events-none absolute flex h-6 items-center gap-1.5 whitespace-nowrap rounded-md bg-black/45 px-2 font-mono text-[11px] leading-none tabular-nums text-white/85 backdrop-blur-sm"
              style={{
                left: "var(--pf-x, 8px)",
                bottom: "calc(100% - var(--pf-top, 40px) + 6px)",
              }}
            >
              <span className="font-semibold text-white">{LABELS[algorithm]}</span>
              <span className="text-white/30">·</span>
              <span className="text-white/50">explored</span>
              <span ref={exploredRef} />
              <span className="text-white/30">·</span>
              <span className="text-white/50">path</span>
              <span ref={stepsRef} />
            </div>
            <div
              className="absolute flex items-center gap-0.5 rounded-md bg-black/45 p-0.5 text-white/85 backdrop-blur-sm"
              style={{
                left: "var(--pf-x, 8px)",
                top: "calc(100% - var(--pf-bottom, 46px) + 6px)",
              }}
            >
              <ToolButton label="New maze" shortcut="M" onPress={() => actRef.current?.("new")}>
                <svg {...ICON}>
                  <path d="M4 9V4h16v11" />
                  <path d="M20 20H4v-7" />
                  <path d="M8 8h8v4" />
                  <path d="M8 12v4h4" />
                </svg>
              </ToolButton>
              <ToolButton label="Run" shortcut="Enter" onPress={() => actRef.current?.("run")}>
                <svg {...ICON}>
                  <path d="M8 5.5v13l10-6.5z" fill="currentColor" />
                </svg>
              </ToolButton>
              <ToolButton label="Clear" shortcut="C" onPress={() => actRef.current?.("clear")}>
                <svg {...ICON}>
                  <path d="M17.5 13.5 11 20H8l-4-4 9.5-9.5a2 2 0 0 1 2.8 0l1.2 1.2a2 2 0 0 1 0 2.8z" />
                  <path d="M8.5 11.5 14 17" />
                  <path d="M12 20h8" />
                </svg>
              </ToolButton>
            </div>
          </>
        )}
      </div>
      <p ref={announceRef} aria-live="polite" className="sr-only" />
    </div>
  );
}

const ICON = {
  viewBox: "0 0 24 24",
  width: 14,
  height: 14,
  fill: "none",
  stroke: "currentColor",
  strokeWidth: 2,
  strokeLinecap: "round",
  strokeLinejoin: "round",
  "aria-hidden": true,
} as const;

function ToolButton({
  label,
  shortcut,
  onPress,
  children,
}: {
  label: string;
  shortcut: string;
  onPress: () => void;
  children: ReactNode;
}) {
  return (
    <button
      type="button"
      aria-label={label}
      title={`${label} (${shortcut})`}
      onClick={onPress}
      className="inline-flex h-7 items-center gap-1.5 rounded px-2 text-[11px] font-medium text-white/80 transition-colors hover:bg-white/10 hover:text-white focus-visible:outline-2 focus-visible:outline-white/70"
    >
      {children}
      <span className="hidden @min-[480px]:inline">{label}</span>
    </button>
  );
}

function trace(from: number, to: number, width: number, visit: (cell: number) => void) {
  let x0 = from % width;
  let y0 = Math.floor(from / width);
  const x1 = to % width;
  const y1 = Math.floor(to / width);
  const dx = Math.abs(x1 - x0);
  const dy = -Math.abs(y1 - y0);
  const sx = x0 < x1 ? 1 : -1;
  const sy = y0 < y1 ? 1 : -1;
  let err = dx + dy;
  for (;;) {
    visit(y0 * width + x0);
    if (x0 === x1 && y0 === y1) break;
    const e2 = 2 * err;
    if (e2 >= dy) {
      err += dy;
      x0 += sx;
    }
    if (e2 <= dx) {
      err += dx;
      y0 += sy;
    }
  }
}

function toRgb(ctx: CanvasRenderingContext2D, color: string, fallback: Rgb): Rgb {
  ctx.fillStyle = `rgb(${fallback[0]},${fallback[1]},${fallback[2]})`;
  ctx.fillStyle = color;
  const s = String(ctx.fillStyle);
  if (s.startsWith("#") && s.length === 7) {
    return [parseInt(s.slice(1, 3), 16), parseInt(s.slice(3, 5), 16), parseInt(s.slice(5, 7), 16)];
  }
  const m = /rgba?\(([^)]+)\)/.exec(s);
  if (m) {
    const [r, g, b] = m[1].split(",").map((v) => Number.parseFloat(v));
    if ([r, g, b].every(Number.isFinite)) return [r, g, b];
  }
  return fallback;
}

function mix(a: Rgb, b: Rgb, k: number): Rgb {
  return [a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k, a[2] + (b[2] - a[2]) * k];
}

function rgba(c: Rgb, alpha: number) {
  return `rgba(${Math.round(c[0])},${Math.round(c[1])},${Math.round(c[2])},${alpha})`;
}

function luminance(c: Rgb) {
  return (0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]) / 255;
}
```

### 2. `components/registry/pathfinder/pathfinder-engine.ts` — supporting file, required

```tsx
export type PathfinderAlgorithm = "astar" | "dijkstra" | "bfs" | "greedy";
export type PathfinderMaze = "backtracker" | "prim" | "scatter";

export interface Maze {
  cols: number;
  rows: number;
  walls: Uint8Array;
  order: Int32Array;
  solid: boolean;
  start: number;
  goal: number;
}

export const mulberry32 = (seed: number) => () => {
  seed |= 0;
  seed = (seed + 0x6d2b79f5) | 0;
  let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
  t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
  return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};

export function corners(cols: number, rows: number, turn: number): [number, number] {
  const lx = Math.max(1, cols % 2 === 1 ? cols - 2 : cols - 3);
  const ly = Math.max(1, rows % 2 === 1 ? rows - 2 : rows - 3);
  const xs = [1, lx, lx, 1];
  const ys = [1, 1, ly, ly];
  const a = ((turn % 4) + 4) % 4;
  const b = (a + 2) % 4;
  return [ys[a] * cols + xs[a], ys[b] * cols + xs[b]];
}

export function generate(
  cols: number,
  rows: number,
  kind: PathfinderMaze,
  seed: number,
  turn: number,
): Maze {
  const [start, goal] = corners(cols, rows, turn);
  if (cols < 3 || rows < 3) {
    const n = Math.max(0, cols * rows);
    return { cols, rows, walls: new Uint8Array(n), order: new Int32Array(0), solid: false, start: 0, goal: Math.max(0, n - 1) };
  }
  const rand = mulberry32(seed);
  if (kind === "scatter") return scatter(cols, rows, rand, start, goal);
  return lattice(cols, rows, rand, start, goal, kind === "prim");
}

function lattice(
  cols: number,
  rows: number,
  rand: () => number,
  start: number,
  goal: number,
  prim: boolean,
): Maze {
  const walls = new Uint8Array(cols * rows).fill(1);
  const rx = Math.max(1, (cols - 1) >> 1);
  const ry = Math.max(1, (rows - 1) >> 1);
  const rooms = rx * ry;
  const order = new Int32Array(rooms * 2 - 1);
  let len = 0;

  const open = (cell: number) => {
    walls[cell] = 0;
    order[len++] = cell;
  };
  const cellOf = (room: number) => {
    const x = room % rx;
    return ((room - x) / rx * 2 + 1) * cols + x * 2 + 1;
  };
  const between = (a: number, b: number) => (cellOf(a) + cellOf(b)) / 2;

  const sx = start % cols;
  const first = (((start - sx) / cols - 1) >> 1) * rx + ((sx - 1) >> 1);
  const visited = new Uint8Array(rooms);
  const near = new Int32Array(4);

  const neighbours = (room: number, wantVisited: number) => {
    const x = room % rx;
    const y = (room - x) / rx;
    let k = 0;
    if (x > 0 && visited[room - 1] === wantVisited) near[k++] = room - 1;
    if (x < rx - 1 && visited[room + 1] === wantVisited) near[k++] = room + 1;
    if (y > 0 && visited[room - rx] === wantVisited) near[k++] = room - rx;
    if (y < ry - 1 && visited[room + rx] === wantVisited) near[k++] = room + rx;
    return k;
  };

  visited[first] = 1;
  open(cellOf(first));

  if (!prim) {
    const stack = new Int32Array(rooms);
    let sp = 0;
    stack[sp++] = first;
    while (sp > 0) {
      const room = stack[sp - 1];
      const k = neighbours(room, 0);
      if (k === 0) {
        sp--;
        continue;
      }
      const next = near[Math.floor(rand() * k)];
      open(between(room, next));
      open(cellOf(next));
      visited[next] = 1;
      stack[sp++] = next;
    }
  } else {
    const frontier = new Int32Array(rooms);
    const inFrontier = new Uint8Array(rooms);
    let fl = 0;
    const grow = (room: number) => {
      const k = neighbours(room, 0);
      for (let i = 0; i < k; i++) {
        const n = near[i];
        if (inFrontier[n]) continue;
        inFrontier[n] = 1;
        frontier[fl++] = n;
      }
    };
    grow(first);
    while (fl > 0) {
      const pick = Math.floor(rand() * fl);
      const room = frontier[pick];
      frontier[pick] = frontier[--fl];
      inFrontier[room] = 0;
      const k = neighbours(room, 1);
      const from = near[Math.floor(rand() * k)];
      open(between(from, room));
      open(cellOf(room));
      visited[room] = 1;
      grow(room);
    }
  }

  return { cols, rows, walls, order: order.slice(0, len), solid: true, start, goal };
}

const SCATTER_DENSITY = 0.28;

function scatter(
  cols: number,
  rows: number,
  rand: () => number,
  start: number,
  goal: number,
): Maze {
  const n = cols * rows;
  const walls = new Uint8Array(n);
  const order: number[] = [];
  const raise = (cell: number) => {
    walls[cell] = 1;
    order.push(cell);
  };

  for (let x = 0; x < cols; x++) raise(x);
  for (let y = 1; y < rows; y++) raise(y * cols + cols - 1);
  for (let x = cols - 2; x >= 0; x--) raise((rows - 1) * cols + x);
  for (let y = rows - 2; y >= 1; y--) raise(y * cols);

  const keep = new Uint8Array(n);
  for (const cell of [start, goal]) {
    const cx = cell % cols;
    const cy = (cell - cx) / cols;
    for (let dy = -1; dy <= 1; dy++) {
      for (let dx = -1; dx <= 1; dx++) {
        const x = cx + dx;
        const y = cy + dy;
        if (x >= 0 && y >= 0 && x < cols && y < rows) keep[y * cols + x] = 1;
      }
    }
  }

  const iw = cols - 2;
  const ih = rows - 2;
  const target = Math.round(iw * ih * SCATTER_DENSITY);
  let placed = 0;
  let attempts = iw * ih * 6;
  while (placed < target && attempts-- > 0) {
    const cx = 1 + Math.floor(rand() * iw);
    const cy = 1 + Math.floor(rand() * ih);
    for (let dy = -1; dy <= 1; dy++) {
      for (let dx = -1; dx <= 1; dx++) {
        const corner = dx !== 0 && dy !== 0;
        const edge = !corner && (dx !== 0 || dy !== 0);
        if (corner && rand() < 0.45) continue;
        if (edge && rand() < 0.12) continue;
        const x = cx + dx;
        const y = cy + dy;
        if (x < 1 || y < 1 || x > cols - 2 || y > rows - 2) continue;
        const cell = y * cols + x;
        if (keep[cell] || walls[cell]) continue;
        raise(cell);
        placed++;
      }
    }
  }

  if (!reachable(walls, cols, rows, start, goal)) corridor(walls, cols, rows, rand, start, goal);

  const kept = order.filter((cell) => walls[cell] === 1);
  return { cols, rows, walls, order: Int32Array.from(kept), solid: false, start, goal };
}

function reachable(walls: Uint8Array, cols: number, rows: number, from: number, to: number) {
  const n = cols * rows;
  const seen = new Uint8Array(n);
  const queue = new Int32Array(n);
  let head = 0;
  let tail = 0;
  queue[tail++] = from;
  seen[from] = 1;
  while (head < tail) {
    const c = queue[head++];
    if (c === to) return true;
    const x = c % cols;
    const y = (c - x) / cols;
    if (x > 0 && !seen[c - 1] && !walls[c - 1]) {
      seen[c - 1] = 1;
      queue[tail++] = c - 1;
    }
    if (x < cols - 1 && !seen[c + 1] && !walls[c + 1]) {
      seen[c + 1] = 1;
      queue[tail++] = c + 1;
    }
    if (y > 0 && !seen[c - cols] && !walls[c - cols]) {
      seen[c - cols] = 1;
      queue[tail++] = c - cols;
    }
    if (y < rows - 1 && !seen[c + cols] && !walls[c + cols]) {
      seen[c + cols] = 1;
      queue[tail++] = c + cols;
    }
  }
  return false;
}

function corridor(
  walls: Uint8Array,
  cols: number,
  rows: number,
  rand: () => number,
  start: number,
  goal: number,
) {
  let x = start % cols;
  let y = (start - x) / cols;
  const gx = goal % cols;
  const gy = (goal - gx) / cols;
  let guard = cols * rows * 8;
  while ((x !== gx || y !== gy) && guard-- > 0) {
    let dx = 0;
    let dy = 0;
    if (rand() < 0.65) {
      if (x !== gx && (y === gy || rand() < 0.5)) dx = Math.sign(gx - x);
      else dy = Math.sign(gy - y);
    } else {
      const d = Math.floor(rand() * 4);
      dx = d === 0 ? 1 : d === 1 ? -1 : 0;
      dy = d === 2 ? 1 : d === 3 ? -1 : 0;
    }
    const nx = x + dx;
    const ny = y + dy;
    if (nx < 1 || ny < 1 || nx > cols - 2 || ny > rows - 2) continue;
    x = nx;
    y = ny;
    walls[y * cols + x] = 0;
  }
  while (x !== gx) {
    x += Math.sign(gx - x);
    walls[y * cols + x] = 0;
  }
  while (y !== gy) {
    y += Math.sign(gy - y);
    walls[y * cols + x] = 0;
  }
}

const SQRT2 = Math.SQRT2;
const DX = [1, -1, 0, 0, 1, 1, -1, -1];
const DY = [0, 0, 1, -1, 1, -1, 1, -1];

class Heap {
  private ids: Int32Array;
  private k1: Float64Array;
  private k2: Float64Array;
  private k3: Float64Array;
  size = 0;

  constructor(capacity: number) {
    const cap = Math.max(16, capacity);
    this.ids = new Int32Array(cap);
    this.k1 = new Float64Array(cap);
    this.k2 = new Float64Array(cap);
    this.k3 = new Float64Array(cap);
  }

  private less(i: number, j: number) {
    const a = this.k1[i];
    const b = this.k1[j];
    if (a !== b) return a < b;
    const c = this.k2[i];
    const d = this.k2[j];
    if (c !== d) return c < d;
    return this.k3[i] < this.k3[j];
  }

  private swap(i: number, j: number) {
    const id = this.ids[i];
    this.ids[i] = this.ids[j];
    this.ids[j] = id;
    const a = this.k1[i];
    this.k1[i] = this.k1[j];
    this.k1[j] = a;
    const b = this.k2[i];
    this.k2[i] = this.k2[j];
    this.k2[j] = b;
    const c = this.k3[i];
    this.k3[i] = this.k3[j];
    this.k3[j] = c;
  }

  private grow() {
    const cap = this.ids.length * 2;
    const ids = new Int32Array(cap);
    ids.set(this.ids);
    this.ids = ids;
    const k1 = new Float64Array(cap);
    k1.set(this.k1);
    this.k1 = k1;
    const k2 = new Float64Array(cap);
    k2.set(this.k2);
    this.k2 = k2;
    const k3 = new Float64Array(cap);
    k3.set(this.k3);
    this.k3 = k3;
  }

  push(id: number, a: number, b: number, c: number) {
    if (this.size === this.ids.length) this.grow();
    let i = this.size++;
    this.ids[i] = id;
    this.k1[i] = a;
    this.k2[i] = b;
    this.k3[i] = c;
    while (i > 0) {
      const parent = (i - 1) >> 1;
      if (!this.less(i, parent)) break;
      this.swap(i, parent);
      i = parent;
    }
  }

  pop(): number {
    if (this.size === 0) return -1;
    const top = this.ids[0];
    const last = --this.size;
    if (last > 0) {
      this.swap(0, last);
      let i = 0;
      for (;;) {
        const l = i * 2 + 1;
        const r = l + 1;
        let m = i;
        if (l < last && this.less(l, m)) m = l;
        if (r < last && this.less(r, m)) m = r;
        if (m === i) break;
        this.swap(i, m);
        i = m;
      }
    }
    return top;
  }
}

export class Search {
  readonly cols: number;
  readonly rows: number;
  readonly state: Uint8Array;
  readonly closedAt: Int32Array;
  readonly came: Int32Array;
  readonly g: Float64Array;
  visited = 0;
  done = false;
  found = false;

  private readonly walls: Uint8Array;
  private readonly start: number;
  private readonly goal: number;
  private readonly gx: number;
  private readonly gy: number;
  private readonly algorithm: PathfinderAlgorithm;
  private readonly diagonal: boolean;
  private readonly heap: Heap | null;
  private readonly queue: Int32Array | null;
  private qHead = 0;
  private qCount = 0;
  private seq = 0;

  constructor(
    walls: Uint8Array,
    cols: number,
    rows: number,
    start: number,
    goal: number,
    algorithm: PathfinderAlgorithm,
    diagonal: boolean,
  ) {
    const n = cols * rows;
    this.cols = cols;
    this.rows = rows;
    this.walls = walls;
    this.start = start;
    this.goal = goal;
    this.gx = goal % cols;
    this.gy = (goal - this.gx) / cols;
    this.algorithm = algorithm;
    this.diagonal = diagonal;
    this.state = new Uint8Array(n);
    this.closedAt = new Int32Array(n).fill(-1);
    this.came = new Int32Array(n).fill(-1);
    this.g = new Float64Array(n).fill(Infinity);

    if (algorithm === "bfs") {
      this.queue = new Int32Array(Math.max(1, n));
      this.heap = null;
    } else {
      this.queue = null;
      this.heap = new Heap(n >> 1);
    }

    if (start < 0 || goal < 0 || start >= n || goal >= n || walls[start] || walls[goal]) {
      this.done = true;
      return;
    }
    this.g[start] = 0;
    this.state[start] = 1;
    this.enqueue(start);
  }

  h(cell: number) {
    const x = cell % this.cols;
    const dx = Math.abs(x - this.gx);
    const dy = Math.abs((cell - x) / this.cols - this.gy);
    return this.diagonal ? dx + dy + (SQRT2 - 2) * Math.min(dx, dy) : dx + dy;
  }

  private enqueue(cell: number) {
    const seq = this.seq++;
    if (this.queue) {
      this.queue[(this.qHead + this.qCount) % this.queue.length] = cell;
      this.qCount++;
      return;
    }
    const heap = this.heap as Heap;
    const g = this.g[cell];
    if (this.algorithm === "astar") {
      const h = this.h(cell);
      heap.push(cell, g + h, h, seq);
    } else if (this.algorithm === "dijkstra") {
      heap.push(cell, g, seq, 0);
    } else {
      heap.push(cell, this.h(cell), seq, 0);
    }
  }

  private next(): number {
    if (this.queue) {
      if (this.qCount === 0) return -1;
      const cell = this.queue[this.qHead];
      this.qHead = (this.qHead + 1) % this.queue.length;
      this.qCount--;
      return cell;
    }
    const heap = this.heap as Heap;
    for (;;) {
      const cell = heap.pop();
      if (cell < 0 || this.state[cell] !== 2) return cell;
    }
  }

  step(n: number): number {
    let k = 0;
    while (k < n && !this.done) {
      const u = this.next();
      if (u < 0) {
        this.done = true;
        break;
      }
      this.state[u] = 2;
      this.closedAt[u] = this.visited++;
      k++;
      if (u === this.goal) {
        this.done = true;
        this.found = true;
        break;
      }
      this.expand(u);
    }
    return k;
  }

  solve(): this {
    while (!this.done) this.step(0x7fffffff);
    return this;
  }

  private expand(u: number) {
    const { cols, rows, walls, state, g, came } = this;
    const x = u % cols;
    const y = (u - x) / cols;
    const dirs = this.diagonal ? 8 : 4;
    const bfs = this.algorithm === "bfs";
    const greedy = this.algorithm === "greedy";
    for (let d = 0; d < dirs; d++) {
      const nx = x + DX[d];
      const ny = y + DY[d];
      if (nx < 0 || ny < 0 || nx >= cols || ny >= rows) continue;
      const v = ny * cols + nx;
      if (walls[v] || state[v] === 2) continue;
      if (d >= 4 && (walls[y * cols + nx] || walls[ny * cols + x])) continue;
      const cost = g[u] + (d >= 4 ? SQRT2 : 1);
      if (state[v] === 0) {
        state[v] = 1;
        g[v] = cost;
        came[v] = u;
        this.enqueue(v);
      } else if (!bfs && cost < g[v] - 1e-9) {
        g[v] = cost;
        came[v] = u;
        if (!greedy) this.enqueue(v);
      }
    }
  }

  path(): Int32Array {
    if (!this.found) return new Int32Array(0);
    let len = 1;
    for (let c = this.goal; c !== this.start && len <= this.visited + 1; c = this.came[c]) len++;
    const out = new Int32Array(len);
    let c = this.goal;
    for (let i = len - 1; i >= 0; i--) {
      out[i] = c;
      c = this.came[c];
    }
    return out;
  }
}
```

### 3. `hooks/use-animation-loop.ts` — peer hook, required

```tsx
"use client";

import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";

export interface Metrics {
  width: number;
  height: number;
  dpr: number;
  bufferWidth: number;
  bufferHeight: number;
}

export interface FrameInfo {
  now: number;
  dt: number;
  elapsed: number;
  frame: number;
}

export interface AnimationLoopHandle {
  start(): void;
  stop(): void;
  paint(): void;
  resize(): void;
  readonly running: boolean;
}

export interface AnimationLoopOptions {
  target: React.RefObject<HTMLElement | null>;
  halted?: boolean;
  dpr?: number | "auto";
  onResize?(metrics: Metrics): void;
  onFrame?(info: FrameInfo): void | false;
  paintWhenHalted?: boolean;
  resizeDebounceMs?: number;
  gl?(): WebGLRenderingContext | WebGL2RenderingContext | null | undefined;
  onDispose?(): void;
  deps?: unknown[];
}

const MAX_DT = 1 / 15;

export function useAnimationLoop(
  options: AnimationLoopOptions,
): AnimationLoopHandle {
  const opts = useRef(options);
  useLayoutEffect(() => {
    opts.current = options;
  });

  const raf = useRef<number | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const running = useRef(false);
  const disposed = useRef(false);
  const startedAt = useRef(0);
  const last = useRef(0);
  const frame = useRef(0);

  const measure = useCallback((): Metrics | null => {
    const el = opts.current.target.current;
    if (!el) return null;
    const rect = el.getBoundingClientRect();
    const cap = opts.current.dpr ?? "auto";
    const limit = cap === "auto" ? 2 : cap;
    const dpr = Math.min(
      typeof window === "undefined" ? 1 : window.devicePixelRatio || 1,
      limit,
    );
    return {
      width: rect.width,
      height: rect.height,
      dpr,
      bufferWidth: Math.max(1, Math.round(rect.width * dpr)),
      bufferHeight: Math.max(1, Math.round(rect.height * dpr)),
    };
  }, []);

  const tick = useCallback(function tick(now: number) {
    if (disposed.current) return;

    if (startedAt.current === 0) startedAt.current = now;
    const dt = last.current === 0 ? 0 : Math.min((now - last.current) / 1000, MAX_DT);
    last.current = now;

    const info: FrameInfo = {
      now,
      dt,
      elapsed: (now - startedAt.current) / 1000,
      frame: frame.current++,
    };

    const verdict = opts.current.onFrame?.(info);

    if (disposed.current) return;

    if (verdict === false || opts.current.halted) {
      running.current = false;
      raf.current = null;
      return;
    }
    raf.current = requestAnimationFrame(tick);
  }, []);

  const start = useCallback(() => {
    if (disposed.current || running.current) return;
    running.current = true;
    last.current = 0;
    raf.current = requestAnimationFrame(tick);
  }, [tick]);

  const stop = useCallback(() => {
    running.current = false;
    if (raf.current !== null) {
      cancelAnimationFrame(raf.current);
      raf.current = null;
    }
  }, []);

  const paint = useCallback(() => start(), [start]);

  const resize = useCallback(() => {
    const metrics = measure();
    if (!metrics) return;
    opts.current.onResize?.(metrics);
    if (opts.current.paintWhenHalted !== false) paint();
    else if (!opts.current.halted) start();
  }, [measure, paint, start]);

  const deps = options.deps ?? [];

  useEffect(() => {
    disposed.current = false;
    const el = opts.current.target.current;
    if (!el) return;

    const run = () => {
      if (disposed.current) return;
      resize();
    };

    const observer = new ResizeObserver(() => {
      const wait = opts.current.resizeDebounceMs ?? 0;
      if (wait <= 0) {
        run();
        return;
      }
      if (timer.current !== null) clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        timer.current = null;
        run();
      }, wait);
    });
    observer.observe(el);

    resize();
    if (!opts.current.halted) start();

    return () => {
      disposed.current = true;
      running.current = false;
      if (raf.current !== null) {
        cancelAnimationFrame(raf.current);
        raf.current = null;
      }
      if (timer.current !== null) {
        clearTimeout(timer.current);
        timer.current = null;
      }
      observer.disconnect();
      opts.current.onDispose?.();
      const context = opts.current.gl?.();
      context?.getExtension("WEBGL_lose_context")?.loseContext();
      startedAt.current = 0;
      last.current = 0;
      frame.current = 0;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  const halted = options.halted ?? false;
  useEffect(() => {
    if (!halted) start();
  }, [halted, start]);

  return useMemo<AnimationLoopHandle>(
    () => ({
      start,
      stop,
      paint,
      resize,
      get running() {
        return running.current;
      },
    }),
    [start, stop, paint, resize],
  );
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `algorithm` | `"astar" | "dijkstra" | "bfs" | "greedy"` | `"astar"` | Which search runs. |
| `maze` | `"backtracker" | "prim" | "scatter"` | `"backtracker"` | How new walls are laid out. |
| `diagonal` | `boolean` | `false` | Allow diagonal steps. A diagonal can't cut across a wall's corner. |
| `speed` | `number` | `1` | How fast the search spreads. Range 0.25–4 ×. |
| `cellSize` | `number` | `18` | Size of one grid cell. Range 10–36 px. |
| `autoplay` | `boolean` | `true` | Build a maze, solve it and start over while you are not editing. |
| `searchColor` | `string (hex)` | `"#a855f7"` | Cells the search has explored. |
| `pathColor` | `string (hex)` | `"#f0abfc"` | The path it found. |
| `boardColor` | `string (hex)` | `"#0d0b12"` | The grid. Walls are drawn a shade off it. |

## Usage

```tsx
import Pathfinder from "@/components/registry/pathfinder/pathfinder";

<Pathfinder
  algorithm="astar"
  maze="backtracker"
  diagonal={false}
  speed={1}
  cellSize={18}
  autoplay={true}
  searchColor="#a855f7"
  pathColor="#f0abfc"
  boardColor="#0d0b12"
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- It runs a free-running animation loop. Halt it when off-screen or backgrounded if you care about battery.
- The `touch-action: none` on the hit target is load-bearing — without it a finger drag scrolls the page instead of driving the effect. Do not strip it as a stray utility class.
- The peer hook is required, not optional. Copy it to `hooks/use-animation-loop.ts` so the component's `@/hooks/use-animation-loop` import resolves.
- The supporting files are part of the component, not examples. Copy every file listed, preserving the directory layout — they import each other by relative path.
- It owns a GPU/canvas context and releases it on unmount. Preserve the cleanup return — leaking contexts kills the tab after a few navigations.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Wire the component into the place I point you at, with sensible props for that context.
4. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
