{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ds-pie-chart",
  "title": "Pie Chart",
  "description": "A responsive pie and donut chart with interactive center label, legend, and outer slice labels.",
  "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-pie-chart.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport {\n  Label,\n  Legend,\n  Pie,\n  PieChart as RechartsPieChart,\n  ResponsiveContainer,\n  Sector,\n  Tooltip,\n} from \"recharts\"\nimport type { PieSectorDataItem } from \"recharts\"\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 {\n  formatChartValue,\n  formatValue,\n  type FormatPreset,\n} from \"@/lib/format-utils\"\nimport { PieChart as PieChartIcon } from \"lucide-react\"\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport type PieChartVariant = \"pie\" | \"donut\"\nexport type LegendPosition = \"top\" | \"bottom\" | \"left\" | \"right\"\n\nexport interface PieChartItem {\n  label: string\n  value: number\n  /** Overrides the auto --chart-N color for this slice */\n  color?: string\n}\n\nexport interface PieChartProps extends React.HTMLAttributes<HTMLDivElement> {\n  data: PieChartItem[]\n  variant?: PieChartVariant\n  title?: string\n  subtitle?: string\n  footer?: React.ReactNode\n  height?: number\n  showLegend?: boolean\n  /** @default \"bottom\" */\n  legendPosition?: LegendPosition\n  showTooltip?: boolean\n  /** Show percentage labels on the outside of each slice */\n  showLabels?: boolean\n  /** Center label shown when no slice is hovered (donut only) — defaults to \"Total\" */\n  innerLabel?: string\n  /** Gap between slices in degrees */\n  paddingAngle?: number\n  /** Format slice values in the tooltip, legend, and donut center */\n  valueFormatter?: (value: number) => string\n  format?: FormatPreset\n  decimals?: number\n  currency?: string\n  abbreviate?: boolean\n  /** Locale used for default number and percentage formatting */\n  locale?: UILocale\n  /** Show animated skeleton in place of the chart while data loads */\n  loading?: boolean\n}\n\n// ── Constants ──────────────────────────────────────────────────────────────\n\nconst LEGEND_LAYOUT: Record<\n  LegendPosition,\n  {\n    verticalAlign: \"top\" | \"middle\" | \"bottom\"\n    align: \"left\" | \"center\" | \"right\"\n    layout: \"horizontal\" | \"vertical\"\n  }\n> = {\n  top: { verticalAlign: \"top\", align: \"center\", layout: \"horizontal\" },\n  bottom: { verticalAlign: \"bottom\", align: \"center\", layout: \"horizontal\" },\n  left: { verticalAlign: \"middle\", align: \"left\", layout: \"vertical\" },\n  right: { verticalAlign: \"middle\", align: \"right\", layout: \"vertical\" },\n}\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\nfunction sectorPath(\n  cx: number,\n  cy: number,\n  r: number,\n  startDeg: number,\n  endDeg: number\n): string {\n  const toRad = (d: number) => (d * Math.PI) / 180\n  const x1 = cx + r * Math.cos(toRad(startDeg - 90))\n  const y1 = cy + r * Math.sin(toRad(startDeg - 90))\n  const x2 = cx + r * Math.cos(toRad(endDeg - 90))\n  const y2 = cy + r * Math.sin(toRad(endDeg - 90))\n  const largeArc = endDeg - startDeg > 180 ? 1 : 0\n  return `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${largeArc} 1 ${x2} ${y2} Z`\n}\n\ninterface PieChartSkeletonProps {\n  height?: number\n  hasTitle?: boolean\n  hasSubtitle?: boolean\n  hasFooter?: boolean\n  isDonut?: boolean\n  className?: string\n}\n\nfunction PieChartSkeleton({\n  height = 280,\n  hasTitle = false,\n  hasSubtitle = false,\n  hasFooter = false,\n  isDonut = false,\n  className,\n}: PieChartSkeletonProps) {\n  // 5 sectors: 25%, 20%, 18%, 22%, 15% = angles 0→90, 90→162, 162→226.8, 226.8→306, 306→360\n  const sectors: [number, number][] = [\n    [0, 90],\n    [90, 162],\n    [162, 226.8],\n    [226.8, 306],\n    [306, 358.5],\n  ]\n\n  return (\n    <div\n      className={cn(\"flex w-full flex-col\", className)}\n      data-slot=\"pie-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=\"flex items-center justify-center\" style={{ height }}>\n        <svg\n          viewBox=\"0 0 100 100\"\n          width={Math.min(height, 200)}\n          height={Math.min(height, 200)}\n          suppressHydrationWarning\n        >\n          {sectors.map(([start, end], i) => (\n            <path\n              key={i}\n              d={sectorPath(50, 50, 40, start + 0.75, end - 0.75)}\n              fill=\"var(--muted)\"\n              className=\"motion-safe:animate-pulse\"\n              style={{ animationDelay: `${i * 0.12}s` }}\n              suppressHydrationWarning\n            />\n          ))}\n          {isDonut && (\n            <circle cx=\"50\" cy=\"50\" r={40 * 0.52} fill=\"var(--background)\" />\n          )}\n        </svg>\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// ── Active Shape ───────────────────────────────────────────────────────────\n\ninterface ActiveShapeProps {\n  cx: number\n  cy: number\n  innerRadius: number\n  outerRadius: number\n  startAngle: number\n  endAngle: number\n  fill: string\n}\n\nfunction ActiveShape(props: PieSectorDataItem): React.ReactElement {\n  const {\n    cx = 0,\n    cy = 0,\n    innerRadius = 0,\n    outerRadius = 0,\n    startAngle = 0,\n    endAngle = 0,\n    fill,\n    payload,\n  } = props as ActiveShapeProps &\n    PieSectorDataItem & { payload?: { color?: string } }\n\n  const customFill = payload?.color ?? fill\n\n  return (\n    <g>\n      {/* Main slice — expanded outward by 8px */}\n      <Sector\n        cx={cx}\n        cy={cy}\n        innerRadius={innerRadius}\n        outerRadius={outerRadius + 8}\n        startAngle={startAngle}\n        endAngle={endAngle}\n        fill={customFill}\n      />\n      {/* Inner ring highlight shown only on donut variant */}\n      {innerRadius > 0 && (\n        <Sector\n          cx={cx}\n          cy={cy}\n          innerRadius={innerRadius - 6}\n          outerRadius={innerRadius - 2}\n          startAngle={startAngle}\n          endAngle={endAngle}\n          fill={customFill}\n        />\n      )}\n    </g>\n  )\n}\n\n// ── Donut Center Label ─────────────────────────────────────────────────────\n\ninterface CenterLabelProps {\n  viewBox?: unknown\n  value: number\n  label: string\n  percent: string | null\n  fmt: (v: number) => string\n}\n\nfunction CenterLabel({\n  viewBox,\n  value,\n  label,\n  percent,\n  fmt,\n}: CenterLabelProps) {\n  const { cx, cy } = (viewBox ?? {}) as { cx?: number; cy?: number }\n  if (cx == null || cy == null) return <g />\n\n  const display = fmt(value)\n  const hasPercent = percent !== null\n\n  return (\n    <g>\n      <text\n        x={cx}\n        y={cy - (hasPercent ? 12 : 7)}\n        textAnchor=\"middle\"\n        fontSize={22}\n        fontWeight={700}\n        fill=\"var(--foreground)\"\n        fontFamily=\"inherit\"\n      >\n        {display}\n      </text>\n      <text\n        x={cx}\n        y={cy + (hasPercent ? 7 : 10)}\n        textAnchor=\"middle\"\n        fontSize={11}\n        fill=\"var(--muted-foreground)\"\n        fontFamily=\"inherit\"\n      >\n        {label}\n      </text>\n      {hasPercent && (\n        <text\n          x={cx}\n          y={cy + 22}\n          textAnchor=\"middle\"\n          fontSize={11}\n          fill=\"var(--muted-foreground)\"\n          fontFamily=\"inherit\"\n        >\n          {percent}\n        </text>\n      )}\n    </g>\n  )\n}\n\n// ── Custom Tooltip ─────────────────────────────────────────────────────────\n\ninterface TooltipPayloadEntry {\n  name: string\n  value: number\n  payload: { color: string }\n}\n\nfunction ChartTooltip({\n  active,\n  payload,\n  total,\n  fmt,\n  locale: localeProp,\n}: {\n  active?: boolean\n  payload?: TooltipPayloadEntry[]\n  total: number\n  fmt: (v: number) => string\n  locale?: UILocale\n}) {\n  const locale = useUILocale(localeProp)\n  if (!active || !payload?.length) return null\n  const entry = payload[0]\n\n  const pct = formatValue(entry.value / total, \"percent\", {\n    decimals: 1,\n    locale,\n  })\n\n  return (\n    <div className=\"min-w-36 rounded-lg border border-border bg-card px-3 py-2 shadow-md\">\n      <div className=\"flex items-center gap-2\">\n        <span\n          className=\"inline-block size-2 shrink-0 rounded-full\"\n          style={{ backgroundColor: entry.payload.color }}\n        />\n        <span className=\"text-xs font-semibold text-foreground\">\n          {entry.name}\n        </span>\n      </div>\n      <div className=\"mt-1.5 flex items-baseline justify-between gap-4\">\n        <span className=\"text-xs text-muted-foreground tabular-nums\">\n          {fmt(entry.value)}\n        </span>\n        <span className=\"text-xs font-semibold text-foreground tabular-nums\">\n          {pct}\n        </span>\n      </div>\n    </div>\n  )\n}\n\n// ── Custom Legend ──────────────────────────────────────────────────────────\n\ninterface NormalizedPieItem {\n  label: string\n  value: number\n  color: string\n}\n\nfunction ChartLegend({\n  items,\n  total,\n  hiddenLabels,\n  onToggle,\n  fmt,\n  position = \"bottom\",\n  locale: localeProp,\n}: {\n  items: NormalizedPieItem[]\n  total: number\n  hiddenLabels: Set<string>\n  onToggle: (label: string) => void\n  fmt: (v: number) => string\n  position?: LegendPosition\n  locale?: UILocale\n}) {\n  const locale = useUILocale(localeProp)\n  // Rendered through Recharts' <Legend> portal, whose container is itself a node\n  // managed elsewhere in the same React tree. React's synthetic click dispatch does\n  // not reliably resolve back to handlers on elements portaled this way, so toggling\n  // is wired through a native listener instead of onClick.\n  const containerRef = React.useRef<HTMLDivElement>(null)\n  const onToggleRef = React.useRef(onToggle)\n  React.useEffect(() => {\n    onToggleRef.current = onToggle\n  }, [onToggle])\n\n  React.useEffect(() => {\n    const container = containerRef.current\n    if (!container) return\n    const handleActivate = (label: string) => onToggleRef.current(label)\n    const handleClick = (e: MouseEvent) => {\n      const target = (e.target as HTMLElement).closest<HTMLElement>(\n        \"[data-legend-label]\"\n      )\n      if (target) handleActivate(target.dataset.legendLabel!)\n    }\n    const handleKeyDown = (e: KeyboardEvent) => {\n      if (e.key !== \"Enter\" && e.key !== \" \") return\n      const target = (e.target as HTMLElement).closest<HTMLElement>(\n        \"[data-legend-label]\"\n      )\n      if (target) {\n        e.preventDefault()\n        handleActivate(target.dataset.legendLabel!)\n      }\n    }\n    container.addEventListener(\"click\", handleClick)\n    container.addEventListener(\"keydown\", handleKeyDown)\n    return () => {\n      container.removeEventListener(\"click\", handleClick)\n      container.removeEventListener(\"keydown\", handleKeyDown)\n    }\n  }, [])\n\n  return (\n    <div\n      ref={containerRef}\n      className={cn(\n        \"flex flex-col gap-1.5 px-1\",\n        position === \"top\" ? \"mb-2\" : \"mt-2\"\n      )}\n      data-slot=\"pie-chart-legend\"\n    >\n      {items.map((item) => {\n        const hidden = hiddenLabels.has(item.label)\n        const pct = formatValue(item.value / total, \"percent\", {\n          decimals: 1,\n          locale,\n        })\n\n        const display = fmt(item.value)\n\n        return (\n          <div\n            key={item.label}\n            data-legend-label={item.label}\n            role=\"button\"\n            tabIndex={0}\n            aria-pressed={hidden}\n            aria-label={item.label}\n            className={cn(\n              \"flex cursor-pointer items-center gap-2 rounded px-1 py-0.5 select-none\",\n              \"transition-opacity focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none\",\n              hidden ? \"opacity-40\" : \"hover:opacity-70\"\n            )}\n          >\n            <span\n              className=\"inline-block size-2.5 shrink-0 rounded-full\"\n              style={{ backgroundColor: item.color }}\n            />\n            <span className=\"min-w-0 flex-1 truncate text-xs text-muted-foreground\">\n              {item.label}\n            </span>\n            <span className=\"text-xs text-muted-foreground tabular-nums\">\n              {display}\n            </span>\n            <span className=\"w-12 text-right text-xs font-semibold text-foreground tabular-nums\">\n              {pct}\n            </span>\n          </div>\n        )\n      })}\n    </div>\n  )\n}\n\n// ── PieChart ───────────────────────────────────────────────────────────────\n\nexport function PieChart({\n  data,\n  variant = \"pie\",\n  title,\n  subtitle,\n  footer,\n  height = 280,\n  showLegend = true,\n  legendPosition = \"bottom\",\n  showTooltip = true,\n  showLabels = false,\n  innerLabel,\n  paddingAngle = 0,\n  valueFormatter,\n  format,\n  decimals,\n  currency,\n  abbreviate,\n  loading = false,\n  locale: localeProp,\n  className,\n  ...props\n}: PieChartProps) {\n  const locale = useUILocale(localeProp)\n  const i18nInnerLabel =\n    innerLabel ??\n    UI_I18N[locale as UILocale]?.pieChart?.total ??\n    UI_I18N[\"en-US\"].pieChart.total\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 [activeLabel, setActiveLabel] = React.useState<string | null>(null)\n  const [hiddenLabels, setHiddenLabels] = React.useState<Set<string>>(new Set())\n\n  const toggleLabel = React.useCallback((label: string) => {\n    setHiddenLabels((prev) => {\n      const next = new Set(prev)\n      if (next.has(label)) next.delete(label)\n      else next.add(label)\n      return next\n    })\n  }, [])\n\n  const items = React.useMemo(\n    () =>\n      data.map((d, i) => ({\n        ...d,\n        color: d.color ?? CHART_COLORS[i % CHART_COLORS.length],\n      })),\n    [data]\n  )\n\n  // Items rendered in the pie — hidden ones are excluded so the remaining slices fill the space\n  const visibleItems = React.useMemo(\n    () => items.filter((d) => !hiddenLabels.has(d.label)),\n    [items, hiddenLabels]\n  )\n\n  // Full total (used for legend percentages — stable even when slices are hidden)\n  const total = React.useMemo(\n    () => items.reduce((sum, d) => sum + d.value, 0),\n    [items]\n  )\n\n  // Visible total (used for center label and tooltip)\n  const visibleTotal = React.useMemo(\n    () => visibleItems.reduce((sum, d) => sum + d.value, 0),\n    [visibleItems]\n  )\n\n  const isDonut = variant === \"donut\"\n\n  // Center label state — computed before early returns so renderCenterLabel hook is unconditional\n  const centerItem =\n    activeLabel !== null\n      ? (visibleItems.find((i) => i.label === activeLabel) ?? null)\n      : null\n  const centerValue = centerItem?.value ?? visibleTotal\n  const centerLabel = centerItem?.label ?? i18nInnerLabel\n  const centerPercent = centerItem\n    ? formatValue(centerItem.value / visibleTotal, \"percent\", {\n        decimals: 1,\n        locale,\n      })\n    : null\n\n  const renderCenterLabel = React.useCallback(\n    ({ viewBox }: { viewBox?: unknown }) => (\n      <CenterLabel\n        viewBox={viewBox}\n        value={centerValue}\n        label={centerLabel}\n        percent={centerPercent}\n        fmt={fmt}\n      />\n    ),\n    [centerValue, centerLabel, centerPercent, fmt]\n  )\n\n  // Stable identity across renders — an inline arrow function here would give Recharts'\n  // Legend a new `content` type every render, forcing it to unmount/remount the legend\n  // subtree instead of reconciling it.\n  const renderLegendContent = React.useCallback(\n    () => (\n      <ChartLegend\n        items={items}\n        total={total}\n        hiddenLabels={hiddenLabels}\n        onToggle={toggleLabel}\n        fmt={fmt}\n        position={legendPosition}\n        locale={locale}\n      />\n    ),\n    [items, total, hiddenLabels, toggleLabel, fmt, legendPosition, locale]\n  )\n\n  if (loading) {\n    return (\n      <PieChartSkeleton\n        height={height}\n        hasTitle={!!title}\n        hasSubtitle={!!subtitle}\n        hasFooter={!!footer}\n        isDonut={isDonut}\n        className={className}\n      />\n    )\n  }\n\n  if (data.length === 0) {\n    return (\n      <div\n        className={cn(chartWrapperVariants(), className)}\n        data-slot=\"pie-chart\"\n        {...props}\n      >\n        {(title || subtitle) && (\n          <div className={chartHeaderVariants()} data-slot=\"pie-chart-header\">\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=\"pie-chart-empty\"\n          style={{ height }}\n        >\n          <div className=\"flex size-10 items-center justify-center rounded-full bg-muted\">\n            <PieChartIcon className=\"size-5\" />\n          </div>\n          <div className=\"text-center\">\n            <p className=\"text-sm font-medium text-foreground\">\n              {UI_I18N[locale as UILocale]?.emptyState?.noData ??\n                UI_I18N[\"en-US\"].emptyState.noData}\n            </p>\n            <p className=\"mt-0.5 text-xs\">\n              {UI_I18N[locale as UILocale]?.emptyState?.dataWillAppear ??\n                UI_I18N[\"en-US\"].emptyState.dataWillAppear}\n            </p>\n          </div>\n        </div>\n        {footer && (\n          <div className={chartFooterVariants()} data-slot=\"pie-chart-footer\">\n            {footer}\n          </div>\n        )}\n      </div>\n    )\n  }\n\n  return (\n    <div\n      className={cn(chartWrapperVariants(), className)}\n      data-slot=\"pie-chart\"\n      {...props}\n    >\n      {(title || subtitle) && (\n        <div className={chartHeaderVariants()} data-slot=\"pie-chart-header\">\n          {title && <p className={chartTitleVariants()}>{title}</p>}\n          {subtitle && <p className={chartSubtitleVariants()}>{subtitle}</p>}\n        </div>\n      )}\n\n      <ResponsiveContainer\n        width=\"100%\"\n        height={height}\n        data-slot=\"pie-chart-chart\"\n      >\n        <RechartsPieChart>\n          {showTooltip && (\n            <Tooltip\n              content={\n                <ChartTooltip total={visibleTotal} fmt={fmt} locale={locale} />\n              }\n            />\n          )}\n\n          {showLegend && (\n            <Legend\n              {...LEGEND_LAYOUT[legendPosition]}\n              content={renderLegendContent}\n            />\n          )}\n\n          <Pie\n            data={visibleItems}\n            dataKey=\"value\"\n            nameKey=\"label\"\n            cx=\"50%\"\n            cy=\"50%\"\n            innerRadius={isDonut ? \"52%\" : 0}\n            outerRadius={showLabels ? \"68%\" : \"78%\"}\n            paddingAngle={paddingAngle}\n            strokeWidth={2}\n            stroke=\"var(--card)\"\n            activeShape={ActiveShape}\n            onMouseEnter={(d) =>\n              setActiveLabel((d as unknown as { label: string }).label)\n            }\n            onMouseLeave={() => setActiveLabel(null)}\n            label={\n              showLabels\n                ? ({ percent }: { percent?: number }) =>\n                    (percent ?? 0) > 0.04\n                      ? formatValue(percent ?? 0, \"percent\", {\n                          decimals: 0,\n                          locale,\n                        })\n                      : \"\"\n                : false\n            }\n            labelLine={\n              showLabels\n                ? { stroke: \"var(--muted-foreground)\", strokeWidth: 1 }\n                : false\n            }\n            shape={(props: unknown) => {\n              const p = props as PieSectorDataItem & {\n                payload?: { color?: string }\n              }\n              return <Sector {...p} fill={p.payload?.color ?? p.fill} />\n            }}\n          >\n            {isDonut && <Label content={renderCenterLabel} position=\"center\" />}\n          </Pie>\n        </RechartsPieChart>\n      </ResponsiveContainer>\n\n      {footer && (\n        <div className={chartFooterVariants()} data-slot=\"pie-chart-footer\">\n          {footer}\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}
