{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "service-map",
  "type": "registry:component",
  "title": "Service map",
  "description": "A live dependency map laid out as a layered graph, with traffic flowing along edges sized by request rate and colored by error rate.",
  "categories": [
    "operations"
  ],
  "dependencies": [
    "@tabler/icons-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/service-map.tsx",
      "type": "registry:component",
      "target": "components/overtrue/service-map.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconBolt,\n  IconCloud,\n  IconDatabase,\n  IconRoute,\n  IconServer,\n  IconStack2,\n  IconWorld,\n  IconX,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* ------------------------------------------------------------------------ */\n/* Types                                                                     */\n/* ------------------------------------------------------------------------ */\n\nexport type ServiceKind =\n  | \"client\"\n  | \"gateway\"\n  | \"service\"\n  | \"database\"\n  | \"cache\"\n  | \"queue\"\n  | \"external\";\n\nexport type ServiceStatus = \"healthy\" | \"degraded\" | \"down\";\n\nexport interface ServiceMetrics {\n  /** Requests per second. */\n  rps?: number;\n  /** Share of failed requests as a 0–1 fraction, e.g. 0.012 for 1.2%. */\n  errorRate?: number;\n  /** 95th percentile latency in milliseconds. */\n  p95?: number;\n}\n\nexport interface ServiceMapNode {\n  id: string;\n  label: string;\n  kind?: ServiceKind;\n  /** Health. Defaults to healthy, or degraded when the error rate crosses the critical threshold. */\n  status?: ServiceStatus;\n  metrics?: ServiceMetrics;\n  /** Team, namespace or region. Shown in the detail readout. */\n  group?: string;\n  /** Replaces the icon picked from `kind`. */\n  icon?: React.ReactNode;\n}\n\nexport interface ServiceMapEdge {\n  id?: string;\n  /** Id of the calling node. */\n  source: string;\n  /** Id of the called node. */\n  target: string;\n  rps?: number;\n  /** Share of failed calls as a 0–1 fraction. */\n  errorRate?: number;\n  /** 95th percentile latency in milliseconds. */\n  p95?: number;\n  /** Overrides the color picked from the error rate. */\n  status?: ServiceStatus;\n}\n\nexport interface ServiceMapThresholds {\n  /** Error rate, as a 0–1 fraction, at which traffic turns amber. Defaults to 0.01. */\n  warn?: number;\n  /** Error rate at which traffic turns destructive. Defaults to 0.05. */\n  critical?: number;\n}\n\n/** Everything known about a node, passed to `renderNode`. */\nexport interface ServiceMapNodeInfo {\n  kind: ServiceKind;\n  status: ServiceStatus;\n  /** Column (or row, top to bottom) the node was placed in, from 0. */\n  layer: number;\n  inbound: ServiceMapEdge[];\n  outbound: ServiceMapEdge[];\n  /** Hovered or focused. */\n  active: boolean;\n  selected: boolean;\n  /** Outside the paths of the hovered, focused or selected node. */\n  dimmed: boolean;\n  /** Metrics run through the formatters; missing metrics are undefined. */\n  formatted: { rps?: string; errorRate?: string; p95?: string };\n  /** The default icon for the node's kind, or its own `icon`. */\n  icon: React.ReactNode;\n}\n\nexport interface ServiceMapProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"onSelect\" | \"children\"\n> {\n  nodes: ServiceMapNode[];\n  edges: ServiceMapEdge[];\n  /** Flow left to right or top to bottom. Defaults to LR. */\n  direction?: \"LR\" | \"TB\";\n  /** Controlled selection. Pass null for none. */\n  selectedId?: string | null;\n  defaultSelectedId?: string | null;\n  onSelect?: (id: string | null, node: ServiceMapNode | null) => void;\n  /** Replaces the content of every node card. The card keeps its size, focus and status ring. */\n  renderNode?: (node: ServiceMapNode, info: ServiceMapNodeInfo) => React.ReactNode;\n  thresholds?: ServiceMapThresholds;\n  rpsFormatter?: (rps: number) => string;\n  latencyFormatter?: (ms: number) => string;\n  errorRateFormatter?: (rate: number) => string;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed at the top right. */\n  actions?: React.ReactNode;\n  /** Show the traffic legend. Defaults to true. */\n  showLegend?: boolean;\n  /** Animate traffic along the edges. Defaults to true; reduced motion shows static dashes. */\n  animate?: boolean;\n  /** Card size in pixels before scaling. Defaults to 148 × 60. */\n  nodeWidth?: number;\n  nodeHeight?: number;\n  /** Smallest scale used to fit the container; below it the map scrolls sideways. Defaults to 0.5. */\n  minScale?: number;\n  /**\n   * Full cards with a metrics line, or compact icon tiles with a label. \"auto\" switches\n   * to compact when cards would have to shrink below a readable size. Defaults to auto.\n   */\n  density?: \"auto\" | \"comfortable\" | \"compact\";\n}\n\n/* ------------------------------------------------------------------------ */\n/* Formatting                                                                */\n/* ------------------------------------------------------------------------ */\n\nfunction formatRps(rps: number) {\n  if (!Number.isFinite(rps)) return \"—\";\n  if (rps >= 1_000_000) return `${+(rps / 1_000_000).toFixed(1)}M rps`;\n  if (rps >= 1000) return `${+(rps / 1000).toFixed(rps >= 10_000 ? 0 : 1)}k rps`;\n  if (rps >= 10) return `${Math.round(rps)} rps`;\n  return `${+rps.toFixed(1)} rps`;\n}\n\nfunction formatErrorRate(rate: number) {\n  if (!Number.isFinite(rate)) return \"—\";\n  const pct = rate * 100;\n  if (pct === 0) return \"0%\";\n  if (pct < 0.1) return `${+pct.toFixed(2)}%`;\n  if (pct < 10) return `${+pct.toFixed(1)}%`;\n  return `${Math.round(pct)}%`;\n}\n\nfunction formatLatency(ms: number) {\n  if (!Number.isFinite(ms)) return \"—\";\n  if (ms < 10) return `${+ms.toFixed(1)} ms`;\n  if (ms < 1000) return `${Math.round(ms)} ms`;\n  return `${+(ms / 1000).toFixed(ms < 10_000 ? 2 : 1)} s`;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Layout                                                                    */\n/* ------------------------------------------------------------------------ */\n\ninterface Item {\n  id: string;\n  layer: number;\n  /** Center on the cross axis, in world pixels. */\n  pos: number;\n  size: number;\n  dummy: boolean;\n  /** Index in `nodes`, used to break ties so the layout follows data order. */\n  rank: number;\n  node?: ServiceMapNode;\n}\n\ninterface Route {\n  key: string;\n  edge: ServiceMapEdge;\n  index: number;\n  /** Item ids from the source to the target in layer order (target first for back edges). */\n  chain: string[];\n  reversed: boolean;\n}\n\ninterface Structure {\n  layers: Item[][];\n  items: Map<string, Item>;\n  routes: Route[];\n  layerOf: Map<string, number>;\n  /** Extent on the cross axis, center to center plus the node size. */\n  span: number;\n}\n\ninterface Point {\n  x: number;\n  y: number;\n}\n\ninterface PlacedEdge {\n  key: string;\n  edge: ServiceMapEdge;\n  index: number;\n  d: string;\n  length: number;\n  mid: Point;\n  start: Point;\n  end: Point;\n}\n\nconst NODE_GAP = 18;\nconst DUMMY_GAP = 12;\nconst PAD = 22;\nconst GAP_MIN = 28;\nconst GAP_MAX = 136;\nconst GAP_TB = 64;\nconst FALLBACK_WIDTH = 720;\nconst COMPACT_W = 76;\nconst COMPACT_TILE = 36;\nconst COMPACT_H = 56;\nconst COMPACT_PAD = 16;\nconst COMPACT_GAP_MIN = 10;\nconst COMPACT_GAP_TB = 40;\n/** Below this scale, \"auto\" density switches cards to compact tiles. */\nconst AUTO_COMPACT_BELOW = 0.62;\n\n/** Pool adjacent violators: positions as close to `desired` as the separations allow, order kept. */\nfunction project(desired: number[], separation: number[]) {\n  const n = desired.length;\n  const offset = new Array<number>(n).fill(0);\n  for (let i = 1; i < n; i++) offset[i] = offset[i - 1] + separation[i - 1];\n  const blocks: { sum: number; count: number; start: number }[] = [];\n  for (let i = 0; i < n; i++) {\n    blocks.push({ sum: desired[i] - offset[i], count: 1, start: i });\n    while (blocks.length > 1) {\n      const b = blocks[blocks.length - 1];\n      const a = blocks[blocks.length - 2];\n      if (a.sum / a.count <= b.sum / b.count) break;\n      a.sum += b.sum;\n      a.count += b.count;\n      blocks.pop();\n    }\n  }\n  const out = new Array<number>(n);\n  blocks.forEach((block, i) => {\n    const end = i + 1 < blocks.length ? blocks[i + 1].start : n;\n    for (let j = block.start; j < end; j++)\n      out[j] = block.sum / block.count + offset[j];\n  });\n  return out;\n}\n\nfunction buildStructure(\n  nodes: ServiceMapNode[],\n  edges: ServiceMapEdge[],\n  crossSize: number,\n  nodeGap = NODE_GAP,\n): Structure {\n  const known = new Map(nodes.map((node, i) => [node.id, i]));\n  const valid = edges\n    .map((edge, index) => ({ edge, index }))\n    .filter(\n      ({ edge }) =>\n        known.has(edge.source) &&\n        known.has(edge.target) &&\n        edge.source !== edge.target,\n    );\n\n  // Break cycles: edges that close a loop in a depth-first walk are laid out reversed.\n  const out = new Map<string, number[]>();\n  const indegree = new Map<string, number>(nodes.map((n) => [n.id, 0]));\n  valid.forEach(({ edge }, i) => {\n    if (!out.has(edge.source)) out.set(edge.source, []);\n    out.get(edge.source)!.push(i);\n    indegree.set(edge.target, (indegree.get(edge.target) ?? 0) + 1);\n  });\n  const state = new Map<string, 1 | 2>();\n  const reversed = new Set<number>();\n  const walk = (id: string) => {\n    state.set(id, 1);\n    for (const i of out.get(id) ?? []) {\n      const target = valid[i].edge.target;\n      const seen = state.get(target);\n      if (seen === 1) reversed.add(i);\n      else if (!seen) walk(target);\n    }\n    state.set(id, 2);\n  };\n  const starts = [\n    ...nodes.filter((n) => indegree.get(n.id) === 0),\n    ...nodes.filter((n) => indegree.get(n.id) !== 0),\n  ];\n  for (const node of starts) if (!state.has(node.id)) walk(node.id);\n\n  // Layer by the longest path from the sources.\n  const dag = valid.map(({ edge }, i) =>\n    reversed.has(i)\n      ? { from: edge.target, to: edge.source }\n      : { from: edge.source, to: edge.target },\n  );\n  const succ = new Map<string, string[]>();\n  const pending = new Map<string, number>(nodes.map((n) => [n.id, 0]));\n  for (const { from, to } of dag) {\n    if (!succ.has(from)) succ.set(from, []);\n    succ.get(from)!.push(to);\n    pending.set(to, (pending.get(to) ?? 0) + 1);\n  }\n  const layerOf = new Map<string, number>(nodes.map((n) => [n.id, 0]));\n  const queue = nodes.filter((n) => pending.get(n.id) === 0).map((n) => n.id);\n  while (queue.length) {\n    const id = queue.shift()!;\n    for (const next of succ.get(id) ?? []) {\n      layerOf.set(next, Math.max(layerOf.get(next)!, layerOf.get(id)! + 1));\n      pending.set(next, pending.get(next)! - 1);\n      if (pending.get(next) === 0) queue.push(next);\n    }\n  }\n\n  // Items: one per node, plus a dummy wherever an edge crosses a layer.\n  const items = new Map<string, Item>();\n  nodes.forEach((node, rank) =>\n    items.set(node.id, {\n      id: node.id,\n      layer: layerOf.get(node.id) ?? 0,\n      pos: 0,\n      size: crossSize,\n      dummy: false,\n      rank,\n      node,\n    }),\n  );\n  const routes: Route[] = [];\n  const up = new Map<string, string[]>();\n  const down = new Map<string, string[]>();\n  const link = (a: string, b: string) => {\n    if (!down.has(a)) down.set(a, []);\n    if (!up.has(b)) up.set(b, []);\n    down.get(a)!.push(b);\n    up.get(b)!.push(a);\n  };\n  valid.forEach(({ edge, index }, i) => {\n    const { from, to } = dag[i];\n    const a = layerOf.get(from)!;\n    const b = layerOf.get(to)!;\n    const key = edge.id ?? `${edge.source}->${edge.target}#${index}`;\n    const chain = [from];\n    for (let layer = a + 1; layer < b; layer++) {\n      const id = `\\u0000${key}\\u0000${layer}`;\n      items.set(id, {\n        id,\n        layer,\n        pos: 0,\n        size: 0,\n        dummy: true,\n        rank: items.get(from)!.rank + 0.5,\n      });\n      chain.push(id);\n    }\n    chain.push(to);\n    for (let j = 1; j < chain.length; j++) link(chain[j - 1], chain[j]);\n    routes.push({ key, edge, index, chain, reversed: reversed.has(i) });\n  });\n\n  const count = Math.max(0, ...[...items.values()].map((item) => item.layer)) + 1;\n  const layers: Item[][] = Array.from({ length: count }, () => []);\n  for (const item of items.values()) layers[item.layer].push(item);\n  for (const layer of layers) layer.sort((a, b) => a.rank - b.rank);\n\n  // Order within layers: barycenter sweeps, keeping the arrangement with fewest crossings.\n  const index = new Map<string, number>();\n  const reindex = () =>\n    layers.forEach((layer) => layer.forEach((item, i) => index.set(item.id, i)));\n  const crossings = () => {\n    let total = 0;\n    for (let l = 0; l + 1 < layers.length; l++) {\n      const segments: [number, number][] = [];\n      for (const item of layers[l])\n        for (const next of down.get(item.id) ?? [])\n          segments.push([index.get(item.id)!, index.get(next)!]);\n      for (let i = 0; i < segments.length; i++)\n        for (let j = i + 1; j < segments.length; j++) {\n          const [a1, b1] = segments[i];\n          const [a2, b2] = segments[j];\n          if ((a1 - a2) * (b1 - b2) < 0) total++;\n        }\n    }\n    return total;\n  };\n  reindex();\n  let best = layers.map((layer) => [...layer]);\n  let bestCrossings = crossings();\n  for (let sweep = 0; sweep < 12 && bestCrossings > 0; sweep++) {\n    const downward = sweep % 2 === 0;\n    const order = downward\n      ? layers.map((_, i) => i).slice(1)\n      : layers.map((_, i) => i).slice(0, -1).reverse();\n    for (const l of order) {\n      const neighbors = downward ? up : down;\n      const weight = new Map<string, number>();\n      layers[l].forEach((item, i) => {\n        const list = neighbors.get(item.id) ?? [];\n        weight.set(\n          item.id,\n          list.length\n            ? list.reduce((sum, id) => sum + index.get(id)!, 0) / list.length\n            : i,\n        );\n      });\n      layers[l].sort(\n        (a, b) => weight.get(a.id)! - weight.get(b.id)! || a.rank - b.rank,\n      );\n      layers[l].forEach((item, i) => index.set(item.id, i));\n    }\n    const score = crossings();\n    if (score < bestCrossings) {\n      bestCrossings = score;\n      best = layers.map((layer) => [...layer]);\n    }\n  }\n  best.forEach((layer, l) => (layers[l] = layer));\n  reindex();\n\n  // Cross-axis positions: pull each item toward its neighbors, keeping order and spacing.\n  const gapBetween = (a: Item, b: Item) =>\n    (a.size + b.size) / 2 +\n    (a.dummy && b.dummy ? DUMMY_GAP : a.dummy || b.dummy ? DUMMY_GAP + 4 : nodeGap);\n  for (const layer of layers) {\n    let cursor = 0;\n    layer.forEach((item, i) => {\n      if (i > 0) cursor += gapBetween(layer[i - 1], item);\n      item.pos = cursor;\n    });\n    const mid = cursor / 2;\n    for (const item of layer) item.pos -= mid;\n  }\n  const center = (id: string) => items.get(id)!.pos;\n  for (let pass = 0; pass < 24; pass++) {\n    const downward = pass % 2 === 0;\n    const order = downward\n      ? layers.map((_, i) => i)\n      : layers.map((_, i) => i).reverse();\n    for (const l of order) {\n      const layer = layers[l];\n      if (!layer.length) continue;\n      const desired = layer.map((item) => {\n        const near = [...(up.get(item.id) ?? []), ...(down.get(item.id) ?? [])];\n        if (!near.length) return item.pos;\n        return near.reduce((sum, id) => sum + center(id), 0) / near.length;\n      });\n      const separation = layer\n        .slice(1)\n        .map((item, i) => gapBetween(layer[i], item));\n      const placed = project(desired, separation);\n      layer.forEach((item, i) => (item.pos = placed[i]));\n    }\n  }\n  let min = Infinity;\n  let max = -Infinity;\n  for (const item of items.values()) {\n    min = Math.min(min, item.pos - item.size / 2);\n    max = Math.max(max, item.pos + item.size / 2);\n  }\n  if (!Number.isFinite(min)) {\n    min = 0;\n    max = 0;\n  }\n  for (const item of items.values()) item.pos -= min;\n  return { layers, items, routes, layerOf, span: max - min };\n}\n\nfunction cubic(a: Point, b: Point, horizontal: boolean, sag = 0) {\n  if (horizontal) {\n    const dx = (b.x - a.x) / 2;\n    return {\n      c1: { x: a.x + dx, y: a.y + sag },\n      c2: { x: b.x - dx, y: b.y + sag },\n    };\n  }\n  const dy = (b.y - a.y) / 2;\n  return {\n    c1: { x: a.x + sag, y: a.y + dy },\n    c2: { x: b.x + sag, y: b.y - dy },\n  };\n}\n\nfunction bezierAt(a: Point, c1: Point, c2: Point, b: Point, t: number): Point {\n  const u = 1 - t;\n  return {\n    x: u * u * u * a.x + 3 * u * u * t * c1.x + 3 * u * t * t * c2.x + t * t * t * b.x,\n    y: u * u * u * a.y + 3 * u * u * t * c1.y + 3 * u * t * t * c2.y + t * t * t * b.y,\n  };\n}\n\nconst r1 = (n: number) => Math.round(n * 10) / 10;\n\n/* ------------------------------------------------------------------------ */\n/* Visual vocabulary                                                         */\n/* ------------------------------------------------------------------------ */\n\nconst kindIcon: Record<ServiceKind, React.ComponentType<{ size?: number; stroke?: number; className?: string; \"aria-hidden\"?: boolean | \"true\" }>> = {\n  client: IconWorld,\n  gateway: IconRoute,\n  service: IconServer,\n  database: IconDatabase,\n  cache: IconBolt,\n  queue: IconStack2,\n  external: IconCloud,\n};\n\nconst kindLabel: Record<ServiceKind, string> = {\n  client: \"client\",\n  gateway: \"gateway\",\n  service: \"service\",\n  database: \"database\",\n  cache: \"cache\",\n  queue: \"queue\",\n  external: \"external service\",\n};\n\nconst statusLabel: Record<ServiceStatus, string> = {\n  healthy: \"Healthy\",\n  degraded: \"Degraded\",\n  down: \"Down\",\n};\n\nconst statusDot: Record<ServiceStatus, string> = {\n  healthy: \"bg-emerald-500\",\n  degraded: \"bg-amber-500\",\n  down: \"bg-destructive\",\n};\n\nconst statusPill: Record<ServiceStatus, string> = {\n  healthy: \"bg-emerald-500/10 text-emerald-700 dark:text-emerald-400\",\n  degraded: \"bg-amber-500/10 text-amber-700 dark:text-amber-400\",\n  down: \"bg-destructive/10 text-destructive\",\n};\n\ntype Severity = \"ok\" | \"warn\" | \"critical\";\n\nconst severityStroke: Record<Severity, string> = {\n  ok: \"var(--sm-ok)\",\n  warn: \"var(--sm-warn)\",\n  critical: \"var(--sm-critical)\",\n};\nconst severityFlow: Record<Severity, string> = {\n  ok: \"var(--sm-flow)\",\n  warn: \"var(--sm-warn)\",\n  critical: \"var(--sm-critical)\",\n};\n\nconst useIsomorphicLayoutEffect =\n  typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (onChange) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", onChange);\n      return () => query.removeEventListener(\"change\", onChange);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction StatusDot({ status, className }: { status: ServiceStatus; className?: string }) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      data-status={status}\n      className={cn(\"relative inline-flex size-2 shrink-0 rounded-full\", statusDot[status], className)}\n    >\n      {status !== \"healthy\" ? (\n        <span\n          className={cn(\n            \"absolute inset-0 rounded-full opacity-60 motion-safe:animate-[service-map-ping_1.8s_cubic-bezier(0,0,0.2,1)_infinite]\",\n            statusDot[status],\n          )}\n        />\n      ) : null}\n    </span>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Component                                                                 */\n/* ------------------------------------------------------------------------ */\n\n/**\n * A live service dependency map. Nodes are laid out as a layered graph, left to\n * right by default; edges carry animated traffic whose width follows request rate\n * and whose color follows error rate. Hover or focus a node to trace its upstream\n * and downstream paths; select it to list its inbound and outbound traffic.\n */\nfunction ServiceMap({\n  nodes,\n  edges,\n  direction = \"LR\",\n  selectedId: selectedProp,\n  defaultSelectedId = null,\n  onSelect,\n  renderNode,\n  thresholds,\n  rpsFormatter = formatRps,\n  latencyFormatter = formatLatency,\n  errorRateFormatter = formatErrorRate,\n  title,\n  description,\n  actions,\n  showLegend = true,\n  animate = true,\n  nodeWidth = 148,\n  nodeHeight = 60,\n  minScale = 0.5,\n  density = \"auto\",\n  className,\n  onKeyDown,\n  ...props\n}: ServiceMapProps) {\n  const id = React.useId();\n  const reduced = useReducedMotion();\n  const viewportRef = React.useRef<HTMLDivElement>(null);\n  const [available, setAvailable] = React.useState(0);\n  const [hoveredId, setHoveredId] = React.useState<string | null>(null);\n  const [focusedId, setFocusedId] = React.useState<string | null>(null);\n  const [hoveredEdge, setHoveredEdge] = React.useState<string | null>(null);\n  const [innerSelected, setInnerSelected] = React.useState<string | null>(\n    defaultSelectedId,\n  );\n  const [revealed, setRevealed] = React.useState(false);\n  const selectedId = selectedProp !== undefined ? selectedProp : innerSelected;\n\n  const warn = thresholds?.warn ?? 0.01;\n  const critical = thresholds?.critical ?? 0.05;\n  const horizontal = direction === \"LR\";\n\n  const byId = React.useMemo(\n    () => new Map(nodes.map((node) => [node.id, node])),\n    [nodes],\n  );\n  const selectedNode = selectedId ? (byId.get(selectedId) ?? null) : null;\n\n  const select = (next: string | null) => {\n    if (selectedProp === undefined) setInnerSelected(next);\n    onSelect?.(next, next ? (byId.get(next) ?? null) : null);\n  };\n\n  const statusOf = React.useCallback(\n    (node: ServiceMapNode): ServiceStatus =>\n      node.status ??\n      ((node.metrics?.errorRate ?? 0) >= critical ? \"degraded\" : \"healthy\"),\n    [critical],\n  );\n  const severityOf = (edge: ServiceMapEdge): Severity => {\n    if (edge.status === \"down\") return \"critical\";\n    if (edge.status === \"degraded\") return \"warn\";\n    if (edge.status === \"healthy\") return \"ok\";\n    const rate = edge.errorRate ?? 0;\n    if (rate >= critical) return \"critical\";\n    if (rate >= warn) return \"warn\";\n    return \"ok\";\n  };\n\n  /* ---------------------------------------------------------- layout */\n\n  const width = available || FALLBACK_WIDTH;\n  const comfortable = React.useMemo(\n    () => buildStructure(nodes, edges, horizontal ? nodeHeight : nodeWidth),\n    [nodes, edges, horizontal, nodeWidth, nodeHeight],\n  );\n  // Cards when they fit at a readable scale; icon tiles with labels otherwise.\n  const comfortableWidth = horizontal\n    ? comfortable.layers.length * nodeWidth +\n      Math.max(0, comfortable.layers.length - 1) * GAP_MIN +\n      PAD * 2\n    : comfortable.span + PAD * 2;\n  const compact =\n    density === \"compact\" ||\n    (density === \"auto\" && width / comfortableWidth < AUTO_COMPACT_BELOW);\n  const compactStructure = React.useMemo(\n    () =>\n      compact\n        ? buildStructure(\n            nodes,\n            edges,\n            horizontal ? COMPACT_H : COMPACT_W,\n            horizontal ? 8 : 12,\n          )\n        : null,\n    [compact, nodes, edges, horizontal],\n  );\n  const structure = compactStructure ?? comfortable;\n  const cardW = compact ? COMPACT_W : nodeWidth;\n  const cardH = compact ? COMPACT_H : nodeHeight;\n  const pad = compact ? COMPACT_PAD : PAD;\n  const mainSize = horizontal ? cardW : cardH;\n  const crossSize = horizontal ? cardH : cardW;\n  // Edges meet the icon tile in compact mode, not the label under it.\n  const portInset = compact && horizontal ? (COMPACT_W - COMPACT_TILE) / 2 : 0;\n  const portShift = compact && horizontal ? (COMPACT_TILE - COMPACT_H) / 2 : 0;\n  const portSpan = compact ? COMPACT_TILE : crossSize;\n  const layerCount = structure.layers.length;\n\n  const gapMin = horizontal\n    ? compact\n      ? COMPACT_GAP_MIN\n      : GAP_MIN\n    : compact\n      ? COMPACT_GAP_TB\n      : GAP_TB;\n  let gap = gapMin;\n  if (horizontal && layerCount > 1) {\n    const fit = (width - pad * 2 - layerCount * mainSize) / (layerCount - 1);\n    gap = Math.min(GAP_MAX, Math.max(gapMin, fit));\n  }\n  const mainExtent = layerCount * mainSize + Math.max(0, layerCount - 1) * gap;\n  const worldW = horizontal ? mainExtent + pad * 2 : structure.span + pad * 2;\n  const worldH = horizontal ? structure.span + pad * 2 : mainExtent + pad * 2;\n  const scale = Math.max(minScale, Math.min(1, width / worldW));\n\n  const placement = React.useMemo(() => {\n    const rects = new Map<string, { x: number; y: number }>();\n    const at = (item: Item): Point => {\n      const main = pad + item.layer * (mainSize + gap);\n      const cross = pad + item.pos;\n      return horizontal ? { x: main, y: cross } : { x: cross, y: main };\n    };\n    for (const item of structure.items.values()) {\n      if (item.dummy) continue;\n      const p = at(item);\n      rects.set(\n        item.id,\n        horizontal\n          ? { x: p.x, y: p.y - cardH / 2 }\n          : { x: p.x - cardW / 2, y: p.y },\n      );\n    }\n\n    // Spread the ports on each side of a node so parallel edges do not merge.\n    const ports = new Map<string, number>();\n    const sides = new Map<string, { key: string; toward: number }[]>();\n    const sideKey = (nodeId: string, side: \"in\" | \"out\") => `${nodeId}|${side}`;\n    const neighborCross = (route: Route, end: \"source\" | \"target\") => {\n      const chain = route.reversed ? [...route.chain].reverse() : route.chain;\n      const id = end === \"source\" ? chain[1] : chain[chain.length - 2];\n      return structure.items.get(id)!.pos;\n    };\n    for (const route of structure.routes) {\n      const outSide = route.reversed ? \"in\" : \"out\";\n      const inSide = route.reversed ? \"out\" : \"in\";\n      const s = sideKey(route.edge.source, outSide);\n      const t = sideKey(route.edge.target, inSide);\n      if (!sides.has(s)) sides.set(s, []);\n      if (!sides.has(t)) sides.set(t, []);\n      sides.get(s)!.push({ key: `${route.key}|s`, toward: neighborCross(route, \"source\") });\n      sides.get(t)!.push({ key: `${route.key}|t`, toward: neighborCross(route, \"target\") });\n    }\n    for (const list of sides.values()) {\n      list.sort((a, b) => a.toward - b.toward);\n      const step =\n        list.length > 1\n          ? Math.min(compact ? 5 : 7, (portSpan - (compact ? 12 : 24)) / (list.length - 1))\n          : 0;\n      list.forEach((entry, i) =>\n        ports.set(entry.key, (i - (list.length - 1) / 2) * step),\n      );\n    }\n\n    const placed: PlacedEdge[] = [];\n    for (const route of structure.routes) {\n      const chain = route.reversed ? [...route.chain].reverse() : route.chain;\n      const source = structure.items.get(chain[0])!;\n      const target = structure.items.get(chain[chain.length - 1])!;\n      const forward = !route.reversed;\n      const ps = at(source);\n      const pt = at(target);\n      const so = ports.get(`${route.key}|s`) ?? 0;\n      const to = ports.get(`${route.key}|t`) ?? 0;\n      const start: Point = horizontal\n        ? {\n            x: forward ? ps.x + mainSize - portInset : ps.x + portInset,\n            y: ps.y + portShift + so,\n          }\n        : { x: ps.x + so, y: forward ? ps.y + mainSize : ps.y };\n      const end: Point = horizontal\n        ? {\n            x: forward ? pt.x + portInset : pt.x + mainSize - portInset,\n            y: pt.y + portShift + to,\n          }\n        : { x: pt.x + to, y: forward ? pt.y : pt.y + mainSize };\n      const waypoints: Point[] = [start];\n      for (const id of chain.slice(1, -1)) {\n        const p = at(structure.items.get(id)!);\n        const enter = forward ? 0 : mainSize;\n        const leave = forward ? mainSize : 0;\n        waypoints.push(\n          horizontal ? { x: p.x + enter, y: p.y } : { x: p.x, y: p.y + enter },\n          horizontal ? { x: p.x + leave, y: p.y } : { x: p.x, y: p.y + leave },\n        );\n      }\n      waypoints.push(end);\n\n      let d = `M${r1(start.x)} ${r1(start.y)}`;\n      const samples: Point[] = [start];\n      for (let i = 1; i < waypoints.length; i++) {\n        const a = waypoints[i - 1];\n        const b = waypoints[i];\n        // Odd segments cross a gap and curve; even ones run straight through a layer.\n        if (i % 2 === 1) {\n          const sag = !forward && waypoints.length === 2 ? crossSize * 0.75 : 0;\n          const { c1, c2 } = cubic(a, b, horizontal, sag);\n          d += ` C${r1(c1.x)} ${r1(c1.y)} ${r1(c2.x)} ${r1(c2.y)} ${r1(b.x)} ${r1(b.y)}`;\n          for (let s = 1; s <= 16; s++) samples.push(bezierAt(a, c1, c2, b, s / 16));\n        } else {\n          d += ` L${r1(b.x)} ${r1(b.y)}`;\n          samples.push(b);\n        }\n      }\n      let length = 0;\n      const cumulative = [0];\n      for (let i = 1; i < samples.length; i++) {\n        length += Math.hypot(samples[i].x - samples[i - 1].x, samples[i].y - samples[i - 1].y);\n        cumulative.push(length);\n      }\n      const half = length / 2;\n      let mid = samples[0];\n      for (let i = 1; i < samples.length; i++)\n        if (cumulative[i] >= half) {\n          const f = (half - cumulative[i - 1]) / (cumulative[i] - cumulative[i - 1] || 1);\n          mid = {\n            x: samples[i - 1].x + (samples[i].x - samples[i - 1].x) * f,\n            y: samples[i - 1].y + (samples[i].y - samples[i - 1].y) * f,\n          };\n          break;\n        }\n      placed.push({ key: route.key, edge: route.edge, index: route.index, d, length, mid, start, end });\n    }\n    return { rects, edges: placed };\n  }, [\n    structure,\n    gap,\n    pad,\n    horizontal,\n    compact,\n    mainSize,\n    crossSize,\n    cardW,\n    cardH,\n    portInset,\n    portShift,\n    portSpan,\n  ]);\n\n  /* ---------------------------------------------------------- measure */\n\n  useIsomorphicLayoutEffect(() => {\n    const element = viewportRef.current;\n    if (!element) return;\n    const measure = () => setAvailable(element.clientWidth);\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(element);\n    return () => observer.disconnect();\n  }, []);\n\n  // When the map scrolls sideways, keep the selected service in view.\n  useIsomorphicLayoutEffect(() => {\n    const viewport = viewportRef.current;\n    const rect = selectedId ? placement.rects.get(selectedId) : undefined;\n    if (!viewport || !rect || viewport.scrollWidth <= viewport.clientWidth) return;\n    const center = (rect.x + cardW / 2) * scale;\n    viewport.scrollLeft = Math.max(0, center - viewport.clientWidth / 2);\n  }, [selectedId, scale, compact]);\n\n  React.useEffect(() => {\n    const timer = window.setTimeout(() => setRevealed(true), 1800);\n    return () => window.clearTimeout(timer);\n  }, []);\n\n  /* ---------------------------------------------------------- relationships */\n\n  const inbound = React.useMemo(() => {\n    const map = new Map<string, ServiceMapEdge[]>();\n    for (const edge of edges) {\n      if (!map.has(edge.target)) map.set(edge.target, []);\n      map.get(edge.target)!.push(edge);\n    }\n    return map;\n  }, [edges]);\n  const outbound = React.useMemo(() => {\n    const map = new Map<string, ServiceMapEdge[]>();\n    for (const edge of edges) {\n      if (!map.has(edge.source)) map.set(edge.source, []);\n      map.get(edge.source)!.push(edge);\n    }\n    return map;\n  }, [edges]);\n\n  const hoveredPlaced = hoveredEdge\n    ? (placement.edges.find((edge) => edge.key === hoveredEdge) ?? null)\n    : null;\n  const activeId = hoveredId ?? focusedId ?? (hoveredPlaced ? null : selectedId);\n  const readoutId = hoveredId ?? focusedId;\n  const readoutNode = readoutId ? (byId.get(readoutId) ?? null) : null;\n\n  // Everything upstream and downstream of the active node, edge by edge.\n  const lit = React.useMemo(() => {\n    if (hoveredPlaced) {\n      return {\n        nodes: new Set([hoveredPlaced.edge.source, hoveredPlaced.edge.target]),\n        edges: new Set([hoveredPlaced.key]),\n      };\n    }\n    if (!activeId || !byId.has(activeId)) return null;\n    const litNodes = new Set<string>([activeId]);\n    const litEdges = new Set<string>();\n    const keyOf = new Map(\n      placement.edges.map((placed) => [placed.edge, placed.key]),\n    );\n    const visit = (start: string, along: \"up\" | \"down\") => {\n      const stack = [start];\n      const seen = new Set([start]);\n      while (stack.length) {\n        const current = stack.pop()!;\n        const list =\n          along === \"down\" ? outbound.get(current) : inbound.get(current);\n        for (const edge of list ?? []) {\n          const key = keyOf.get(edge);\n          if (key) litEdges.add(key);\n          const next = along === \"down\" ? edge.target : edge.source;\n          litNodes.add(next);\n          if (!seen.has(next)) {\n            seen.add(next);\n            stack.push(next);\n          }\n        }\n      }\n    };\n    visit(activeId, \"up\");\n    visit(activeId, \"down\");\n    return { nodes: litNodes, edges: litEdges };\n  }, [activeId, hoveredPlaced, byId, inbound, outbound, placement.edges]);\n\n  /* ---------------------------------------------------------- keyboard */\n\n  const tabOrder = React.useMemo(\n    () =>\n      structure.layers.flatMap((layer) =>\n        layer.filter((item) => !item.dummy).map((item) => item.id),\n      ),\n    [structure],\n  );\n\n  const focusNode = (nodeId: string | undefined) => {\n    if (!nodeId) return;\n    viewportRef.current\n      ?.querySelector<HTMLElement>(\n        `[data-slot=\"service-map-node\"][data-id=\"${CSS.escape(nodeId)}\"]`,\n      )\n      ?.focus();\n  };\n\n  const onNodeKeyDown = (event: React.KeyboardEvent<HTMLElement>, nodeId: string) => {\n    const item = structure.items.get(nodeId);\n    if (!item) return;\n    const layer = structure.layers[item.layer].filter((entry) => !entry.dummy);\n    const position = layer.indexOf(item);\n    const across = (delta: 1 | -1) => {\n      for (\n        let l = item.layer + delta;\n        l >= 0 && l < structure.layers.length;\n        l += delta\n      ) {\n        const candidates = structure.layers[l].filter((entry) => !entry.dummy);\n        if (!candidates.length) continue;\n        return candidates.reduce((best, entry) =>\n          Math.abs(entry.pos - item.pos) < Math.abs(best.pos - item.pos)\n            ? entry\n            : best,\n        ).id;\n      }\n      return undefined;\n    };\n    const keys: Record<string, () => string | undefined> = horizontal\n      ? {\n          ArrowUp: () => layer[position - 1]?.id,\n          ArrowDown: () => layer[position + 1]?.id,\n          ArrowLeft: () => across(-1),\n          ArrowRight: () => across(1),\n        }\n      : {\n          ArrowLeft: () => layer[position - 1]?.id,\n          ArrowRight: () => layer[position + 1]?.id,\n          ArrowUp: () => across(-1),\n          ArrowDown: () => across(1),\n        };\n    keys.Home = () => tabOrder[0];\n    keys.End = () => tabOrder[tabOrder.length - 1];\n    const move = keys[event.key];\n    if (!move) return;\n    event.preventDefault();\n    focusNode(move());\n  };\n\n  /* ---------------------------------------------------------- render helpers */\n\n  const maxRps = Math.max(1, ...edges.map((edge) => edge.rps ?? 0));\n  const formatMetrics = (metrics?: ServiceMetrics) => ({\n    rps: metrics?.rps != null ? rpsFormatter(metrics.rps) : undefined,\n    errorRate:\n      metrics?.errorRate != null ? errorRateFormatter(metrics.errorRate) : undefined,\n    p95: metrics?.p95 != null ? latencyFormatter(metrics.p95) : undefined,\n  });\n  const errorClass = (rate: number | undefined) =>\n    rate == null\n      ? \"\"\n      : rate >= critical\n        ? \"text-destructive\"\n        : rate >= warn\n          ? \"text-amber-700 dark:text-amber-400\"\n          : \"\";\n  const iconFor = (node: ServiceMapNode, size = 15) => {\n    if (node.icon) return node.icon;\n    const Icon = kindIcon[node.kind ?? \"service\"];\n    return <Icon aria-hidden=\"true\" size={size} stroke={1.75} />;\n  };\n\n  const describeNode = (node: ServiceMapNode) => {\n    const status = statusOf(node);\n    const parts = [node.label, kindLabel[node.kind ?? \"service\"], statusLabel[status]];\n    const m = formatMetrics(node.metrics);\n    if (m.rps) parts.push(m.rps);\n    if (m.errorRate) parts.push(`${m.errorRate} errors`);\n    if (m.p95) parts.push(`p95 ${m.p95}`);\n    const ins = inbound.get(node.id)?.length ?? 0;\n    const outs = outbound.get(node.id)?.length ?? 0;\n    parts.push(`${ins} inbound, ${outs} outbound`);\n    return parts.join(\", \");\n  };\n\n  const edgeSummary = (edge: ServiceMapEdge) =>\n    [\n      edge.rps != null ? rpsFormatter(edge.rps) : null,\n      edge.errorRate != null ? `${errorRateFormatter(edge.errorRate)} errors` : null,\n      edge.p95 != null ? `p95 ${latencyFormatter(edge.p95)}` : null,\n    ]\n      .filter(Boolean)\n      .join(\" · \");\n\n  const counts = { healthy: 0, degraded: 0, down: 0 };\n  for (const node of nodes) counts[statusOf(node)] += 1;\n\n  const hasHeader = title != null || description != null || actions != null;\n  const mapLabel = typeof title === \"string\" ? title : \"Service map\";\n  const motion = animate && !reduced;\n  const offsetX = Math.max(0, (width - worldW * scale) / 2);\n\n  /* ---------------------------------------------------------- render */\n\n  return (\n    <div\n      data-slot=\"service-map\"\n      data-direction={direction}\n      data-selected={selectedNode ? true : undefined}\n      onKeyDown={(event) => {\n        onKeyDown?.(event);\n        if (event.defaultPrevented || event.key !== \"Escape\") return;\n        if (selectedId == null && !hoveredEdge) return;\n        event.preventDefault();\n        setHoveredEdge(null);\n        if (selectedId != null) select(null);\n      }}\n      className={cn(\n        \"@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)]\",\n        \"[--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))]\",\n        \"[--sm-flow:var(--color-chart-1)] [--sm-warn:var(--color-amber-500,oklch(76.9%_0.188_70.08))] [--sm-critical:var(--color-destructive)]\",\n        className,\n      )}\n      {...props}\n    >\n      <style href=\"overtrue-service-map\" precedence=\"default\">\n        {`@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}}`}\n      </style>\n\n      {hasHeader || nodes.length > 0 ? (\n        <div className=\"flex flex-wrap items-start justify-between gap-x-6 gap-y-3 px-5 pt-5\">\n          <div className=\"min-w-0 space-y-1\">\n            {title != null ? (\n              <h3 className=\"text-sm leading-5 font-semibold tracking-tight\">\n                {title}\n              </h3>\n            ) : null}\n            {description != null ? (\n              <p\n                id={`${id}-description`}\n                className=\"text-[13px] leading-5 text-muted-foreground\"\n              >\n                {description}\n              </p>\n            ) : null}\n          </div>\n          <div className=\"flex shrink-0 flex-wrap items-center gap-3\">\n            {nodes.length > 0 ? (\n              <ul\n                data-slot=\"service-map-summary\"\n                aria-label=\"Health summary\"\n                className=\"flex items-center gap-3 text-xs text-muted-foreground\"\n              >\n                {([\"healthy\", \"degraded\", \"down\"] as const)\n                  .filter((status) => status === \"healthy\" || counts[status] > 0)\n                  .map((status) => (\n                    <li key={status} className=\"flex items-center gap-1.5\">\n                      <StatusDot status={status} />\n                      <span className=\"font-medium text-foreground tabular-nums\">\n                        {counts[status]}\n                      </span>\n                      {statusLabel[status].toLowerCase()}\n                    </li>\n                  ))}\n              </ul>\n            ) : null}\n            {actions != null ? (\n              <div className=\"flex items-center gap-1\">{actions}</div>\n            ) : null}\n          </div>\n        </div>\n      ) : null}\n\n      <div className=\"px-3 pt-4 pb-3\">\n        <div\n          ref={viewportRef}\n          data-slot=\"service-map-viewport\"\n          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]\"\n        >\n          {nodes.length === 0 ? (\n            <p className=\"grid h-40 place-items-center text-xs text-muted-foreground\">\n              No services to show.\n            </p>\n          ) : (\n            <div\n              className=\"relative\"\n              style={{\n                width: worldW * scale,\n                height: worldH * scale,\n                marginLeft: offsetX,\n              }}\n            >\n              <div\n                role=\"group\"\n                aria-roledescription=\"service map\"\n                aria-label={`${mapLabel}: ${nodes.length} services, ${edges.length} connections. Arrow keys move between services, Enter selects, Escape clears.`}\n                aria-describedby={description != null ? `${id}-description` : undefined}\n                data-slot=\"service-map-world\"\n                className=\"absolute top-0 left-0 origin-top-left\"\n                style={{\n                  width: worldW,\n                  height: worldH,\n                  transform: scale === 1 ? undefined : `scale(${scale})`,\n                }}\n                onPointerLeave={() => {\n                  setHoveredId(null);\n                  setHoveredEdge(null);\n                }}\n              >\n                <svg\n                  aria-hidden=\"true\"\n                  data-slot=\"service-map-edges\"\n                  className=\"absolute inset-0 overflow-visible\"\n                  width={worldW}\n                  height={worldH}\n                  viewBox={`0 0 ${worldW} ${worldH}`}\n                >\n                  {placement.edges.map((placed) => {\n                    const { edge } = placed;\n                    const severity = severityOf(edge);\n                    const share = Math.sqrt(Math.max(0, edge.rps ?? 0) / maxRps);\n                    const strokeWidth = edge.rps != null ? 1 + share * 3 : 1.25;\n                    const highlighted = lit?.edges.has(placed.key) ?? false;\n                    const dimmed = lit != null && !highlighted;\n                    const sourceLayer = structure.layerOf.get(edge.source) ?? 0;\n                    const particles = Math.min(4, Math.max(1, Math.round(1 + share * 3)));\n                    const speed = 38 + share * 72;\n                    const duration = Math.max(1.2, placed.length / speed);\n                    const stroke =\n                      severity === \"ok\" && highlighted\n                        ? \"color-mix(in oklab, var(--sm-flow) 70%, var(--sm-ok))\"\n                        : severityStroke[severity];\n                    return (\n                      <g\n                        key={placed.key}\n                        data-slot=\"service-map-edge\"\n                        data-id={placed.key}\n                        data-severity={severity}\n                        data-active={highlighted || undefined}\n                        data-dimmed={dimmed || undefined}\n                        className=\"transition-opacity duration-150 motion-reduce:transition-none\"\n                        style={{\n                          opacity: dimmed ? 0.16 : 1,\n                          color: severityFlow[severity],\n                        }}\n                      >\n                        <path\n                          d={placed.d}\n                          fill=\"none\"\n                          stroke={stroke}\n                          strokeWidth={strokeWidth}\n                          strokeLinecap=\"round\"\n                          className={cn(\n                            \"transition-[stroke] duration-150 motion-reduce:transition-none\",\n                            severity !== \"ok\" &&\n                              \"dark:[filter:drop-shadow(0_0_5px_color-mix(in_oklab,currentColor_55%,transparent))]\",\n                            highlighted &&\n                              \"dark:[filter:drop-shadow(0_0_6px_color-mix(in_oklab,currentColor_60%,transparent))]\",\n                            !revealed &&\n                              \"motion-safe:[stroke-dasharray:var(--len)] motion-safe:animate-[service-map-draw_900ms_cubic-bezier(0.22,1,0.36,1)_backwards]\",\n                          )}\n                          style={\n                            {\n                              \"--len\": Math.ceil(placed.length + 4),\n                              animationDelay: revealed ? undefined : `${160 + sourceLayer * 110}ms`,\n                            } as React.CSSProperties\n                          }\n                        />\n                        {motion ? (\n                          <g\n                            data-slot=\"service-map-flow\"\n                            className={cn(\n                              \"dark:[filter:drop-shadow(0_0_3px_currentColor)]\",\n                              !revealed &&\n                                \"motion-safe:animate-[service-map-fade_600ms_ease-out_backwards]\",\n                            )}\n                            style={{\n                              animationDelay: revealed ? undefined : `${700 + sourceLayer * 110}ms`,\n                            }}\n                          >\n                            {Array.from({ length: particles }, (_, i) => (\n                              <circle\n                                key={i}\n                                r={highlighted ? 2.4 : 2}\n                                fill=\"currentColor\"\n                                opacity={severity === \"ok\" ? 0.9 : 1}\n                              >\n                                <animateMotion\n                                  dur={`${duration.toFixed(2)}s`}\n                                  begin={`${(-(duration * i) / particles - (placed.index % 5) * 0.37).toFixed(2)}s`}\n                                  repeatCount=\"indefinite\"\n                                  path={placed.d}\n                                />\n                              </circle>\n                            ))}\n                          </g>\n                        ) : (\n                          <path\n                            data-slot=\"service-map-flow\"\n                            d={placed.d}\n                            fill=\"none\"\n                            stroke=\"currentColor\"\n                            strokeWidth={Math.min(2.6, strokeWidth + 0.4)}\n                            strokeLinecap=\"round\"\n                            strokeDasharray=\"0 11\"\n                            opacity={severity === \"ok\" ? 0.8 : 0.95}\n                          />\n                        )}\n                        <circle\n                          cx={placed.end.x}\n                          cy={placed.end.y}\n                          r={2.5}\n                          fill=\"var(--color-card)\"\n                          stroke={stroke}\n                          strokeWidth={1.5}\n                          className={cn(\n                            !revealed &&\n                              \"motion-safe:animate-[service-map-fade_300ms_ease-out_backwards]\",\n                          )}\n                          style={{\n                            animationDelay: revealed\n                              ? undefined\n                              : `${760 + sourceLayer * 110}ms`,\n                          }}\n                        />\n                        <path\n                          d={placed.d}\n                          fill=\"none\"\n                          stroke=\"transparent\"\n                          strokeWidth={14}\n                          className=\"pointer-events-[stroke] cursor-default\"\n                          onPointerEnter={() => {\n                            setHoveredId(null);\n                            setHoveredEdge(placed.key);\n                          }}\n                          onPointerLeave={() => setHoveredEdge(null)}\n                        />\n                      </g>\n                    );\n                  })}\n                </svg>\n\n                {tabOrder.map((nodeId) => {\n                  const node = byId.get(nodeId)!;\n                  const rect = placement.rects.get(nodeId)!;\n                  const status = statusOf(node);\n                  const kind = node.kind ?? \"service\";\n                  const selected = selectedId === nodeId;\n                  const active = hoveredId === nodeId || focusedId === nodeId;\n                  const onPath = lit?.nodes.has(nodeId) ?? false;\n                  const dimmed = lit != null && !onPath;\n                  const formatted = formatMetrics(node.metrics);\n                  const layer = structure.layerOf.get(nodeId) ?? 0;\n                  // The lit surface: a card in comfortable density, the icon tile in compact.\n                  const surface = cn(\n                    \"border border-border/80 bg-card\",\n                    \"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)]\",\n                    \"transition-[opacity,box-shadow,border-color,translate] duration-150 ease-out motion-reduce:transition-none\",\n                    active &&\n                      status === \"healthy\" &&\n                      !selected &&\n                      \"border-foreground/25 shadow-[0_1px_2px_rgb(0_0_0/0.06),0_10px_24px_-10px_rgb(0_0_0/0.25)]\",\n                    status === \"degraded\" &&\n                      \"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)]\",\n                    status === \"down\" &&\n                      \"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)]\",\n                    selected &&\n                      \"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)]\",\n                  );\n                  const downRing =\n                    status === \"down\" ? (\n                      <span\n                        aria-hidden=\"true\"\n                        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]\"\n                      />\n                    ) : null;\n                  const iconTint = cn(\n                    \"text-muted-foreground transition-colors duration-150 motion-reduce:transition-none\",\n                    (active || selected) && \"text-foreground\",\n                    status === \"degraded\" && \"text-amber-700 dark:text-amber-400\",\n                    status === \"down\" && \"text-destructive\",\n                  );\n                  const shared = {\n                    type: \"button\" as const,\n                    \"data-slot\": \"service-map-node\",\n                    \"data-id\": nodeId,\n                    \"data-status\": status,\n                    \"data-kind\": kind,\n                    \"data-density\": compact ? \"compact\" : \"comfortable\",\n                    \"data-active\": active || (lit != null && onPath) || undefined,\n                    \"data-selected\": selected || undefined,\n                    \"data-dimmed\": dimmed || undefined,\n                    \"aria-label\": describeNode(node),\n                    \"aria-pressed\": selected,\n                    onClick: () => select(selected ? null : nodeId),\n                    onPointerEnter: () => {\n                      setHoveredEdge(null);\n                      setHoveredId(nodeId);\n                    },\n                    onPointerLeave: () => setHoveredId(null),\n                    onFocus: (event: React.FocusEvent<HTMLButtonElement>) =>\n                      setFocusedId(\n                        event.currentTarget.matches(\":focus-visible\") ? nodeId : null,\n                      ),\n                    onBlur: () => setFocusedId(null),\n                    onKeyDown: (event: React.KeyboardEvent<HTMLButtonElement>) =>\n                      onNodeKeyDown(event, nodeId),\n                    style: {\n                      left: rect.x,\n                      top: rect.y,\n                      width: cardW,\n                      height: cardH,\n                      animationDelay: revealed ? undefined : `${layer * 110}ms`,\n                    } as React.CSSProperties,\n                  };\n                  const reveal =\n                    !revealed &&\n                    \"motion-safe:animate-[service-map-rise_700ms_cubic-bezier(0.22,1,0.36,1)_backwards]\";\n\n                  if (compact) {\n                    return (\n                      <button\n                        key={nodeId}\n                        {...shared}\n                        className={cn(\n                          \"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\",\n                          dimmed && \"opacity-40\",\n                          reveal,\n                        )}\n                      >\n                        <span\n                          aria-hidden=\"true\"\n                          data-slot=\"service-map-node-tile\"\n                          className={cn(\n                            \"relative grid shrink-0 place-items-center rounded-[11px] [&>svg]:size-4\",\n                            surface,\n                            iconTint,\n                            \"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\",\n                          )}\n                          style={{ width: COMPACT_TILE, height: COMPACT_TILE }}\n                        >\n                          {downRing}\n                          {iconFor(node, 16)}\n                          <StatusDot\n                            status={status}\n                            className=\"absolute -top-1 -right-1 ring-2 ring-card\"\n                          />\n                        </span>\n                        <span className=\"max-w-full truncate px-0.5 text-[11.5px] leading-4 font-medium tracking-tight\">\n                          {node.label}\n                        </span>\n                      </button>\n                    );\n                  }\n\n                  const info: ServiceMapNodeInfo = {\n                    kind,\n                    status,\n                    layer,\n                    inbound: inbound.get(nodeId) ?? [],\n                    outbound: outbound.get(nodeId) ?? [],\n                    active,\n                    selected,\n                    dimmed,\n                    formatted,\n                    icon: iconFor(node),\n                  };\n                  return (\n                    <button\n                      key={nodeId}\n                      {...shared}\n                      className={cn(\n                        \"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\",\n                        surface,\n                        \"focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-2 focus-visible:ring-offset-card\",\n                        dimmed && \"opacity-40\",\n                        reveal,\n                      )}\n                    >\n                      {downRing}\n                      {renderNode ? (\n                        renderNode(node, info)\n                      ) : (\n                        <>\n                          <span className=\"flex min-w-0 items-center gap-2 px-2.5 pt-2.5\">\n                            <span\n                              aria-hidden=\"true\"\n                              className={cn(\n                                \"grid size-6 shrink-0 place-items-center rounded-md bg-muted ring-1 ring-border/60 ring-inset [&>svg]:size-3.5\",\n                                iconTint,\n                                status === \"degraded\" && \"bg-amber-500/12 ring-amber-500/25\",\n                                status === \"down\" && \"bg-destructive/12 ring-destructive/25\",\n                              )}\n                            >\n                              {iconFor(node, 14)}\n                            </span>\n                            <span className=\"min-w-0 flex-1 truncate text-[13px] leading-5 font-medium tracking-tight\">\n                              {node.label}\n                            </span>\n                            <StatusDot status={status} />\n                          </span>\n                          <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\">\n                            {[\n                              formatted.rps ? (\n                                <span key=\"rps\" className=\"text-foreground/85\">\n                                  {formatted.rps}\n                                </span>\n                              ) : null,\n                              formatted.errorRate ? (\n                                <span key=\"err\" className={errorClass(node.metrics?.errorRate)}>\n                                  {formatted.errorRate}\n                                </span>\n                              ) : null,\n                              formatted.p95 ? <span key=\"p95\">{formatted.p95}</span> : null,\n                            ]\n                              .filter(Boolean)\n                              .flatMap((part, i) =>\n                                i === 0\n                                  ? [part]\n                                  : [\n                                      <span key={`sep${i}`} aria-hidden=\"true\" className=\"text-muted-foreground/45\">\n                                        ·\n                                      </span>,\n                                      part,\n                                    ],\n                              )}\n                          </span>\n                        </>\n                      )}\n                    </button>\n                  );\n                })}\n              </div>\n\n              {compact && readoutNode && !hoveredPlaced ? (\n                <NodeReadout\n                  node={readoutNode}\n                  status={statusOf(readoutNode)}\n                  formatted={formatMetrics(readoutNode.metrics)}\n                  errorClass={errorClass(readoutNode.metrics?.errorRate)}\n                  rect={placement.rects.get(readoutNode.id)!}\n                  cardW={cardW}\n                  cardH={cardH}\n                  scale={scale}\n                  worldWidth={worldW * scale}\n                />\n              ) : null}\n\n              {hoveredPlaced ? (\n                <div\n                  aria-hidden=\"true\"\n                  data-slot=\"service-map-edge-readout\"\n                  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]\"\n                  style={{\n                    left: Math.min(\n                      Math.max(hoveredPlaced.mid.x * scale, 96),\n                      worldW * scale - 96,\n                    ),\n                    top: Math.max(hoveredPlaced.mid.y * scale, 64),\n                  }}\n                >\n                  <p className=\"flex items-center gap-1.5 text-xs font-medium\">\n                    {byId.get(hoveredPlaced.edge.source)?.label}\n                    <span aria-hidden=\"true\" className=\"text-muted-foreground\">\n                      →\n                    </span>\n                    {byId.get(hoveredPlaced.edge.target)?.label}\n                  </p>\n                  <EdgeMetrics\n                    edge={hoveredPlaced.edge}\n                    className=\"mt-1\"\n                    rpsFormatter={rpsFormatter}\n                    latencyFormatter={latencyFormatter}\n                    errorRateFormatter={errorRateFormatter}\n                    errorClass={errorClass}\n                  />\n                </div>\n              ) : null}\n            </div>\n          )}\n        </div>\n      </div>\n\n      {selectedNode ? (\n        <ServiceDetail\n          key={selectedNode.id}\n          node={selectedNode}\n          status={statusOf(selectedNode)}\n          icon={iconFor(selectedNode, 16)}\n          inbound={inbound.get(selectedNode.id) ?? []}\n          outbound={outbound.get(selectedNode.id) ?? []}\n          byId={byId}\n          statusOf={statusOf}\n          severityOf={severityOf}\n          formatMetrics={formatMetrics}\n          errorClass={errorClass}\n          edgeKey={(edge) =>\n            placement.edges.find((placed) => placed.edge === edge)?.key ?? null\n          }\n          onHoverEdge={setHoveredEdge}\n          onSelect={(nodeId) => {\n            select(nodeId);\n            requestAnimationFrame(() => focusNode(nodeId));\n          }}\n          onClose={() => select(null)}\n          rpsFormatter={rpsFormatter}\n          latencyFormatter={latencyFormatter}\n          errorRateFormatter={errorRateFormatter}\n        />\n      ) : null}\n\n      {showLegend ? (\n        <div\n          data-slot=\"service-map-legend\"\n          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\"\n        >\n          {(\n            [\n              [\"ok\", \"Healthy traffic\"],\n              [\"warn\", `Errors ≥ ${errorRateFormatter(warn)}`],\n              [\"critical\", `Errors ≥ ${errorRateFormatter(critical)}`],\n            ] as const\n          ).map(([severity, label]) => (\n            <span key={severity} className=\"flex items-center gap-2\">\n              <svg aria-hidden=\"true\" width=\"22\" height=\"8\" className=\"shrink-0 overflow-visible\">\n                <line\n                  x1=\"1\"\n                  y1=\"4\"\n                  x2=\"21\"\n                  y2=\"4\"\n                  stroke={severityStroke[severity]}\n                  strokeWidth=\"2\"\n                  strokeLinecap=\"round\"\n                />\n                <circle cx=\"13\" cy=\"4\" r=\"2\" fill={severityFlow[severity]} />\n              </svg>\n              {label}\n            </span>\n          ))}\n          <span className=\"flex items-center gap-2 @2xl/service-map:ml-auto\">\n            <svg aria-hidden=\"true\" width=\"22\" height=\"8\" className=\"shrink-0\">\n              <path d=\"M1 3.5 L21 1 L21 7 L1 4.5 Z\" fill=\"var(--sm-ok)\" />\n            </svg>\n            Width shows requests per second\n          </span>\n        </div>\n      ) : null}\n\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {selectedNode\n          ? `${selectedNode.label} selected, ${statusLabel[statusOf(selectedNode)].toLowerCase()}. ${inbound.get(selectedNode.id)?.length ?? 0} inbound and ${outbound.get(selectedNode.id)?.length ?? 0} outbound connections.`\n          : \"\"}\n        {hoveredPlaced ? ` ${byId.get(hoveredPlaced.edge.source)?.label} to ${byId.get(hoveredPlaced.edge.target)?.label}: ${edgeSummary(hoveredPlaced.edge)}` : \"\"}\n      </p>\n    </div>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Detail                                                                    */\n/* ------------------------------------------------------------------------ */\n\n/** Floating readout for compact tiles, which have no room for a metrics line. */\nfunction NodeReadout({\n  node,\n  status,\n  formatted,\n  errorClass,\n  rect,\n  cardW,\n  cardH,\n  scale,\n  worldWidth,\n}: {\n  node: ServiceMapNode;\n  status: ServiceStatus;\n  formatted: { rps?: string; errorRate?: string; p95?: string };\n  errorClass: string;\n  rect: { x: number; y: number };\n  cardW: number;\n  cardH: number;\n  scale: number;\n  worldWidth: number;\n}) {\n  const above = rect.y * scale > 56;\n  const parts = [\n    formatted.rps ? <span key=\"rps\" className=\"font-medium text-foreground\">{formatted.rps}</span> : null,\n    formatted.errorRate ? (\n      <span key=\"err\" className={cn(\"font-medium text-foreground\", errorClass)}>\n        {formatted.errorRate}\n      </span>\n    ) : null,\n    formatted.p95 ? <span key=\"p95\">p95 {formatted.p95}</span> : null,\n  ].filter(Boolean);\n  return (\n    <div\n      aria-hidden=\"true\"\n      data-slot=\"service-map-node-readout\"\n      className={cn(\n        \"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]\",\n        above ? \"-translate-y-[calc(100%+6px)]\" : \"translate-y-1.5\",\n      )}\n      style={{\n        left: Math.min(Math.max((rect.x + cardW / 2) * scale, 84), worldWidth - 84),\n        top: above ? rect.y * scale : (rect.y + cardH) * scale,\n      }}\n    >\n      <p className=\"flex items-center gap-1.5 text-xs font-medium\">\n        <StatusDot status={status} />\n        {node.label}\n        <span className=\"font-normal text-muted-foreground\">\n          {statusLabel[status].toLowerCase()}\n        </span>\n      </p>\n      {parts.length ? (\n        <p className=\"mt-1 flex items-center gap-1.5 text-xs text-muted-foreground tabular-nums\">\n          {parts.flatMap((part, i) =>\n            i === 0\n              ? [part]\n              : [\n                  <span key={`sep${i}`} aria-hidden=\"true\" className=\"text-muted-foreground/45\">\n                    ·\n                  </span>,\n                  part,\n                ],\n          )}\n        </p>\n      ) : null}\n    </div>\n  );\n}\n\nfunction EdgeMetrics({\n  edge,\n  className,\n  rpsFormatter,\n  latencyFormatter,\n  errorRateFormatter,\n  errorClass,\n}: {\n  edge: ServiceMapEdge;\n  className?: string;\n  rpsFormatter: (rps: number) => string;\n  latencyFormatter: (ms: number) => string;\n  errorRateFormatter: (rate: number) => string;\n  errorClass: (rate: number | undefined) => string;\n}) {\n  return (\n    <p className={cn(\"flex items-center gap-3 text-xs text-muted-foreground tabular-nums\", className)}>\n      {edge.rps != null ? (\n        <span>\n          <span className=\"font-medium text-foreground\">{rpsFormatter(edge.rps)}</span>\n        </span>\n      ) : null}\n      {edge.errorRate != null ? (\n        <span>\n          <span className={cn(\"font-medium text-foreground\", errorClass(edge.errorRate))}>\n            {errorRateFormatter(edge.errorRate)}\n          </span>{\" \"}\n          errors\n        </span>\n      ) : null}\n      {edge.p95 != null ? (\n        <span>\n          p95{\" \"}\n          <span className=\"font-medium text-foreground\">{latencyFormatter(edge.p95)}</span>\n        </span>\n      ) : null}\n    </p>\n  );\n}\n\nfunction ServiceDetail({\n  node,\n  status,\n  icon,\n  inbound,\n  outbound,\n  byId,\n  statusOf,\n  severityOf,\n  formatMetrics,\n  errorClass,\n  edgeKey,\n  onHoverEdge,\n  onSelect,\n  onClose,\n  rpsFormatter,\n  latencyFormatter,\n  errorRateFormatter,\n}: {\n  node: ServiceMapNode;\n  status: ServiceStatus;\n  icon: React.ReactNode;\n  inbound: ServiceMapEdge[];\n  outbound: ServiceMapEdge[];\n  byId: Map<string, ServiceMapNode>;\n  statusOf: (node: ServiceMapNode) => ServiceStatus;\n  severityOf: (edge: ServiceMapEdge) => Severity;\n  formatMetrics: (metrics?: ServiceMetrics) => { rps?: string; errorRate?: string; p95?: string };\n  errorClass: (rate: number | undefined) => string;\n  edgeKey: (edge: ServiceMapEdge) => string | null;\n  onHoverEdge: (key: string | null) => void;\n  onSelect: (id: string) => void;\n  onClose: () => void;\n  rpsFormatter: (rps: number) => string;\n  latencyFormatter: (ms: number) => string;\n  errorRateFormatter: (rate: number) => string;\n}) {\n  const formatted = formatMetrics(node.metrics);\n  const figures = [\n    { key: \"rps\", label: \"Requests\", value: formatted.rps, className: \"\" },\n    {\n      key: \"err\",\n      label: \"Error rate\",\n      value: formatted.errorRate,\n      className: errorClass(node.metrics?.errorRate),\n    },\n    { key: \"p95\", label: \"p95 latency\", value: formatted.p95, className: \"\" },\n  ].filter((figure) => figure.value != null);\n\n  const list = (title: string, items: ServiceMapEdge[], side: \"in\" | \"out\") => (\n    <div className=\"min-w-0\">\n      <h4 className=\"mb-1.5 flex items-baseline gap-1.5 text-xs text-muted-foreground\">\n        {title}\n        <span className=\"tabular-nums\">{items.length}</span>\n      </h4>\n      {items.length ? (\n        <ul className=\"-mx-2 flex flex-col\">\n          {items.map((edge, i) => {\n            const otherId = side === \"in\" ? edge.source : edge.target;\n            const other = byId.get(otherId);\n            const severity = severityOf(edge);\n            const key = edgeKey(edge);\n            return (\n              <li key={`${otherId}-${i}`}>\n                <button\n                  type=\"button\"\n                  data-slot=\"service-map-detail-edge\"\n                  data-severity={severity}\n                  onPointerEnter={() => onHoverEdge(key)}\n                  onPointerLeave={() => onHoverEdge(null)}\n                  onFocus={() => onHoverEdge(key)}\n                  onBlur={() => onHoverEdge(null)}\n                  onClick={() => other && onSelect(other.id)}\n                  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}.`}\n                  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\"\n                >\n                  <span className=\"flex min-w-0 items-center gap-2\">\n                    <span\n                      aria-hidden=\"true\"\n                      className=\"h-0.5 w-3 shrink-0 rounded-full\"\n                      style={{ backgroundColor: severityStroke[severity] === \"var(--sm-ok)\" ? \"var(--sm-flow)\" : severityStroke[severity] }}\n                    />\n                    <span className=\"truncate font-medium text-foreground\">\n                      {other?.label ?? otherId}\n                    </span>\n                    {other && statusOf(other) !== \"healthy\" ? (\n                      <StatusDot status={statusOf(other)} className=\"size-1.5\" />\n                    ) : null}\n                  </span>\n                  <span className=\"text-right text-foreground tabular-nums\">\n                    {edge.rps != null ? rpsFormatter(edge.rps) : \"—\"}\n                  </span>\n                  <span className={cn(\"text-right text-muted-foreground tabular-nums\", errorClass(edge.errorRate))}>\n                    {edge.errorRate != null ? errorRateFormatter(edge.errorRate) : \"—\"}\n                  </span>\n                  <span className=\"text-right text-muted-foreground tabular-nums\">\n                    {edge.p95 != null ? latencyFormatter(edge.p95) : \"—\"}\n                  </span>\n                </button>\n              </li>\n            );\n          })}\n        </ul>\n      ) : (\n        <p className=\"py-1.5 text-xs text-muted-foreground\">None</p>\n      )}\n    </div>\n  );\n\n  return (\n    <section\n      data-slot=\"service-map-detail\"\n      aria-label={`${node.label} details`}\n      className=\"border-t border-border/60 px-5 pt-4 pb-4 motion-safe:animate-[service-map-fade_240ms_ease-out]\"\n    >\n      <div className=\"flex items-start gap-3\">\n        <span\n          aria-hidden=\"true\"\n          className={cn(\n            \"grid size-9 shrink-0 place-items-center rounded-lg bg-muted text-foreground ring-1 ring-border/60 ring-inset [&>svg]:size-4\",\n            status === \"degraded\" && \"bg-amber-500/12 text-amber-700 ring-amber-500/25 dark:text-amber-400\",\n            status === \"down\" && \"bg-destructive/12 text-destructive ring-destructive/25\",\n          )}\n        >\n          {icon}\n        </span>\n        <div className=\"min-w-0 flex-1\">\n          <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n            <h4 className=\"text-sm leading-5 font-semibold tracking-tight\">\n              {node.label}\n            </h4>\n            <span\n              className={cn(\n                \"inline-flex h-5 items-center gap-1.5 rounded-full px-2 text-[11px] font-medium\",\n                statusPill[status],\n              )}\n            >\n              <span aria-hidden=\"true\" className={cn(\"size-1.5 rounded-full\", statusDot[status])} />\n              {statusLabel[status]}\n            </span>\n          </div>\n          <p className=\"text-xs text-muted-foreground\">\n            {kindLabel[node.kind ?? \"service\"][0].toUpperCase() + kindLabel[node.kind ?? \"service\"].slice(1)}\n            {node.group ? (\n              <>\n                {\" · \"}\n                <span className=\"font-mono\">{node.group}</span>\n              </>\n            ) : null}\n          </p>\n        </div>\n        <button\n          type=\"button\"\n          onClick={onClose}\n          aria-label=\"Clear selection\"\n          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\"\n        >\n          <IconX aria-hidden=\"true\" size={15} />\n        </button>\n      </div>\n\n      {figures.length ? (\n        <dl className=\"mt-3 grid grid-cols-3 gap-2\">\n          {figures.map((figure) => {\n            const match = /^([-+<]?[\\d.,]+)\\s*(\\D.*)?$/.exec(figure.value!);\n            return (\n              <div\n                key={figure.key}\n                className=\"rounded-lg bg-muted/40 px-3 py-2 ring-1 ring-border/50 ring-inset\"\n              >\n                <dt className=\"text-[11px] text-muted-foreground\">{figure.label}</dt>\n                <dd className={cn(\"text-lg leading-7 font-semibold tracking-[-0.02em] tabular-nums\", figure.className)}>\n                  {match ? (\n                    <>\n                      {match[1]}\n                      {match[2] ? (\n                        <span\n                          className={cn(\n                            \"text-xs font-medium tracking-normal text-muted-foreground\",\n                            /^[a-zµ]/i.test(match[2]) && \"ml-0.5\",\n                          )}\n                        >\n                          {match[2]}\n                        </span>\n                      ) : null}\n                    </>\n                  ) : (\n                    figure.value\n                  )}\n                </dd>\n              </div>\n            );\n          })}\n        </dl>\n      ) : null}\n\n      <div className=\"mt-4 grid gap-x-8 gap-y-4 @2xl/service-map:grid-cols-2\">\n        {list(\"Inbound\", inbound, \"in\")}\n        {list(\"Outbound\", outbound, \"out\")}\n      </div>\n    </section>\n  );\n}\n\nexport { ServiceMap };\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/service-map. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
