{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ds-sankey-chart",
  "description": "Sankey diagram using pure SVG — no external dependencies.",
  "dependencies": [
    "class-variance-authority"
  ],
  "registryDependencies": [
    "@lema-ds/skeleton",
    "@lema-ds/card",
    "@lema-ds/ui-i18n",
    "@lema-ds/format-utils",
    "@lema-ds/ds-locale-provider"
  ],
  "files": [
    {
      "path": "components/ds/ds-sankey-chart.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { cva } from \"class-variance-authority\"\nimport { cn } from \"@/lib/utils\"\nimport { Skeleton } from \"@/components/ui/skeleton\"\nimport { UI_I18N, type UILocale } from \"@/lib/ui-i18n\"\nimport { useUILocale } from \"@/components/ui/ds-locale-provider\"\nimport { formatChartValue, type FormatPreset } from \"@/lib/format-utils\"\nimport {\n  Card,\n  CardContent,\n  CardDescription,\n  CardFooter,\n  CardHeader,\n  CardTitle,\n} from \"@/components/ui/card\"\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface SankeyNode {\n  id: string\n  name: string\n  color?: string\n}\n\nexport interface SankeyLink {\n  source: string\n  target: string\n  value: number\n}\n\nexport interface SankeyChartProps extends React.HTMLAttributes<HTMLDivElement> {\n  nodes: SankeyNode[]\n  links: SankeyLink[]\n  title?: string\n  subtitle?: string\n  footer?: React.ReactNode\n  height?: number\n  nodeWidth?: number\n  nodePadding?: number\n  showLabels?: boolean\n  showValues?: boolean\n  valueFormatter?: (v: number) => string\n  format?: FormatPreset\n  decimals?: number\n  currency?: string\n  abbreviate?: boolean\n  loading?: boolean\n  locale?: UILocale\n}\n\n// ── Variants ───────────────────────────────────────────────────────────────\n\nexport const sankeyChartContainerVariants = cva(\"w-full overflow-visible\", {\n  variants: {},\n})\n\n// ── Constants ──────────────────────────────────────────────────────────────\n\nconst CHART_COLORS = [\n  \"var(--chart-1)\",\n  \"var(--chart-2)\",\n  \"var(--chart-3)\",\n  \"var(--chart-4)\",\n  \"var(--chart-5)\",\n]\n\n// ── SVG Sankey Layout Engine ───────────────────────────────────────────────\n\ninterface LayoutNode extends SankeyNode {\n  x: number\n  y: number\n  width: number\n  height: number\n  column: number\n  colorIndex: number\n}\n\ninterface LayoutLink {\n  source: LayoutNode\n  target: LayoutNode\n  value: number\n  sourceY: number\n  targetY: number\n  thickness: number\n  color: string\n  opacity: number\n}\n\nfunction layoutSankey(\n  nodes: SankeyNode[],\n  links: SankeyLink[],\n  width: number,\n  height: number,\n  nodeWidth: number,\n  nodePadding: number\n): { nodes: LayoutNode[]; links: LayoutLink[] } {\n  // Build adjacency\n  const nodeMap = new Map<string, number>()\n  nodes.forEach((n, i) => nodeMap.set(n.id, i))\n\n  // Determine columns using BFS from source nodes\n  const inDegree = new Map<string, number>()\n  nodes.forEach((n) => inDegree.set(n.id, 0))\n  links.forEach((l) =>\n    inDegree.set(l.target, (inDegree.get(l.target) ?? 0) + 1)\n  )\n\n  const columns = new Map<string, number>()\n  const queue = nodes\n    .filter((n) => (inDegree.get(n.id) ?? 0) === 0)\n    .map((n) => n.id)\n  queue.forEach((id) => columns.set(id, 0))\n\n  let head = 0\n  while (head < queue.length) {\n    const curr = queue[head++]!\n    links.forEach((l) => {\n      if (l.source === curr) {\n        const newCol = (columns.get(curr) ?? 0) + 1\n        if ((columns.get(l.target) ?? -1) < newCol) {\n          columns.set(l.target, newCol)\n          queue.push(l.target)\n        }\n      }\n    })\n  }\n\n  // Nodes not reachable from source\n  nodes.forEach((n) => {\n    if (!columns.has(n.id)) columns.set(n.id, 0)\n  })\n\n  const maxCol = Math.max(...Array.from(columns.values()))\n  const numCols = maxCol + 1\n\n  // Group by column\n  const byCol: Map<number, SankeyNode[]> = new Map()\n  nodes.forEach((n) => {\n    const col = columns.get(n.id) ?? 0\n    if (!byCol.has(col)) byCol.set(col, [])\n    byCol.get(col)!.push(n)\n  })\n\n  // Compute node values (sum of outgoing or incoming links)\n  const nodeValue = new Map<string, number>()\n  nodes.forEach((n) => nodeValue.set(n.id, 0))\n  links.forEach((l) => {\n    nodeValue.set(l.source, (nodeValue.get(l.source) ?? 0) + l.value)\n    nodeValue.set(l.target, (nodeValue.get(l.target) ?? 0) + l.value)\n  })\n\n  // Compute layout\n  const colXStep = numCols > 1 ? (width - nodeWidth) / (numCols - 1) : 0\n  const layoutNodes: LayoutNode[] = []\n  let colorIdx = 0\n\n  for (const [col, colNodes] of byCol.entries()) {\n    const totalValue = colNodes.reduce(\n      (s, n) => s + (nodeValue.get(n.id) ?? 1),\n      0\n    )\n    const availableHeight = height - nodePadding * (colNodes.length - 1)\n    let yOffset = 0\n\n    colNodes.forEach((n) => {\n      const v = nodeValue.get(n.id) ?? 1\n      const nodeH = Math.max(8, (v / totalValue) * availableHeight)\n      layoutNodes.push({\n        ...n,\n        x: col * colXStep,\n        y: yOffset,\n        width: nodeWidth,\n        height: nodeH,\n        column: col,\n        colorIndex: colorIdx % 5,\n      })\n      yOffset += nodeH + nodePadding\n      colorIdx++\n    })\n  }\n\n  // Compute link paths\n  const nodeById = new Map<string, LayoutNode>()\n  layoutNodes.forEach((n) => nodeById.set(n.id, n))\n\n  // Track offsets for link placement on source/target nodes\n  const sourceOffset = new Map<string, number>()\n  const targetOffset = new Map<string, number>()\n  layoutNodes.forEach((n) => {\n    sourceOffset.set(n.id, n.y)\n    targetOffset.set(n.id, n.y)\n  })\n\n  const layoutLinks: LayoutLink[] = links.map((l) => {\n    const src = nodeById.get(l.source)!\n    const tgt = nodeById.get(l.target)!\n    const srcNode = layoutNodes.find((n) => n.id === l.source)!\n    const tgtNode = layoutNodes.find((n) => n.id === l.target)!\n\n    const totalSrcValue = links\n      .filter((lk) => lk.source === l.source)\n      .reduce((s, lk) => s + lk.value, 0)\n    const totalTgtValue = links\n      .filter((lk) => lk.target === l.target)\n      .reduce((s, lk) => s + lk.value, 0)\n\n    const srcH = (l.value / totalSrcValue) * srcNode.height\n    const tgtH = (l.value / totalTgtValue) * tgtNode.height\n    const thickness = Math.max(2, Math.min(srcH, tgtH))\n\n    const sy = (sourceOffset.get(l.source) ?? srcNode.y) + thickness / 2\n    const ty = (targetOffset.get(l.target) ?? tgtNode.y) + thickness / 2\n\n    sourceOffset.set(l.source, sy - thickness / 2 + thickness)\n    targetOffset.set(l.target, ty - thickness / 2 + thickness)\n\n    const srcColor =\n      src.color ?? CHART_COLORS[src.colorIndex % CHART_COLORS.length]!\n\n    return {\n      source: src,\n      target: tgt,\n      value: l.value,\n      sourceY: sy,\n      targetY: ty,\n      thickness,\n      color: srcColor,\n      opacity: 0.35,\n    }\n  })\n\n  return { nodes: layoutNodes, links: layoutLinks }\n}\n\n// ── SankeyChart ────────────────────────────────────────────────────────────\n\nexport function SankeyChart({\n  nodes,\n  links,\n  title,\n  subtitle,\n  footer,\n  height = 360,\n  nodeWidth = 18,\n  nodePadding = 16,\n  showLabels = true,\n  showValues = true,\n  valueFormatter,\n  format,\n  decimals = 0,\n  currency = \"USD\",\n  abbreviate = false,\n  loading = false,\n  locale: localeProp,\n  className,\n  ...props\n}: SankeyChartProps) {\n  const locale = useUILocale(localeProp)\n  const containerRef = React.useRef<HTMLDivElement>(null)\n  const [svgWidth, setSvgWidth] = React.useState(600)\n\n  React.useEffect(() => {\n    const el = containerRef.current\n    if (!el) return\n    setSvgWidth(el.clientWidth)\n    const ro = new ResizeObserver((entries) => {\n      setSvgWidth(entries[0]!.contentRect.width)\n    })\n    ro.observe(el)\n    return () => ro.disconnect()\n  }, [])\n\n  const formatValue = React.useCallback(\n    (v: number) => {\n      if (valueFormatter) return valueFormatter(v)\n      return formatChartValue(v, {\n        format,\n        decimals,\n        locale,\n        currency,\n        abbreviate,\n      })\n    },\n    [valueFormatter, format, decimals, locale, currency, abbreviate]\n  )\n\n  // ── Loading ─────────────────────────────────────────────────────────────\n\n  if (loading) {\n    return (\n      <Card className={cn(\"w-full\", className)} {...props}>\n        {(title || subtitle) && (\n          <CardHeader>\n            {title && <Skeleton className=\"h-5 w-48\" />}\n            {subtitle && <Skeleton className=\"mt-1 h-4 w-64\" />}\n          </CardHeader>\n        )}\n        <CardContent>\n          <Skeleton className=\"w-full rounded-lg\" style={{ height }} />\n        </CardContent>\n        {footer && <CardFooter>{footer}</CardFooter>}\n      </Card>\n    )\n  }\n\n  // ── Empty ────────────────────────────────────────────────────────────────\n\n  if (nodes.length === 0 || links.length === 0) {\n    return (\n      <Card className={cn(\"w-full\", className)} {...props}>\n        {(title || subtitle) && (\n          <CardHeader>\n            {title && <CardTitle>{title}</CardTitle>}\n            {subtitle && <CardDescription>{subtitle}</CardDescription>}\n          </CardHeader>\n        )}\n        <CardContent>\n          <div\n            className=\"flex items-center justify-center text-sm text-muted-foreground\"\n            style={{ height }}\n          >\n            {UI_I18N[locale].emptyState.noData}\n          </div>\n        </CardContent>\n        {footer && <CardFooter>{footer}</CardFooter>}\n      </Card>\n    )\n  }\n\n  const innerH = height - 16\n  const innerW = svgWidth - (showLabels ? 80 : 16)\n  const { nodes: lnodes, links: llinks } = layoutSankey(\n    nodes,\n    links,\n    innerW,\n    innerH,\n    nodeWidth,\n    nodePadding\n  )\n\n  const labelOffset = showLabels ? 40 : 8\n\n  return (\n    <Card className={cn(\"w-full\", className)} {...props}>\n      {(title || subtitle) && (\n        <CardHeader>\n          {title && <CardTitle>{title}</CardTitle>}\n          {subtitle && <CardDescription>{subtitle}</CardDescription>}\n        </CardHeader>\n      )}\n      <CardContent>\n        <div\n          ref={containerRef}\n          className={sankeyChartContainerVariants()}\n          style={{ height }}\n          role=\"img\"\n          aria-label={title ?? \"Sankey diagram\"}\n        >\n          <svg\n            width=\"100%\"\n            height={innerH}\n            viewBox={`0 0 ${svgWidth} ${innerH}`}\n            overflow=\"visible\"\n          >\n            <g transform={`translate(${labelOffset}, 8)`}>\n              {/* Links */}\n              {llinks.map((link, i) => {\n                const x1 = link.source.x + nodeWidth\n                const x2 = link.target.x\n                const y1 = link.sourceY\n                const y2 = link.targetY\n                const cx = (x1 + x2) / 2\n                const d = `M ${x1},${y1} C ${cx},${y1} ${cx},${y2} ${x2},${y2}`\n                return (\n                  <path\n                    key={`link-${i}`}\n                    d={d}\n                    fill=\"none\"\n                    stroke={link.color}\n                    strokeWidth={link.thickness}\n                    strokeOpacity={link.opacity}\n                  >\n                    <title>\n                      {link.source.name} → {link.target.name}:{\" \"}\n                      {formatValue(link.value)}\n                    </title>\n                  </path>\n                )\n              })}\n\n              {/* Nodes */}\n              {lnodes.map((node) => {\n                const color =\n                  node.color ??\n                  CHART_COLORS[node.colorIndex % CHART_COLORS.length]\n                const isLastCol =\n                  node.column === Math.max(...lnodes.map((n) => n.column))\n\n                return (\n                  <g key={node.id}>\n                    <rect\n                      x={node.x}\n                      y={node.y}\n                      width={nodeWidth}\n                      height={node.height}\n                      fill={color}\n                      rx={3}\n                    >\n                      <title>{node.name}</title>\n                    </rect>\n                    {showLabels && (\n                      <text\n                        x={isLastCol ? node.x + nodeWidth + 6 : node.x - 6}\n                        y={node.y + node.height / 2}\n                        textAnchor={isLastCol ? \"start\" : \"end\"}\n                        dominantBaseline=\"middle\"\n                        className=\"fill-foreground text-xs font-medium\"\n                        fontSize={11}\n                      >\n                        {node.name}\n                      </text>\n                    )}\n                    {showValues && (\n                      <text\n                        x={isLastCol ? node.x + nodeWidth + 6 : node.x - 6}\n                        y={node.y + node.height / 2 + 14}\n                        textAnchor={isLastCol ? \"start\" : \"end\"}\n                        dominantBaseline=\"middle\"\n                        className=\"fill-muted-foreground\"\n                        fontSize={10}\n                      >\n                        {formatValue(\n                          links\n                            .filter(\n                              (l) =>\n                                l.source === node.id || l.target === node.id\n                            )\n                            .reduce((s, l) => s + l.value, 0) / 2\n                        )}\n                      </text>\n                    )}\n                  </g>\n                )\n              })}\n            </g>\n          </svg>\n        </div>\n      </CardContent>\n      {footer && <CardFooter>{footer}</CardFooter>}\n    </Card>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}
