{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ds-heatmap-chart",
  "title": "Heatmap Chart",
  "description": "A responsive heatmap chart built with pure CSS grid and color-mix for smooth color interpolation.",
  "dependencies": [
    "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-heatmap-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 { Grid3X3 } from \"lucide-react\"\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\"\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport type HeatmapPalette =\n  \"blue\" | \"green\" | \"orange\" | \"purple\" | \"red\" | \"custom\"\n\nexport interface HeatmapCell {\n  /** Column label */\n  x: string\n  /** Row label */\n  y: string\n  value: number\n  /** Optional override label shown inside the cell */\n  label?: string\n}\n\nexport interface HeatmapChartProps extends React.HTMLAttributes<HTMLDivElement> {\n  data: HeatmapCell[]\n  title?: string\n  subtitle?: string\n  footer?: React.ReactNode\n  /** Preset color palette for the gradient scale */\n  palette?: HeatmapPalette\n  /** Low-end color for custom palette — any CSS color */\n  colorFrom?: string\n  /** High-end color for custom palette — any CSS color */\n  colorTo?: string\n  /** Display the numeric value inside each cell */\n  showValues?: boolean\n  /** Show a gradient legend bar below the heatmap */\n  showScale?: boolean\n  /** Fixed cell width in px; auto-sizes when omitted */\n  cellSize?: number\n  /** Fixed cell height in px — defaults to `cellSize` when set, or `32` for fluid-width cells */\n  cellHeight?: number\n  /** Gap between cells in px */\n  gap?: number\n  /** Format cell values in tooltips and inside cells */\n  valueFormatter?: (value: number) => string\n  format?: FormatPreset\n  decimals?: number\n  currency?: string\n  abbreviate?: boolean\n  /** Override the computed min (floor of the color scale) */\n  min?: number\n  /** Override the computed max (ceiling of the color scale) */\n  max?: number\n  /** Show animated skeleton in place of the chart while data loads */\n  loading?: boolean\n  locale?: UILocale\n}\n\n// ── Constants ──────────────────────────────────────────────────────────────\n\nconst PALETTES: Record<\n  Exclude<HeatmapPalette, \"custom\">,\n  { from: string; to: string }\n> = {\n  blue: { from: \"var(--card)\", to: \"var(--chart-1)\" },\n  green: { from: \"var(--card)\", to: \"var(--chart-2)\" },\n  orange: { from: \"var(--card)\", to: \"var(--chart-3)\" },\n  purple: { from: \"var(--card)\", to: \"var(--chart-4)\" },\n  red: { from: \"var(--card)\", to: \"var(--chart-5)\" },\n}\n\n// ── Variants ───────────────────────────────────────────────────────────────\n\nconst chartWrapperVariants = cva(\"flex w-full flex-col\")\nconst chartHeaderVariants = cva(\"flex flex-col px-1 pb-4\")\nconst chartTitleVariants = cva(\n  \"text-sm leading-tight font-semibold text-foreground\"\n)\nconst chartSubtitleVariants = cva(\"mt-0.5 text-xs text-muted-foreground\")\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// ── Helpers ────────────────────────────────────────────────────────────────\n\nfunction unique<T>(arr: T[]): T[] {\n  return Array.from(new Set(arr))\n}\n\nfunction clamp(v: number, lo: number, hi: number) {\n  return Math.max(lo, Math.min(hi, v))\n}\n\n/** CSS color-mix interpolation between two colors at `t` (0 = from, 1 = to) */\nfunction mixColor(from: string, to: string, t: number) {\n  const pct = Math.round(clamp(t, 0, 1) * 100)\n  return `color-mix(in oklch, ${to} ${pct}%, ${from})`\n}\n\n// ── Skeleton ───────────────────────────────────────────────────────────────\n\ninterface HeatmapChartSkeletonProps {\n  height?: number\n  hasTitle?: boolean\n  hasSubtitle?: boolean\n  hasFooter?: boolean\n  className?: string\n}\n\nfunction HeatmapChartSkeleton({\n  hasTitle = false,\n  hasSubtitle = false,\n  hasFooter = false,\n  className,\n}: HeatmapChartSkeletonProps) {\n  const rows = 6\n  const cols = 8\n\n  return (\n    <div\n      className={cn(\"flex w-full flex-col\", className)}\n      data-slot=\"heatmap-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=\"w-full overflow-x-auto\">\n        <div className=\"w-full\" style={{ padding: 2 }}>\n          {/* X-axis header row */}\n          <div className=\"mb-1 flex\" style={{ paddingLeft: 96, gap: 3 }}>\n            {Array.from({ length: cols }).map((_, i) => (\n              <Skeleton\n                key={i}\n                className=\"h-3 flex-1 rounded-sm\"\n                style={{ animationDelay: `${0.05 + i * 0.05}s` }}\n              />\n            ))}\n          </div>\n\n          {/* Rows */}\n          {Array.from({ length: rows }).map((_, row) => (\n            <div\n              key={row}\n              className=\"flex items-center\"\n              style={{ marginBottom: 3 }}\n            >\n              {/* Y-axis label */}\n              <div className=\"flex w-24 shrink-0 justify-end pr-2\">\n                <Skeleton\n                  className=\"h-2.5 rounded-sm\"\n                  style={{\n                    width: 40 + (row % 3) * 12,\n                    animationDelay: `${row * 0.08}s`,\n                  }}\n                />\n              </div>\n\n              {/* Cells */}\n              <div className=\"flex flex-1\" style={{ gap: 3 }}>\n                {Array.from({ length: cols }).map((_, col) => (\n                  <Skeleton\n                    key={col}\n                    className=\"flex-1 rounded-sm\"\n                    style={{\n                      height: 32,\n                      animationDelay: `${Math.min((row * cols + col) * 0.03, 1.5)}s`,\n                    }}\n                  />\n                ))}\n              </div>\n            </div>\n          ))}\n        </div>\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// ── Sub-components ─────────────────────────────────────────────────────────\n\ninterface CellTooltipProps {\n  x: string\n  y: string\n  formatted: string\n}\n\nfunction CellTooltip({ x, y, formatted }: CellTooltipProps) {\n  return (\n    <div className=\"pointer-events-none absolute bottom-full left-1/2 z-50 mb-2 -translate-x-1/2 rounded-lg border border-border bg-card px-3 py-2 whitespace-nowrap shadow-lg\">\n      <p className=\"text-xs font-semibold text-foreground\">\n        {y} · {x}\n      </p>\n      <p className=\"mt-0.5 text-xs text-muted-foreground\">{formatted}</p>\n    </div>\n  )\n}\n\n// ── HeatmapChart ───────────────────────────────────────────────────────────\n\nexport function HeatmapChart({\n  data,\n  title,\n  subtitle,\n  footer,\n  palette = \"blue\",\n  colorFrom,\n  colorTo,\n  showValues = false,\n  showScale = true,\n  cellSize,\n  cellHeight,\n  gap = 3,\n  valueFormatter,\n  format,\n  decimals,\n  currency,\n  abbreviate,\n  min: minProp,\n  max: maxProp,\n  loading = false,\n  locale: localeProp,\n  className,\n  ...props\n}: HeatmapChartProps) {\n  const locale = useUILocale(localeProp)\n  // Hooks must be called unconditionally before any early returns\n  const [hovered, setHovered] = React.useState<{ x: string; y: string } | null>(\n    null\n  )\n\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 lookup = React.useMemo(() => {\n    const m = new Map<string, HeatmapCell>()\n    data.forEach((d) => m.set(`${d.y}|||${d.x}`, d))\n    return m\n  }, [data])\n\n  if (loading) {\n    return (\n      <HeatmapChartSkeleton\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=\"heatmap-chart\"\n        {...props}\n      >\n        {(title || subtitle) && (\n          <div\n            className={chartHeaderVariants()}\n            data-slot=\"heatmap-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=\"heatmap-chart-empty\"\n          style={{ height: 200 }}\n        >\n          <div className=\"flex size-10 items-center justify-center rounded-full bg-muted\">\n            <Grid3X3 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=\"heatmap-chart-footer\"\n          >\n            {footer}\n          </div>\n        )}\n      </div>\n    )\n  }\n\n  // Derive ordered axis labels\n  const xLabels = unique(data.map((d) => d.x))\n  const yLabels = unique(data.map((d) => d.y))\n\n  // Color scale\n  const values = data.map((d) => d.value)\n  const computedMin = minProp ?? Math.min(...values)\n  const computedMax = maxProp ?? Math.max(...values)\n  const range = computedMax - computedMin || 1\n\n  const { from, to } =\n    palette === \"custom\"\n      ? { from: colorFrom ?? \"var(--card)\", to: colorTo ?? \"var(--chart-1)\" }\n      : PALETTES[palette]\n\n  const getCellColor = (value: number) =>\n    mixColor(from, to, (value - computedMin) / range)\n\n  // Text contrast: use foreground on light cells, card on dark cells\n  const getTextColor = (value: number): string => {\n    const t = (value - computedMin) / range\n    return t > 0.55 ? \"var(--card)\" : \"var(--foreground)\"\n  }\n\n  const fixedCell = !!cellSize\n  // Priority: explicit cellHeight > cellSize (when fixed) > 32px default (fluid mode)\n  const effectiveHeight = cellHeight ?? (fixedCell ? cellSize : 32)\n  const cellStyle = fixedCell\n    ? { width: cellSize, height: effectiveHeight, flexShrink: 0 }\n    : { flex: 1, minWidth: 0, height: effectiveHeight }\n\n  return (\n    <div\n      className={cn(chartWrapperVariants(), className)}\n      data-slot=\"heatmap-chart\"\n      {...props}\n    >\n      {(title || subtitle) && (\n        <div className={chartHeaderVariants()} data-slot=\"heatmap-chart-header\">\n          {title && <p className={chartTitleVariants()}>{title}</p>}\n          {subtitle && <p className={chartSubtitleVariants()}>{subtitle}</p>}\n        </div>\n      )}\n\n      {/* Grid */}\n      <div className=\"w-full overflow-x-auto\" data-slot=\"heatmap-chart-grid\">\n        <div className=\"w-full\" style={{ padding: 2 }}>\n          {/* X-axis labels */}\n          <div className=\"mb-1 flex\" style={{ paddingLeft: 96, gap }}>\n            {xLabels.map((x) => (\n              <div\n                key={x}\n                className={cn(\n                  \"min-w-0 truncate text-center text-xs transition-colors duration-150\",\n                  fixedCell ? \"shrink-0\" : \"flex-1\",\n                  hovered?.x === x\n                    ? \"font-semibold text-foreground\"\n                    : \"text-muted-foreground\"\n                )}\n                style={fixedCell ? { width: cellSize } : { flex: 1 }}\n                title={x}\n              >\n                {x}\n              </div>\n            ))}\n          </div>\n\n          {/* Rows */}\n          {yLabels.map((y) => (\n            <div\n              key={y}\n              className=\"flex items-center\"\n              style={{ marginBottom: gap }}\n            >\n              {/* Y-axis label */}\n              <div\n                className={cn(\n                  \"w-24 shrink-0 pr-2 text-right text-xs transition-colors duration-150\",\n                  hovered?.y === y\n                    ? \"font-semibold text-foreground\"\n                    : \"text-muted-foreground\"\n                )}\n                title={y}\n              >\n                <span className=\"block truncate\">{y}</span>\n              </div>\n\n              {/* Cells */}\n              <div className=\"flex flex-1\" style={{ gap }}>\n                {xLabels.map((x) => {\n                  const cell = lookup.get(`${y}|||${x}`)\n                  const isHovered = hovered?.x === x && hovered?.y === y\n                  const isFaded =\n                    hovered !== null && (hovered.x !== x || hovered.y !== y)\n\n                  if (!cell) {\n                    return (\n                      <div\n                        key={x}\n                        className=\"shrink-0 rounded-sm bg-muted/30\"\n                        style={cellStyle}\n                      />\n                    )\n                  }\n\n                  const bg = getCellColor(cell.value)\n                  const textColor = getTextColor(cell.value)\n\n                  return (\n                    <div\n                      key={x}\n                      className={cn(\n                        \"relative shrink-0 cursor-default rounded-sm transition-all duration-150\",\n                        isHovered\n                          ? \"z-10 scale-110 shadow-md ring-2 ring-foreground/40\"\n                          : isFaded\n                            ? \"opacity-40\"\n                            : \"hover:ring-1 hover:ring-foreground/20\"\n                      )}\n                      style={{ ...cellStyle, backgroundColor: bg }}\n                      onMouseEnter={() => setHovered({ x, y })}\n                      onMouseLeave={() => setHovered(null)}\n                    >\n                      {/* Value label */}\n                      {showValues && (\n                        <span\n                          className=\"pointer-events-none absolute inset-0 flex items-center justify-center text-xs leading-none font-semibold tabular-nums\"\n                          style={{ color: textColor }}\n                        >\n                          {cell.label ?? fmt(cell.value)}\n                        </span>\n                      )}\n\n                      {/* Tooltip */}\n                      {isHovered && (\n                        <CellTooltip x={x} y={y} formatted={fmt(cell.value)} />\n                      )}\n                    </div>\n                  )\n                })}\n              </div>\n            </div>\n          ))}\n        </div>\n      </div>\n\n      {/* Color scale legend */}\n      {showScale && (\n        <div className=\"mt-4 flex items-center gap-3 px-1\">\n          <span className=\"text-xs text-muted-foreground tabular-nums\">\n            {fmt(computedMin)}\n          </span>\n          <div\n            className=\"h-2.5 flex-1 rounded-full\"\n            style={{\n              background: `linear-gradient(to right, ${from}, ${to})`,\n            }}\n          />\n          <span className=\"text-xs text-muted-foreground tabular-nums\">\n            {fmt(computedMax)}\n          </span>\n        </div>\n      )}\n\n      {footer && (\n        <div className={chartFooterVariants()} data-slot=\"heatmap-chart-footer\">\n          {footer}\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}
