# Service explorer

> A live service map that drives the rest of the page: pick a service to see its latency, its slowest request and a CPU flame graph.

A shadcn/ui block from the [@overtrue](https://ui.overtrue.xyz/?utm_source=shadcn.exchange) registry, listed on [shadcn.exchange](https://shadcn.exchange/r/overtrue/service-explorer).

- Page, with a live preview: https://shadcn.exchange/r/overtrue/service-explorer
- Screenshot: https://shadcn.exchange/shot/overtrue/service-explorer/light.png
- Registry item: https://ui.overtrue.xyz/r/service-explorer.json
- Categories: blocks
- Listed: 2026-10-28, source last changed 2026-10-28

## Install

```bash
npx shadcn@latest add https://shadcn.exchange/r/overtrue/service-explorer.json
```

Run it in a project that has shadcn/ui set up. It adds the files below and installs what they depend on.

## Dependencies

- npm packages: `@tabler/icons-react`

## Notes from the registry

Documentation: https://ui.overtrue.xyz/blocks/service-explorer. Requires an initialized shadcn/ui project with Tailwind CSS v4.

## Files

### `src/registry/overtrue/service-explorer.tsx`

```tsx
"use client";

import * as React from "react";
import { IconPointer } from "@tabler/icons-react";

import { cn } from "@/lib/utils";
import {
  ServiceMap,
  type ServiceMapEdge,
  type ServiceMapNode,
} from "./service-map";
import { FlameGraph, type FlameNode } from "./flame-graph";
import { LatencyHistogram } from "./latency-histogram";
import { JsonViewer } from "./json-viewer";

export interface ExploredService {
  /** Request latencies in milliseconds for the window. */
  latency: number[];
  /** Objective drawn on the histogram, in milliseconds. */
  threshold?: number;
  /** A sampled CPU profile for the service. */
  profile: FlameNode;
  /** The slowest request in the window, shown as JSON. */
  slowest?: unknown;
}

export interface ServiceExplorerData {
  title: string;
  /** Context under the title, e.g. "Production · last 5 minutes". */
  description?: string;
  nodes: ServiceMapNode[];
  edges: ServiceMapEdge[];
  /** Detail per service id. Nodes without an entry can be selected but show a hint. */
  services: Record<string, ExploredService>;
}

export interface ServiceExplorerProps
  extends Omit<React.ComponentProps<"section">, "title" | "onSelect"> {
  data: ServiceExplorerData;
  /** Controlled selection. */
  selectedId?: string | null;
  defaultSelectedId?: string | null;
  onSelect?: (id: string | null) => void;
  actions?: React.ReactNode;
}

/** Pick a service on the live map to see its latency, its slowest request and a CPU profile. */
export function ServiceExplorer({
  data,
  selectedId,
  defaultSelectedId = null,
  onSelect,
  actions,
  className,
  ...props
}: ServiceExplorerProps) {
  const [internal, setInternal] = React.useState<string | null>(
    defaultSelectedId,
  );
  const selected = selectedId !== undefined ? selectedId : internal;
  const select = (id: string | null) => {
    if (selectedId === undefined) setInternal(id);
    onSelect?.(id);
  };
  const node = data.nodes.find((entry) => entry.id === selected) ?? null;
  const detail = selected ? data.services[selected] : undefined;

  return (
    <section
      data-slot="service-explorer"
      aria-label={data.title}
      className={cn(
        "@container/explorer flex min-w-0 flex-col gap-3 text-foreground sm:gap-4",
        className,
      )}
      {...props}
    >
      <header className="flex flex-wrap items-end justify-between gap-3">
        <div className="min-w-0">
          <h2 className="truncate text-base font-semibold tracking-tight">
            {data.title}
          </h2>
          {data.description && (
            <p className="truncate text-xs text-muted-foreground">
              {data.description}
            </p>
          )}
        </div>
        {actions && (
          <div className="flex flex-wrap items-center gap-2">{actions}</div>
        )}
      </header>

      <div className="grid gap-3 sm:gap-4">
        <ServiceMap
          title="Service map"
          description="Select a service to inspect it"
          nodes={data.nodes}
          edges={data.edges}
          selectedId={selected}
          onSelect={(id) => select(id)}
        />

        {node && detail ? (
          <div
            key={node.id}
            data-slot="service-explorer-detail"
            className="grid gap-3 sm:gap-4"
          >
            <div className="grid gap-3 sm:gap-4 @4xl/explorer:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]">
              <LatencyHistogram
                title="Latency"
                description={`Every ${node.label} request in the window`}
                values={detail.latency}
                threshold={detail.threshold}
                thresholdLabel="SLO"
              />
              {detail.slowest !== undefined && (
                <JsonViewer
                  title="Slowest request"
                  description="Span attributes and timings"
                  data={detail.slowest}
                  rootName="span"
                  defaultExpandDepth={1}
                  maxHeight={360}
                />
              )}
            </div>
            <FlameGraph
              title="CPU profile"
              description={`Sampled from ${node.label} during the window`}
              data={detail.profile}
              showTopFunctions={5}
              height={320}
            />
          </div>
        ) : (
          <div
            data-slot="service-explorer-empty"
            className="flex flex-col items-center gap-2 rounded-2xl border border-dashed border-border/80 px-6 py-10 text-center"
          >
            <span className="grid size-10 place-items-center rounded-xl bg-muted/60 text-muted-foreground">
              <IconPointer aria-hidden="true" className="size-5" />
            </span>
            <p className="text-sm font-medium">
              {node
                ? `No profile for ${node.label}`
                : "Select a service on the map"}
            </p>
            <p className="max-w-sm text-[13px] text-muted-foreground">
              {node
                ? "Clients, data stores and external providers have no CPU profile here. Select one of the services."
                : "Its latency, its slowest request and a CPU profile appear here."}
            </p>
          </div>
        )}
      </div>
    </section>
  );
}

/* Sample data --------------------------------------------------------------- */

function random(seed: number) {
  return () => {
    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;
  };
}
function logNormal(count: number, median: number, spread: number, seed: number) {
  const next = random(seed);
  return Array.from({ length: count }, () => {
    const u = Math.max(next(), 1e-9);
    const v = next();
    const z = Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
    return Math.round(median * Math.exp(spread * z) * 10) / 10;
  });
}
/** A frame with children; the value includes the frame's own self time. */
const f = (name: string, self: number, ...children: FlameNode[]): FlameNode => ({
  name,
  value: self + children.reduce((sum, child) => sum + child.value, 0),
  ...(children.length ? { children } : {}),
});
const http = (...children: FlameNode[]) =>
  f("node.main", 4, f("http.Server.emit", 6, f("router.handle", 8, f("middleware.auth", 14, f("jwt.verify", 22)), ...children)));

const checkoutProfile = http(
  f("checkout.submit", 18,
    f("cart.load", 12, f("db.query", 64, f("pg.Client.query", 21)), f("cart.normalize", 18)),
    f("pricing.quote", 26, f("promotions.match", 44, f("db.query", 120, f("pg.Client.query", 38))), f("tax.calculate", 31)),
    f("payments.authorize", 9, f("http.request", 182, f("tls.handshake", 26), f("JSON.parse", 14))),
    f("orders.create", 15, f("db.transaction", 36, f("pg.Client.query", 22)), f("kafka.produce", 17)),
  ),
  f("render.response", 8, f("JSON.stringify", 46), f("zlib.gzip", 28)),
);
const paymentsProfile = http(
  f("payments.authorize", 22,
    f("fraud.score", 38, f("features.load", 41, f("db.query", 58)), f("model.predict", 92)),
    f("provider.authorize", 14, f("http.request", 296, f("tls.handshake", 31), f("JSON.parse", 12)), f("retry.backoff", 64)),
    f("ledger.write", 11, f("db.transaction", 44, f("pg.Client.query", 27))),
  ),
  f("render.response", 6, f("JSON.stringify", 12)),
);
const catalogProfile = http(
  f("catalog.list", 12,
    f("cache.get", 9, f("redis.GET", 14)),
    f("db.query", 52, f("pg.Client.query", 26)),
    f("products.hydrate", 34, f("images.sign", 41), f("prices.attach", 22)),
  ),
  f("render.response", 6, f("JSON.stringify", 58), f("zlib.gzip", 31)),
);
const searchProfile = http(
  f("search.query", 16,
    f("query.parse", 18),
    f("index.lookup", 24, f("bm25.score", 66), f("vector.knn", 88)),
    f("results.rerank", 14, f("model.predict", 47)),
    f("catalog.fetch", 9, f("http.request", 42)),
  ),
  f("render.response", 5, f("JSON.stringify", 21)),
);
const cartProfile = http(
  f("cart.update", 10, f("cache.get", 7, f("redis.GET", 9)), f("cart.normalize", 14), f("cache.set", 6, f("redis.SET", 8))),
  f("render.response", 4, f("JSON.stringify", 9)),
);
const authProfile = http(
  f("session.verify", 8, f("cache.get", 5, f("redis.GET", 6)), f("crypto.verify", 31)),
  f("render.response", 3, f("JSON.stringify", 4)),
);
const gatewayProfile = f("node.main", 4,
  f("proxy.handle", 12, f("ratelimit.check", 9, f("redis.INCR", 7)), f("route.match", 14), f("upstream.request", 21, f("http.request", 38), f("tls.handshake", 12))),
  f("access.log", 6, f("JSON.stringify", 8)),
);

const slowest = (service: string, route: string, duration: number, extra: Record<string, unknown>) => ({
  traceId: "4bf92f3577b34da6a3ce929d0e0e4736",
  spanId: "00f067aa0ba902b7",
  service,
  name: route,
  startTime: "2026-10-14T14:05:12.284Z",
  durationMs: duration,
  status: { code: duration > 400 ? "error" : "ok", message: duration > 400 ? "deadline exceeded" : null },
  attributes: {
    "http.method": route.split(" ")[0],
    "http.route": route.split(" ")[1],
    "http.status_code": duration > 400 ? 504 : 200,
    "net.peer.ip": "10.4.18.231",
    ...extra,
  },
});

/** A fictional checkout platform with profiles for its services, for demos and tests. */
export const sampleServiceExplorer: ServiceExplorerData = {
  title: "Service explorer",
  description: "Acme Shop checkout platform · production · last 5 minutes",
  nodes: [
    { id: "web", label: "Web", kind: "client", metrics: { rps: 1840, errorRate: 0.002, p95: 182 } },
    { id: "mobile", label: "Mobile", kind: "client", metrics: { rps: 1260, errorRate: 0.003, p95: 214 } },
    { id: "gateway", label: "API gateway", kind: "gateway", group: "edge", metrics: { rps: 3100, errorRate: 0.004, p95: 96 } },
    { id: "auth", label: "Auth", kind: "service", group: "identity", metrics: { rps: 2980, errorRate: 0.001, p95: 12 } },
    { id: "search", label: "Search", kind: "service", group: "discovery", metrics: { rps: 860, errorRate: 0.006, p95: 74 } },
    { id: "catalog", label: "Catalog", kind: "service", group: "discovery", metrics: { rps: 1840, errorRate: 0.002, p95: 38 } },
    { id: "cart", label: "Cart", kind: "service", group: "commerce", metrics: { rps: 610, errorRate: 0.003, p95: 28 } },
    { id: "checkout", label: "Checkout", kind: "service", group: "commerce", metrics: { rps: 124, errorRate: 0.004, p95: 220 } },
    { id: "payments", label: "Payments", kind: "service", group: "commerce", status: "degraded", metrics: { rps: 118, errorRate: 0.012, p95: 340 } },
    { id: "postgres", label: "Postgres", kind: "database", group: "data", metrics: { rps: 1650, errorRate: 0, p95: 6.4 } },
    { id: "redis", label: "Redis", kind: "cache", group: "data", metrics: { rps: 5440, errorRate: 0, p95: 0.8 } },
    { id: "kafka", label: "Kafka", kind: "queue", group: "data", metrics: { rps: 116, errorRate: 0, p95: 3.1 } },
    { id: "payrail", label: "PayRail", kind: "external", metrics: { rps: 116, errorRate: 0.018, p95: 410 } },
  ],
  edges: [
    { source: "web", target: "gateway", rps: 1840, errorRate: 0.002, p95: 182 },
    { source: "mobile", target: "gateway", rps: 1260, errorRate: 0.003, p95: 214 },
    { source: "gateway", target: "auth", rps: 2980, errorRate: 0.001, p95: 12 },
    { source: "gateway", target: "search", rps: 860, errorRate: 0.006, p95: 74 },
    { source: "gateway", target: "catalog", rps: 1420, errorRate: 0.002, p95: 38 },
    { source: "gateway", target: "cart", rps: 490, errorRate: 0.003, p95: 28 },
    { source: "gateway", target: "checkout", rps: 124, errorRate: 0.004, p95: 220 },
    { source: "search", target: "catalog", rps: 420, errorRate: 0.002, p95: 22 },
    { source: "auth", target: "redis", rps: 2980, errorRate: 0, p95: 0.8 },
    { source: "catalog", target: "postgres", rps: 1180, errorRate: 0, p95: 6.2 },
    { source: "catalog", target: "redis", rps: 1640, errorRate: 0, p95: 0.7 },
    { source: "cart", target: "redis", rps: 820, errorRate: 0, p95: 0.6 },
    { source: "checkout", target: "cart", rps: 120, errorRate: 0.002, p95: 18 },
    { source: "checkout", target: "payments", rps: 118, errorRate: 0.012, p95: 340 },
    { source: "checkout", target: "kafka", rps: 116, errorRate: 0, p95: 3.1 },
    { source: "checkout", target: "postgres", rps: 240, errorRate: 0.001, p95: 7.8 },
    { source: "payments", target: "payrail", rps: 116, errorRate: 0.018, p95: 410 },
    { source: "payments", target: "postgres", rps: 230, errorRate: 0, p95: 5.4 },
  ],
  services: {
    gateway: {
      latency: logNormal(2400, 44, 0.55, 3),
      threshold: 150,
      profile: gatewayProfile,
      slowest: slowest("api-gateway", "POST /api/checkout", 248, { "upstream.service": "checkout", "ratelimit.remaining": 412 }),
    },
    auth: {
      latency: logNormal(2400, 5, 0.6, 5),
      threshold: 25,
      profile: authProfile,
      slowest: slowest("auth", "GET /session", 31, { "session.cache": "miss", "jwt.alg": "EdDSA" }),
    },
    search: {
      latency: logNormal(2000, 33, 0.58, 7),
      threshold: 120,
      profile: searchProfile,
      slowest: slowest("search", "GET /search", 186, { "search.query": "linen throw blanket", "search.results": 48, "rerank.model": "rerank-v2" }),
    },
    catalog: {
      latency: logNormal(2400, 16, 0.55, 9),
      threshold: 80,
      profile: catalogProfile,
      slowest: slowest("catalog", "GET /products", 112, { "cache.hit": false, "db.rows": 240, "images.signed": 240 }),
    },
    cart: {
      latency: logNormal(2000, 12, 0.5, 11),
      threshold: 60,
      profile: cartProfile,
      slowest: slowest("cart", "PATCH /cart", 64, { "cart.items": 14, "cache.hit": true }),
    },
    checkout: {
      latency: [...logNormal(1800, 96, 0.5, 13), ...logNormal(300, 320, 0.3, 17)],
      threshold: 400,
      profile: checkoutProfile,
      slowest: slowest("checkout", "POST /api/checkout", 1243, {
        "cart.items": 14,
        "db.queries": 15,
        "payment.provider": "payrail",
        "order.id": "ord_8F3k2Lq",
        timings: { cart: 84, pricing: 962, payments: 118, orders: 61 },
      }),
    },
    payments: {
      latency: [...logNormal(1600, 150, 0.45, 19), ...logNormal(400, 520, 0.3, 23)],
      threshold: 500,
      profile: paymentsProfile,
      slowest: slowest("payments", "POST /authorize", 1980, {
        "payment.provider": "payrail",
        "provider.attempts": 3,
        "provider.status": 504,
        "fraud.score": 0.08,
        retries: [
          { attempt: 1, status: 504, durationMs: 640 },
          { attempt: 2, status: 504, durationMs: 610 },
          { attempt: 3, status: 200, durationMs: 412 },
        ],
      }),
    },
  },
};
```

### `src/registry/overtrue/service-map.tsx`

```tsx
"use client";

import * as React from "react";
import {
  IconBolt,
  IconCloud,
  IconDatabase,
  IconRoute,
  IconServer,
  IconStack2,
  IconWorld,
  IconX,
} from "@tabler/icons-react";

import { cn } from "@/lib/utils";

/* ------------------------------------------------------------------------ */
/* Types                                                                     */
/* ------------------------------------------------------------------------ */

export type ServiceKind =
  | "client"
  | "gateway"
  | "service"
  | "database"
  | "cache"
  | "queue"
  | "external";

export type ServiceStatus = "healthy" | "degraded" | "down";

export interface ServiceMetrics {
  /** Requests per second. */
  rps?: number;
  /** Share of failed requests as a 0–1 fraction, e.g. 0.012 for 1.2%. */
  errorRate?: number;
  /** 95th percentile latency in milliseconds. */
  p95?: number;
}

export interface ServiceMapNode {
  id: string;
  label: string;
  kind?: ServiceKind;
  /** Health. Defaults to healthy, or degraded when the error rate crosses the critical threshold. */
  status?: ServiceStatus;
  metrics?: ServiceMetrics;
  /** Team, namespace or region. Shown in the detail readout. */
  group?: string;
  /** Replaces the icon picked from `kind`. */
  icon?: React.ReactNode;
}

export interface ServiceMapEdge {
  id?: string;
  /** Id of the calling node. */
  source: string;
  /** Id of the called node. */
  target: string;
  rps?: number;
  /** Share of failed calls as a 0–1 fraction. */
  errorRate?: number;
  /** 95th percentile latency in milliseconds. */
  p95?: number;
  /** Overrides the color picked from the error rate. */
  status?: ServiceStatus;
}

export interface ServiceMapThresholds {
  /** Error rate, as a 0–1 fraction, at which traffic turns amber. Defaults to 0.01. */
  warn?: number;
  /** Error rate at which traffic turns destructive. Defaults to 0.05. */
  critical?: number;
}

/** Everything known about a node, passed to `renderNode`. */
export interface ServiceMapNodeInfo {
  kind: ServiceKind;
  status: ServiceStatus;
  /** Column (or row, top to bottom) the node was placed in, from 0. */
  layer: number;
  inbound: ServiceMapEdge[];
  outbound: ServiceMapEdge[];
  /** Hovered or focused. */
  active: boolean;
  selected: boolean;
  /** Outside the paths of the hovered, focused or selected node. */
  dimmed: boolean;
  /** Metrics run through the formatters; missing metrics are undefined. */
  formatted: { rps?: string; errorRate?: string; p95?: string };
  /** The default icon for the node's kind, or its own `icon`. */
  icon: React.ReactNode;
}

export interface ServiceMapProps extends Omit<
  React.ComponentProps<"div">,
  "title" | "onSelect" | "children"
> {
  nodes: ServiceMapNode[];
  edges: ServiceMapEdge[];
  /** Flow left to right or top to bottom. Defaults to LR. */
  direction?: "LR" | "TB";
  /** Controlled selection. Pass null for none. */
  selectedId?: string | null;
  defaultSelectedId?: string | null;
  onSelect?: (id: string | null, node: ServiceMapNode | null) => void;
  /** Replaces the content of every node card. The card keeps its size, focus and status ring. */
  renderNode?: (node: ServiceMapNode, info: ServiceMapNodeInfo) => React.ReactNode;
  thresholds?: ServiceMapThresholds;
  rpsFormatter?: (rps: number) => string;
  latencyFormatter?: (ms: number) => string;
  errorRateFormatter?: (rate: number) => string;
  title?: React.ReactNode;
  description?: React.ReactNode;
  /** Controls placed at the top right. */
  actions?: React.ReactNode;
  /** Show the traffic legend. Defaults to true. */
  showLegend?: boolean;
  /** Animate traffic along the edges. Defaults to true; reduced motion shows static dashes. */
  animate?: boolean;
  /** Card size in pixels before scaling. Defaults to 148 × 60. */
  nodeWidth?: number;
  nodeHeight?: number;
  /** Smallest scale used to fit the container; below it the map scrolls sideways. Defaults to 0.5. */
  minScale?: number;
  /**
   * Full cards with a metrics line, or compact icon tiles with a label. "auto" switches
   * to compact when cards would have to shrink below a readable size. Defaults to auto.
   */
  density?: "auto" | "comfortable" | "compact";
}

/* ------------------------------------------------------------------------ */
/* Formatting                                                                */
/* ------------------------------------------------------------------------ */

function formatRps(rps: number) {
  if (!Number.isFinite(rps)) return "—";
  if (rps >= 1_000_000) return `${+(rps / 1_000_000).toFixed(1)}M rps`;
  if (rps >= 1000) return `${+(rps / 1000).toFixed(rps >= 10_000 ? 0 : 1)}k rps`;
  if (rps >= 10) return `${Math.round(rps)} rps`;
  return `${+rps.toFixed(1)} rps`;
}

function formatErrorRate(rate: number) {
  if (!Number.isFinite(rate)) return "—";
  const pct = rate * 100;
  if (pct === 0) return "0%";
  if (pct < 0.1) return `${+pct.toFixed(2)}%`;
  if (pct < 10) return `${+pct.toFixed(1)}%`;
  return `${Math.round(pct)}%`;
}

function formatLatency(ms: number) {
  if (!Number.isFinite(ms)) return "—";
  if (ms < 10) return `${+ms.toFixed(1)} ms`;
  if (ms < 1000) return `${Math.round(ms)} ms`;
  return `${+(ms / 1000).toFixed(ms < 10_000 ? 2 : 1)} s`;
}

/* ------------------------------------------------------------------------ */
/* Layout                                                                    */
/* ------------------------------------------------------------------------ */

interface Item {
  id: string;
  layer: number;
  /** Center on the cross axis, in world pixels. */
  pos: number;
  size: number;
  dummy: boolean;
  /** Index in `nodes`, used to break ties so the layout follows data order. */
  rank: number;
  node?: ServiceMapNode;
}

interface Route {
  key: string;
  edge: ServiceMapEdge;
  index: number;
  /** Item ids from the source to the target in layer order (target first for back edges). */
  chain: string[];
  reversed: boolean;
}

interface Structure {
  layers: Item[][];
  items: Map<string, Item>;
  routes: Route[];
  layerOf: Map<string, number>;
  /** Extent on the cross axis, center to center plus the node size. */
  span: number;
}

interface Point {
  x: number;
  y: number;
}

interface PlacedEdge {
  key: string;
  edge: ServiceMapEdge;
  index: number;
  d: string;
  length: number;
  mid: Point;
  start: Point;
  end: Point;
}

const NODE_GAP = 18;
const DUMMY_GAP = 12;
const PAD = 22;
const GAP_MIN = 28;
const GAP_MAX = 136;
const GAP_TB = 64;
const FALLBACK_WIDTH = 720;
const COMPACT_W = 76;
const COMPACT_TILE = 36;
const COMPACT_H = 56;
const COMPACT_PAD = 16;
const COMPACT_GAP_MIN = 10;
const COMPACT_GAP_TB = 40;
/** Below this scale, "auto" density switches cards to compact tiles. */
const AUTO_COMPACT_BELOW = 0.62;

/** Pool adjacent violators: positions as close to `desired` as the separations allow, order kept. */
function project(desired: number[], separation: number[]) {
  const n = desired.length;
  const offset = new Array<number>(n).fill(0);
  for (let i = 1; i < n; i++) offset[i] = offset[i - 1] + separation[i - 1];
  const blocks: { sum: number; count: number; start: number }[] = [];
  for (let i = 0; i < n; i++) {
    blocks.push({ sum: desired[i] - offset[i], count: 1, start: i });
    while (blocks.length > 1) {
      const b = blocks[blocks.length - 1];
      const a = blocks[blocks.length - 2];
      if (a.sum / a.count <= b.sum / b.count) break;
      a.sum += b.sum;
      a.count += b.count;
      blocks.pop();
    }
  }
  const out = new Array<number>(n);
  blocks.forEach((block, i) => {
    const end = i + 1 < blocks.length ? blocks[i + 1].start : n;
    for (let j = block.start; j < end; j++)
      out[j] = block.sum / block.count + offset[j];
  });
  return out;
}

function buildStructure(
  nodes: ServiceMapNode[],
  edges: ServiceMapEdge[],
  crossSize: number,
  nodeGap = NODE_GAP,
): Structure {
  const known = new Map(nodes.map((node, i) => [node.id, i]));
  const valid = edges
    .map((edge, index) => ({ edge, index }))
    .filter(
      ({ edge }) =>
        known.has(edge.source) &&
        known.has(edge.target) &&
        edge.source !== edge.target,
    );

  // Break cycles: edges that close a loop in a depth-first walk are laid out reversed.
  const out = new Map<string, number[]>();
  const indegree = new Map<string, number>(nodes.map((n) => [n.id, 0]));
  valid.forEach(({ edge }, i) => {
    if (!out.has(edge.source)) out.set(edge.source, []);
    out.get(edge.source)!.push(i);
    indegree.set(edge.target, (indegree.get(edge.target) ?? 0) + 1);
  });
  const state = new Map<string, 1 | 2>();
  const reversed = new Set<number>();
  const walk = (id: string) => {
    state.set(id, 1);
    for (const i of out.get(id) ?? []) {
      const target = valid[i].edge.target;
      const seen = state.get(target);
      if (seen === 1) reversed.add(i);
      else if (!seen) walk(target);
    }
    state.set(id, 2);
  };
  const starts = [
    ...nodes.filter((n) => indegree.get(n.id) === 0),
    ...nodes.filter((n) => indegree.get(n.id) !== 0),
  ];
  for (const node of starts) if (!state.has(node.id)) walk(node.id);

  // Layer by the longest path from the sources.
  const dag = valid.map(({ edge }, i) =>
    reversed.has(i)
      ? { from: edge.target, to: edge.source }
      : { from: edge.source, to: edge.target },
  );
  const succ = new Map<string, string[]>();
  const pending = new Map<string, number>(nodes.map((n) => [n.id, 0]));
  for (const { from, to } of dag) {
    if (!succ.has(from)) succ.set(from, []);
    succ.get(from)!.push(to);
    pending.set(to, (pending.get(to) ?? 0) + 1);
  }
  const layerOf = new Map<string, number>(nodes.map((n) => [n.id, 0]));
  const queue = nodes.filter((n) => pending.get(n.id) === 0).map((n) => n.id);
  while (queue.length) {
    const id = queue.shift()!;
    for (const next of succ.get(id) ?? []) {
      layerOf.set(next, Math.max(layerOf.get(next)!, layerOf.get(id)! + 1));
      pending.set(next, pending.get(next)! - 1);
      if (pending.get(next) === 0) queue.push(next);
    }
  }

  // Items: one per node, plus a dummy wherever an edge crosses a layer.
  const items = new Map<string, Item>();
  nodes.forEach((node, rank) =>
    items.set(node.id, {
      id: node.id,
      layer: layerOf.get(node.id) ?? 0,
      pos: 0,
      size: crossSize,
      dummy: false,
      rank,
      node,
    }),
  );
  const routes: Route[] = [];
  const up = new Map<string, string[]>();
  const down = new Map<string, string[]>();
  const link = (a: string, b: string) => {
    if (!down.has(a)) down.set(a, []);
    if (!up.has(b)) up.set(b, []);
    down.get(a)!.push(b);
    up.get(b)!.push(a);
  };
  valid.forEach(({ edge, index }, i) => {
    const { from, to } = dag[i];
    const a = layerOf.get(from)!;
    const b = layerOf.get(to)!;
    const key = edge.id ?? `${edge.source}->${edge.target}#${index}`;
    const chain = [from];
    for (let layer = a + 1; layer < b; layer++) {
      const id = `\u0000${key}\u0000${layer}`;
      items.set(id, {
        id,
        layer,
        pos: 0,
        size: 0,
        dummy: true,
        rank: items.get(from)!.rank + 0.5,
      });
      chain.push(id);
    }
    chain.push(to);
    for (let j = 1; j < chain.length; j++) link(chain[j - 1], chain[j]);
    routes.push({ key, edge, index, chain, reversed: reversed.has(i) });
  });

  const count = Math.max(0, ...[...items.values()].map((item) => item.layer)) + 1;
  const layers: Item[][] = Array.from({ length: count }, () => []);
  for (const item of items.values()) layers[item.layer].push(item);
  for (const layer of layers) layer.sort((a, b) => a.rank - b.rank);

  // Order within layers: barycenter sweeps, keeping the arrangement with fewest crossings.
  const index = new Map<string, number>();
  const reindex = () =>
    layers.forEach((layer) => layer.forEach((item, i) => index.set(item.id, i)));
  const crossings = () => {
    let total = 0;
    for (let l = 0; l + 1 < layers.length; l++) {
      const segments: [number, number][] = [];
      for (const item of layers[l])
        for (const next of down.get(item.id) ?? [])
          segments.push([index.get(item.id)!, index.get(next)!]);
      for (let i = 0; i < segments.length; i++)
        for (let j = i + 1; j < segments.length; j++) {
          const [a1, b1] = segments[i];
          const [a2, b2] = segments[j];
          if ((a1 - a2) * (b1 - b2) < 0) total++;
        }
    }
    return total;
  };
  reindex();
  let best = layers.map((layer) => [...layer]);
  let bestCrossings = crossings();
  for (let sweep = 0; sweep < 12 && bestCrossings > 0; sweep++) {
    const downward = sweep % 2 === 0;
    const order = downward
      ? layers.map((_, i) => i).slice(1)
      : layers.map((_, i) => i).slice(0, -1).reverse();
    for (const l of order) {
      const neighbors = downward ? up : down;
      const weight = new Map<string, number>();
      layers[l].forEach((item, i) => {
        const list = neighbors.get(item.id) ?? [];
        weight.set(
          item.id,
          list.length
            ? list.reduce((sum, id) => sum + index.get(id)!, 0) / list.length
            : i,
        );
      });
      layers[l].sort(
        (a, b) => weight.get(a.id)! - weight.get(b.id)! || a.rank - b.rank,
      );
      layers[l].forEach((item, i) => index.set(item.id, i));
    }
    const score = crossings();
    if (score < bestCrossings) {
      bestCrossings = score;
      best = layers.map((layer) => [...layer]);
    }
  }
  best.forEach((layer, l) => (layers[l] = layer));
  reindex();

  // Cross-axis positions: pull each item toward its neighbors, keeping order and spacing.
  const gapBetween = (a: Item, b: Item) =>
    (a.size + b.size) / 2 +
    (a.dummy && b.dummy ? DUMMY_GAP : a.dummy || b.dummy ? DUMMY_GAP + 4 : nodeGap);
  for (const layer of layers) {
    let cursor = 0;
    layer.forEach((item, i) => {
      if (i > 0) cursor += gapBetween(layer[i - 1], item);
      item.pos = cursor;
    });
    const mid = cursor / 2;
    for (const item of layer) item.pos -= mid;
  }
  const center = (id: string) => items.get(id)!.pos;
  for (let pass = 0; pass < 24; pass++) {
    const downward = pass % 2 === 0;
    const order = downward
      ? layers.map((_, i) => i)
      : layers.map((_, i) => i).reverse();
    for (const l of order) {
      const layer = layers[l];
      if (!layer.length) continue;
      const desired = layer.map((item) => {
        const near = [...(up.get(item.id) ?? []), ...(down.get(item.id) ?? [])];
        if (!near.length) return item.pos;
        return near.reduce((sum, id) => sum + center(id), 0) / near.length;
      });
      const separation = layer
        .slice(1)
        .map((item, i) => gapBetween(layer[i], item));
      const placed = project(desired, separation);
      layer.forEach((item, i) => (item.pos = placed[i]));
    }
  }
  let min = Infinity;
  let max = -Infinity;
  for (const item of items.values()) {
    min = Math.min(min, item.pos - item.size / 2);
    max = Math.max(max, item.pos + item.size / 2);
  }
  if (!Number.isFinite(min)) {
    min = 0;
    max = 0;
  }
  for (const item of items.values()) item.pos -= min;
  return { layers, items, routes, layerOf, span: max - min };
}

function cubic(a: Point, b: Point, horizontal: boolean, sag = 0) {
  if (horizontal) {
    const dx = (b.x - a.x) / 2;
    return {
      c1: { x: a.x + dx, y: a.y + sag },
      c2: { x: b.x - dx, y: b.y + sag },
    };
  }
  const dy = (b.y - a.y) / 2;
  return {
    c1: { x: a.x + sag, y: a.y + dy },
    c2: { x: b.x + sag, y: b.y - dy },
  };
}

function bezierAt(a: Point, c1: Point, c2: Point, b: Point, t: number): Point {
  const u = 1 - t;
  return {
    x: u * u * u * a.x + 3 * u * u * t * c1.x + 3 * u * t * t * c2.x + t * t * t * b.x,
    y: u * u * u * a.y + 3 * u * u * t * c1.y + 3 * u * t * t * c2.y + t * t * t * b.y,
  };
}

const r1 = (n: number) => Math.round(n * 10) / 10;

/* ------------------------------------------------------------------------ */
/* Visual vocabulary                                                         */
/* ------------------------------------------------------------------------ */

const kindIcon: Record<ServiceKind, React.ComponentType<{ size?: number; stroke?: number; className?: string; "aria-hidden"?: boolean | "true" }>> = {
  client: IconWorld,
  gateway: IconRoute,
  service: IconServer,
  database: IconDatabase,
  cache: IconBolt,
  queue: IconStack2,
  external: IconCloud,
};

const kindLabel: Record<ServiceKind, string> = {
  client: "client",
  gateway: "gateway",
  service: "service",
  database: "database",
  cache: "cache",
  queue: "queue",
  external: "external service",
};

const statusLabel: Record<ServiceStatus, string> = {
  healthy: "Healthy",
  degraded: "Degraded",
  down: "Down",
};

const statusDot: Record<ServiceStatus, string> = {
  healthy: "bg-emerald-500",
  degraded: "bg-amber-500",
  down: "bg-destructive",
};

const statusPill: Record<ServiceStatus, string> = {
  healthy: "bg-emerald-500/10 text-emerald-700 dark:text-emerald-400",
  degraded: "bg-amber-500/10 text-amber-700 dark:text-amber-400",
  down: "bg-destructive/10 text-destructive",
};

type Severity = "ok" | "warn" | "critical";

const severityStroke: Record<Severity, string> = {
  ok: "var(--sm-ok)",
  warn: "var(--sm-warn)",
  critical: "var(--sm-critical)",
};
const severityFlow: Record<Severity, string> = {
  ok: "var(--sm-flow)",
  warn: "var(--sm-warn)",
  critical: "var(--sm-critical)",
};

const useIsomorphicLayoutEffect =
  typeof window === "undefined" ? React.useEffect : React.useLayoutEffect;

function useReducedMotion() {
  return React.useSyncExternalStore(
    (onChange) => {
      const query = window.matchMedia("(prefers-reduced-motion: reduce)");
      query.addEventListener("change", onChange);
      return () => query.removeEventListener("change", onChange);
    },
    () => window.matchMedia("(prefers-reduced-motion: reduce)").matches,
    () => false,
  );
}

function StatusDot({ status, className }: { status: ServiceStatus; className?: string }) {
  return (
    <span
      aria-hidden="true"
      data-status={status}
      className={cn("relative inline-flex size-2 shrink-0 rounded-full", statusDot[status], className)}
    >
      {status !== "healthy" ? (
        <span
          className={cn(
            "absolute inset-0 rounded-full opacity-60 motion-safe:animate-[service-map-ping_1.8s_cubic-bezier(0,0,0.2,1)_infinite]",
            statusDot[status],
          )}
        />
      ) : null}
    </span>
  );
}

/* ------------------------------------------------------------------------ */
/* Component                                                                 */
/* ------------------------------------------------------------------------ */

/**
 * A live service dependency map. Nodes are laid out as a layered graph, left to
 * right by default; edges carry animated traffic whose width follows request rate
 * and whose color follows error rate. Hover or focus a node to trace its upstream
 * and downstream paths; select it to list its inbound and outbound traffic.
 */
function ServiceMap({
  nodes,
  edges,
  direction = "LR",
  selectedId: selectedProp,
  defaultSelectedId = null,
  onSelect,
  renderNode,
  thresholds,
  rpsFormatter = formatRps,
  latencyFormatter = formatLatency,
  errorRateFormatter = formatErrorRate,
  title,
  description,
  actions,
  showLegend = true,
  animate = true,
  nodeWidth = 148,
  nodeHeight = 60,
  minScale = 0.5,
  density = "auto",
  className,
  onKeyDown,
  ...props
}: ServiceMapProps) {
  const id = React.useId();
  const reduced = useReducedMotion();
  const viewportRef = React.useRef<HTMLDivElement>(null);
  const [available, setAvailable] = React.useState(0);
  const [hoveredId, setHoveredId] = React.useState<string | null>(null);
  const [focusedId, setFocusedId] = React.useState<string | null>(null);
  const [hoveredEdge, setHoveredEdge] = React.useState<string | null>(null);
  const [innerSelected, setInnerSelected] = React.useState<string | null>(
    defaultSelectedId,
  );
  const [revealed, setRevealed] = React.useState(false);
  const selectedId = selectedProp !== undefined ? selectedProp : innerSelected;

  const warn = thresholds?.warn ?? 0.01;
  const critical = thresholds?.critical ?? 0.05;
  const horizontal = direction === "LR";

  const byId = React.useMemo(
    () => new Map(nodes.map((node) => [node.id, node])),
    [nodes],
  );
  const selectedNode = selectedId ? (byId.get(selectedId) ?? null) : null;

  const select = (next: string | null) => {
    if (selectedProp === undefined) setInnerSelected(next);
    onSelect?.(next, next ? (byId.get(next) ?? null) : null);
  };

  const statusOf = React.useCallback(
    (node: ServiceMapNode): ServiceStatus =>
      node.status ??
      ((node.metrics?.errorRate ?? 0) >= critical ? "degraded" : "healthy"),
    [critical],
  );
  const severityOf = (edge: ServiceMapEdge): Severity => {
    if (edge.status === "down") return "critical";
    if (edge.status === "degraded") return "warn";
    if (edge.status === "healthy") return "ok";
    const rate = edge.errorRate ?? 0;
    if (rate >= critical) return "critical";
    if (rate >= warn) return "warn";
    return "ok";
  };

  /* ---------------------------------------------------------- layout */

  const width = available || FALLBACK_WIDTH;
  const comfortable = React.useMemo(
    () => buildStructure(nodes, edges, horizontal ? nodeHeight : nodeWidth),
    [nodes, edges, horizontal, nodeWidth, nodeHeight],
  );
  // Cards when they fit at a readable scale; icon tiles with labels otherwise.
  const comfortableWidth = horizontal
    ? comfortable.layers.length * nodeWidth +
      Math.max(0, comfortable.layers.length - 1) * GAP_MIN +
      PAD * 2
    : comfortable.span + PAD * 2;
  const compact =
    density === "compact" ||
    (density === "auto" && width / comfortableWidth < AUTO_COMPACT_BELOW);
  const compactStructure = React.useMemo(
    () =>
      compact
        ? buildStructure(
            nodes,
            edges,
            horizontal ? COMPACT_H : COMPACT_W,
            horizontal ? 8 : 12,
          )
        : null,
    [compact, nodes, edges, horizontal],
  );
  const structure = compactStructure ?? comfortable;
  const cardW = compact ? COMPACT_W : nodeWidth;
  const cardH = compact ? COMPACT_H : nodeHeight;
  const pad = compact ? COMPACT_PAD : PAD;
  const mainSize = horizontal ? cardW : cardH;
  const crossSize = horizontal ? cardH : cardW;
  // Edges meet the icon tile in compact mode, not the label under it.
  const portInset = compact && horizontal ? (COMPACT_W - COMPACT_TILE) / 2 : 0;
  const portShift = compact && horizontal ? (COMPACT_TILE - COMPACT_H) / 2 : 0;
  const portSpan = compact ? COMPACT_TILE : crossSize;
  const layerCount = structure.layers.length;

  const gapMin = horizontal
    ? compact
      ? COMPACT_GAP_MIN
      : GAP_MIN
    : compact
      ? COMPACT_GAP_TB
      : GAP_TB;
  let gap = gapMin;
  if (horizontal && layerCount > 1) {
    const fit = (width - pad * 2 - layerCount * mainSize) / (layerCount - 1);
    gap = Math.min(GAP_MAX, Math.max(gapMin, fit));
  }
  const mainExtent = layerCount * mainSize + Math.max(0, layerCount - 1) * gap;
  const worldW = horizontal ? mainExtent + pad * 2 : structure.span + pad * 2;
  const worldH = horizontal ? structure.span + pad * 2 : mainExtent + pad * 2;
  const scale = Math.max(minScale, Math.min(1, width / worldW));

  const placement = React.useMemo(() => {
    const rects = new Map<string, { x: number; y: number }>();
    const at = (item: Item): Point => {
      const main = pad + item.layer * (mainSize + gap);
      const cross = pad + item.pos;
      return horizontal ? { x: main, y: cross } : { x: cross, y: main };
    };
    for (const item of structure.items.values()) {
      if (item.dummy) continue;
      const p = at(item);
      rects.set(
        item.id,
        horizontal
          ? { x: p.x, y: p.y - cardH / 2 }
          : { x: p.x - cardW / 2, y: p.y },
      );
    }

    // Spread the ports on each side of a node so parallel edges do not merge.
    const ports = new Map<string, number>();
    const sides = new Map<string, { key: string; toward: number }[]>();
    const sideKey = (nodeId: string, side: "in" | "out") => `${nodeId}|${side}`;
    const neighborCross = (route: Route, end: "source" | "target") => {
      const chain = route.reversed ? [...route.chain].reverse() : route.chain;
      const id = end === "source" ? chain[1] : chain[chain.length - 2];
      return structure.items.get(id)!.pos;
    };
    for (const route of structure.routes) {
      const outSide = route.reversed ? "in" : "out";
      const inSide = route.reversed ? "out" : "in";
      const s = sideKey(route.edge.source, outSide);
      const t = sideKey(route.edge.target, inSide);
      if (!sides.has(s)) sides.set(s, []);
      if (!sides.has(t)) sides.set(t, []);
      sides.get(s)!.push({ key: `${route.key}|s`, toward: neighborCross(route, "source") });
      sides.get(t)!.push({ key: `${route.key}|t`, toward: neighborCross(route, "target") });
    }
    for (const list of sides.values()) {
      list.sort((a, b) => a.toward - b.toward);
      const step =
        list.length > 1
          ? Math.min(compact ? 5 : 7, (portSpan - (compact ? 12 : 24)) / (list.length - 1))
          : 0;
      list.forEach((entry, i) =>
        ports.set(entry.key, (i - (list.length - 1) / 2) * step),
      );
    }

    const placed: PlacedEdge[] = [];
    for (const route of structure.routes) {
      const chain = route.reversed ? [...route.chain].reverse() : route.chain;
      const source = structure.items.get(chain[0])!;
      const target = structure.items.get(chain[chain.length - 1])!;
      const forward = !route.reversed;
      const ps = at(source);
      const pt = at(target);
      const so = ports.get(`${route.key}|s`) ?? 0;
      const to = ports.get(`${route.key}|t`) ?? 0;
      const start: Point = horizontal
        ? {
            x: forward ? ps.x + mainSize - portInset : ps.x + portInset,
            y: ps.y + portShift + so,
          }
        : { x: ps.x + so, y: forward ? ps.y + mainSize : ps.y };
      const end: Point = horizontal
        ? {
            x: forward ? pt.x + portInset : pt.x + mainSize - portInset,
            y: pt.y + portShift + to,
          }
        : { x: pt.x + to, y: forward ? pt.y : pt.y + mainSize };
      const waypoints: Point[] = [start];
      for (const id of chain.slice(1, -1)) {
        const p = at(structure.items.get(id)!);
        const enter = forward ? 0 : mainSize;
        const leave = forward ? mainSize : 0;
        waypoints.push(
          horizontal ? { x: p.x + enter, y: p.y } : { x: p.x, y: p.y + enter },
          horizontal ? { x: p.x + leave, y: p.y } : { x: p.x, y: p.y + leave },
        );
      }
      waypoints.push(end);

      let d = `M${r1(start.x)} ${r1(start.y)}`;
      const samples: Point[] = [start];
      for (let i = 1; i < waypoints.length; i++) {
        const a = waypoints[i - 1];
        const b = waypoints[i];
        // Odd segments cross a gap and curve; even ones run straight through a layer.
        if (i % 2 === 1) {
          const sag = !forward && waypoints.length === 2 ? crossSize * 0.75 : 0;
          const { c1, c2 } = cubic(a, b, horizontal, sag);
          d += ` C${r1(c1.x)} ${r1(c1.y)} ${r1(c2.x)} ${r1(c2.y)} ${r1(b.x)} ${r1(b.y)}`;
          for (let s = 1; s <= 16; s++) samples.push(bezierAt(a, c1, c2, b, s / 16));
        } else {
          d += ` L${r1(b.x)} ${r1(b.y)}`;
          samples.push(b);
        }
      }
      let length = 0;
      const cumulative = [0];
      for (let i = 1; i < samples.length; i++) {
        length += Math.hypot(samples[i].x - samples[i - 1].x, samples[i].y - samples[i - 1].y);
        cumulative.push(length);
      }
      const half = length / 2;
      let mid = samples[0];
      for (let i = 1; i < samples.length; i++)
        if (cumulative[i] >= half) {
          const f = (half - cumulative[i - 1]) / (cumulative[i] - cumulative[i - 1] || 1);
          mid = {
            x: samples[i - 1].x + (samples[i].x - samples[i - 1].x) * f,
            y: samples[i - 1].y + (samples[i].y - samples[i - 1].y) * f,
          };
          break;
        }
      placed.push({ key: route.key, edge: route.edge, index: route.index, d, length, mid, start, end });
    }
    return { rects, edges: placed };
  }, [
    structure,
    gap,
    pad,
    horizontal,
    compact,
    mainSize,
    crossSize,
    cardW,
    cardH,
    portInset,
    portShift,
    portSpan,
  ]);

  /* ---------------------------------------------------------- measure */

  useIsomorphicLayoutEffect(() => {
    const element = viewportRef.current;
    if (!element) return;
    const measure = () => setAvailable(element.clientWidth);
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(element);
    return () => observer.disconnect();
  }, []);

  // When the map scrolls sideways, keep the selected service in view.
  useIsomorphicLayoutEffect(() => {
    const viewport = viewportRef.current;
    const rect = selectedId ? placement.rects.get(selectedId) : undefined;
    if (!viewport || !rect || viewport.scrollWidth <= viewport.clientWidth) return;
    const center = (rect.x + cardW / 2) * scale;
    viewport.scrollLeft = Math.max(0, center - viewport.clientWidth / 2);
  }, [selectedId, scale, compact]);

  React.useEffect(() => {
    const timer = window.setTimeout(() => setRevealed(true), 1800);
    return () => window.clearTimeout(timer);
  }, []);

  /* ---------------------------------------------------------- relationships */

  const inbound = React.useMemo(() => {
    const map = new Map<string, ServiceMapEdge[]>();
    for (const edge of edges) {
      if (!map.has(edge.target)) map.set(edge.target, []);
      map.get(edge.target)!.push(edge);
    }
    return map;
  }, [edges]);
  const outbound = React.useMemo(() => {
    const map = new Map<string, ServiceMapEdge[]>();
    for (const edge of edges) {
      if (!map.has(edge.source)) map.set(edge.source, []);
      map.get(edge.source)!.push(edge);
    }
    return map;
  }, [edges]);

  const hoveredPlaced = hoveredEdge
    ? (placement.edges.find((edge) => edge.key === hoveredEdge) ?? null)
    : null;
  const activeId = hoveredId ?? focusedId ?? (hoveredPlaced ? null : selectedId);
  const readoutId = hoveredId ?? focusedId;
  const readoutNode = readoutId ? (byId.get(readoutId) ?? null) : null;

  // Everything upstream and downstream of the active node, edge by edge.
  const lit = React.useMemo(() => {
    if (hoveredPlaced) {
      return {
        nodes: new Set([hoveredPlaced.edge.source, hoveredPlaced.edge.target]),
        edges: new Set([hoveredPlaced.key]),
      };
    }
    if (!activeId || !byId.has(activeId)) return null;
    const litNodes = new Set<string>([activeId]);
    const litEdges = new Set<string>();
    const keyOf = new Map(
      placement.edges.map((placed) => [placed.edge, placed.key]),
    );
    const visit = (start: string, along: "up" | "down") => {
      const stack = [start];
      const seen = new Set([start]);
      while (stack.length) {
        const current = stack.pop()!;
        const list =
          along === "down" ? outbound.get(current) : inbound.get(current);
        for (const edge of list ?? []) {
          const key = keyOf.get(edge);
          if (key) litEdges.add(key);
          const next = along === "down" ? edge.target : edge.source;
          litNodes.add(next);
          if (!seen.has(next)) {
            seen.add(next);
            stack.push(next);
          }
        }
      }
    };
    visit(activeId, "up");
    visit(activeId, "down");
    return { nodes: litNodes, edges: litEdges };
  }, [activeId, hoveredPlaced, byId, inbound, outbound, placement.edges]);

  /* ---------------------------------------------------------- keyboard */

  const tabOrder = React.useMemo(
    () =>
      structure.layers.flatMap((layer) =>
        layer.filter((item) => !item.dummy).map((item) => item.id),
      ),
    [structure],
  );

  const focusNode = (nodeId: string | undefined) => {
    if (!nodeId) return;
    viewportRef.current
      ?.querySelector<HTMLElement>(
        `[data-slot="service-map-node"][data-id="${CSS.escape(nodeId)}"]`,
      )
      ?.focus();
  };

  const onNodeKeyDown = (event: React.KeyboardEvent<HTMLElement>, nodeId: string) => {
    const item = structure.items.get(nodeId);
    if (!item) return;
    const layer = structure.layers[item.layer].filter((entry) => !entry.dummy);
    const position = layer.indexOf(item);
    const across = (delta: 1 | -1) => {
      for (
        let l = item.layer + delta;
        l >= 0 && l < structure.layers.length;
        l += delta
      ) {
        const candidates = structure.layers[l].filter((entry) => !entry.dummy);
        if (!candidates.length) continue;
        return candidates.reduce((best, entry) =>
          Math.abs(entry.pos - item.pos) < Math.abs(best.pos - item.pos)
            ? entry
            : best,
        ).id;
      }
      return undefined;
    };
    const keys: Record<string, () => string | undefined> = horizontal
      ? {
          ArrowUp: () => layer[position - 1]?.id,
          ArrowDown: () => layer[position + 1]?.id,
          ArrowLeft: () => across(-1),
          ArrowRight: () => across(1),
        }
      : {
          ArrowLeft: () => layer[position - 1]?.id,
          ArrowRight: () => layer[position + 1]?.id,
          ArrowUp: () => across(-1),
          ArrowDown: () => across(1),
        };
    keys.Home = () => tabOrder[0];
    keys.End = () => tabOrder[tabOrder.length - 1];
    const move = keys[event.key];
    if (!move) return;
    event.preventDefault();
    focusNode(move());
  };

  /* ---------------------------------------------------------- render helpers */

  const maxRps = Math.max(1, ...edges.map((edge) => edge.rps ?? 0));
  const formatMetrics = (metrics?: ServiceMetrics) => ({
    rps: metrics?.rps != null ? rpsFormatter(metrics.rps) : undefined,
    errorRate:
      metrics?.errorRate != null ? errorRateFormatter(metrics.errorRate) : undefined,
    p95: metrics?.p95 != null ? latencyFormatter(metrics.p95) : undefined,
  });
  const errorClass = (rate: number | undefined) =>
    rate == null
      ? ""
      : rate >= critical
        ? "text-destructive"
        : rate >= warn
          ? "text-amber-700 dark:text-amber-400"
          : "";
  const iconFor = (node: ServiceMapNode, size = 15) => {
    if (node.icon) return node.icon;
    const Icon = kindIcon[node.kind ?? "service"];
    return <Icon aria-hidden="true" size={size} stroke={1.75} />;
  };

  const describeNode = (node: ServiceMapNode) => {
    const status = statusOf(node);
    const parts = [node.label, kindLabel[node.kind ?? "service"], statusLabel[status]];
    const m = formatMetrics(node.metrics);
    if (m.rps) parts.push(m.rps);
    if (m.errorRate) parts.push(`${m.errorRate} errors`);
    if (m.p95) parts.push(`p95 ${m.p95}`);
    const ins = inbound.get(node.id)?.length ?? 0;
    const outs = outbound.get(node.id)?.length ?? 0;
    parts.push(`${ins} inbound, ${outs} outbound`);
    return parts.join(", ");
  };

  const edgeSummary = (edge: ServiceMapEdge) =>
    [
      edge.rps != null ? rpsFormatter(edge.rps) : null,
      edge.errorRate != null ? `${errorRateFormatter(edge.errorRate)} errors` : null,
      edge.p95 != null ? `p95 ${latencyFormatter(edge.p95)}` : null,
    ]
      .filter(Boolean)
      .join(" · ");

  const counts = { healthy: 0, degraded: 0, down: 0 };
  for (const node of nodes) counts[statusOf(node)] += 1;

  const hasHeader = title != null || description != null || actions != null;
  const mapLabel = typeof title === "string" ? title : "Service map";
  const motion = animate && !reduced;
  const offsetX = Math.max(0, (width - worldW * scale) / 2);

  /* ---------------------------------------------------------- render */

  return (
    <div
      data-slot="service-map"
      data-direction={direction}
      data-selected={selectedNode ? true : undefined}
      onKeyDown={(event) => {
        onKeyDown?.(event);
        if (event.defaultPrevented || event.key !== "Escape") return;
        if (selectedId == null && !hoveredEdge) return;
        event.preventDefault();
        setHoveredEdge(null);
        if (selectedId != null) select(null);
      }}
      className={cn(
        "@container/service-map flex min-w-0 flex-col rounded-2xl border border-border/70 bg-card text-card-foreground shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.05),0_1px_2px_rgb(0_0_0/0.5)]",
        "[--sm-ok:color-mix(in_oklab,var(--color-muted-foreground)_34%,var(--color-card))] dark:[--sm-ok:color-mix(in_oklab,var(--color-chart-1)_26%,var(--color-muted))]",
        "[--sm-flow:var(--color-chart-1)] [--sm-warn:var(--color-amber-500,oklch(76.9%_0.188_70.08))] [--sm-critical:var(--color-destructive)]",
        className,
      )}
      {...props}
    >
      <style href="overtrue-service-map" precedence="default">
        {`@keyframes service-map-ping{75%,100%{transform:scale(2.4);opacity:0}}@keyframes service-map-draw{from{stroke-dashoffset:var(--len)}}@keyframes service-map-rise{from{opacity:0;transform:translateY(6px) scale(.97)}}@keyframes service-map-fade{from{opacity:0}}@keyframes service-map-glow{0%,100%{opacity:.55}50%{opacity:1}}`}
      </style>

      {hasHeader || nodes.length > 0 ? (
        <div className="flex flex-wrap items-start justify-between gap-x-6 gap-y-3 px-5 pt-5">
          <div className="min-w-0 space-y-1">
            {title != null ? (
              <h3 className="text-sm leading-5 font-semibold tracking-tight">
                {title}
              </h3>
            ) : null}
            {description != null ? (
              <p
                id={`${id}-description`}
                className="text-[13px] leading-5 text-muted-foreground"
              >
                {description}
              </p>
            ) : null}
          </div>
          <div className="flex shrink-0 flex-wrap items-center gap-3">
            {nodes.length > 0 ? (
              <ul
                data-slot="service-map-summary"
                aria-label="Health summary"
                className="flex items-center gap-3 text-xs text-muted-foreground"
              >
                {(["healthy", "degraded", "down"] as const)
                  .filter((status) => status === "healthy" || counts[status] > 0)
                  .map((status) => (
                    <li key={status} className="flex items-center gap-1.5">
                      <StatusDot status={status} />
                      <span className="font-medium text-foreground tabular-nums">
                        {counts[status]}
                      </span>
                      {statusLabel[status].toLowerCase()}
                    </li>
                  ))}
              </ul>
            ) : null}
            {actions != null ? (
              <div className="flex items-center gap-1">{actions}</div>
            ) : null}
          </div>
        </div>
      ) : null}

      <div className="px-3 pt-4 pb-3">
        <div
          ref={viewportRef}
          data-slot="service-map-viewport"
          className="relative overflow-x-auto overflow-y-hidden overscroll-x-contain rounded-xl bg-muted/35 ring-1 ring-border/50 ring-inset [scrollbar-width:thin]"
        >
          {nodes.length === 0 ? (
            <p className="grid h-40 place-items-center text-xs text-muted-foreground">
              No services to show.
            </p>
          ) : (
            <div
              className="relative"
              style={{
                width: worldW * scale,
                height: worldH * scale,
                marginLeft: offsetX,
              }}
            >
              <div
                role="group"
                aria-roledescription="service map"
                aria-label={`${mapLabel}: ${nodes.length} services, ${edges.length} connections. Arrow keys move between services, Enter selects, Escape clears.`}
                aria-describedby={description != null ? `${id}-description` : undefined}
                data-slot="service-map-world"
                className="absolute top-0 left-0 origin-top-left"
                style={{
                  width: worldW,
                  height: worldH,
                  transform: scale === 1 ? undefined : `scale(${scale})`,
                }}
                onPointerLeave={() => {
                  setHoveredId(null);
                  setHoveredEdge(null);
                }}
              >
                <svg
                  aria-hidden="true"
                  data-slot="service-map-edges"
                  className="absolute inset-0 overflow-visible"
                  width={worldW}
                  height={worldH}
                  viewBox={`0 0 ${worldW} ${worldH}`}
                >
                  {placement.edges.map((placed) => {
                    const { edge } = placed;
                    const severity = severityOf(edge);
                    const share = Math.sqrt(Math.max(0, edge.rps ?? 0) / maxRps);
                    const strokeWidth = edge.rps != null ? 1 + share * 3 : 1.25;
                    const highlighted = lit?.edges.has(placed.key) ?? false;
                    const dimmed = lit != null && !highlighted;
                    const sourceLayer = structure.layerOf.get(edge.source) ?? 0;
                    const particles = Math.min(4, Math.max(1, Math.round(1 + share * 3)));
                    const speed = 38 + share * 72;
                    const duration = Math.max(1.2, placed.length / speed);
                    const stroke =
                      severity === "ok" && highlighted
                        ? "color-mix(in oklab, var(--sm-flow) 70%, var(--sm-ok))"
                        : severityStroke[severity];
                    return (
                      <g
                        key={placed.key}
                        data-slot="service-map-edge"
                        data-id={placed.key}
                        data-severity={severity}
                        data-active={highlighted || undefined}
                        data-dimmed={dimmed || undefined}
                        className="transition-opacity duration-150 motion-reduce:transition-none"
                        style={{
                          opacity: dimmed ? 0.16 : 1,
                          color: severityFlow[severity],
                        }}
                      >
                        <path
                          d={placed.d}
                          fill="none"
                          stroke={stroke}
                          strokeWidth={strokeWidth}
                          strokeLinecap="round"
                          className={cn(
                            "transition-[stroke] duration-150 motion-reduce:transition-none",
                            severity !== "ok" &&
                              "dark:[filter:drop-shadow(0_0_5px_color-mix(in_oklab,currentColor_55%,transparent))]",
                            highlighted &&
                              "dark:[filter:drop-shadow(0_0_6px_color-mix(in_oklab,currentColor_60%,transparent))]",
                            !revealed &&
                              "motion-safe:[stroke-dasharray:var(--len)] motion-safe:animate-[service-map-draw_900ms_cubic-bezier(0.22,1,0.36,1)_backwards]",
                          )}
                          style={
                            {
                              "--len": Math.ceil(placed.length + 4),
                              animationDelay: revealed ? undefined : `${160 + sourceLayer * 110}ms`,
                            } as React.CSSProperties
                          }
                        />
                        {motion ? (
                          <g
                            data-slot="service-map-flow"
                            className={cn(
                              "dark:[filter:drop-shadow(0_0_3px_currentColor)]",
                              !revealed &&
                                "motion-safe:animate-[service-map-fade_600ms_ease-out_backwards]",
                            )}
                            style={{
                              animationDelay: revealed ? undefined : `${700 + sourceLayer * 110}ms`,
                            }}
                          >
                            {Array.from({ length: particles }, (_, i) => (
                              <circle
                                key={i}
                                r={highlighted ? 2.4 : 2}
                                fill="currentColor"
                                opacity={severity === "ok" ? 0.9 : 1}
                              >
                                <animateMotion
                                  dur={`${duration.toFixed(2)}s`}
                                  begin={`${(-(duration * i) / particles - (placed.index % 5) * 0.37).toFixed(2)}s`}
                                  repeatCount="indefinite"
                                  path={placed.d}
                                />
                              </circle>
                            ))}
                          </g>
                        ) : (
                          <path
                            data-slot="service-map-flow"
                            d={placed.d}
                            fill="none"
                            stroke="currentColor"
                            strokeWidth={Math.min(2.6, strokeWidth + 0.4)}
                            strokeLinecap="round"
                            strokeDasharray="0 11"
                            opacity={severity === "ok" ? 0.8 : 0.95}
                          />
                        )}
                        <circle
                          cx={placed.end.x}
                          cy={placed.end.y}
                          r={2.5}
                          fill="var(--color-card)"
                          stroke={stroke}
                          strokeWidth={1.5}
                          className={cn(
                            !revealed &&
                              "motion-safe:animate-[service-map-fade_300ms_ease-out_backwards]",
                          )}
                          style={{
                            animationDelay: revealed
                              ? undefined
                              : `${760 + sourceLayer * 110}ms`,
                          }}
                        />
                        <path
                          d={placed.d}
                          fill="none"
                          stroke="transparent"
                          strokeWidth={14}
                          className="pointer-events-[stroke] cursor-default"
                          onPointerEnter={() => {
                            setHoveredId(null);
                            setHoveredEdge(placed.key);
                          }}
                          onPointerLeave={() => setHoveredEdge(null)}
                        />
                      </g>
                    );
                  })}
                </svg>

                {tabOrder.map((nodeId) => {
                  const node = byId.get(nodeId)!;
                  const rect = placement.rects.get(nodeId)!;
                  const status = statusOf(node);
                  const kind = node.kind ?? "service";
                  const selected = selectedId === nodeId;
                  const active = hoveredId === nodeId || focusedId === nodeId;
                  const onPath = lit?.nodes.has(nodeId) ?? false;
                  const dimmed = lit != null && !onPath;
                  const formatted = formatMetrics(node.metrics);
                  const layer = structure.layerOf.get(nodeId) ?? 0;
                  // The lit surface: a card in comfortable density, the icon tile in compact.
                  const surface = cn(
                    "border border-border/80 bg-card",
                    "shadow-[0_1px_2px_rgb(0_0_0/0.05),0_4px_12px_-6px_rgb(0_0_0/0.12)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06),0_1px_2px_rgb(0_0_0/0.5)]",
                    "transition-[opacity,box-shadow,border-color,translate] duration-150 ease-out motion-reduce:transition-none",
                    active &&
                      status === "healthy" &&
                      !selected &&
                      "border-foreground/25 shadow-[0_1px_2px_rgb(0_0_0/0.06),0_10px_24px_-10px_rgb(0_0_0/0.25)]",
                    status === "degraded" &&
                      "border-amber-500/70 shadow-[0_0_0_3px_color-mix(in_oklab,var(--sm-warn)_16%,transparent),0_8px_24px_-8px_color-mix(in_oklab,var(--sm-warn)_45%,transparent)] dark:shadow-[0_0_0_3px_color-mix(in_oklab,var(--sm-warn)_18%,transparent),0_0_28px_-6px_color-mix(in_oklab,var(--sm-warn)_55%,transparent)]",
                    status === "down" &&
                      "border-destructive/80 shadow-[0_0_0_3px_color-mix(in_oklab,var(--sm-critical)_16%,transparent),0_8px_24px_-8px_color-mix(in_oklab,var(--sm-critical)_50%,transparent)] dark:shadow-[0_0_0_3px_color-mix(in_oklab,var(--sm-critical)_20%,transparent),0_0_32px_-6px_color-mix(in_oklab,var(--sm-critical)_60%,transparent)]",
                    selected &&
                      "border-primary/70 shadow-[0_0_0_4px_color-mix(in_oklab,var(--color-primary)_22%,transparent),0_10px_30px_-10px_color-mix(in_oklab,var(--color-primary)_55%,transparent)] dark:shadow-[0_0_0_4px_color-mix(in_oklab,var(--color-primary)_26%,transparent),0_0_32px_-4px_color-mix(in_oklab,var(--color-primary)_55%,transparent)]",
                  );
                  const downRing =
                    status === "down" ? (
                      <span
                        aria-hidden="true"
                        className="pointer-events-none absolute -inset-[5px] rounded-[inherit] border border-destructive/50 opacity-60 motion-safe:animate-[service-map-glow_2.2s_ease-in-out_infinite]"
                      />
                    ) : null;
                  const iconTint = cn(
                    "text-muted-foreground transition-colors duration-150 motion-reduce:transition-none",
                    (active || selected) && "text-foreground",
                    status === "degraded" && "text-amber-700 dark:text-amber-400",
                    status === "down" && "text-destructive",
                  );
                  const shared = {
                    type: "button" as const,
                    "data-slot": "service-map-node",
                    "data-id": nodeId,
                    "data-status": status,
                    "data-kind": kind,
                    "data-density": compact ? "compact" : "comfortable",
                    "data-active": active || (lit != null && onPath) || undefined,
                    "data-selected": selected || undefined,
                    "data-dimmed": dimmed || undefined,
                    "aria-label": describeNode(node),
                    "aria-pressed": selected,
                    onClick: () => select(selected ? null : nodeId),
                    onPointerEnter: () => {
                      setHoveredEdge(null);
                      setHoveredId(nodeId);
                    },
                    onPointerLeave: () => setHoveredId(null),
                    onFocus: (event: React.FocusEvent<HTMLButtonElement>) =>
                      setFocusedId(
                        event.currentTarget.matches(":focus-visible") ? nodeId : null,
                      ),
                    onBlur: () => setFocusedId(null),
                    onKeyDown: (event: React.KeyboardEvent<HTMLButtonElement>) =>
                      onNodeKeyDown(event, nodeId),
                    style: {
                      left: rect.x,
                      top: rect.y,
                      width: cardW,
                      height: cardH,
                      animationDelay: revealed ? undefined : `${layer * 110}ms`,
                    } as React.CSSProperties,
                  };
                  const reveal =
                    !revealed &&
                    "motion-safe:animate-[service-map-rise_700ms_cubic-bezier(0.22,1,0.36,1)_backwards]";

                  if (compact) {
                    return (
                      <button
                        key={nodeId}
                        {...shared}
                        className={cn(
                          "group/node absolute flex flex-col items-center gap-1 bg-transparent p-0 text-center outline-none select-none transition-opacity duration-150 motion-reduce:transition-none",
                          dimmed && "opacity-40",
                          reveal,
                        )}
                      >
                        <span
                          aria-hidden="true"
                          data-slot="service-map-node-tile"
                          className={cn(
                            "relative grid shrink-0 place-items-center rounded-[11px] [&>svg]:size-4",
                            surface,
                            iconTint,
                            "group-hover/node:-translate-y-px group-focus-visible/node:ring-2 group-focus-visible/node:ring-ring/60 group-focus-visible/node:ring-offset-2 group-focus-visible/node:ring-offset-card",
                          )}
                          style={{ width: COMPACT_TILE, height: COMPACT_TILE }}
                        >
                          {downRing}
                          {iconFor(node, 16)}
                          <StatusDot
                            status={status}
                            className="absolute -top-1 -right-1 ring-2 ring-card"
                          />
                        </span>
                        <span className="max-w-full truncate px-0.5 text-[11.5px] leading-4 font-medium tracking-tight">
                          {node.label}
                        </span>
                      </button>
                    );
                  }

                  const info: ServiceMapNodeInfo = {
                    kind,
                    status,
                    layer,
                    inbound: inbound.get(nodeId) ?? [],
                    outbound: outbound.get(nodeId) ?? [],
                    active,
                    selected,
                    dimmed,
                    formatted,
                    icon: iconFor(node),
                  };
                  return (
                    <button
                      key={nodeId}
                      {...shared}
                      className={cn(
                        "group/node absolute flex flex-col overflow-visible rounded-xl p-0 text-left text-card-foreground outline-none select-none hover:-translate-y-px",
                        surface,
                        "focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-2 focus-visible:ring-offset-card",
                        dimmed && "opacity-40",
                        reveal,
                      )}
                    >
                      {downRing}
                      {renderNode ? (
                        renderNode(node, info)
                      ) : (
                        <>
                          <span className="flex min-w-0 items-center gap-2 px-2.5 pt-2.5">
                            <span
                              aria-hidden="true"
                              className={cn(
                                "grid size-6 shrink-0 place-items-center rounded-md bg-muted ring-1 ring-border/60 ring-inset [&>svg]:size-3.5",
                                iconTint,
                                status === "degraded" && "bg-amber-500/12 ring-amber-500/25",
                                status === "down" && "bg-destructive/12 ring-destructive/25",
                              )}
                            >
                              {iconFor(node, 14)}
                            </span>
                            <span className="min-w-0 flex-1 truncate text-[13px] leading-5 font-medium tracking-tight">
                              {node.label}
                            </span>
                            <StatusDot status={status} />
                          </span>
                          <span className="flex min-w-0 items-center gap-1 overflow-hidden px-2.5 pt-1.5 text-[11px] leading-4 whitespace-nowrap text-muted-foreground tabular-nums">
                            {[
                              formatted.rps ? (
                                <span key="rps" className="text-foreground/85">
                                  {formatted.rps}
                                </span>
                              ) : null,
                              formatted.errorRate ? (
                                <span key="err" className={errorClass(node.metrics?.errorRate)}>
                                  {formatted.errorRate}
                                </span>
                              ) : null,
                              formatted.p95 ? <span key="p95">{formatted.p95}</span> : null,
                            ]
                              .filter(Boolean)
                              .flatMap((part, i) =>
                                i === 0
                                  ? [part]
                                  : [
                                      <span key={`sep${i}`} aria-hidden="true" className="text-muted-foreground/45">
                                        ·
                                      </span>,
                                      part,
                                    ],
                              )}
                          </span>
                        </>
                      )}
                    </button>
                  );
                })}
              </div>

              {compact && readoutNode && !hoveredPlaced ? (
                <NodeReadout
                  node={readoutNode}
                  status={statusOf(readoutNode)}
                  formatted={formatMetrics(readoutNode.metrics)}
                  errorClass={errorClass(readoutNode.metrics?.errorRate)}
                  rect={placement.rects.get(readoutNode.id)!}
                  cardW={cardW}
                  cardH={cardH}
                  scale={scale}
                  worldWidth={worldW * scale}
                />
              ) : null}

              {hoveredPlaced ? (
                <div
                  aria-hidden="true"
                  data-slot="service-map-edge-readout"
                  className="pointer-events-none absolute z-30 w-max -translate-x-1/2 -translate-y-[calc(100%+10px)] rounded-xl border border-border/70 bg-popover/90 px-3 py-2 text-popover-foreground shadow-xl backdrop-blur-md motion-safe:animate-[service-map-fade_150ms_ease-out]"
                  style={{
                    left: Math.min(
                      Math.max(hoveredPlaced.mid.x * scale, 96),
                      worldW * scale - 96,
                    ),
                    top: Math.max(hoveredPlaced.mid.y * scale, 64),
                  }}
                >
                  <p className="flex items-center gap-1.5 text-xs font-medium">
                    {byId.get(hoveredPlaced.edge.source)?.label}
                    <span aria-hidden="true" className="text-muted-foreground">
                      →
                    </span>
                    {byId.get(hoveredPlaced.edge.target)?.label}
                  </p>
                  <EdgeMetrics
                    edge={hoveredPlaced.edge}
                    className="mt-1"
                    rpsFormatter={rpsFormatter}
                    latencyFormatter={latencyFormatter}
                    errorRateFormatter={errorRateFormatter}
                    errorClass={errorClass}
                  />
                </div>
              ) : null}
            </div>
          )}
        </div>
      </div>

      {selectedNode ? (
        <ServiceDetail
          key={selectedNode.id}
          node={selectedNode}
          status={statusOf(selectedNode)}
          icon={iconFor(selectedNode, 16)}
          inbound={inbound.get(selectedNode.id) ?? []}
          outbound={outbound.get(selectedNode.id) ?? []}
          byId={byId}
          statusOf={statusOf}
          severityOf={severityOf}
          formatMetrics={formatMetrics}
          errorClass={errorClass}
          edgeKey={(edge) =>
            placement.edges.find((placed) => placed.edge === edge)?.key ?? null
          }
          onHoverEdge={setHoveredEdge}
          onSelect={(nodeId) => {
            select(nodeId);
            requestAnimationFrame(() => focusNode(nodeId));
          }}
          onClose={() => select(null)}
          rpsFormatter={rpsFormatter}
          latencyFormatter={latencyFormatter}
          errorRateFormatter={errorRateFormatter}
        />
      ) : null}

      {showLegend ? (
        <div
          data-slot="service-map-legend"
          className="flex flex-wrap items-center gap-x-5 gap-y-2 border-t border-border/60 px-5 py-3 text-xs text-muted-foreground"
        >
          {(
            [
              ["ok", "Healthy traffic"],
              ["warn", `Errors ≥ ${errorRateFormatter(warn)}`],
              ["critical", `Errors ≥ ${errorRateFormatter(critical)}`],
            ] as const
          ).map(([severity, label]) => (
            <span key={severity} className="flex items-center gap-2">
              <svg aria-hidden="true" width="22" height="8" className="shrink-0 overflow-visible">
                <line
                  x1="1"
                  y1="4"
                  x2="21"
                  y2="4"
                  stroke={severityStroke[severity]}
                  strokeWidth="2"
                  strokeLinecap="round"
                />
                <circle cx="13" cy="4" r="2" fill={severityFlow[severity]} />
              </svg>
              {label}
            </span>
          ))}
          <span className="flex items-center gap-2 @2xl/service-map:ml-auto">
            <svg aria-hidden="true" width="22" height="8" className="shrink-0">
              <path d="M1 3.5 L21 1 L21 7 L1 4.5 Z" fill="var(--sm-ok)" />
            </svg>
            Width shows requests per second
          </span>
        </div>
      ) : null}

      <p className="sr-only" aria-live="polite">
        {selectedNode
          ? `${selectedNode.label} selected, ${statusLabel[statusOf(selectedNode)].toLowerCase()}. ${inbound.get(selectedNode.id)?.length ?? 0} inbound and ${outbound.get(selectedNode.id)?.length ?? 0} outbound connections.`
          : ""}
        {hoveredPlaced ? ` ${byId.get(hoveredPlaced.edge.source)?.label} to ${byId.get(hoveredPlaced.edge.target)?.label}: ${edgeSummary(hoveredPlaced.edge)}` : ""}
      </p>
    </div>
  );
}

/* ------------------------------------------------------------------------ */
/* Detail                                                                    */
/* ------------------------------------------------------------------------ */

/** Floating readout for compact tiles, which have no room for a metrics line. */
function NodeReadout({
  node,
  status,
  formatted,
  errorClass,
  rect,
  cardW,
  cardH,
  scale,
  worldWidth,
}: {
  node: ServiceMapNode;
  status: ServiceStatus;
  formatted: { rps?: string; errorRate?: string; p95?: string };
  errorClass: string;
  rect: { x: number; y: number };
  cardW: number;
  cardH: number;
  scale: number;
  worldWidth: number;
}) {
  const above = rect.y * scale > 56;
  const parts = [
    formatted.rps ? <span key="rps" className="font-medium text-foreground">{formatted.rps}</span> : null,
    formatted.errorRate ? (
      <span key="err" className={cn("font-medium text-foreground", errorClass)}>
        {formatted.errorRate}
      </span>
    ) : null,
    formatted.p95 ? <span key="p95">p95 {formatted.p95}</span> : null,
  ].filter(Boolean);
  return (
    <div
      aria-hidden="true"
      data-slot="service-map-node-readout"
      className={cn(
        "pointer-events-none absolute z-30 w-max -translate-x-1/2 rounded-xl border border-border/70 bg-popover/90 px-3 py-2 text-popover-foreground shadow-xl backdrop-blur-md motion-safe:animate-[service-map-fade_150ms_ease-out]",
        above ? "-translate-y-[calc(100%+6px)]" : "translate-y-1.5",
      )}
      style={{
        left: Math.min(Math.max((rect.x + cardW / 2) * scale, 84), worldWidth - 84),
        top: above ? rect.y * scale : (rect.y + cardH) * scale,
      }}
    >
      <p className="flex items-center gap-1.5 text-xs font-medium">
        <StatusDot status={status} />
        {node.label}
        <span className="font-normal text-muted-foreground">
          {statusLabel[status].toLowerCase()}
        </span>
      </p>
      {parts.length ? (
        <p className="mt-1 flex items-center gap-1.5 text-xs text-muted-foreground tabular-nums">
          {parts.flatMap((part, i) =>
            i === 0
              ? [part]
              : [
                  <span key={`sep${i}`} aria-hidden="true" className="text-muted-foreground/45">
                    ·
                  </span>,
                  part,
                ],
          )}
        </p>
      ) : null}
    </div>
  );
}

function EdgeMetrics({
  edge,
  className,
  rpsFormatter,
  latencyFormatter,
  errorRateFormatter,
  errorClass,
}: {
  edge: ServiceMapEdge;
  className?: string;
  rpsFormatter: (rps: number) => string;
  latencyFormatter: (ms: number) => string;
  errorRateFormatter: (rate: number) => string;
  errorClass: (rate: number | undefined) => string;
}) {
  return (
    <p className={cn("flex items-center gap-3 text-xs text-muted-foreground tabular-nums", className)}>
      {edge.rps != null ? (
        <span>
          <span className="font-medium text-foreground">{rpsFormatter(edge.rps)}</span>
        </span>
      ) : null}
      {edge.errorRate != null ? (
        <span>
          <span className={cn("font-medium text-foreground", errorClass(edge.errorRate))}>
            {errorRateFormatter(edge.errorRate)}
          </span>{" "}
          errors
        </span>
      ) : null}
      {edge.p95 != null ? (
        <span>
          p95{" "}
          <span className="font-medium text-foreground">{latencyFormatter(edge.p95)}</span>
        </span>
      ) : null}
    </p>
  );
}

function ServiceDetail({
  node,
  status,
  icon,
  inbound,
  outbound,
  byId,
  statusOf,
  severityOf,
  formatMetrics,
  errorClass,
  edgeKey,
  onHoverEdge,
  onSelect,
  onClose,
  rpsFormatter,
  latencyFormatter,
  errorRateFormatter,
}: {
  node: ServiceMapNode;
  status: ServiceStatus;
  icon: React.ReactNode;
  inbound: ServiceMapEdge[];
  outbound: ServiceMapEdge[];
  byId: Map<string, ServiceMapNode>;
  statusOf: (node: ServiceMapNode) => ServiceStatus;
  severityOf: (edge: ServiceMapEdge) => Severity;
  formatMetrics: (metrics?: ServiceMetrics) => { rps?: string; errorRate?: string; p95?: string };
  errorClass: (rate: number | undefined) => string;
  edgeKey: (edge: ServiceMapEdge) => string | null;
  onHoverEdge: (key: string | null) => void;
  onSelect: (id: string) => void;
  onClose: () => void;
  rpsFormatter: (rps: number) => string;
  latencyFormatter: (ms: number) => string;
  errorRateFormatter: (rate: number) => string;
}) {
  const formatted = formatMetrics(node.metrics);
  const figures = [
    { key: "rps", label: "Requests", value: formatted.rps, className: "" },
    {
      key: "err",
      label: "Error rate",
      value: formatted.errorRate,
      className: errorClass(node.metrics?.errorRate),
    },
    { key: "p95", label: "p95 latency", value: formatted.p95, className: "" },
  ].filter((figure) => figure.value != null);

  const list = (title: string, items: ServiceMapEdge[], side: "in" | "out") => (
    <div className="min-w-0">
      <h4 className="mb-1.5 flex items-baseline gap-1.5 text-xs text-muted-foreground">
        {title}
        <span className="tabular-nums">{items.length}</span>
      </h4>
      {items.length ? (
        <ul className="-mx-2 flex flex-col">
          {items.map((edge, i) => {
            const otherId = side === "in" ? edge.source : edge.target;
            const other = byId.get(otherId);
            const severity = severityOf(edge);
            const key = edgeKey(edge);
            return (
              <li key={`${otherId}-${i}`}>
                <button
                  type="button"
                  data-slot="service-map-detail-edge"
                  data-severity={severity}
                  onPointerEnter={() => onHoverEdge(key)}
                  onPointerLeave={() => onHoverEdge(null)}
                  onFocus={() => onHoverEdge(key)}
                  onBlur={() => onHoverEdge(null)}
                  onClick={() => other && onSelect(other.id)}
                  aria-label={`${side === "in" ? "From" : "To"} ${other?.label ?? otherId}${edge.rps != null ? `, ${rpsFormatter(edge.rps)}` : ""}${edge.errorRate != null ? `, ${errorRateFormatter(edge.errorRate)} errors` : ""}${edge.p95 != null ? `, p95 ${latencyFormatter(edge.p95)}` : ""}. Select ${other?.label ?? otherId}.`}
                  className="grid h-8 w-full grid-cols-[minmax(0,1fr)_3.75rem_2.75rem_3.25rem] items-center gap-2 rounded-lg px-2 @md/service-map:grid-cols-[minmax(0,1fr)_4.5rem_3.5rem_4rem] text-left text-xs outline-none transition-colors hover:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none"
                >
                  <span className="flex min-w-0 items-center gap-2">
                    <span
                      aria-hidden="true"
                      className="h-0.5 w-3 shrink-0 rounded-full"
                      style={{ backgroundColor: severityStroke[severity] === "var(--sm-ok)" ? "var(--sm-flow)" : severityStroke[severity] }}
                    />
                    <span className="truncate font-medium text-foreground">
                      {other?.label ?? otherId}
                    </span>
                    {other && statusOf(other) !== "healthy" ? (
                      <StatusDot status={statusOf(other)} className="size-1.5" />
                    ) : null}
                  </span>
                  <span className="text-right text-foreground tabular-nums">
                    {edge.rps != null ? rpsFormatter(edge.rps) : "—"}
                  </span>
                  <span className={cn("text-right text-muted-foreground tabular-nums", errorClass(edge.errorRate))}>
                    {edge.errorRate != null ? errorRateFormatter(edge.errorRate) : "—"}
                  </span>
                  <span className="text-right text-muted-foreground tabular-nums">
                    {edge.p95 != null ? latencyFormatter(edge.p95) : "—"}
                  </span>
                </button>
              </li>
            );
          })}
        </ul>
      ) : (
        <p className="py-1.5 text-xs text-muted-foreground">None</p>
      )}
    </div>
  );

  return (
    <section
      data-slot="service-map-detail"
      aria-label={`${node.label} details`}
      className="border-t border-border/60 px-5 pt-4 pb-4 motion-safe:animate-[service-map-fade_240ms_ease-out]"
    >
      <div className="flex items-start gap-3">
        <span
          aria-hidden="true"
          className={cn(
            "grid size-9 shrink-0 place-items-center rounded-lg bg-muted text-foreground ring-1 ring-border/60 ring-inset [&>svg]:size-4",
            status === "degraded" && "bg-amber-500/12 text-amber-700 ring-amber-500/25 dark:text-amber-400",
            status === "down" && "bg-destructive/12 text-destructive ring-destructive/25",
          )}
        >
          {icon}
        </span>
        <div className="min-w-0 flex-1">
          <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
            <h4 className="text-sm leading-5 font-semibold tracking-tight">
              {node.label}
            </h4>
            <span
              className={cn(
                "inline-flex h-5 items-center gap-1.5 rounded-full px-2 text-[11px] font-medium",
                statusPill[status],
              )}
            >
              <span aria-hidden="true" className={cn("size-1.5 rounded-full", statusDot[status])} />
              {statusLabel[status]}
            </span>
          </div>
          <p className="text-xs text-muted-foreground">
            {kindLabel[node.kind ?? "service"][0].toUpperCase() + kindLabel[node.kind ?? "service"].slice(1)}
            {node.group ? (
              <>
                {" · "}
                <span className="font-mono">{node.group}</span>
              </>
            ) : null}
          </p>
        </div>
        <button
          type="button"
          onClick={onClose}
          aria-label="Clear selection"
          className="inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none"
        >
          <IconX aria-hidden="true" size={15} />
        </button>
      </div>

      {figures.length ? (
        <dl className="mt-3 grid grid-cols-3 gap-2">
          {figures.map((figure) => {
            const match = /^([-+<]?[\d.,]+)\s*(\D.*)?$/.exec(figure.value!);
            return (
              <div
                key={figure.key}
                className="rounded-lg bg-muted/40 px-3 py-2 ring-1 ring-border/50 ring-inset"
              >
                <dt className="text-[11px] text-muted-foreground">{figure.label}</dt>
                <dd className={cn("text-lg leading-7 font-semibold tracking-[-0.02em] tabular-nums", figure.className)}>
                  {match ? (
                    <>
                      {match[1]}
                      {match[2] ? (
                        <span
                          className={cn(
                            "text-xs font-medium tracking-normal text-muted-foreground",
                            /^[a-zµ]/i.test(match[2]) && "ml-0.5",
                          )}
                        >
                          {match[2]}
                        </span>
                      ) : null}
                    </>
                  ) : (
                    figure.value
                  )}
                </dd>
              </div>
            );
          })}
        </dl>
      ) : null}

      <div className="mt-4 grid gap-x-8 gap-y-4 @2xl/service-map:grid-cols-2">
        {list("Inbound", inbound, "in")}
        {list("Outbound", outbound, "out")}
      </div>
    </section>
  );
}

export { ServiceMap };
```

### `src/registry/overtrue/flame-graph.tsx`

```tsx
"use client";

import * as React from "react";
import { IconSearch, IconX, IconZoomReset } from "@tabler/icons-react";

import { cn } from "@/lib/utils";

/* ------------------------------------------------------------------------ */
/* Types                                                                     */
/* ------------------------------------------------------------------------ */

export interface FlameNode {
  /** Stable id. Defaults to the node's position in the tree. Must be unique when set. */
  id?: string;
  /** Function or frame name, e.g. "db.query" or "react-dom.renderToString". */
  name: string;
  /** Total (inclusive) cost of the frame. When the children add up to more, their sum is used. */
  value: number;
  children?: FlameNode[];
  /** Color group. Defaults to the name's package prefix, e.g. "db" for "db.query". */
  group?: string;
  /** Anything else your tooltip or handlers need, such as a file and line. */
  meta?: Record<string, unknown>;
}

export type FlameGraphOrientation = "icicle" | "flame";

/** Everything derived about one frame, passed to `renderTooltip`, `onSelect` and `colorBy`. */
export interface FlameFrameInfo {
  id: string;
  node: FlameNode;
  /** 0 for the root. */
  depth: number;
  /** Resolved color group. */
  group: string;
  /** Inclusive value: the frame and everything it called. */
  total: number;
  /** Value spent in the frame itself: total minus children. */
  self: number;
  /** Total as a 0–1 share of the root. */
  share: number;
  /** Self as a 0–1 share of the root. */
  selfShare: number;
  /** Total as a 0–1 share of the parent; 1 for the root. */
  parentShare: number;
  parent: FlameNode | null;
  /** Nodes from the root down to and including this one. */
  path: FlameNode[];
  /** Resolved fill and a readable ink for it. */
  fill: string;
  ink: string;
  /** Whether the frame matches the current search. */
  match: boolean;
}

/** Context passed to a `colorBy` function. */
export interface FlameColorContext {
  depth: number;
  group: string;
  total: number;
  self: number;
  /** Total as a 0–1 share of the root. */
  share: number;
  /** Self time relative to the hottest frame in the profile, 0–1. */
  heat: number;
}

export type FlameGraphColorBy =
  | "group"
  | "self"
  | ((node: FlameNode, context: FlameColorContext) => string);

export interface FlameGraphProps extends Omit<
  React.ComponentProps<"div">,
  "title" | "children" | "onSelect"
> {
  /** The root frame, or several roots that are drawn under one `rootName` frame. */
  data: FlameNode | FlameNode[];
  /** Name of the synthetic root when `data` is an array. Defaults to "all". */
  rootName?: string;
  /** "icicle" draws the root on top; "flame" draws it at the bottom. Defaults to icicle. */
  orientation?: FlameGraphOrientation;
  /** Row height in pixels. Defaults to 22. */
  rowHeight?: number;
  /** Frames narrower than this many pixels are skipped. Defaults to 2. */
  minFrameWidth?: number;
  /** Maximum height of the frame area in pixels; deeper profiles scroll. Defaults to fitting every row. */
  height?: number;
  /** Color by package group, by self time as a heat scale, or with your own function. Defaults to group. */
  colorBy?: FlameGraphColorBy;
  /**
   * Group palette, hashed by group. With `colorBy="self"`, the stops of the heat
   * scale from cold to hot. Defaults to chart-1 … chart-5, and to a neutral, amber
   * and destructive ramp.
   */
  colors?: string[];
  /** Controlled zoom: the id of the frame drawn at full width, or null for the root. */
  zoomedId?: string | null;
  defaultZoomedId?: string | null;
  onZoomChange?: (id: string | null, node: FlameNode | null) => void;
  /** Show the built-in search field. Defaults to true. */
  showSearch?: boolean;
  /** Controlled search. Frames whose name contains it are highlighted. */
  search?: string;
  defaultSearch?: string;
  onSearchChange?: (search: string) => void;
  searchPlaceholder?: string;
  /** Formats values. Defaults to milliseconds. */
  valueFormatter?: (value: number) => string;
  /** Replaces the content of the hover and focus readout. */
  renderTooltip?: (info: FlameFrameInfo) => React.ReactNode;
  /** List the heaviest functions by aggregated self time. Pass a number for the count; true shows 8. */
  showTopFunctions?: boolean | number;
  /** Called when a frame is clicked or activated with Enter, before it zooms. */
  onSelect?: (node: FlameNode, info: FlameFrameInfo) => void;
  title?: React.ReactNode;
  description?: React.ReactNode;
  /** Controls placed at the top right, before the total. */
  actions?: React.ReactNode;
}

/* ------------------------------------------------------------------------ */
/* Model                                                                     */
/* ------------------------------------------------------------------------ */

interface Frame {
  id: string;
  node: FlameNode;
  name: string;
  lower: string;
  group: string;
  depth: number;
  /** Start and end as 0–1 fractions of the root. */
  start: number;
  end: number;
  total: number;
  self: number;
  heat: number;
  parent: Frame | null;
  children: Frame[];
}

interface Model {
  root: Frame | null;
  byId: Map<string, Frame>;
  maxDepth: number;
  count: number;
}

interface View {
  v0: number;
  vs: number;
}

const ROOT_KEY = "root";
const DURATION = 300;
/** Horizontal padding plus about four monospace characters: anything less is noise. */
const labelFits = (frame: { name: string }, px: number) =>
  px >= 13 + 6.7 * Math.min(frame.name.length, 4);
const FALLBACK_WIDTH = 640;

const defaultPalette = [
  "var(--color-chart-1)",
  "var(--color-chart-2)",
  "var(--color-chart-3)",
  "var(--color-chart-4)",
  "var(--color-chart-5)",
];

const AMBER = "var(--color-amber-400, oklch(82.8% 0.189 84.429))";
const defaultHeat = [
  "color-mix(in oklab, var(--color-muted-foreground) 24%, var(--color-card))",
  AMBER,
  "var(--color-destructive)",
];

/** The package a frame belongs to: "db" for "db.query", "react-dom" for "react-dom.render". */
function packageOf(name: string) {
  const match =
    /^\s*(@[\w.-]+\/[\w-]+|[\w$-]+)(?:\.|\/|::|:|#)/.exec(name) ??
    /^\s*([\w$-]+)/.exec(name);
  return match ? match[1] : name;
}

function hash(text: string) {
  let h = 0x811c9dc5;
  for (let i = 0; i < text.length; i++) {
    h ^= text.charCodeAt(i);
    h = Math.imul(h, 0x01000193);
  }
  return h >>> 0;
}

function buildModel(data: FlameNode | FlameNode[], rootName: string): Model {
  const byId = new Map<string, Frame>();
  const order: Frame[] = [];
  let maxDepth = 0;
  const rootNode: FlameNode = Array.isArray(data)
    ? { name: rootName, value: 0, children: data }
    : data;

  const visit = (
    node: FlameNode,
    parent: Frame | null,
    depth: number,
    offset: number,
    key: string,
  ): Frame | null => {
    const id = node.id ?? key;
    const frame: Frame = {
      id,
      node,
      name: node.name,
      lower: node.name.toLowerCase(),
      group: node.group ?? packageOf(node.name),
      depth,
      start: offset,
      end: offset,
      total: 0,
      self: 0,
      heat: 0,
      parent,
      children: [],
    };
    const at = order.length;
    order.push(frame);
    let cursor = offset;
    node.children?.forEach((child, index) => {
      const built = visit(child, frame, depth + 1, cursor, `${id}/${index}`);
      if (!built) return;
      frame.children.push(built);
      cursor += built.total;
    });
    const childSum = cursor - offset;
    const own = Number(node.value);
    frame.total = Math.max(Number.isFinite(own) && own > 0 ? own : 0, childSum);
    frame.self = Math.max(0, frame.total - childSum);
    frame.end = offset + frame.total;
    if (!(frame.total > 0)) {
      order.length = at;
      return null;
    }
    return frame;
  };

  const root = visit(rootNode, null, 0, 0, ROOT_KEY);
  if (!root) return { root: null, byId, maxDepth: 0, count: 0 };
  const scale = root.total;
  let maxSelf = 0;
  for (const frame of order) maxSelf = Math.max(maxSelf, frame.self);
  for (const frame of order) {
    frame.start /= scale;
    frame.end /= scale;
    frame.heat = maxSelf > 0 ? Math.sqrt(frame.self / maxSelf) : 0;
    maxDepth = Math.max(maxDepth, frame.depth);
    byId.set(frame.id, frame);
  }
  return { root, byId, maxDepth, count: order.length };
}

function lineage(frame: Frame) {
  const chain: Frame[] = [];
  for (let current: Frame | null = frame; current; current = current.parent)
    chain.unshift(current);
  return chain;
}

/** Frames wider than `minWidth` pixels inside the view, in depth-first order. */
function visibleFrames(root: Frame, view: View, width: number, min: number) {
  const out: Frame[] = [];
  const lo = view.v0;
  const hi = view.v0 + view.vs;
  const stack = [root];
  while (stack.length) {
    const frame = stack.pop()!;
    const a = Math.max(frame.start, lo);
    const b = Math.min(frame.end, hi);
    if (b <= a || ((b - a) / view.vs) * width < min) continue;
    out.push(frame);
    for (let i = frame.children.length - 1; i >= 0; i--)
      stack.push(frame.children[i]);
  }
  return out;
}

function pixelWidth(frame: Frame, view: View, width: number) {
  const a = Math.max(frame.start, view.v0);
  const b = Math.min(frame.end, view.v0 + view.vs);
  return b > a ? ((b - a) / view.vs) * width : 0;
}

/**
 * Zoom about the one point that stays put on screen, with the scale changing
 * geometrically, so deep zooms feel as steady as shallow ones.
 */
function interpolate(a: View, b: View, t: number): View {
  if (Math.abs(a.vs - b.vs) < 1e-12)
    return { v0: a.v0 + (b.v0 - a.v0) * t, vs: a.vs };
  const vs = a.vs * Math.pow(b.vs / a.vs, t);
  const fixed = (b.v0 * a.vs - a.v0 * b.vs) / (a.vs - b.vs);
  return { v0: fixed - (fixed - a.v0) * (vs / a.vs), vs };
}

const easeOut = (t: number) => 1 - Math.pow(1 - t, 3);

/* ------------------------------------------------------------------------ */
/* Formatting and color                                                     */
/* ------------------------------------------------------------------------ */

function formatMs(ms: number) {
  if (!Number.isFinite(ms)) return "—";
  const a = Math.abs(ms);
  if (a === 0) return "0 ms";
  if (a < 1) return `${ms.toFixed(2)} ms`;
  if (a < 10) return `${ms.toFixed(1)} ms`;
  if (a < 1000) return `${Math.round(ms)} ms`;
  if (a < 10_000) return `${(ms / 1000).toFixed(2)} s`;
  return `${(ms / 1000).toFixed(1)} s`;
}

function percent(share: number) {
  const pct = share * 100;
  if (!(pct > 0)) return "0%";
  if (pct < 0.1) return "<0.1%";
  if (pct >= 99.95) return "100%";
  return `${+pct.toFixed(1)}%`;
}

/** Light or dark ink picked from the fill's own lightness. */
function inkFor(fill: string) {
  return `oklch(from ${fill} clamp(0.21, (0.66 - l) * 1000, 0.985) min(c, 0.035) h)`;
}

function mix(a: string, b: string, t: number) {
  const pct = Math.round(Math.min(1, Math.max(0, t)) * 100);
  if (pct <= 0) return b;
  if (pct >= 100) return a;
  return `color-mix(in oklab, ${a} ${pct}%, ${b})`;
}

function rampAt(stops: string[], t: number) {
  if (stops.length === 1) return stops[0];
  const scaled = Math.min(1, Math.max(0, t)) * (stops.length - 1);
  const i = Math.min(stops.length - 2, Math.floor(scaled));
  return mix(stops[i + 1], stops[i], scaled - i);
}

/** Splits "482 ms" into digits and a quieter unit. */
function Figure({ text, className }: { text: string; className?: string }) {
  const match = /^([-+]?[\d.,]+)\s*(\D.*)$/.exec(text);
  if (!match) return <span className={className}>{text}</span>;
  return (
    <span className={className}>
      {match[1]}
      <span className="ml-0.5 text-[0.62em] font-medium tracking-normal text-muted-foreground">
        {match[2]}
      </span>
    </span>
  );
}

/* ------------------------------------------------------------------------ */
/* Hooks                                                                     */
/* ------------------------------------------------------------------------ */

const useIsomorphicLayoutEffect =
  typeof window === "undefined" ? React.useEffect : React.useLayoutEffect;

function useReducedMotion() {
  return React.useSyncExternalStore(
    (onChange) => {
      const query = window.matchMedia("(prefers-reduced-motion: reduce)");
      query.addEventListener("change", onChange);
      return () => query.removeEventListener("change", onChange);
    },
    () => window.matchMedia("(prefers-reduced-motion: reduce)").matches,
    () => false,
  );
}

function useControllable<T>(
  value: T | undefined,
  defaultValue: T,
  onChange?: (value: T) => void,
) {
  const [inner, setInner] = React.useState(defaultValue);
  const controlled = value !== undefined;
  const current = controlled ? value : inner;
  const set = React.useCallback(
    (next: T) => {
      if (!controlled) setInner(next);
      onChange?.(next);
    },
    [controlled, onChange],
  );
  return [current, set] as const;
}

/* ------------------------------------------------------------------------ */
/* Frame                                                                     */
/* ------------------------------------------------------------------------ */

interface FrameProps {
  frame: Frame;
  top: number;
  height: number;
  fill: string;
  label: boolean;
  query: string;
  match: boolean;
  dimmed: boolean;
  ancestor: boolean;
  zoomed: boolean;
  active: boolean;
  tabStop: boolean;
  ariaLabel: string;
  reveal: number | null;
}

function Highlighted({ text, query }: { text: string; query: string }) {
  const at = query ? text.toLowerCase().indexOf(query) : -1;
  if (at < 0) return <>{text}</>;
  return (
    <>
      {text.slice(0, at)}
      <mark className="bg-transparent font-bold text-inherit underline decoration-current/70 decoration-[1.5px] underline-offset-[3px]">
        {text.slice(at, at + query.length)}
      </mark>
      {text.slice(at + query.length)}
    </>
  );
}

/** Memoised so hovering one frame re-renders two, not the whole profile. */
const FlameFrame = React.memo(function FlameFrame({
  frame,
  top,
  height,
  fill: baseFill,
  label,
  query,
  match,
  dimmed,
  ancestor,
  zoomed,
  active,
  tabStop,
  ariaLabel,
  reveal,
}: FrameProps) {
  // Dimming mixes the fill toward the surface instead of fading it, so the ink is
  // always picked against the color that is actually on screen.
  const fill = active
    ? baseFill
    : dimmed
      ? `color-mix(in oklab, ${baseFill} 26%, var(--color-muted))`
      : ancestor
        ? `color-mix(in oklab, ${baseFill} 48%, var(--color-card))`
        : baseFill;
  const ink =
    dimmed && !active ? "var(--color-muted-foreground)" : inkFor(fill);
  return (
    <button
      type="button"
      data-slot="flame-graph-frame"
      data-id={frame.id}
      data-depth={frame.depth}
      data-match={match || undefined}
      data-dimmed={dimmed || undefined}
      data-ancestor={ancestor || undefined}
      data-zoomed={zoomed || undefined}
      data-active={active || undefined}
      aria-label={ariaLabel}
      aria-current={zoomed ? "true" : undefined}
      tabIndex={tabStop ? 0 : -1}
      className={cn(
        "group/frame absolute block overflow-hidden rounded-[3px] p-0 text-left outline-none select-none",
        ancestor ? "cursor-zoom-out" : zoomed ? "cursor-default" : "cursor-zoom-in",
        "data-[active]:z-10 focus-visible:z-20",
        reveal != null &&
          "motion-safe:animate-[flame-frame-in_720ms_cubic-bezier(0.22,1,0.36,1)_backwards]",
      )}
      style={
        {
          "--x0": +frame.start.toFixed(9),
          "--x1": +frame.end.toFixed(9),
          "--frame-fill": baseFill,
          top,
          height,
          color: ink,
          animationDelay: reveal != null ? `${reveal}ms` : undefined,
        } as React.CSSProperties
      }
    >
      <span
        aria-hidden="true"
        data-slot="flame-graph-frame-fill"
        className={cn(
          "absolute inset-0 rounded-[inherit] transition-[background-color,box-shadow] duration-150 motion-reduce:transition-none",
          // A soft top light gives each frame a little depth without changing its hue.
          !dimmed &&
            "bg-[linear-gradient(to_bottom,rgb(255_255_255/0.18),rgb(255_255_255/0)_75%)] dark:bg-[linear-gradient(to_bottom,rgb(255_255_255/0.12),rgb(255_255_255/0)_75%)]",
          match &&
            "shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--frame-fill)_55%,var(--color-foreground))] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.4),0_0_14px_-3px_var(--frame-fill)]",
          "group-data-[active]/frame:shadow-[inset_0_0_0_1.5px_color-mix(in_oklab,var(--color-foreground)_82%,transparent),0_0_18px_-4px_var(--frame-fill)]",
          "group-focus-visible/frame:shadow-[inset_0_0_0_2px_var(--color-ring),inset_0_0_0_3px_var(--color-card)]",
        )}
        style={{ backgroundColor: fill }}
      />
      {label ? (
        <span
          aria-hidden="true"
          className="relative block truncate px-1.5 font-mono text-[11px] transition-colors duration-150 motion-reduce:transition-none"
          style={{ lineHeight: `${height}px` }}
        >
          {match ? <Highlighted text={frame.name} query={query} /> : frame.name}
        </span>
      ) : null}
    </button>
  );
});

/* ------------------------------------------------------------------------ */
/* Tooltip                                                                   */
/* ------------------------------------------------------------------------ */

function DefaultTooltip({
  info,
  format,
}: {
  info: FlameFrameInfo;
  format: (value: number) => string;
}) {
  return (
    <div className="w-max max-w-72 min-w-52">
      <div className="flex items-start gap-2 px-3 pt-2.5 pb-2">
        <span
          aria-hidden="true"
          className="mt-[3px] size-2.5 shrink-0 rounded-[3px]"
          style={{ backgroundColor: info.fill }}
        />
        <div className="min-w-0 space-y-0.5">
          <p className="font-mono text-xs leading-4 font-medium break-all text-foreground">
            {info.node.name}
          </p>
          <p className="text-[11px] leading-4 text-muted-foreground">
            {info.group !== info.node.name ? (
              <>
                <span className="font-mono">{info.group}</span>
                {" · "}
              </>
            ) : null}
            depth <span className="tabular-nums">{info.depth}</span>
          </p>
        </div>
      </div>
      <dl className="grid grid-cols-[auto_1fr_auto] items-baseline gap-x-4 gap-y-1 border-t border-border/60 px-3 py-2 text-xs tabular-nums">
        <dt className="text-muted-foreground">Total</dt>
        <dd className="text-right font-medium text-foreground">
          {format(info.total)}
        </dd>
        <dd className="text-right text-muted-foreground">
          {percent(info.share)}
        </dd>
        <dt className="text-muted-foreground">Self</dt>
        <dd className="text-right font-medium text-foreground">
          {format(info.self)}
        </dd>
        <dd className="text-right text-muted-foreground">
          {percent(info.selfShare)}
        </dd>
        {info.parent ? (
          <>
            <dt className="text-muted-foreground">Of parent</dt>
            <dd className="col-span-2 flex min-w-0 items-baseline justify-end gap-1 text-right">
              <span className="font-medium text-foreground">
                {percent(info.parentShare)}
              </span>
              <span className="truncate font-mono text-[11px] text-muted-foreground">
                {info.parent.name}
              </span>
            </dd>
          </>
        ) : null}
      </dl>
    </div>
  );
}

/* ------------------------------------------------------------------------ */
/* Component                                                                 */
/* ------------------------------------------------------------------------ */

const toolButton =
  "inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none";

/**
 * A profiler flame graph. Frames are HTML, so labels stay crisp at any zoom.
 * Click or press Enter on a frame to zoom it to full width; Escape zooms out.
 * Search highlights matching frames and reports their share of the total.
 */
function FlameGraph({
  data,
  rootName = "all",
  orientation = "icicle",
  rowHeight = 22,
  minFrameWidth = 2,
  height,
  colorBy = "group",
  colors,
  zoomedId: zoomedIdProp,
  defaultZoomedId = null,
  onZoomChange,
  showSearch = true,
  search: searchProp,
  defaultSearch = "",
  onSearchChange,
  searchPlaceholder = "Search functions",
  valueFormatter = formatMs,
  renderTooltip,
  showTopFunctions = false,
  onSelect,
  title,
  description,
  actions,
  className,
  onKeyDown,
  ...props
}: FlameGraphProps) {
  const id = React.useId();
  const reduced = useReducedMotion();
  const format = valueFormatter;
  const rootRef = React.useRef<HTMLDivElement>(null);
  const scrollRef = React.useRef<HTMLDivElement>(null);
  const canvasRef = React.useRef<HTMLDivElement>(null);
  const tipRef = React.useRef<HTMLDivElement>(null);
  const pointer = React.useRef<{ x: number; y: number } | null>(null);
  const pendingFocus = React.useRef(false);

  const model = React.useMemo(() => buildModel(data, rootName), [data, rootName]);
  const { root, byId, maxDepth } = model;

  /* ---------------------------------------------------------- state */

  const [innerZoom, setInnerZoom] = React.useState<string | null>(
    defaultZoomedId,
  );
  const requestedZoom =
    zoomedIdProp !== undefined ? zoomedIdProp : innerZoom;
  const focus =
    (requestedZoom != null ? byId.get(requestedZoom) : undefined) ?? root;
  const zoomed = focus != null && focus !== root;

  const [search, setSearch] = useControllable(
    searchProp,
    defaultSearch,
    onSearchChange,
  );
  const query = search.trim().toLowerCase();

  const [width, setWidth] = React.useState(0);
  const [hoveredId, setHoveredId] = React.useState<string | null>(null);
  const [focusedId, setFocusedId] = React.useState<string | null>(null);
  const [tabStopId, setTabStopId] = React.useState<string | null>(null);
  const [tween, setTween] = React.useState<{ from: View; to: View } | null>(
    null,
  );
  const [revealed, setRevealed] = React.useState(false);

  const target: View = focus
    ? { v0: focus.start, vs: focus.end - focus.start || 1 }
    : { v0: 0, vs: 1 };
  const [initialView] = React.useState(target);
  const shown = React.useRef<View>(target);

  const commitZoom = (frame: Frame | null) => {
    const next = frame && frame !== root ? frame : null;
    if (zoomedIdProp === undefined) setInnerZoom(next?.id ?? null);
    onZoomChange?.(next?.id ?? null, next?.node ?? null);
  };

  /* ---------------------------------------------------------- measure */

  useIsomorphicLayoutEffect(() => {
    const element = canvasRef.current;
    if (!element) return;
    const measure = () => setWidth(element.clientWidth);
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(element);
    return () => observer.disconnect();
  }, [root != null]);

  React.useEffect(() => {
    const timer = window.setTimeout(() => setRevealed(true), 1400);
    return () => window.clearTimeout(timer);
  }, []);

  // Flame graphs grow upward, so a scrolling one starts at the root.
  useIsomorphicLayoutEffect(() => {
    const scroller = scrollRef.current;
    if (scroller && orientation === "flame")
      scroller.scrollTop = scroller.scrollHeight;
  }, [orientation, height]);

  /* ---------------------------------------------------------- zoom tween */

  useIsomorphicLayoutEffect(() => {
    const element = canvasRef.current;
    if (!element) return;
    const to = target;
    const from = shown.current;
    const apply = (view: View) => {
      element.style.setProperty("--flame-v0", String(view.v0));
      element.style.setProperty("--flame-vs", String(view.vs));
      shown.current = view;
    };
    const same =
      Math.abs(from.v0 - to.v0) < 1e-12 && Math.abs(from.vs - to.vs) < 1e-12;
    if (same || reduced) {
      apply(to);
      setTween(null);
      return;
    }
    setTween({ from, to });
    const startedAt = performance.now();
    let frame = requestAnimationFrame(function step(now) {
      const t = Math.min(1, (now - startedAt) / DURATION);
      apply(interpolate(from, to, easeOut(t)));
      if (t < 1) frame = requestAnimationFrame(step);
      else setTween(null);
    });
    return () => cancelAnimationFrame(frame);
  }, [target.v0, target.vs, reduced]);

  /* ---------------------------------------------------------- colors */

  const paletteKey = (colors ?? []).join("|");
  const colorMap = React.useMemo(() => {
    const map = new Map<string, string>();
    if (!root) return map;
    const custom = paletteKey ? paletteKey.split("|") : null;
    for (const frame of byId.values()) {
      let fill: string;
      if (typeof colorBy === "function") {
        fill = colorBy(frame.node, {
          depth: frame.depth,
          group: frame.group,
          total: frame.total,
          self: frame.self,
          share: frame.total / root.total,
          heat: frame.heat,
        });
      } else if (colorBy === "self") {
        fill = rampAt(custom ?? defaultHeat, frame.heat);
      } else {
        const palette = custom ?? defaultPalette;
        const base = palette[hash(frame.group) % palette.length];
        // Group picks the hue; the function picks one of three tints within it.
        const tint = hash(frame.name) % 3;
        fill = `color-mix(in oklab, ${base} var(--flame-tint-${tint}), var(--color-card))`;
      }
      map.set(frame.id, fill);
    }
    return map;
    // paletteKey stands in for `colors`, so inline arrays do not recolor.
  }, [byId, root, colorBy, paletteKey]);

  /* ---------------------------------------------------------- search */

  const matches = React.useMemo(() => {
    if (!root || !query) return null;
    const ids = new Set<string>();
    let covered = 0;
    const walk = (frame: Frame, inside: boolean) => {
      const hit = frame.lower.includes(query);
      if (hit) {
        ids.add(frame.id);
        if (!inside) covered += frame.total;
      }
      for (const child of frame.children) walk(child, inside || hit);
    };
    walk(root, false);
    return { ids, count: ids.size, share: covered / root.total };
  }, [root, query]);

  /* ---------------------------------------------------------- frames */

  const measured = width || FALLBACK_WIDTH;
  const rendered = React.useMemo(() => {
    if (!root) return [] as Frame[];
    const now = visibleFrames(root, target, measured, minFrameWidth);
    if (!tween) return now;
    const seen = new Set(now);
    for (const frame of visibleFrames(
      root,
      tween.from,
      measured,
      minFrameWidth,
    ))
      if (!seen.has(frame)) now.push(frame);
    return now;
  }, [root, target.v0, target.vs, measured, minFrameWidth, tween]);

  const renderedIds = React.useMemo(
    () => new Set(rendered.map((frame) => frame.id)),
    [rendered],
  );
  const stopId =
    tabStopId && renderedIds.has(tabStopId)
      ? tabStopId
      : (focus?.id ?? null);

  const infoFor = (frame: Frame): FlameFrameInfo => {
    const fill = colorMap.get(frame.id) ?? defaultPalette[0];
    const rootTotal = root?.total || 1;
    return {
      id: frame.id,
      node: frame.node,
      depth: frame.depth,
      group: frame.group,
      total: frame.total,
      self: frame.self,
      share: frame.total / rootTotal,
      selfShare: frame.self / rootTotal,
      parentShare: frame.parent ? frame.total / frame.parent.total : 1,
      parent: frame.parent?.node ?? null,
      path: lineage(frame).map((entry) => entry.node),
      fill,
      ink: inkFor(fill),
      match: matches?.ids.has(frame.id) ?? false,
    };
  };

  const describe = (frame: Frame) =>
    `${frame.name}, ${format(frame.total)}, ${percent(frame.total / (root?.total || 1))} of total` +
    (frame.children.length ? `, self ${format(frame.self)}` : "");

  /* ---------------------------------------------------------- top functions */

  const topCount =
    showTopFunctions === true
      ? 8
      : typeof showTopFunctions === "number"
        ? Math.max(1, Math.floor(showTopFunctions))
        : 0;
  const topFunctions = React.useMemo(() => {
    if (!focus || !topCount) return [];
    const map = new Map<
      string,
      { name: string; self: number; calls: number; sample: Frame }
    >();
    const stack = [focus];
    while (stack.length) {
      const frame = stack.pop()!;
      if (frame.self > 0) {
        const entry = map.get(frame.name);
        if (entry) {
          entry.self += frame.self;
          entry.calls += 1;
          if (frame.self > entry.sample.self) entry.sample = frame;
        } else
          map.set(frame.name, {
            name: frame.name,
            self: frame.self,
            calls: 1,
            sample: frame,
          });
      }
      stack.push(...frame.children);
    }
    return [...map.values()]
      .sort((a, b) => b.self - a.self)
      .slice(0, topCount);
  }, [focus, topCount]);

  /* ---------------------------------------------------------- interaction */

  const activeId = tween ? null : (hoveredId ?? focusedId);
  const activeFrame = activeId ? (byId.get(activeId) ?? null) : null;

  const placeTip = React.useCallback(() => {
    const tip = tipRef.current;
    const host = rootRef.current;
    if (!tip || !host) return;
    const box = host.getBoundingClientRect();
    const w = tip.offsetWidth;
    const h = tip.offsetHeight;
    let x: number;
    let y: number;
    const p = pointer.current;
    if (p) {
      x = p.x - box.left + 14;
      y = p.y - box.top + 18;
      if (x + w > box.width - 8) x = p.x - box.left - w - 14;
      if (y + h > box.height + 24) y = p.y - box.top - h - 14;
    } else {
      const id = tip.dataset.for;
      const element = id
        ? canvasRef.current?.querySelector<HTMLElement>(
            `[data-slot="flame-graph-frame"][data-id="${CSS.escape(id)}"]`,
          )
        : null;
      if (!element) return;
      const r = element.getBoundingClientRect();
      x = Math.min(r.left - box.left, box.width - w - 8);
      y = r.bottom - box.top + 6;
      if (y + h > box.height + 24) y = r.top - box.top - h - 6;
    }
    x = Math.max(8, x);
    tip.style.transform = `translate3d(${Math.round(x)}px, ${Math.round(y)}px, 0)`;
  }, []);

  useIsomorphicLayoutEffect(() => {
    if (activeFrame) placeTip();
  }, [activeFrame, placeTip]);

  const frameFromEvent = (event: React.SyntheticEvent) => {
    const element = (event.target as HTMLElement).closest<HTMLElement>(
      '[data-slot="flame-graph-frame"]',
    );
    return element ? (byId.get(element.dataset.id ?? "") ?? null) : null;
  };

  const focusFrame = (frame: Frame | null | undefined) => {
    if (!frame) return;
    setTabStopId(frame.id);
    canvasRef.current
      ?.querySelector<HTMLElement>(
        `[data-slot="flame-graph-frame"][data-id="${CSS.escape(frame.id)}"]`,
      )
      ?.focus({ preventScroll: false });
  };

  const activate = (frame: Frame, fromKeyboard: boolean) => {
    onSelect?.(frame.node, infoFor(frame));
    // Activating the zoomed frame steps out; anything else zooms to it.
    const next = frame === focus ? (frame.parent ?? null) : frame;
    commitZoom(next);
    if (fromKeyboard) setTabStopId(frame.id);
  };

  const zoomOut = () => {
    if (focus?.parent) commitZoom(focus.parent);
  };

  const onCanvasKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    const frame = frameFromEvent(event);
    if (!frame || !root) return;
    const visible = (candidate: Frame | null | undefined) =>
      candidate && renderedIds.has(candidate.id) ? candidate : null;
    const firstChild = () =>
      frame.children.find((child) => renderedIds.has(child.id)) ?? null;
    const along = (direction: 1 | -1) => {
      const row = rendered
        .filter((candidate) => candidate.depth === frame.depth)
        .sort((a, b) => a.start - b.start);
      return row[row.indexOf(frame) + direction] ?? null;
    };
    const up = orientation === "icicle" ? frame.parent : firstChild();
    const down = orientation === "icicle" ? firstChild() : frame.parent;
    switch (event.key) {
      case "ArrowUp":
        focusFrame(visible(up));
        break;
      case "ArrowDown":
        focusFrame(visible(down));
        break;
      case "ArrowLeft":
        focusFrame(along(-1));
        break;
      case "ArrowRight":
        focusFrame(along(1));
        break;
      case "Home":
        focusFrame(focus);
        break;
      case "Enter":
      case " ":
        activate(frame, true);
        break;
      case "Escape":
        if (zoomed) zoomOut();
        else if (query) setSearch("");
        else return;
        break;
      default:
        return;
    }
    event.preventDefault();
  };

  // Keep keyboard focus on a frame that is still drawn after a zoom, and move it
  // into the graph when the reset button that had it becomes disabled.
  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || !focus) return;
    if (pendingFocus.current) {
      pendingFocus.current = false;
      focusFrame(focus);
      return;
    }
    const active = document.activeElement as HTMLElement | null;
    if (!active || !canvas.contains(active)) return;
    if (
      active.dataset.slot === "flame-graph-frame" &&
      renderedIds.has(active.dataset.id ?? "")
    )
      return;
    focusFrame(focus);
    // Only after a zoom settles.
  }, [focus, tween == null]);

  /* ---------------------------------------------------------- render */

  const rowTop = (depth: number) =>
    (orientation === "icicle" ? depth : maxDepth - depth) * rowHeight;
  const canvasHeight = (maxDepth + 1) * rowHeight;
  const focusChain = focus ? new Set(lineage(focus)) : new Set<Frame>();
  const rootTotal = root?.total ?? 0;
  const hasHeader = title != null || description != null || actions != null;
  const graphLabel = typeof title === "string" ? title : "Flame graph";
  const activeInfo = activeFrame ? infoFor(activeFrame) : null;

  return (
    <div
      ref={rootRef}
      data-slot="flame-graph"
      data-orientation={orientation}
      data-zoomed={zoomed || undefined}
      data-searching={query ? true : undefined}
      onKeyDown={(event) => {
        onKeyDown?.(event);
        if (event.key !== "Escape" || event.defaultPrevented || !zoomed) return;
        if ((event.target as HTMLElement).tagName === "INPUT") return;
        event.preventDefault();
        zoomOut();
      }}
      className={cn(
        "@container/flame relative flex min-w-0 flex-col rounded-2xl border border-border/70 bg-card text-card-foreground shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.05),0_1px_2px_rgb(0_0_0/0.5)]",
        "[--flame-tint-0:70%] [--flame-tint-1:54%] [--flame-tint-2:40%] dark:[--flame-tint-0:92%] dark:[--flame-tint-1:78%] dark:[--flame-tint-2:64%]",
        className,
      )}
      {...props}
    >
      <style href="overtrue-flame-graph" precedence="default">
        {`[data-slot=flame-graph-frame]{left:max(0%,calc((var(--x0) - var(--flame-v0)) / var(--flame-vs) * 100%));width:max(0px,calc(min(100%,(var(--x1) - var(--flame-v0)) / var(--flame-vs) * 100%) - max(0%,(var(--x0) - var(--flame-v0)) / var(--flame-vs) * 100%) - 1px))}@keyframes flame-frame-in{from{opacity:0;clip-path:inset(0 100% 0 0)}to{clip-path:inset(0 0 0 0)}}`}
      </style>

      {hasHeader || rootTotal > 0 ? (
        <div className="flex items-start justify-between gap-x-6 gap-y-3 px-5 pt-5">
          <div className="min-w-0 space-y-1">
            {title != null ? (
              <h3 className="truncate text-sm leading-5 font-semibold tracking-tight">
                {title}
              </h3>
            ) : null}
            {description != null ? (
              <p
                id={`${id}-description`}
                className="text-[13px] leading-5 text-muted-foreground"
              >
                {description}
              </p>
            ) : null}
          </div>
          <div className="flex shrink-0 items-start gap-3">
            {actions != null ? (
              <div className="flex items-center gap-1">{actions}</div>
            ) : null}
            {rootTotal > 0 ? (
              <p
                data-slot="flame-graph-total"
                className="flex flex-col items-end gap-0.5"
              >
                <span className="text-xs leading-4 text-muted-foreground">
                  Total
                </span>
                <Figure
                  text={format(rootTotal)}
                  className="text-xl leading-6 font-semibold tracking-[-0.02em] tabular-nums"
                />
              </p>
            ) : null}
          </div>
        </div>
      ) : null}

      <div
        data-slot="flame-graph-toolbar"
        className="flex min-h-7 flex-wrap items-center gap-x-3 gap-y-2 px-5 pt-4"
      >
        {showSearch ? (
          <div className="relative min-w-0 flex-1 @lg/flame:w-60 @lg/flame:flex-none">
            <IconSearch
              aria-hidden="true"
              size={15}
              className="pointer-events-none absolute top-1/2 left-2.5 -translate-y-1/2 text-muted-foreground"
            />
            <input
              type="search"
              data-slot="flame-graph-search"
              value={search}
              onChange={(event) => setSearch(event.target.value)}
              onKeyDown={(event) => {
                if (event.key === "Escape" && search) {
                  event.preventDefault();
                  setSearch("");
                }
              }}
              placeholder={searchPlaceholder}
              aria-label="Search frames"
              aria-describedby={query ? `${id}-matches` : undefined}
              spellCheck={false}
              autoComplete="off"
              className="h-8 w-full rounded-lg border border-input/80 bg-transparent pr-8 pl-8 font-mono text-xs shadow-[0_1px_1px_rgb(0_0_0/0.03)] outline-none transition-[border-color,box-shadow] placeholder:font-sans placeholder:text-[13px] placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30 motion-reduce:transition-none [&::-webkit-search-cancel-button]:hidden"
            />
            {search ? (
              <button
                type="button"
                aria-label="Clear search"
                onClick={() => setSearch("")}
                className="absolute top-1/2 right-1 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50"
              >
                <IconX aria-hidden="true" size={13} />
              </button>
            ) : null}
          </div>
        ) : null}

        {(query && matches) || zoomed ? (
          <div className="order-2 flex min-w-0 basis-full flex-wrap items-center justify-between gap-x-4 gap-y-1 @lg/flame:order-1 @lg/flame:basis-0 @lg/flame:flex-1">
            {query && matches ? (
              <p
                id={`${id}-matches`}
                data-slot="flame-graph-matches"
                className="text-xs text-muted-foreground tabular-nums"
              >
                {matches.count > 0 ? (
                  <>
                    <span className="font-medium text-foreground">
                      {matches.count}
                    </span>{" "}
                    {matches.count === 1 ? "match" : "matches"}
                    <span
                      aria-hidden="true"
                      className="px-1.5 text-muted-foreground/50"
                    >
                      ·
                    </span>
                    <span className="font-medium text-foreground">
                      {percent(matches.share)}
                    </span>{" "}
                    of total
                  </>
                ) : (
                  "No matches"
                )}
              </p>
            ) : (
              <span />
            )}
            {zoomed && focus ? (
              <p
                data-slot="flame-graph-zoom"
                className="flex min-w-0 items-baseline gap-1.5 text-xs text-muted-foreground tabular-nums motion-safe:animate-[flame-fade_200ms_ease-out]"
              >
                <span className="max-w-[12rem] truncate font-mono text-foreground">
                  {focus.name}
                </span>
                <span className="shrink-0">
                  {format(focus.total)} · {percent(focus.total / rootTotal)}
                </span>
              </p>
            ) : null}
          </div>
        ) : null}

        <button
          type="button"
          data-slot="flame-graph-reset"
          className={cn(toolButton, "order-1 ml-auto @lg/flame:order-2")}
          disabled={!zoomed}
          onClick={(event) => {
            if (event.detail === 0) pendingFocus.current = true;
            commitZoom(null);
          }}
          title="Reset zoom"
        >
          <IconZoomReset aria-hidden="true" size={16} />
          <span className="sr-only">Reset zoom</span>
        </button>
      </div>

      <div className="px-5 pt-3 pb-5">
        {root ? (
          <div
            ref={scrollRef}
            className={cn(
              "relative",
              height != null && "overflow-y-auto overscroll-contain",
            )}
            style={height != null ? { maxHeight: height } : undefined}
          >
            <div
              ref={canvasRef}
              role="group"
              aria-roledescription="flame graph"
              aria-label={`${graphLabel}: ${model.count} frames. Arrow keys move between frames, Enter zooms in, Escape zooms out.`}
              aria-describedby={
                description != null ? `${id}-description` : undefined
              }
              data-slot="flame-graph-canvas"
              data-tweening={tween ? true : undefined}
              className="relative w-full overflow-hidden"
              style={
                {
                  height: canvasHeight,
                  "--flame-v0": initialView.v0,
                  "--flame-vs": initialView.vs,
                } as React.CSSProperties
              }
              onPointerMove={(event) => {
                if (event.pointerType === "touch") return;
                pointer.current = { x: event.clientX, y: event.clientY };
                const frame = frameFromEvent(event);
                const next = frame?.id ?? null;
                if (next !== hoveredId) setHoveredId(next);
                else placeTip();
              }}
              onPointerLeave={() => {
                pointer.current = null;
                setHoveredId(null);
              }}
              onClick={(event) => {
                const frame = frameFromEvent(event);
                if (frame) activate(frame, false);
              }}
              onKeyDown={onCanvasKeyDown}
              onFocus={(event) => {
                const frame = frameFromEvent(event);
                if (!frame) return;
                setTabStopId(frame.id);
                const visible = (event.target as HTMLElement).matches(
                  ":focus-visible",
                );
                setFocusedId(visible ? frame.id : null);
              }}
              onBlur={(event) => {
                if (!event.currentTarget.contains(event.relatedTarget as Node))
                  setFocusedId(null);
              }}
            >
              {rendered.map((frame) => {
                const fill = colorMap.get(frame.id) ?? defaultPalette[0];
                const ancestor = zoomed && focusChain.has(frame) && frame !== focus;
                const match = matches?.ids.has(frame.id) ?? false;
                const labelWide =
                  labelFits(frame, pixelWidth(frame, target, measured)) ||
                  (tween != null &&
                    labelFits(frame, pixelWidth(frame, tween.from, measured)));
                return (
                  <FlameFrame
                    key={frame.id}
                    frame={frame}
                    top={rowTop(frame.depth)}
                    height={rowHeight - 1}
                    fill={fill}
                    label={labelWide}
                    query={match ? query : ""}
                    match={match}
                    dimmed={matches != null && !match}
                    ancestor={ancestor}
                    zoomed={frame === focus && zoomed}
                    active={frame.id === activeId}
                    tabStop={frame.id === stopId}
                    ariaLabel={describe(frame)}
                    reveal={
                      revealed ? null : Math.min(frame.depth, 16) * 34
                    }
                  />
                );
              })}
            </div>
          </div>
        ) : (
          <p className="grid h-28 place-items-center rounded-xl bg-muted/40 text-xs text-muted-foreground ring-1 ring-border/60 ring-inset">
            No samples to show.
          </p>
        )}
      </div>

      {topCount > 0 && topFunctions.length > 0 && focus ? (
        <div
          data-slot="flame-graph-top-functions"
          className="border-t border-border/60 px-5 pt-4 pb-5"
        >
          <div className="mb-2.5 flex items-baseline justify-between gap-3">
            <h4 className="text-xs font-medium text-foreground">
              Top functions by self time
            </h4>
            <span className="truncate text-xs text-muted-foreground">
              {zoomed ? (
                <>
                  in <span className="font-mono">{focus.name}</span>
                </>
              ) : (
                "Select one to search"
              )}
            </span>
          </div>
          <ol className="grid gap-x-6 gap-y-0.5 @4xl/flame:grid-cols-2">
            {topFunctions.map((entry, index) => {
              const share = entry.self / focus.total;
              const lead = topFunctions[0].self || 1;
              const pressed = search === entry.name;
              const fill = colorMap.get(entry.sample.id) ?? defaultPalette[0];
              return (
                <li key={entry.name} className="min-w-0">
                  <button
                    type="button"
                    data-slot="flame-graph-top-function"
                    aria-pressed={pressed}
                    onClick={() => setSearch(pressed ? "" : entry.name)}
                    className="group/top grid h-8 w-full grid-cols-[1rem_minmax(0,1fr)_4rem_3rem] items-center gap-2.5 rounded-lg px-2 text-left text-xs @md/flame:grid-cols-[1rem_minmax(0,1fr)_6rem_4.5rem_3.25rem] @md/flame:gap-3 @2xl/flame:grid-cols-[1rem_minmax(0,1fr)_12rem_4.5rem_3.25rem] outline-none transition-colors hover:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring/50 aria-pressed:bg-muted motion-reduce:transition-none"
                  >
                    <span className="text-right text-[11px] text-muted-foreground tabular-nums">
                      {index + 1}
                    </span>
                    <span className="flex min-w-0 items-center gap-2">
                      <span
                        aria-hidden="true"
                        className="size-2 shrink-0 rounded-[2px]"
                        style={{ backgroundColor: fill }}
                      />
                      <span className="truncate font-mono text-foreground">
                        {entry.name}
                      </span>
                      {entry.calls > 1 ? (
                        <span className="shrink-0 text-[11px] text-muted-foreground tabular-nums">
                          ×{entry.calls}
                        </span>
                      ) : null}
                    </span>
                    <span
                      aria-hidden="true"
                      className="relative hidden h-1.5 overflow-hidden rounded-full bg-muted @md/flame:block"
                    >
                      <span
                        className="absolute inset-y-0 left-0 rounded-full motion-safe:animate-[flame-bar-in_700ms_cubic-bezier(0.22,1,0.36,1)_backwards]"
                        style={{
                          width: `${Math.max(4, (entry.self / lead) * 100)}%`,
                          backgroundImage: `linear-gradient(to right, color-mix(in oklab, ${fill} 72%, transparent), ${fill})`,
                          animationDelay: `${index * 30}ms`,
                        }}
                      />
                    </span>
                    <span className="text-right font-medium text-foreground tabular-nums">
                      {format(entry.self)}
                    </span>
                    <span className="text-right text-muted-foreground tabular-nums">
                      {percent(share)}
                    </span>
                  </button>
                </li>
              );
            })}
          </ol>
        </div>
      ) : null}

      {activeFrame && activeInfo ? (
        <div
          ref={tipRef}
          aria-hidden="true"
          data-slot="flame-graph-tooltip"
          data-for={activeFrame.id}
          className="pointer-events-none absolute top-0 left-0 z-30 overflow-hidden rounded-xl border border-border/70 bg-popover/90 text-popover-foreground shadow-xl backdrop-blur-md"
        >
          {renderTooltip ? (
            renderTooltip(activeInfo)
          ) : (
            <DefaultTooltip info={activeInfo} format={format} />
          )}
        </div>
      ) : null}

      <p className="sr-only" aria-live="polite">
        {zoomed && focus
          ? `Zoomed to ${focus.name}, ${format(focus.total)}, ${percent(focus.total / rootTotal)} of total.`
          : ""}
        {query && matches
          ? ` ${matches.count} ${matches.count === 1 ? "match" : "matches"}, ${percent(matches.share)} of total.`
          : ""}
      </p>
      <style href="overtrue-flame-graph-motion" precedence="default">
        {`@keyframes flame-fade{from{opacity:0}}@keyframes flame-bar-in{from{transform:scaleX(0);transform-origin:left}}`}
      </style>
    </div>
  );
}

export { FlameGraph };
```

### `src/registry/overtrue/latency-histogram.tsx`

```tsx
"use client";

import * as React from "react";
import { IconX as X } from "@tabler/icons-react";

import { cn } from "@/lib/utils";

export type LatencyScale = "linear" | "log";

export type LatencyRange = [min: number, max: number];

export interface LatencyBucket {
  /** Inclusive lower edge. */
  start: number;
  /** Exclusive upper edge. */
  end: number;
  count: number;
}

/** One bar as drawn, passed to `renderTooltip`. */
export interface LatencyHistogramBucket extends LatencyBucket {
  index: number;
  /** Share of all requests in this bucket, 0–1. */
  share: number;
  /** Share of requests at or below this bucket's upper edge, 0–1. */
  cumulative: number;
  /** Raw comparison count in the same range, when `compare` is set. */
  compare?: number;
  /** Comparison share of its own total, 0–1. */
  compareShare?: number;
  /** The catch-all bar for values past the linear domain. */
  overflow: boolean;
  /** Whether the bucket lies past `threshold`. */
  overThreshold: boolean;
}

export interface LatencyHistogramColors {
  bar: string;
  compare: string;
  threshold: string;
  marker: string;
  selection: string;
}

export interface LatencyHistogramProps extends Omit<
  React.ComponentProps<"div">,
  "title" | "children" | "color"
> {
  /** Raw samples. Bucketed for you, with exact percentiles. */
  values?: number[];
  /** Pre-bucketed counts, used when `values` is not given. Percentiles are interpolated. */
  buckets?: LatencyBucket[];
  /** A comparison distribution, e.g. yesterday. Scaled to the main total so shapes compare. */
  compare?: number[] | LatencyBucket[];
  /** Name of the comparison in the legend and tooltip. */
  compareLabel?: string;
  /** Name of the main series in the legend. */
  seriesLabel?: string;
  /** Draw the comparison as a stepped line or as outlined bars. */
  compareStyle?: "step" | "outline";
  /** Percentiles to mark, as numbers such as 50 or 99.9. */
  percentiles?: number[];
  /** Latency objective. The slow tail past it is shaded and measured. */
  threshold?: number;
  thresholdLabel?: string;
  /** X scale. Pass with `onScaleChange` to control the built-in toggle. */
  scale?: LatencyScale;
  defaultScale?: LatencyScale;
  onScaleChange?: (scale: LatencyScale) => void;
  /** Show the linear/log toggle. Defaults to true. */
  showScaleToggle?: boolean;
  /** Brushed range. Pass `null` for none; leave undefined to let the component manage it. */
  range?: LatencyRange | null;
  defaultRange?: LatencyRange | null;
  onRangeChange?: (range: LatencyRange | null) => void;
  title?: React.ReactNode;
  description?: React.ReactNode;
  /** Controls placed at the top right, before the scale toggle. */
  actions?: React.ReactNode;
  /** Unit of the values. Defaults to "ms"; ms readouts switch to seconds from 1,000. */
  unit?: string;
  /** Formats latencies in readouts, markers, and ticks. */
  valueFormatter?: (value: number) => string;
  /** Target number of bars. Defaults to 40. */
  bucketCount?: number;
  /** Fix the latency domain. Linear charts otherwise end near p99.5 and gather the rest in an overflow bar. */
  domain?: LatencyRange;
  /** Plot height in pixels. Defaults to a third of the plot width, between 140 and 220. */
  height?: number;
  /** Override any series color with a CSS color. */
  colors?: Partial<LatencyHistogramColors>;
  /** Replaces the hover tooltip content. */
  renderTooltip?: (bucket: LatencyHistogramBucket) => React.ReactNode;
  /** Show the percentile summary above the plot. Defaults to true. */
  showSummary?: boolean;
}

/* ------------------------------------------------------------------------ */
/* Formatting                                                                */
/* ------------------------------------------------------------------------ */

const tidy = (value: number) => +value.toPrecision(12);
const compact = new Intl.NumberFormat("en-US", {
  notation: "compact",
  maximumFractionDigits: 1,
});
const whole = new Intl.NumberFormat("en-US");

function makeFormatter(unit: string) {
  const tight = unit.length <= 2;
  const join = (text: string, u: string) =>
    u ? `${text}${tight ? "" : " "}${u}` : text;
  return (value: number) => {
    if (!Number.isFinite(value)) return "—";
    const a = Math.abs(value);
    if (unit === "ms" && a >= 1000)
      return `${tidy(+(value / 1000).toFixed(a >= 10_000 ? 1 : 2))}s`;
    const digits = a >= 100 || a === 0 ? 0 : a >= 10 ? 1 : a >= 1 ? 2 : 3;
    return join(String(tidy(+value.toFixed(digits))), unit);
  };
}

function makeTickFormatter(unit: string) {
  const tight = unit.length <= 2;
  return (value: number) => {
    if (value === 0) return "0";
    if (unit === "ms" && Math.abs(value) >= 1000)
      return `${tidy(value / 1000)}s`;
    return `${tidy(value)}${tight ? "" : " "}${unit}`;
  };
}

function percentLabel(share: number) {
  const pct = share * 100;
  if (pct === 0) return "0%";
  if (pct < 0.1) return "<0.1%";
  if (pct > 99.9 && pct < 100) return ">99.9%";
  return `${pct >= 10 ? pct.toFixed(1) : pct.toFixed(2)}%`;
}

function niceStep(raw: number) {
  if (!(raw > 0)) return 1;
  const magnitude = 10 ** Math.floor(Math.log10(raw));
  const r = raw / magnitude;
  return (
    (r <= 1 ? 1 : r <= 2 ? 2 : r <= 2.5 ? 2.5 : r <= 5 ? 5 : 10) * magnitude
  );
}

/** Round down or up to the nearest 1, 2, or 5 times a power of ten. */
function nice125(value: number, up: boolean) {
  const magnitude = 10 ** Math.floor(Math.log10(value));
  const r = value / magnitude;
  const steps = [1, 2, 5, 10];
  if (up) return (steps.find((s) => s >= r - 1e-9) ?? 10) * magnitude;
  return ([...steps].reverse().find((s) => s <= r + 1e-9) ?? 1) * magnitude;
}

function lowerBound(sorted: Float64Array, value: number) {
  let lo = 0;
  let hi = sorted.length;
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    if (sorted[mid] < value) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

function upperBound(sorted: Float64Array, value: number) {
  let lo = 0;
  let hi = sorted.length;
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    if (sorted[mid] <= value) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

/* ------------------------------------------------------------------------ */
/* Model                                                                     */
/* ------------------------------------------------------------------------ */

interface Bar extends LatencyBucket {
  overflow: boolean;
  /** Left and right edges as 0–1 positions. */
  x0: number;
  x1: number;
}

interface Distribution {
  sorted: Float64Array | null;
  buckets: LatencyBucket[] | null;
  total: number;
  min: number;
  max: number;
  mean: number;
}

function distributionOf(
  values?: number[],
  buckets?: LatencyBucket[],
): Distribution {
  if (values) {
    const clean = values.filter((value) => Number.isFinite(value));
    const sorted = Float64Array.from(clean).sort();
    let sum = 0;
    for (const value of sorted) sum += value;
    return {
      sorted,
      buckets: null,
      total: sorted.length,
      min: sorted.length ? sorted[0] : 0,
      max: sorted.length ? sorted[sorted.length - 1] : 0,
      mean: sorted.length ? sum / sorted.length : 0,
    };
  }
  const list = (buckets ?? [])
    .filter(
      (b) =>
        Number.isFinite(b.start) && Number.isFinite(b.end) && b.end > b.start,
    )
    .sort((a, b) => a.start - b.start);
  let total = 0;
  let sum = 0;
  for (const b of list) {
    total += Math.max(0, b.count);
    sum += (Math.max(0, b.count) * (b.start + b.end)) / 2;
  }
  return {
    sorted: null,
    buckets: list,
    total,
    min: list.length ? list[0].start : 0,
    max: list.length ? list[list.length - 1].end : 0,
    mean: total ? sum / total : 0,
  };
}

/** Nearest-rank percentile from samples; interpolated inside buckets otherwise. */
function quantile(d: Distribution, p: number) {
  if (!d.total) return 0;
  if (d.sorted)
    return d.sorted[
      Math.min(d.total - 1, Math.max(0, Math.ceil(p * d.total) - 1))
    ];
  const target = p * d.total;
  let cumulative = 0;
  for (const b of d.buckets!) {
    if (cumulative + b.count >= target && b.count > 0)
      return b.start + ((target - cumulative) / b.count) * (b.end - b.start);
    cumulative += b.count;
  }
  return d.max;
}

/** Requests with a value in [a, b]. Partial buckets count in proportion. */
function countBetween(d: Distribution, a: number, b: number) {
  if (d.sorted) return upperBound(d.sorted, b) - lowerBound(d.sorted, a);
  let count = 0;
  for (const bucket of d.buckets!) {
    const overlap = Math.min(b, bucket.end) - Math.max(a, bucket.start);
    if (overlap > 0)
      count += (bucket.count * overlap) / (bucket.end - bucket.start);
  }
  return count;
}

function countAbove(d: Distribution, value: number) {
  if (d.sorted) return d.total - upperBound(d.sorted, value);
  return countBetween(d, value, Infinity);
}

interface Layout {
  bars: Bar[];
  lo: number;
  hi: number;
  /** Largest value covered, including the overflow bar. */
  top: number;
  pos: (value: number) => number;
  inv: (x: number) => number;
}

function layoutOf(
  d: Distribution,
  scale: LatencyScale,
  bucketCount: number,
  reach: number,
  domain?: LatencyRange,
): Layout {
  const count = Math.max(4, Math.round(bucketCount));
  // Pre-bucketed data keeps its own edges.
  if (d.buckets) {
    const list = d.buckets;
    const first = list[0]?.start ?? 0;
    const last = list[list.length - 1]?.end ?? 1;
    if (scale === "log") {
      const positive =
        list.find((b) => b.start > 0)?.start ?? list[0]?.end ?? 1;
      const lo = first > 0 ? first : positive / 2;
      const span = Math.log(last / lo) || 1;
      const pos = (v: number) =>
        Math.min(1, Math.max(0, Math.log(Math.max(v, lo) / lo) / span));
      const inv = (x: number) => lo * Math.exp(x * span);
      return {
        bars: list.map((b) => ({
          ...b,
          overflow: false,
          x0: pos(b.start),
          x1: pos(b.end),
        })),
        lo,
        hi: last,
        top: last,
        pos,
        inv,
      };
    }
    const span = last - first || 1;
    const pos = (v: number) => Math.min(1, Math.max(0, (v - first) / span));
    const inv = (x: number) => first + x * span;
    return {
      bars: list.map((b) => ({
        ...b,
        overflow: false,
        x0: pos(b.start),
        x1: pos(b.end),
      })),
      lo: first,
      hi: last,
      top: last,
      pos,
      inv,
    };
  }

  const sorted = d.sorted!;
  if (scale === "log") {
    const positive = sorted[lowerBound(sorted, Number.MIN_VALUE)] ?? 1;
    const lo =
      domain?.[0] && domain[0] > 0
        ? domain[0]
        : nice125(Math.max(positive, 1e-9), false);
    const hi = Math.max(
      domain?.[1] ?? nice125(Math.max(d.max, lo * 10), true),
      lo * 1.0001,
    );
    const span = Math.log(hi / lo);
    const step = span / count;
    const bars: Bar[] = Array.from({ length: count }, (_, i) => ({
      start: lo * Math.exp(i * step),
      end: lo * Math.exp((i + 1) * step),
      count: 0,
      overflow: false,
      x0: i / count,
      x1: (i + 1) / count,
    }));
    for (const v of sorted) {
      const i = v <= lo ? 0 : Math.floor(Math.log(v / lo) / step);
      bars[Math.min(count - 1, Math.max(0, i))].count += 1;
    }
    const pos = (v: number) =>
      Math.min(1, Math.max(0, Math.log(Math.max(v, lo) / lo) / span));
    return { bars, lo, hi, top: hi, pos, inv: (x) => lo * Math.exp(x * span) };
  }

  const lo = domain?.[0] ?? (d.min >= 0 ? 0 : -niceStep(-d.min));
  const wanted = domain?.[1] ?? Math.max(reach, lo + 1e-9);
  const step = niceStep((wanted - lo) / count);
  const n = Math.max(1, Math.ceil((wanted - lo) / step - 1e-9));
  const hi = lo + n * step;
  const overflowCount = d.total - upperBound(sorted, hi);
  const units = overflowCount > 0 ? n + 1.7 : n;
  const bars: Bar[] = Array.from({ length: n }, (_, i) => ({
    start: tidy(lo + i * step),
    end: tidy(lo + (i + 1) * step),
    count: 0,
    overflow: false,
    x0: i / units,
    x1: (i + 1) / units,
  }));
  for (
    let k = lowerBound(sorted, lo), end = upperBound(sorted, hi);
    k < end;
    k++
  )
    bars[Math.min(n - 1, Math.floor((sorted[k] - lo) / step))].count += 1;
  // Values below a fixed domain fold into the first bar.
  bars[0].count += lowerBound(sorted, lo);
  const top = Math.max(hi, d.max);
  if (overflowCount > 0)
    bars.push({
      start: hi,
      end: top,
      count: overflowCount,
      overflow: true,
      x0: (n + 0.7) / units,
      x1: 1,
    });
  const mainEnd = n / units;
  const overflowStart = (n + 0.7) / units;
  const pos = (v: number) => {
    if (v <= hi) return Math.max(0, ((v - lo) / (hi - lo)) * mainEnd);
    if (overflowCount <= 0 || top <= hi) return mainEnd;
    return Math.min(
      1,
      overflowStart + ((v - hi) / (top - hi)) * (1 - overflowStart),
    );
  };
  const inv = (x: number) => {
    if (x <= mainEnd) return lo + (x / mainEnd) * (hi - lo);
    if (x < overflowStart || overflowCount <= 0) return hi;
    return hi + ((x - overflowStart) / (1 - overflowStart)) * (top - hi);
  };
  return { bars, lo, hi, top, pos, inv };
}

/** Bin a comparison into the main bars' edges. */
function binCompare(compare: number[] | LatencyBucket[], bars: Bar[]) {
  const counts = new Array<number>(bars.length).fill(0);
  if (!bars.length) return { counts, total: 0 };
  const find = (v: number) => {
    let lo = 0;
    let hi = bars.length - 1;
    while (lo < hi) {
      const mid = (lo + hi + 1) >> 1;
      if (bars[mid].start <= v) lo = mid;
      else hi = mid - 1;
    }
    return lo;
  };
  let total = 0;
  for (const item of compare as (number | LatencyBucket)[]) {
    if (typeof item === "number") {
      if (!Number.isFinite(item)) continue;
      counts[find(item)] += 1;
      total += 1;
    } else if (Number.isFinite(item.count)) {
      counts[find((item.start + item.end) / 2)] += item.count;
      total += item.count;
    }
  }
  return { counts, total };
}

/* ------------------------------------------------------------------------ */
/* Hooks                                                                     */
/* ------------------------------------------------------------------------ */

function useReducedMotion() {
  return React.useSyncExternalStore(
    (onChange) => {
      const query = window.matchMedia("(prefers-reduced-motion: reduce)");
      query.addEventListener("change", onChange);
      return () => query.removeEventListener("change", onChange);
    },
    () => window.matchMedia("(prefers-reduced-motion: reduce)").matches,
    () => false,
  );
}

function useControllable<T>(
  value: T | undefined,
  defaultValue: T,
  onChange?: (value: T) => void,
) {
  const [inner, setInner] = React.useState(defaultValue);
  const controlled = value !== undefined;
  const set = React.useCallback(
    (next: T) => {
      if (!controlled) setInner(next);
      onChange?.(next);
    },
    [controlled, onChange],
  );
  return [controlled ? value : inner, set] as const;
}

const focusRing =
  "outline-none focus-visible:ring-2 focus-visible:ring-ring/50";
const percentileName = (p: number) => `p${tidy(p)}`;

/* ------------------------------------------------------------------------ */
/* LatencyHistogram                                                          */
/* ------------------------------------------------------------------------ */

/**
 * A latency distribution: bucketed requests with percentile markers, an SLO tail,
 * an optional comparison, and brushing to measure any range.
 */
export function LatencyHistogram({
  values,
  buckets,
  compare,
  compareLabel = "Previous",
  seriesLabel = "Current",
  compareStyle = "step",
  percentiles = [50, 90, 95, 99],
  threshold,
  thresholdLabel = "SLO",
  scale: scaleProp,
  defaultScale = "linear",
  onScaleChange,
  showScaleToggle = true,
  range: rangeProp,
  defaultRange = null,
  onRangeChange,
  title,
  description,
  actions,
  unit = "ms",
  valueFormatter,
  bucketCount = 40,
  domain,
  height,
  colors: colorsProp,
  renderTooltip,
  showSummary = true,
  className,
  ...props
}: LatencyHistogramProps) {
  const id = React.useId();
  const reduced = useReducedMotion();
  const format = React.useMemo(
    () => valueFormatter ?? makeFormatter(unit),
    [valueFormatter, unit],
  );
  const formatTick = React.useMemo(
    () => valueFormatter ?? makeTickFormatter(unit),
    [valueFormatter, unit],
  );
  const colors: LatencyHistogramColors = {
    bar: "var(--color-chart-1)",
    compare: "var(--color-muted-foreground)",
    threshold: "var(--color-destructive)",
    marker: "var(--color-foreground)",
    selection: "var(--color-primary)",
    ...colorsProp,
  };
  const [scale, setScale] = useControllable(
    scaleProp,
    defaultScale,
    onScaleChange,
  );
  const [range, setRange] = useControllable<LatencyRange | null>(
    rangeProp,
    defaultRange,
    onRangeChange,
  );
  const hasThreshold = threshold != null && Number.isFinite(threshold);

  const dist = React.useMemo(
    () => distributionOf(values, buckets),
    [values, buckets],
  );
  const sortedPercentiles = React.useMemo(
    () =>
      [...new Set(percentiles.filter((p) => p > 0 && p < 100))].sort(
        (a, b) => a - b,
      ),
    [percentiles],
  );
  const empty = dist.total === 0;
  const marks = React.useMemo(
    () =>
      dist.total === 0
        ? []
        : sortedPercentiles.map((p) => ({ p, value: quantile(dist, p / 100) })),
    [dist, sortedPercentiles],
  );

  // Linear charts end just past the slow tail (and the SLO); the rest lands in an overflow bar.
  const reach = Math.max(
    quantile(dist, 0.995),
    (marks[marks.length - 1]?.value ?? 0) * 1.04,
    hasThreshold ? threshold! * 1.12 : 0,
  );
  const layout = React.useMemo(
    () => layoutOf(dist, scale, bucketCount, reach, domain),
    [dist, scale, bucketCount, reach, domain],
  );
  const { bars, pos, inv } = layout;

  const comparison = React.useMemo(() => {
    if (!compare?.length) return null;
    const { counts, total } = binCompare(compare, bars);
    const percentilesOf = (() => {
      if (typeof compare[0] === "number") {
        const d = distributionOf(compare as number[]);
        return sortedPercentiles.map((p) => quantile(d, p / 100));
      }
      const d = distributionOf(undefined, compare as LatencyBucket[]);
      return sortedPercentiles.map((p) => quantile(d, p / 100));
    })();
    const factor = total ? dist.total / total : 0;
    return {
      counts,
      total,
      scaled: counts.map((c) => c * factor),
      percentiles: percentilesOf,
    };
  }, [compare, bars, dist.total, sortedPercentiles]);

  const maxCount = Math.max(
    1,
    ...bars.map((b) => b.count),
    ...(comparison?.scaled ?? [0]),
  );
  // The tallest bar fills the plot; gridlines sit at round counts below it.
  const yMax = maxCount * 1.06;
  const yStep = niceStep(maxCount / 3.2);
  const yTicks = Array.from(
    { length: Math.floor(yMax / yStep + 1e-9) + 1 },
    (_, i) => tidy(i * yStep),
  );

  const over = hasThreshold ? countAbove(dist, threshold!) : 0;
  const overShare = dist.total ? over / dist.total : 0;
  const thresholdX = hasThreshold ? pos(threshold!) : 1;

  const cumulative = React.useMemo(() => {
    let running = 0;
    return bars.map((b) => (running += b.count) / (dist.total || 1));
  }, [bars, dist.total]);

  const bucketAt = (index: number): LatencyHistogramBucket => {
    const b = bars[index];
    return {
      index,
      start: b.start,
      end: b.end,
      count: b.count,
      share: dist.total ? b.count / dist.total : 0,
      cumulative: cumulative[index] ?? 0,
      compare: comparison ? comparison.counts[index] : undefined,
      compareShare: comparison?.total
        ? comparison.counts[index] / comparison.total
        : undefined,
      overflow: b.overflow,
      overThreshold: hasThreshold && b.start >= threshold!,
    };
  };

  /* -------------------------------------------------------------- layout */

  const plotRef = React.useRef<HTMLDivElement>(null);
  const [width, setWidth] = React.useState(0);
  React.useLayoutEffect(() => {
    const el = plotRef.current;
    if (!el) return;
    const measure = () => setWidth(el.clientWidth);
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(el);
    return () => observer.disconnect();
  }, []);
  const W = width || 560;

  // Percentile chips stack into lanes only when they would collide.
  // With the summary on show, crowded chips drop their values, which the summary repeats.
  const chips = React.useMemo(() => {
    const place = (withValue: boolean) => {
      const lanes: number[] = [];
      return marks.map((mark) => {
        const text = withValue
          ? `${percentileName(mark.p)} ${format(mark.value)}`
          : percentileName(mark.p);
        const w = text.length * 6.1 + 14;
        const x = pos(mark.value) * W;
        const left = Math.min(Math.max(0, x - w / 2), Math.max(0, W - w));
        let lane = lanes.findIndex((right) => right + 4 <= left);
        if (lane < 0) lane = lanes.push(0) - 1;
        lanes[lane] = left + w;
        return { ...mark, x, left, lane, w, withValue };
      });
    };
    const full = place(true);
    if (!showSummary || full.every((chip) => chip.lane === 0)) return full;
    return place(false);
  }, [marks, pos, W, format, showSummary]);
  const laneCount = Math.max(1, ...chips.map((chip) => chip.lane + 1));
  const chipTop = laneCount * 20 + 6;
  // Without a fixed height the plot follows the card width, shorter on narrow cards.
  const H = Math.max(
    80,
    height ?? Math.round(Math.min(220, Math.max(140, W * 0.34))),
  );
  const barsHeight = H - chipTop;

  const xTicks = React.useMemo(() => {
    const ticks: number[] = [];
    if (empty) return ticks;
    if (scale === "log" || dist.buckets) {
      if (scale === "log") {
        const lo = layout.lo;
        const hi = layout.hi;
        const candidates: number[] = [];
        for (
          let e = Math.floor(Math.log10(lo));
          e <= Math.ceil(Math.log10(hi));
          e++
        )
          for (const m of [1, 2, 5]) {
            const v = tidy(m * 10 ** e);
            if (v >= lo * 0.999 && v <= hi * 1.001) candidates.push(v);
          }
        // Thin out 2s and then 5s until labels have room.
        for (const keep of [[1, 2, 5], [1, 5], [1]]) {
          const list = candidates.filter((v) =>
            keep.includes(
              Math.round(v / 10 ** Math.floor(Math.log10(v) + 1e-9)),
            ),
          );
          let ok = true;
          for (let i = 1; i < list.length; i++)
            if ((pos(list[i]) - pos(list[i - 1])) * W < 44) ok = false;
          if (ok || keep.length === 1) return list;
        }
      }
    }
    const lo = layout.lo;
    const hi = layout.hi;
    const step = niceStep((hi - lo) / Math.max(2, Math.floor(W / 76)));
    for (
      let v = Math.ceil(lo / step - 1e-9) * step;
      v <= hi + step * 1e-6;
      v += step
    )
      ticks.push(tidy(v));
    return ticks;
  }, [scale, dist.buckets, layout, pos, W, empty]);

  /* ----------------------------------------------------------- animation */

  // Bars grow in on mount and whenever the bucket layout changes; data updates tween.
  // Keyed on scale and bar count only, so live data with a drifting tail tweens instead of regrowing.
  const structure = `${scale}:${bars.length}`;
  const [grown, setGrown] = React.useState<string | null>(null);
  const [intro, setIntro] = React.useState(true);
  React.useEffect(() => {
    if (reduced) {
      setGrown(structure);
      setIntro(false);
      return;
    }
    setIntro(true);
    let frame = requestAnimationFrame(() => {
      frame = requestAnimationFrame(() => setGrown(structure));
    });
    const timer = window.setTimeout(
      () => setIntro(false),
      900 + bars.length * 9,
    );
    return () => {
      cancelAnimationFrame(frame);
      window.clearTimeout(timer);
    };
  }, [structure, reduced, bars.length]);
  const isGrown = grown === structure;

  /* --------------------------------------------------------- interaction */

  const [hover, setHover] = React.useState<number | null>(null);
  const [active, setActive] = React.useState<number | null>(null);
  const [brush, setBrush] = React.useState<LatencyRange | null>(null);
  const drag = React.useRef<{
    x: number;
    value: number;
    moved: boolean;
  } | null>(null);
  const anchor = React.useRef<number | null>(null);

  const xToFraction = (clientX: number) => {
    const rect = plotRef.current!.getBoundingClientRect();
    return Math.min(1, Math.max(0, (clientX - rect.left) / (rect.width || 1)));
  };
  const barAt = (x: number) => {
    for (let i = 0; i < bars.length; i++)
      if (x >= bars[i].x0 && x <= bars[i].x1) return i;
    // In a gap: the nearest bar.
    let best = -1;
    let distance = Infinity;
    bars.forEach((b, i) => {
      const dd = Math.min(Math.abs(x - b.x0), Math.abs(x - b.x1));
      if (dd < distance) {
        distance = dd;
        best = i;
      }
    });
    return best < 0 ? null : best;
  };

  const clampRange = (a: number, b: number): LatencyRange => [
    Math.min(a, b),
    Math.max(a, b),
  ];

  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
    if (event.button !== 0 || !bars.length) return;
    const x = xToFraction(event.clientX);
    drag.current = { x: event.clientX, value: inv(x), moved: false };
    event.currentTarget.setPointerCapture(event.pointerId);
  };
  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
    if (!bars.length) return;
    const x = xToFraction(event.clientX);
    const d = drag.current;
    if (d) {
      if (!d.moved && Math.abs(event.clientX - d.x) > 3) d.moved = true;
      if (d.moved) {
        setBrush(clampRange(d.value, inv(x)));
        setHover(null);
        return;
      }
    }
    setHover(barAt(x));
  };
  const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
    const d = drag.current;
    drag.current = null;
    if (!d) return;
    if (d.moved) {
      const next = clampRange(d.value, inv(xToFraction(event.clientX)));
      setBrush(null);
      setRange(next[1] - next[0] > 0 ? next : null);
    } else if (range) setRange(null);
  };

  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    if (!bars.length) return;
    const current = active ?? -1;
    const step = (delta: number) =>
      Math.min(
        bars.length - 1,
        Math.max(
          0,
          current < 0 ? (delta > 0 ? 0 : bars.length - 1) : current + delta,
        ),
      );
    let next: number | null = null;
    if (event.key === "ArrowRight") next = step(1);
    else if (event.key === "ArrowLeft") next = step(-1);
    else if (event.key === "Home") next = 0;
    else if (event.key === "End") next = bars.length - 1;
    else if (event.key === "Enter" && current >= 0) {
      setRange([bars[current].start, bars[current].end]);
      event.preventDefault();
      return;
    } else if (event.key === "Escape") {
      if (range) setRange(null);
      else setActive(null);
      anchor.current = null;
      event.preventDefault();
      return;
    }
    if (next == null) return;
    event.preventDefault();
    if (event.shiftKey) {
      if (anchor.current == null) anchor.current = current < 0 ? next : current;
      const a = Math.min(anchor.current, next);
      const b = Math.max(anchor.current, next);
      setRange([bars[a].start, bars[b].end]);
    } else anchor.current = null;
    setActive(next);
  };

  const shownRange = brush ?? range;
  const rangeCount = shownRange
    ? countBetween(dist, shownRange[0], shownRange[1])
    : 0;
  const rangeShare = dist.total ? rangeCount / dist.total : 0;
  const focusIndex = hover ?? active;
  const focusBucket =
    focusIndex != null && bars[focusIndex] ? bucketAt(focusIndex) : null;

  /* -------------------------------------------------------------- render */

  const describeBucket = (b: LatencyHistogramBucket) =>
    `${b.overflow ? `${format(b.start)} and above` : `${format(b.start)} to ${format(b.end)}`}: ${whole.format(Math.round(b.count))} requests, ${percentLabel(b.share)}`;
  const summaryText = [
    `${whole.format(Math.round(dist.total))} requests.`,
    marks
      .map((mark) => `${percentileName(mark.p)} ${format(mark.value)}`)
      .join(", ") + ".",
    hasThreshold
      ? `${percentLabel(overShare)} over the ${thresholdLabel} of ${format(threshold!)}.`
      : "",
  ]
    .filter(Boolean)
    .join(" ");
  const hasHeader =
    title != null || description != null || actions != null || showScaleToggle;
  const transition = intro
    ? "transform 760ms cubic-bezier(.16,1,.3,1)"
    : "transform 520ms cubic-bezier(.16,1,.3,1)";
  const barFill = (color: string) =>
    `color-mix(in oklab, ${color} 72%, var(--color-card))`;

  // The comparison as one stepped path across the bars.
  const comparePath = React.useMemo(() => {
    if (!comparison || compareStyle !== "step") return null;
    let path = "";
    let previousEnd = -1;
    bars.forEach((b, i) => {
      const y = 100 - (comparison.scaled[i] / yMax) * 100;
      const x0 = b.x0 * 1000;
      const x1 = b.x1 * 1000;
      if (Math.abs(x0 - previousEnd) > 0.5)
        path += `${path ? "V100" : ""}M${x0.toFixed(2)} 100`;
      path += `V${y.toFixed(2)}H${x1.toFixed(2)}`;
      previousEnd = x1;
    });
    return path + "V100";
  }, [comparison, compareStyle, bars, yMax]);

  return (
    <div
      data-slot="latency-histogram"
      data-scale={scale}
      data-brushing={brush ? true : undefined}
      className={cn(
        "@container/histogram flex min-w-0 flex-col rounded-xl border bg-card text-card-foreground shadow-xs",
        className,
      )}
      {...props}
    >
      {hasHeader && (
        <div className="flex items-start gap-3 px-4 pt-3.5">
          <div className="min-w-0 flex-1 space-y-1">
            {title != null && (
              <h3 className="truncate text-sm leading-6 font-semibold tracking-tight">
                {title}
              </h3>
            )}
            {description != null && (
              <p
                id={`${id}-description`}
                className="text-xs text-muted-foreground"
              >
                {description}
              </p>
            )}
          </div>
          <div className="flex shrink-0 items-center gap-2">
            {actions}
            {showScaleToggle && (
              <div
                role="group"
                aria-label="X axis scale"
                data-slot="histogram-scale-toggle"
                className="inline-flex h-7 items-center rounded-md border bg-muted/40 p-0.5"
              >
                {(["linear", "log"] as const).map((option) => (
                  <button
                    key={option}
                    type="button"
                    aria-pressed={scale === option}
                    onClick={() => setScale(option)}
                    className={cn(
                      "h-full rounded-[5px] px-2 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground aria-pressed:bg-card aria-pressed:text-foreground aria-pressed:shadow-xs motion-reduce:transition-none",
                      focusRing,
                    )}
                  >
                    {option === "linear" ? "Linear" : "Log"}
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>
      )}

      {showSummary && (marks.length > 0 || hasThreshold) && (
        // Narrow cards trade the stat grid for one line, so the distribution stays in view.
        <dl
          data-slot="histogram-summary-compact"
          className={cn(
            "mx-4 flex flex-wrap items-baseline gap-x-3 gap-y-1 text-xs @md/histogram:hidden",
            hasHeader ? "mt-1.5" : "mt-4",
          )}
        >
          {marks.map((mark, i) => {
            const previous = comparison?.percentiles[i];
            const delta = previous != null ? mark.value - previous : null;
            const hot = hasThreshold && mark.value > threshold!;
            return (
              <div key={mark.p} className="flex items-baseline gap-1">
                <dt className="font-mono text-[11px] text-muted-foreground">
                  {percentileName(mark.p)}
                </dt>
                <dd
                  className={cn(
                    "font-semibold tabular-nums",
                    hot && "text-destructive",
                  )}
                >
                  {format(mark.value)}
                </dd>
                {delta != null && Math.abs(delta) > 0 && (
                  <dd
                    className={cn(
                      "font-mono text-[10px] tabular-nums",
                      delta > 0
                        ? "text-destructive"
                        : "text-emerald-700 dark:text-emerald-400",
                    )}
                  >
                    {delta > 0 ? "▲" : "▼"}
                    {format(Math.abs(delta))}
                  </dd>
                )}
              </div>
            );
          })}
          {hasThreshold && (
            <div className="flex items-baseline gap-1">
              <dd
                className={cn(
                  "font-semibold tabular-nums",
                  over > 0
                    ? "text-destructive"
                    : "text-emerald-700 dark:text-emerald-400",
                )}
              >
                {percentLabel(overShare)}
              </dd>
              <dt className="text-[11px] text-muted-foreground">
                over {thresholdLabel}
              </dt>
            </div>
          )}
        </dl>
      )}

      {showSummary && (marks.length > 0 || hasThreshold) && (
        <dl
          data-slot="histogram-summary"
          className={cn(
            "mx-4 hidden overflow-hidden rounded-lg bg-muted/50 @md/histogram:grid dark:bg-muted/30",
            hasHeader ? "mt-3" : "mt-4",
          )}
          style={{
            gridTemplateColumns: `repeat(${marks.length + (hasThreshold ? 1 : 0)}, minmax(0, 1fr))`,
          }}
        >
          {marks.map((mark, i) => {
            const previous = comparison?.percentiles[i];
            const delta = previous != null ? mark.value - previous : null;
            const hot = hasThreshold && mark.value > threshold!;
            return (
              <div
                key={mark.p}
                className="min-w-0 border-s border-border/60 px-2 py-1.5 first:border-s-0 @sm/histogram:px-2.5 @md/histogram:px-3 @md/histogram:py-2"
              >
                <dt className="font-mono text-[11px] leading-4 text-muted-foreground">
                  {percentileName(mark.p)}
                </dt>
                <dd
                  className={cn(
                    "truncate text-sm leading-6 font-semibold tracking-tight tabular-nums @sm/histogram:text-base @md/histogram:text-lg",
                    hot && "text-destructive",
                  )}
                >
                  {format(mark.value)}
                </dd>
                {delta != null && Math.abs(delta) > 0 && (
                  <dd
                    className={cn(
                      "truncate font-mono text-[11px] leading-4 whitespace-nowrap tabular-nums",
                      delta > 0
                        ? "text-destructive"
                        : "text-emerald-700 dark:text-emerald-400",
                    )}
                    title={`${compareLabel}: ${format(previous!)}`}
                  >
                    {delta > 0 ? "▲" : "▼"} {format(Math.abs(delta))}
                  </dd>
                )}
              </div>
            );
          })}
          {hasThreshold && (
            <div className="min-w-0 border-s border-border/60 px-2 py-1.5 first:border-s-0 @sm/histogram:px-2.5 @md/histogram:px-3 @md/histogram:py-2">
              <dt className="truncate text-[11px] leading-4 text-muted-foreground">
                Over {thresholdLabel}
              </dt>
              <dd
                className={cn(
                  "truncate text-sm leading-6 font-semibold tracking-tight tabular-nums @sm/histogram:text-base @md/histogram:text-lg",
                  over > 0
                    ? "text-destructive"
                    : "text-emerald-700 dark:text-emerald-400",
                )}
              >
                {percentLabel(overShare)}
              </dd>
              <dd className="truncate font-mono text-[11px] leading-4 text-muted-foreground tabular-nums">
                {whole.format(Math.round(over))}
                <span className="hidden @sm/histogram:inline">
                  {" "}
                  of {compact.format(dist.total).replace("K", "k")}
                </span>
              </dd>
            </div>
          )}
        </dl>
      )}

      <div className="mt-3 flex px-4 @md/histogram:mt-4">
        <div className="min-w-0 flex-1">
          <div
            ref={plotRef}
            data-slot="histogram-plot"
            role="group"
            aria-roledescription="histogram"
            aria-label={`${typeof title === "string" ? `${title}. ` : ""}${summaryText} Use the arrow keys to read buckets, Shift to select a range.`}
            aria-describedby={
              description != null ? `${id}-description` : undefined
            }
            tabIndex={0}
            onPointerDown={onPointerDown}
            onPointerMove={onPointerMove}
            onPointerUp={onPointerUp}
            onPointerCancel={() => {
              drag.current = null;
              setBrush(null);
            }}
            onPointerLeave={() => {
              if (!drag.current) setHover(null);
            }}
            onKeyDown={onKeyDown}
            onBlur={() => setActive(null)}
            className={cn(
              "relative cursor-crosshair touch-pan-y rounded-sm select-none",
              "outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-4 focus-visible:ring-offset-card",
            )}
            style={{ height: H }}
          >
            {empty && (
              <p className="absolute inset-0 grid place-items-center text-xs text-muted-foreground">
                No requests to show.
              </p>
            )}

            {/* Value grid */}
            <div
              aria-hidden="true"
              className="pointer-events-none absolute inset-x-0 bottom-0"
              style={{ top: chipTop }}
            >
              {yTicks.map((tick) => (
                <span
                  key={tick}
                  className={cn(
                    "absolute inset-x-0 h-px",
                    tick === 0 ? "bg-border" : "bg-border/55",
                  )}
                  style={{ bottom: `${(tick / yMax) * 100}%` }}
                />
              ))}
            </div>

            {/* SLO tail */}
            {hasThreshold && thresholdX < 1 && (
              <div
                aria-hidden="true"
                data-slot="histogram-threshold-region"
                className="pointer-events-none absolute inset-y-0 right-0"
                style={{
                  left: `${thresholdX * 100}%`,
                  background: `linear-gradient(to bottom, color-mix(in oklab, ${colors.threshold} 9%, transparent), color-mix(in oklab, ${colors.threshold} 3%, transparent)), repeating-linear-gradient(-45deg, color-mix(in oklab, ${colors.threshold} 9%, transparent) 0 1px, transparent 1px 6px)`,
                }}
              />
            )}

            {/* Bars */}
            <div
              aria-hidden="true"
              className="pointer-events-none absolute inset-x-0 bottom-0"
              style={{ top: chipTop }}
            >
              {comparison &&
                compareStyle === "outline" &&
                bars.map((b, i) => (
                  <span
                    key={`c-${structure}-${i}`}
                    className="absolute bottom-0 origin-bottom rounded-t-[2px] border border-b-0 border-dashed"
                    style={{
                      left: `calc(${b.x0 * 100}% + 1px)`,
                      width: `calc(${(b.x1 - b.x0) * 100}% - 2px)`,
                      height: `${(comparison.scaled[i] / yMax) * 100}%`,
                      borderColor: `color-mix(in oklab, ${colors.compare} 70%, transparent)`,
                      transform: `scaleY(${isGrown ? 1 : 0})`,
                      transition: reduced ? undefined : transition,
                    }}
                  />
                ))}
              {bars.map((b, i) => {
                const h = b.count / yMax;
                const inRange = shownRange
                  ? b.end > shownRange[0] && b.start < shownRange[1]
                  : true;
                const dim =
                  (focusIndex != null && focusIndex !== i) || !inRange;
                const split =
                  hasThreshold && b.start < threshold! && b.end > threshold!;
                const hot = hasThreshold && b.start >= threshold!;
                const color = hot ? colors.threshold : colors.bar;
                const cut = split
                  ? ((thresholdX - b.x0) / (b.x1 - b.x0)) * 100
                  : 0;
                const fill = split
                  ? `linear-gradient(to right, ${barFill(colors.bar)} ${cut}%, ${barFill(colors.threshold)} ${cut}%)`
                  : barFill(color);
                const cap = split
                  ? `linear-gradient(to right, ${colors.bar} ${cut}%, ${colors.threshold} ${cut}%)`
                  : color;
                return (
                  <span
                    key={`${structure}-${i}`}
                    data-slot="histogram-bar"
                    data-index={i}
                    data-over={hot || undefined}
                    data-overflow={b.overflow || undefined}
                    className={cn(
                      "absolute inset-y-0 transition-opacity duration-200 motion-reduce:transition-none",
                      dim &&
                        (shownRange && !inRange ? "opacity-30" : "opacity-55"),
                    )}
                    style={{
                      left: `${b.x0 * 100}%`,
                      width: `${(b.x1 - b.x0) * 100}%`,
                    }}
                  >
                    <span
                      className="absolute inset-x-px bottom-0 h-full origin-bottom @lg/histogram:inset-x-[1.5px]"
                      style={{
                        transform: `scaleY(${isGrown ? h : 0})`,
                        transition: reduced ? undefined : transition,
                        transitionDelay:
                          intro && !reduced ? `${i * 9}ms` : undefined,
                      }}
                    >
                      <span
                        className={cn(
                          "absolute inset-0 rounded-t-[2px]",
                          b.overflow &&
                            "[mask-image:repeating-linear-gradient(-45deg,#000_0_3px,rgb(0_0_0/0.55)_3px_5px)]",
                        )}
                        style={{ background: fill }}
                      />
                    </span>
                    {/* The cap is drawn unscaled so it stays a crisp line at any height. */}
                    {b.count > 0 && (
                      <span
                        className="absolute inset-x-px h-[1.5px] rounded-full @lg/histogram:inset-x-[1.5px]"
                        style={{
                          bottom: `calc(${(isGrown ? h : 0) * 100}% - 1px)`,
                          background: cap,
                          transition: reduced
                            ? undefined
                            : intro
                              ? "bottom 760ms cubic-bezier(.16,1,.3,1)"
                              : "bottom 520ms cubic-bezier(.16,1,.3,1)",
                          transitionDelay:
                            intro && !reduced ? `${i * 9}ms` : undefined,
                        }}
                      />
                    )}
                  </span>
                );
              })}
              {comparePath && (
                <svg
                  data-slot="histogram-compare"
                  className="absolute inset-0 size-full origin-bottom overflow-visible"
                  viewBox="0 0 1000 100"
                  preserveAspectRatio="none"
                  style={{
                    transform: `scaleY(${isGrown ? 1 : 0})`,
                    transition: reduced ? undefined : transition,
                  }}
                >
                  <path
                    d={comparePath}
                    fill="none"
                    stroke={colors.compare}
                    strokeWidth={1.5}
                    strokeDasharray="4 3"
                    strokeLinejoin="round"
                    vectorEffect="non-scaling-stroke"
                    opacity={0.85}
                  />
                </svg>
              )}
            </div>

            {/* Selection */}
            {shownRange && (
              <div
                aria-hidden="true"
                data-slot="histogram-selection"
                className="pointer-events-none absolute inset-y-0"
                style={{
                  left: `${pos(shownRange[0]) * 100}%`,
                  width: `${Math.max(0, pos(shownRange[1]) - pos(shownRange[0])) * 100}%`,
                  background: `color-mix(in oklab, ${colors.selection} 9%, transparent)`,
                  boxShadow: `inset 1.5px 0 0 ${colors.selection}, inset -1.5px 0 0 ${colors.selection}`,
                }}
              >
                <span
                  className="absolute top-1/2 -left-[3px] h-5 w-1.5 -translate-y-1/2 rounded-full border border-card"
                  style={{ background: colors.selection }}
                />
                <span
                  className="absolute top-1/2 -right-[3px] h-5 w-1.5 -translate-y-1/2 rounded-full border border-card"
                  style={{ background: colors.selection }}
                />
              </div>
            )}

            {/* Threshold line */}
            {hasThreshold && thresholdX < 1 && (
              <div
                aria-hidden="true"
                data-slot="histogram-threshold"
                className="pointer-events-none absolute bottom-0"
                style={{ left: `${thresholdX * 100}%`, top: chipTop - 2 }}
              >
                <span
                  className="absolute inset-y-0 w-0 border-l-[1.5px] border-dashed"
                  style={{ borderColor: colors.threshold }}
                />
                <span
                  className="absolute top-1 left-1 rounded-sm bg-card/85 px-1 font-mono text-[10px] leading-4 font-medium whitespace-nowrap"
                  style={{ color: colors.threshold }}
                >
                  {thresholdLabel} {format(threshold!)}
                </span>
              </div>
            )}

            {/* Percentile markers */}
            {chips.map((chip) => {
              const hot = hasThreshold && chip.value > threshold!;
              const color = hot ? colors.threshold : colors.marker;
              return (
                <div
                  key={chip.p}
                  data-slot="histogram-marker"
                  data-percentile={chip.p}
                  aria-hidden="true"
                  className="pointer-events-none"
                >
                  <span
                    className="absolute bottom-0 w-0 border-l border-dashed opacity-55"
                    style={{
                      left: chip.x,
                      top: chip.lane * 20 + 18,
                      borderColor: color,
                    }}
                  />
                  <span
                    className={cn(
                      "absolute flex h-[18px] items-center gap-1 rounded-[5px] border bg-card px-1.5 font-mono text-[10px] leading-none whitespace-nowrap shadow-xs tabular-nums",
                      intro &&
                        !reduced &&
                        "motion-safe:animate-[histogram-rise_.5s_.35s_cubic-bezier(.16,1,.3,1)_both]",
                    )}
                    style={{
                      left: chip.left,
                      top: chip.lane * 20,
                      borderColor: `color-mix(in oklab, ${color} 28%, var(--color-border))`,
                    }}
                  >
                    <span className="text-muted-foreground">
                      {percentileName(chip.p)}
                    </span>
                    {chip.withValue && (
                      <span className="font-semibold" style={{ color }}>
                        {format(chip.value)}
                      </span>
                    )}
                  </span>
                </div>
              );
            })}

            {/* Tooltip */}
            {focusBucket && !brush && (
              <div
                data-slot="histogram-tooltip"
                aria-hidden="true"
                className="pointer-events-none absolute z-10 min-w-36 rounded-lg border bg-popover px-2.5 py-2 text-xs text-popover-foreground shadow-md"
                style={{
                  top: chipTop + 4,
                  // Sit beside the bar, on the side with more room, so it never hides it.
                  ...(bars[focusBucket.index].x0 + bars[focusBucket.index].x1 <
                  1
                    ? { left: bars[focusBucket.index].x1 * W + 8 }
                    : { right: W - bars[focusBucket.index].x0 * W + 8 }),
                }}
              >
                {renderTooltip ? (
                  renderTooltip(focusBucket)
                ) : (
                  <>
                    <p className="font-mono text-[11px] text-muted-foreground tabular-nums">
                      {focusBucket.overflow
                        ? `≥ ${format(focusBucket.start)}`
                        : `${format(focusBucket.start)} – ${format(focusBucket.end)}`}
                    </p>
                    <p className="mt-0.5 flex items-baseline gap-1.5">
                      <span className="text-sm font-semibold tabular-nums">
                        {whole.format(Math.round(focusBucket.count))}
                      </span>
                      <span className="text-muted-foreground tabular-nums">
                        {percentLabel(focusBucket.share)}
                      </span>
                    </p>
                    <p className="mt-1 text-[11px] text-muted-foreground tabular-nums">
                      {percentLabel(focusBucket.cumulative)} at or faster
                    </p>
                    {focusBucket.compare != null && comparison && (
                      <p className="mt-1.5 flex items-center gap-1.5 border-t border-dashed pt-1.5 text-[11px] text-muted-foreground tabular-nums">
                        <span
                          aria-hidden="true"
                          className="w-3 border-t-[1.5px] border-dashed"
                          style={{ borderColor: colors.compare }}
                        />
                        {compareLabel}
                        <span className="ml-auto font-medium text-foreground">
                          {whole.format(Math.round(focusBucket.compare))}
                        </span>
                        <span>
                          {percentLabel(focusBucket.compareShare ?? 0)}
                        </span>
                      </p>
                    )}
                  </>
                )}
              </div>
            )}
          </div>

          {/* Latency axis */}
          <div
            aria-hidden="true"
            className="relative mt-1.5 h-4 font-mono text-[10px] leading-4 text-muted-foreground tabular-nums"
          >
            {xTicks.map((tick, i) => {
              const x = pos(tick);
              if (x > layout.pos(layout.hi) + 1e-6) return null;
              return (
                <span
                  key={tick}
                  className={cn(
                    "absolute whitespace-nowrap",
                    i === 0 && x < 0.02
                      ? ""
                      : x > 0.97
                        ? "-translate-x-full"
                        : "-translate-x-1/2",
                  )}
                  style={{ left: `${x * 100}%` }}
                >
                  {formatTick(tick)}
                </span>
              );
            })}
            {bars[bars.length - 1]?.overflow && (
              <span
                className="absolute -translate-x-1/2 whitespace-nowrap"
                style={{
                  left: `${((bars[bars.length - 1].x0 + 1) / 2) * 100}%`,
                }}
              >
                +
              </span>
            )}
          </div>
        </div>
        <div
          aria-hidden="true"
          className="relative ml-2 w-8 shrink-0"
          style={{ height: H }}
        >
          {yTicks.map((tick) => (
            <span
              key={tick}
              className="absolute right-0 translate-y-1/2 font-mono text-[10px] leading-none text-muted-foreground tabular-nums"
              style={{ bottom: `${(tick / yMax) * (barsHeight / H) * 100}%` }}
            >
              {tick === 0 ? "0" : compact.format(tick).replace("K", "k")}
            </span>
          ))}
        </div>
      </div>

      <div
        data-slot="histogram-footer"
        className="mt-3 flex min-h-11 flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t px-4 py-2"
      >
        <div
          data-slot="histogram-status"
          className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 text-xs"
        >
          {shownRange ? (
            <>
              <span
                className="rounded-[4px] px-1.5 py-px font-mono text-[11px] tabular-nums"
                style={{
                  background: `color-mix(in oklab, ${colors.selection} 10%, transparent)`,
                  color: colors.selection,
                }}
              >
                {format(shownRange[0])} – {format(shownRange[1])}
              </span>
              <span className="font-semibold tabular-nums">
                {percentLabel(rangeShare)}
              </span>
              <span className="text-muted-foreground tabular-nums">
                {whole.format(Math.round(rangeCount))} of{" "}
                {whole.format(Math.round(dist.total))} requests
              </span>
              {!brush && (
                <button
                  type="button"
                  onClick={() => setRange(null)}
                  className={cn(
                    "inline-flex size-5 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground",
                    focusRing,
                  )}
                >
                  <X className="size-3.5" aria-hidden="true" />
                  <span className="sr-only">Clear selection</span>
                </button>
              )}
            </>
          ) : (
            <span className="text-muted-foreground tabular-nums">
              <span className="font-medium text-foreground">
                {whole.format(Math.round(dist.total))}
              </span>{" "}
              requests
              <span aria-hidden="true"> · </span>mean{" "}
              <span className="font-medium text-foreground">
                {format(dist.mean)}
              </span>
              <span className="hidden @md/histogram:inline">
                <span aria-hidden="true"> · </span>max{" "}
                <span className="font-medium text-foreground">
                  {format(dist.max)}
                </span>
              </span>
              <span className="hidden @lg/histogram:inline">
                {" "}
                · drag to measure a range
              </span>
            </span>
          )}
        </div>
        {comparison && (
          <div
            data-slot="histogram-legend"
            className="flex items-center gap-3 text-[11px] text-muted-foreground"
          >
            <span className="flex items-center gap-1.5">
              <span
                aria-hidden="true"
                className="size-2.5 rounded-[2px]"
                style={{
                  background: barFill(colors.bar),
                  boxShadow: `inset 0 1.5px 0 ${colors.bar}`,
                }}
              />
              {seriesLabel}
            </span>
            <span className="flex items-center gap-1.5">
              <span
                aria-hidden="true"
                className="w-3.5 border-t-[1.5px] border-dashed"
                style={{ borderColor: colors.compare }}
              />
              {compareLabel}
            </span>
          </div>
        )}
      </div>

      <div className="sr-only">
        <table>
          <caption>{summaryText}</caption>
          <thead>
            <tr>
              <th scope="col">Latency</th>
              <th scope="col">Requests</th>
              {comparison && <th scope="col">{compareLabel}</th>}
            </tr>
          </thead>
          <tbody>
            {bars.map((b, i) =>
              b.count > 0 || comparison?.counts[i] ? (
                <tr key={i}>
                  <th scope="row">
                    {b.overflow
                      ? `${format(b.start)} and above`
                      : `${format(b.start)} to ${format(b.end)}`}
                  </th>
                  <td>{whole.format(Math.round(b.count))}</td>
                  {comparison && (
                    <td>{whole.format(Math.round(comparison.counts[i]))}</td>
                  )}
                </tr>
              ) : null,
            )}
          </tbody>
        </table>
      </div>
      <p className="sr-only" aria-live="polite">
        {active != null && bars[active]
          ? describeBucket(bucketAt(active))
          : range
            ? `Selected ${format(range[0])} to ${format(range[1])}: ${percentLabel(dist.total ? countBetween(dist, range[0], range[1]) / dist.total : 0)} of requests.`
            : ""}
      </p>

      <style href="overtrue-latency-histogram" precedence="default">
        {`@keyframes histogram-rise{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}`}
      </style>
    </div>
  );
}
```

### `src/registry/overtrue/json-viewer.tsx`

Left out to keep this page a readable size (54,004 characters). It is in the registry item above.
