{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ds-treemap-chart",
  "title": "Treemap Chart",
  "description": "A responsive treemap chart with hierarchical drill-down, breadcrumb navigation, and aspect ratio control.",
  "dependencies": [
    "recharts",
    "class-variance-authority",
    "lucide-react"
  ],
  "registryDependencies": [
    "@lema-ds/skeleton",
    "@lema-ds/ui-i18n",
    "@lema-ds/format-utils",
    "@lema-ds/ds-locale-provider"
  ],
  "files": [
    {
      "path": "components/ds/ds-treemap-chart.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { ResponsiveContainer, Treemap, Tooltip } from \"recharts\"\nimport { cva } from \"class-variance-authority\"\nimport { ChevronRight, Home, Layers } from \"lucide-react\"\nimport { cn } from \"@/lib/utils\"\nimport { Skeleton } from \"@/components/ui/skeleton\"\nimport { formatChartValue, type FormatPreset } from \"@/lib/format-utils\"\nimport { UI_I18N, type UILocale } from \"@/lib/ui-i18n\"\nimport { useUILocale } from \"@/components/ui/ds-locale-provider\"\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface TreeMapItem {\n  name: string\n  value?: number\n  color?: string\n  children?: TreeMapItem[]\n}\n\ninterface EnrichedItem extends Omit<TreeMapItem, \"children\"> {\n  color: string\n  /** True when this node has drillable children */\n  _hasChildren: boolean\n  /** Enriched children for drill-down (separate from recharts' `children`) */\n  _children?: EnrichedItem[]\n  children?: EnrichedItem[]\n  [key: string]: unknown\n}\n\nexport interface TreeMapChartProps extends React.HTMLAttributes<HTMLDivElement> {\n  data: TreeMapItem[]\n  title?: string\n  subtitle?: string\n  footer?: React.ReactNode\n  height?: number\n  aspectRatio?: number\n  /** Show name + value labels inside each cell (hidden below size threshold) */\n  showLabels?: boolean\n  showTooltip?: boolean\n  /** Format the numeric value displayed in labels and tooltip */\n  valueFormatter?: (value: number) => string\n  format?: FormatPreset\n  decimals?: number\n  currency?: string\n  abbreviate?: boolean\n  /** Show animated skeleton in place of the chart while data loads */\n  loading?: boolean\n  locale?: UILocale\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// ── Skeleton ───────────────────────────────────────────────────────────────\n\nconst TREEMAP_TILES = [\n  { x: 0, y: 0, w: 57, h: 54 },\n  { x: 57, y: 0, w: 43, h: 30 },\n  { x: 57, y: 30, w: 43, h: 24 },\n  { x: 0, y: 54, w: 34, h: 46 },\n  { x: 34, y: 54, w: 28, h: 46 },\n  { x: 62, y: 54, w: 38, h: 24 },\n  { x: 62, y: 78, w: 38, h: 22 },\n]\n\ninterface TreeMapChartSkeletonProps {\n  height?: number\n  hasTitle?: boolean\n  hasSubtitle?: boolean\n  hasFooter?: boolean\n  className?: string\n}\n\nfunction TreeMapChartSkeleton({\n  height = 360,\n  hasTitle = false,\n  hasSubtitle = false,\n  hasFooter = false,\n  className,\n}: TreeMapChartSkeletonProps) {\n  return (\n    <div\n      className={cn(\"flex w-full flex-col\", className)}\n      data-slot=\"treemap-chart-skeleton\"\n    >\n      {(hasTitle || hasSubtitle) && (\n        <div className=\"flex flex-col gap-1.5 px-1 pb-4\">\n          {hasTitle && (\n            <Skeleton\n              className=\"h-3.5 w-44 rounded-md\"\n              style={{ animationDelay: \"0s\" }}\n            />\n          )}\n          {hasSubtitle && (\n            <Skeleton\n              className=\"mt-0.5 h-2.5 w-28 rounded-md\"\n              style={{ animationDelay: \"0.1s\" }}\n            />\n          )}\n        </div>\n      )}\n\n      <div className=\"relative w-full\" style={{ height }}>\n        {TREEMAP_TILES.map((tile, i) => (\n          <Skeleton\n            key={i}\n            className=\"absolute rounded-sm\"\n            style={{\n              left: `${tile.x}%`,\n              top: `${tile.y}%`,\n              width: `calc(${tile.w}% - 4px)`,\n              height: `calc(${tile.h}% - 4px)`,\n              animationDelay: `${i * 0.1}s`,\n            }}\n          />\n        ))}\n      </div>\n\n      {hasFooter && (\n        <div className=\"mt-4 flex items-center gap-2 border-t border-border px-1 pt-3\">\n          <Skeleton\n            className=\"h-3.5 w-3.5 shrink-0 rounded-full\"\n            style={{ animationDelay: \"0.7s\" }}\n          />\n          <Skeleton\n            className=\"h-2.5 w-36 rounded-md\"\n            style={{ animationDelay: \"0.8s\" }}\n          />\n          <Skeleton\n            className=\"ml-auto h-2.5 w-20 rounded-md\"\n            style={{ animationDelay: \"0.9s\" }}\n          />\n        </div>\n      )}\n    </div>\n  )\n}\n\n// ── Variants ───────────────────────────────────────────────────────────────\n\nconst chartWrapperVariants = cva(\"flex w-full flex-col\")\n\nconst chartHeaderVariants = cva(\"flex flex-col px-1 pb-4\")\n\nconst chartTitleVariants = cva(\n  \"text-sm leading-tight font-semibold text-foreground\"\n)\n\nconst chartSubtitleVariants = cva(\"mt-0.5 text-xs text-muted-foreground\")\n\nconst chartFooterVariants = cva(\n  \"mt-4 flex items-center gap-2 border-t border-border px-1 pt-3 text-xs text-muted-foreground\"\n)\n\n// ── Custom Tooltip ─────────────────────────────────────────────────────────\n\ninterface TooltipEntry {\n  name?: string\n  value?: number\n  payload?: Record<string, unknown>\n}\n\nfunction ChartTooltip({\n  active,\n  payload,\n  fmt,\n}: {\n  active?: boolean\n  payload?: TooltipEntry[]\n  fmt: (v: number) => string\n}) {\n  if (!active || !payload?.length) return null\n\n  const entry = payload[0]\n  const name = entry.name ?? (entry.payload?.name as string | undefined) ?? \"\"\n  const value = entry.value ?? (entry.payload?.value as number | undefined)\n  const color = (entry.payload?.color as string | undefined) ?? \"var(--chart-1)\"\n\n  return (\n    <div className=\"min-w-36 rounded-lg border border-border bg-card px-3 py-2 shadow-md\">\n      <p className=\"mb-1.5 text-xs font-semibold text-foreground\">{name}</p>\n      {value !== undefined && (\n        <div className=\"flex items-center gap-2\">\n          <span\n            className=\"inline-block size-2 shrink-0 rounded-full\"\n            style={{ backgroundColor: color }}\n          />\n          <span className=\"ml-auto text-xs font-semibold text-foreground tabular-nums\">\n            {fmt(value)}\n          </span>\n        </div>\n      )}\n    </div>\n  )\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\nfunction enrichData(\n  items: TreeMapItem[],\n  idx = 0,\n  parentColor?: string\n): EnrichedItem[] {\n  return items.map((item, i) => {\n    const color =\n      item.color ?? parentColor ?? CHART_COLORS[(idx + i) % CHART_COLORS.length]\n    const enrichedChildren = item.children?.length\n      ? enrichData(item.children, idx + i + 1, color)\n      : undefined\n    return {\n      ...item,\n      color,\n      _hasChildren: !!item.children?.length,\n      _children: enrichedChildren,\n      children: enrichedChildren,\n    }\n  })\n}\n\n// ── CustomizedContent ─────────────────────────────────────────────────────\n\ninterface CellDataProps {\n  x?: number\n  y?: number\n  width?: number\n  height?: number\n  depth?: number\n  name?: string\n  value?: number\n  color?: string\n  _hasChildren?: boolean\n  _children?: EnrichedItem[]\n}\n\ninterface CellBehaviorProps {\n  showLabels: boolean\n  fmt: (v: number) => string\n  locale: string\n  onNodeClick?: (name: string, children: EnrichedItem[]) => void\n}\n\nfunction CustomizedContent(props: CellDataProps & CellBehaviorProps) {\n  const {\n    x = 0,\n    y = 0,\n    width = 0,\n    height = 0,\n    depth = 0,\n    name = \"\",\n    value = 0,\n    color = \"var(--chart-1)\",\n    _hasChildren = false,\n    _children,\n    showLabels,\n    fmt,\n    locale,\n    onNodeClick,\n  } = props\n\n  const formatted = fmt(value)\n  const canLabel = showLabels && width > 64 && height > 44\n  const nameFontSize = Math.max(Math.min(width / 11, 13), 10)\n  const valueFontSize = Math.max(Math.min(width / 14, 11), 9)\n\n  const handleClick = () => {\n    if (_hasChildren && _children?.length && onNodeClick) {\n      onNodeClick(name, _children)\n    }\n  }\n\n  return (\n    <g>\n      <rect\n        x={x}\n        y={y}\n        width={width}\n        height={height}\n        style={{\n          fill: color,\n          stroke: \"var(--card)\",\n          strokeWidth: depth <= 1 ? 2 : 1,\n          cursor: _hasChildren ? \"pointer\" : \"default\",\n          transition: \"filter 0.15s ease\",\n        }}\n        onClick={handleClick}\n        className={_hasChildren ? \"hover:brightness-110\" : undefined}\n      />\n      {canLabel && (\n        <foreignObject\n          x={x + 4}\n          y={y + 4}\n          width={width - 8}\n          height={height - 8}\n        >\n          <div\n            className=\"flex h-full w-full flex-col items-center justify-center overflow-hidden px-1\"\n            style={{ pointerEvents: \"none\", userSelect: \"none\" }}\n          >\n            <span\n              className=\"w-full truncate text-center leading-snug font-semibold text-white [text-shadow:0_1px_3px_rgba(0,0,0,0.45)]\"\n              style={{ fontSize: `${nameFontSize}px` }}\n            >\n              {name}\n            </span>\n            {value > 0 && (\n              <span\n                className=\"mt-0.5 w-full truncate text-center leading-snug text-white/90 [text-shadow:0_1px_3px_rgba(0,0,0,0.45)]\"\n                style={{ fontSize: `${valueFontSize}px` }}\n              >\n                {formatted}\n              </span>\n            )}\n            {_hasChildren && height > 60 && (\n              <span\n                className=\"mt-1 rounded-full bg-white/20 px-1.5 py-0.5 text-white/80 [text-shadow:0_1px_2px_rgba(0,0,0,0.4)]\"\n                style={{ fontSize: \"8px\", lineHeight: \"1.2\" }}\n              >\n                {UI_I18N[locale as UILocale]?.treemap?.explore ??\n                  \"click to explore\"}\n              </span>\n            )}\n          </div>\n        </foreignObject>\n      )}\n    </g>\n  )\n}\n\n// ── TreeMapChart ───────────────────────────────────────────────────────────\n\nexport function TreeMapChart({\n  data,\n  title,\n  subtitle,\n  footer,\n  height = 360,\n  aspectRatio = 4 / 3,\n  showLabels = true,\n  showTooltip = true,\n  valueFormatter,\n  format,\n  decimals,\n  currency,\n  abbreviate,\n  loading = false,\n  locale: localeProp,\n  className,\n  ...props\n}: TreeMapChartProps) {\n  const locale = useUILocale(localeProp)\n  // Hooks must be called unconditionally before any early returns\n  const fmt = React.useCallback(\n    (v: number) =>\n      formatChartValue(v, {\n        format,\n        decimals,\n        locale,\n        currency,\n        abbreviate,\n        valueFormatter,\n      }),\n    [valueFormatter, format, decimals, locale, currency, abbreviate]\n  )\n\n  const enrichedData = React.useMemo(() => enrichData(data), [data])\n\n  const [drillStack, setDrillStack] = React.useState<\n    { name: string; items: EnrichedItem[] }[]\n  >([])\n\n  const handleNodeClick = React.useCallback(\n    (name: string, children: EnrichedItem[]) => {\n      setDrillStack((prev) => [...prev, { name, items: children }])\n    },\n    []\n  )\n\n  const handleBreadcrumbClick = React.useCallback((index: number) => {\n    setDrillStack((prev) => prev.slice(0, index))\n  }, [])\n\n  const [prevData, setPrevData] = React.useState(data)\n  if (data !== prevData) {\n    setPrevData(data)\n    if (drillStack.length > 0) setDrillStack([])\n  }\n\n  const currentData =\n    drillStack.length > 0\n      ? drillStack[drillStack.length - 1].items\n      : enrichedData\n\n  if (loading) {\n    return (\n      <TreeMapChartSkeleton\n        height={height}\n        hasTitle={!!title}\n        hasSubtitle={!!subtitle}\n        hasFooter={!!footer}\n        className={className}\n      />\n    )\n  }\n\n  if (data.length === 0) {\n    return (\n      <div\n        className={cn(chartWrapperVariants(), className)}\n        data-slot=\"treemap-chart\"\n        {...props}\n      >\n        {(title || subtitle) && (\n          <div\n            className={chartHeaderVariants()}\n            data-slot=\"treemap-chart-header\"\n          >\n            {title && <p className={chartTitleVariants()}>{title}</p>}\n            {subtitle && <p className={chartSubtitleVariants()}>{subtitle}</p>}\n          </div>\n        )}\n        <div\n          className=\"flex flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border text-muted-foreground\"\n          data-slot=\"treemap-chart-empty\"\n          style={{ height }}\n        >\n          <div className=\"flex size-10 items-center justify-center rounded-full bg-muted\">\n            <Layers className=\"size-5\" />\n          </div>\n          <div className=\"text-center\">\n            <p className=\"text-sm font-medium text-foreground\">\n              {UI_I18N[locale].emptyState.noData}\n            </p>\n            <p className=\"mt-0.5 text-xs\">\n              {UI_I18N[locale].emptyState.dataWillAppear}\n            </p>\n          </div>\n        </div>\n        {footer && (\n          <div\n            className={chartFooterVariants()}\n            data-slot=\"treemap-chart-footer\"\n          >\n            {footer}\n          </div>\n        )}\n      </div>\n    )\n  }\n\n  return (\n    <div\n      className={cn(chartWrapperVariants(), className)}\n      data-slot=\"treemap-chart\"\n      {...props}\n    >\n      {(title || subtitle) && (\n        <div className={chartHeaderVariants()} data-slot=\"treemap-chart-header\">\n          {title && <p className={chartTitleVariants()}>{title}</p>}\n          {subtitle && <p className={chartSubtitleVariants()}>{subtitle}</p>}\n        </div>\n      )}\n\n      {drillStack.length > 0 && (\n        <nav\n          aria-label={UI_I18N[locale].treemap.breadcrumb}\n          className=\"mb-3 flex flex-wrap items-center gap-0.5 text-xs\"\n        >\n          <button\n            className=\"flex items-center gap-1 rounded px-1.5 py-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none\"\n            onClick={() => handleBreadcrumbClick(0)}\n          >\n            <Home className=\"size-3\" />\n            <span>Root</span>\n          </button>\n\n          {drillStack.map((seg, i) => (\n            <React.Fragment key={i}>\n              <ChevronRight className=\"size-3 shrink-0 text-muted-foreground/50\" />\n              <button\n                disabled={i === drillStack.length - 1}\n                className={cn(\n                  \"rounded px-1.5 py-0.5 transition-colors focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none\",\n                  i === drillStack.length - 1\n                    ? \"font-medium text-foreground\"\n                    : \"text-muted-foreground hover:bg-accent hover:text-accent-foreground\"\n                )}\n                onClick={() => handleBreadcrumbClick(i + 1)}\n              >\n                {seg.name}\n              </button>\n            </React.Fragment>\n          ))}\n        </nav>\n      )}\n\n      <ResponsiveContainer\n        width=\"100%\"\n        height={height}\n        data-slot=\"treemap-chart-chart\"\n      >\n        <Treemap\n          data={currentData}\n          dataKey=\"value\"\n          nameKey=\"name\"\n          aspectRatio={aspectRatio}\n          stroke=\"transparent\"\n          isAnimationActive\n          animationDuration={400}\n          content={\n            (\n              <CustomizedContent\n                showLabels={showLabels}\n                fmt={fmt}\n                locale={locale}\n                onNodeClick={handleNodeClick}\n              />\n            ) as unknown as React.ReactElement\n          }\n        >\n          {showTooltip && <Tooltip content={<ChartTooltip fmt={fmt} />} />}\n        </Treemap>\n      </ResponsiveContainer>\n\n      {footer && (\n        <div className={chartFooterVariants()} data-slot=\"treemap-chart-footer\">\n          {footer}\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}
