{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ds-scatter-chart",
  "title": "Scatter Chart",
  "description": "A responsive scatter and bubble chart with trend lines, multi-series, and brush zoom.",
  "dependencies": [
    "recharts",
    "class-variance-authority",
    "lucide-react"
  ],
  "registryDependencies": [
    "@lema-ds/skeleton",
    "@lema-ds/ui-i18n",
    "@lema-ds/format-utils",
    "@lema-ds/chart-axis-width",
    "@lema-ds/ds-locale-provider"
  ],
  "files": [
    {
      "path": "components/ds/ds-scatter-chart.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport {\n  CartesianGrid,\n  ResponsiveContainer,\n  Scatter,\n  ScatterChart as RechartsScatterChart,\n  Tooltip,\n  XAxis,\n  YAxis,\n  ZAxis,\n} from \"recharts\"\nimport { cva } from \"class-variance-authority\"\nimport { Crosshair } from \"lucide-react\"\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 { measureAxisWidth } from \"@/lib/chart-axis-width\"\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport type LegendPosition = \"top\" | \"bottom\" | \"left\" | \"right\"\nexport type ScatterDotShape =\n  \"circle\" | \"cross\" | \"diamond\" | \"square\" | \"star\" | \"triangle\" | \"wye\"\n\nexport interface ScatterPoint {\n  x: number\n  y: number\n  /** Optional third dimension — encodes dot size when z values are present in any series */\n  z?: number\n  [key: string]: string | number | undefined\n}\n\nexport interface ScatterSeries {\n  name: string\n  data: ScatterPoint[]\n  /** Overrides the auto --chart-N color */\n  color?: string\n  /** @default \"circle\" */\n  shape?: ScatterDotShape\n}\n\nexport interface ScatterChartProps extends React.HTMLAttributes<HTMLDivElement> {\n  series: ScatterSeries[]\n  title?: string\n  subtitle?: string\n  footer?: React.ReactNode\n  height?: number\n  showGrid?: boolean\n  showLegend?: boolean\n  /** @default \"bottom\" */\n  legendPosition?: LegendPosition\n  showTooltip?: boolean\n  /**\n   * Draw a dashed linear-regression line through each series.\n   * Useful for spotting correlations and outliers.\n   */\n  showTrendLine?: boolean\n  /** Label displayed below the X axis */\n  xLabel?: string\n  /** Label displayed beside the Y axis */\n  yLabel?: string\n  xFormatter?: (value: number) => string\n  yFormatter?: (value: number) => string\n  /** Unified value formatter (applies to all axes & tooltip). */\n  valueFormatter?: (value: number) => string\n  /**\n   * Point size range for the z dimension `[min, max]`.\n   * Ignored when no data point has a `z` value.\n   * @default [40, 400]\n   */\n  bubbleRange?: [number, number]\n  /**\n   * Show a dual-handle range brush below the chart to pan and zoom the X axis.\n   * Drag either handle to change the visible range, or drag the selection bar\n   * to pan the entire window.\n   */\n  showBrush?: boolean\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 SCATTER_DOTS: [number, number][] = [\n  [15, 72],\n  [28, 45],\n  [42, 60],\n  [55, 28],\n  [68, 55],\n  [80, 38],\n  [22, 85],\n  [35, 18],\n  [50, 78],\n  [62, 42],\n  [75, 68],\n  [88, 25],\n  [10, 50],\n  [45, 90],\n  [72, 15],\n]\nconst SCATTER_DOT_RADII = [\n  3, 2.5, 3.5, 2.5, 4, 3, 2.5, 3.5, 3, 4, 2.5, 3, 3.5, 2.5, 4,\n]\n\ninterface ScatterChartSkeletonProps {\n  height?: number\n  hasTitle?: boolean\n  hasSubtitle?: boolean\n  hasFooter?: boolean\n  className?: string\n}\n\nfunction ScatterChartSkeleton({\n  height = 320,\n  hasTitle = false,\n  hasSubtitle = false,\n  hasFooter = false,\n  className,\n}: ScatterChartSkeletonProps) {\n  const YAXIS_WIDTHS = [28, 20, 24, 18]\n  const XAXIS_WIDTHS = [28, 36, 24, 32]\n\n  return (\n    <div\n      className={cn(\"flex w-full flex-col\", className)}\n      data-slot=\"scatter-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 overflow-hidden\" style={{ height }}>\n        {/* Y-axis tick labels */}\n        <div className=\"absolute top-2 bottom-8 left-0 flex w-9 flex-col items-end justify-between pr-1\">\n          {YAXIS_WIDTHS.map((w, i) => (\n            <Skeleton\n              key={i}\n              className=\"h-2.5 rounded-sm\"\n              style={{ width: w, animationDelay: `${0.5 + i * 0.12}s` }}\n            />\n          ))}\n        </div>\n\n        {/* Chart area with SVG scatter dots */}\n        <div className=\"absolute top-2 right-1 bottom-8 left-11\">\n          <svg\n            viewBox=\"0 0 100 100\"\n            preserveAspectRatio=\"none\"\n            className=\"h-full w-full\"\n          >\n            {/* Grid lines */}\n            {[25, 50, 75].map((v) => (\n              <line\n                key={`h${v}`}\n                x1=\"0\"\n                y1={v}\n                x2=\"100\"\n                y2={v}\n                stroke=\"var(--muted)\"\n                strokeWidth=\"0.6\"\n                opacity={0.5}\n              />\n            ))}\n            {[25, 50, 75].map((v) => (\n              <line\n                key={`v${v}`}\n                x1={v}\n                y1=\"0\"\n                x2={v}\n                y2=\"100\"\n                stroke=\"var(--muted)\"\n                strokeWidth=\"0.6\"\n                opacity={0.5}\n              />\n            ))}\n            {/* Dots */}\n            {SCATTER_DOTS.map(([x, y], i) => (\n              <circle\n                key={i}\n                cx={x}\n                cy={y}\n                r={SCATTER_DOT_RADII[i]}\n                fill=\"var(--muted)\"\n                className=\"motion-safe:animate-pulse\"\n                style={{ animationDelay: `${i * 0.06}s` }}\n              />\n            ))}\n          </svg>\n        </div>\n\n        {/* X-axis tick labels */}\n        <div className=\"absolute right-1 bottom-0 left-11 flex h-7 items-center justify-around\">\n          {XAXIS_WIDTHS.map((w, i) => (\n            <Skeleton\n              key={i}\n              className=\"h-2.5 rounded-sm\"\n              style={{ width: w, animationDelay: `${0.05 + i * 0.1}s` }}\n            />\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// ── 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  fill?: string\n  payload?: Record<string, unknown>\n}\n\nfunction ChartTooltip({\n  active,\n  payload,\n  label,\n  xLabel,\n  yLabel,\n  xFormatter,\n  yFormatter,\n  fmt,\n}: {\n  active?: boolean\n  payload?: TooltipEntry[]\n  label?: string | number\n  xLabel?: string\n  yLabel?: string\n  xFormatter?: (v: number) => string\n  yFormatter?: (v: number) => string\n  fmt: (v: number) => string\n}) {\n  if (!active || !payload?.length) return null\n\n  const raw = payload[0]?.payload as Record<string, unknown> | undefined\n  const seriesName =\n    (typeof label === \"string\" && label) ||\n    (raw?._series as string | undefined) ||\n    \"\"\n  const color =\n    (raw?._color as string | undefined) ?? payload[0]?.fill ?? \"var(--chart-1)\"\n\n  // payload order: x axis entry, y axis entry, z axis entry (optional)\n  const xEntry = payload[0]\n  const yEntry = payload[1]\n  const zEntry = payload[2]\n\n  const display = (entry: TooltipEntry, formatter?: (v: number) => string) =>\n    entry.value !== undefined\n      ? formatter\n        ? formatter(entry.value)\n        : fmt(entry.value)\n      : \"—\"\n\n  return (\n    <div className=\"min-w-40 rounded-lg border border-border bg-card px-3 py-2 shadow-md\">\n      {seriesName && (\n        <div className=\"mb-1.5 flex items-center gap-1.5\">\n          <span\n            className=\"inline-block size-2 shrink-0 rounded-full\"\n            style={{ backgroundColor: color }}\n          />\n          <p className=\"text-xs font-semibold text-foreground\">{seriesName}</p>\n        </div>\n      )}\n      <div className=\"flex flex-col gap-1\">\n        {xEntry && (\n          <div className=\"flex items-center justify-between gap-4\">\n            <span className=\"text-xs text-muted-foreground\">\n              {xLabel ?? xEntry.name ?? \"X\"}\n            </span>\n            <span className=\"text-xs font-semibold text-foreground tabular-nums\">\n              {display(xEntry, xFormatter)}\n            </span>\n          </div>\n        )}\n        {yEntry && (\n          <div className=\"flex items-center justify-between gap-4\">\n            <span className=\"text-xs text-muted-foreground\">\n              {yLabel ?? yEntry.name ?? \"Y\"}\n            </span>\n            <span className=\"text-xs font-semibold text-foreground tabular-nums\">\n              {display(yEntry, yFormatter)}\n            </span>\n          </div>\n        )}\n        {zEntry && (\n          <div className=\"flex items-center justify-between gap-4\">\n            <span className=\"text-xs text-muted-foreground\">\n              {zEntry.name ?? \"Size\"}\n            </span>\n            <span className=\"text-xs font-semibold text-foreground tabular-nums\">\n              {display(zEntry)}\n            </span>\n          </div>\n        )}\n      </div>\n    </div>\n  )\n}\n\n// ── Custom Legend ──────────────────────────────────────────────────────────\n\ninterface LegendPayloadEntry {\n  value: string\n  color: string\n}\n\nfunction ChartLegend({\n  payload,\n  hiddenSeries,\n  onToggle,\n  vertical = false,\n}: {\n  payload?: LegendPayloadEntry[]\n  hiddenSeries: Set<string>\n  onToggle: (name: string) => void\n  vertical?: boolean\n}) {\n  if (!payload?.length) return null\n\n  return (\n    <div\n      className={cn(\n        \"flex gap-y-1\",\n        vertical\n          ? \"flex-col px-2 py-1\"\n          : \"flex-wrap items-center justify-center gap-x-4 pt-3\"\n      )}\n    >\n      {payload.map((entry, i) => {\n        const hidden = hiddenSeries.has(entry.value)\n        return (\n          <div\n            key={entry.value ?? i}\n            role=\"button\"\n            tabIndex={0}\n            aria-pressed={hidden}\n            aria-label={entry.value}\n            onClick={() => onToggle(entry.value)}\n            onKeyDown={(e) =>\n              (e.key === \"Enter\" || e.key === \" \") && onToggle(entry.value)\n            }\n            className={cn(\n              \"flex cursor-pointer items-center gap-1.5 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 shrink-0 rounded-full\"\n              style={{ backgroundColor: entry.color }}\n            />\n            <span className=\"text-xs text-muted-foreground\">{entry.value}</span>\n          </div>\n        )\n      })}\n    </div>\n  )\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\nfunction assignColors(\n  series: ScatterSeries[]\n): (ScatterSeries & { fill: string })[] {\n  return series.map((s, i) => ({\n    ...s,\n    fill: s.color ?? CHART_COLORS[i % CHART_COLORS.length],\n  }))\n}\n\nfunction linearRegression(\n  points: ScatterPoint[]\n): { slope: number; intercept: number } | null {\n  const n = points.length\n  if (n < 2) return null\n  const sumX = points.reduce((s, p) => s + p.x, 0)\n  const sumY = points.reduce((s, p) => s + p.y, 0)\n  const sumXY = points.reduce((s, p) => s + p.x * p.y, 0)\n  const sumXX = points.reduce((s, p) => s + p.x * p.x, 0)\n  const denom = n * sumXX - sumX * sumX\n  if (denom === 0) return null\n  const slope = (n * sumXY - sumX * sumY) / denom\n  const intercept = (sumY - slope * sumX) / n\n  return { slope, intercept }\n}\n\nfunction trendLinePoints(\n  points: ScatterPoint[],\n  slope: number,\n  intercept: number\n): { x: number; y: number }[] {\n  const xs = points.map((p) => p.x)\n  const xMin = Math.min(...xs)\n  const xMax = Math.max(...xs)\n  return [\n    { x: xMin, y: slope * xMin + intercept },\n    { x: xMax, y: slope * xMax + intercept },\n  ]\n}\n\n// Invisible dot for trend-line scatter series\nfunction TrendDot(): React.ReactElement {\n  return <></>\n}\n\n// ── Continuous Brush ───────────────────────────────────────────────────────\n// recharts Brush only works with indexed (categorical) data, so for the\n// continuous numeric X axis of a scatter chart we implement our own.\n\ninterface ContinuousBrushProps {\n  min: number\n  max: number\n  low: number\n  high: number\n  onChange: (low: number, high: number) => void\n  formatter?: (v: number) => string\n  fmt: (v: number) => string\n  locale?: UILocale\n}\n\nfunction ContinuousBrush({\n  min,\n  max,\n  low,\n  high,\n  onChange,\n  formatter,\n  fmt,\n  locale: localeProp,\n}: ContinuousBrushProps) {\n  const locale = useUILocale(localeProp)\n  const trackRef = React.useRef<HTMLDivElement>(null)\n  const range = max - min || 1\n  const lowPct = Math.max(0, Math.min(100, ((low - min) / range) * 100))\n  const highPct = Math.max(0, Math.min(100, ((high - min) / range) * 100))\n\n  const valueAt = React.useCallback(\n    (clientX: number) => {\n      const rect = trackRef.current?.getBoundingClientRect()\n      if (!rect) return min\n      return (\n        min +\n        Math.max(0, Math.min(1, (clientX - rect.left) / rect.width)) * range\n      )\n    },\n    [min, range]\n  )\n\n  // Returns a mousedown/touchstart handler for each interactive element\n  const startDrag = React.useCallback(\n    (role: \"low\" | \"high\" | \"mid\") =>\n      (ev: React.MouseEvent | React.TouchEvent) => {\n        ev.preventDefault()\n        const startClientX =\n          \"touches\" in ev ? ev.touches[0].clientX : ev.clientX\n        const snapLow = low\n        const snapHigh = high\n        const window = snapHigh - snapLow\n        const minGap = range * 0.02\n\n        const onMove = (e: MouseEvent | TouchEvent) => {\n          const cx = \"touches\" in e ? e.touches[0].clientX : e.clientX\n          if (role === \"mid\") {\n            const delta =\n              ((cx - startClientX) /\n                (trackRef.current?.getBoundingClientRect().width ?? 1)) *\n              range\n            const newLow = Math.max(\n              min,\n              Math.min(max - window, snapLow + delta)\n            )\n            onChange(newLow, newLow + window)\n          } else if (role === \"low\") {\n            const v = valueAt(cx)\n            onChange(Math.max(min, Math.min(high - minGap, v)), high)\n          } else {\n            const v = valueAt(cx)\n            onChange(low, Math.max(low + minGap, Math.min(max, v)))\n          }\n        }\n\n        const onUp = () => {\n          document.removeEventListener(\"mousemove\", onMove)\n          document.removeEventListener(\"mouseup\", onUp)\n          document.removeEventListener(\"touchmove\", onMove)\n          document.removeEventListener(\"touchend\", onUp)\n        }\n\n        document.addEventListener(\"mousemove\", onMove)\n        document.addEventListener(\"mouseup\", onUp)\n        document.addEventListener(\"touchmove\", onMove, { passive: false })\n        document.addEventListener(\"touchend\", onUp)\n      },\n    [min, max, low, high, range, onChange, valueAt]\n  )\n\n  const display = (v: number) => (formatter ? formatter(v) : fmt(v))\n\n  return (\n    <div className=\"mt-2 px-2 pb-1 select-none\">\n      <div ref={trackRef} className=\"relative flex h-6 items-center\">\n        {/* Base track */}\n        <div className=\"absolute inset-x-0 h-[3px] rounded-full bg-border\" />\n\n        {/* Selection highlight — draggable to pan */}\n        <div\n          className=\"absolute h-[3px] cursor-grab rounded-full bg-foreground/25 active:cursor-grabbing\"\n          style={{ left: `${lowPct}%`, right: `${100 - highPct}%` }}\n          onMouseDown={startDrag(\"mid\")}\n          onTouchStart={startDrag(\"mid\")}\n        />\n\n        {/* Low handle */}\n        <div\n          className=\"absolute flex h-5 w-2.5 -translate-x-1/2 cursor-ew-resize items-center justify-center rounded border border-border bg-card shadow-sm transition-colors hover:bg-accent focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none\"\n          style={{ left: `${lowPct}%` }}\n          role=\"slider\"\n          aria-label={UI_I18N[locale].scatterChart.rangeStart}\n          aria-valuenow={low}\n          aria-valuemin={min}\n          aria-valuemax={high}\n          tabIndex={0}\n          onMouseDown={startDrag(\"low\")}\n          onTouchStart={startDrag(\"low\")}\n        >\n          <div className=\"h-2.5 w-px rounded-full bg-muted-foreground/50\" />\n        </div>\n\n        {/* High handle */}\n        <div\n          className=\"absolute flex h-5 w-2.5 -translate-x-1/2 cursor-ew-resize items-center justify-center rounded border border-border bg-card shadow-sm transition-colors hover:bg-accent focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none\"\n          style={{ left: `${highPct}%` }}\n          role=\"slider\"\n          aria-label={UI_I18N[locale].scatterChart.rangeEnd}\n          aria-valuenow={high}\n          aria-valuemin={low}\n          aria-valuemax={max}\n          tabIndex={0}\n          onMouseDown={startDrag(\"high\")}\n          onTouchStart={startDrag(\"high\")}\n        >\n          <div className=\"h-2.5 w-px rounded-full bg-muted-foreground/50\" />\n        </div>\n      </div>\n\n      {/* Value labels under handles */}\n      <div className=\"mt-0.5 flex justify-between text-xs text-muted-foreground\">\n        <span>{display(low)}</span>\n        <span>{display(high)}</span>\n      </div>\n    </div>\n  )\n}\n\n// ── ScatterChart ───────────────────────────────────────────────────────────\n\nexport function ScatterChart({\n  series,\n  title,\n  subtitle,\n  footer,\n  height = 320,\n  showGrid = true,\n  showLegend = false,\n  legendPosition = \"bottom\",\n  showTooltip = true,\n  showTrendLine = false,\n  xLabel,\n  yLabel,\n  xFormatter,\n  yFormatter,\n  valueFormatter,\n  format,\n  decimals,\n  currency,\n  abbreviate,\n  bubbleRange = [40, 400],\n  showBrush = false,\n  loading = false,\n  locale: localeProp,\n  className,\n  ...props\n}: ScatterChartProps) {\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 colored = React.useMemo(() => assignColors(series), [series])\n\n  const legendPayload = React.useMemo(\n    () => colored.map((s) => ({ value: s.name, color: s.fill })),\n    [colored]\n  )\n\n  const [hiddenSeries, setHiddenSeries] = React.useState<Set<string>>(new Set())\n  const toggleSeries = React.useCallback((name: string) => {\n    setHiddenSeries((prev) => {\n      const next = new Set(prev)\n      if (next.has(name)) next.delete(name)\n      else next.add(name)\n      return next\n    })\n  }, [])\n\n  const visibleSeries = React.useMemo(\n    () => colored.filter((s) => !hiddenSeries.has(s.name)),\n    [colored, hiddenSeries]\n  )\n\n  // Enable ZAxis when any visible series has z values\n  const hasBubble = visibleSeries.some((s) =>\n    s.data.some((p) => p.z !== undefined)\n  )\n\n  // Enrich each point with series metadata for the tooltip\n  const enrichedSeries = React.useMemo(\n    () =>\n      visibleSeries.map((s) => ({\n        ...s,\n        enrichedData: s.data.map((p) => ({\n          ...p,\n          _series: s.name,\n          _color: s.fill,\n        })),\n      })),\n    [visibleSeries]\n  )\n\n  // Global X extent across all series (used for the brush domain)\n  const [globalXMin, globalXMax] = React.useMemo(() => {\n    const xs = series.flatMap((s) => s.data.map((p) => p.x))\n    if (!xs.length) return [0, 1]\n    return [Math.min(...xs), Math.max(...xs)]\n  }, [series])\n\n  // brushX tracks the user-selected range; clampedBrush is what the chart consumes\n  const [brushX, setBrushX] = React.useState<[number, number]>(() => [\n    globalXMin,\n    globalXMax,\n  ])\n\n  const [prevDomain, setPrevDomain] = React.useState({ globalXMin, globalXMax })\n  if (\n    showBrush &&\n    (globalXMin !== prevDomain.globalXMin ||\n      globalXMax !== prevDomain.globalXMax)\n  ) {\n    setPrevDomain({ globalXMin, globalXMax })\n    setBrushX([globalXMin, globalXMax])\n  }\n\n  const xDomain = showBrush\n    ? ([brushX[0], brushX[1]] as [number, number])\n    : undefined\n\n  const isVerticalLegend =\n    legendPosition === \"left\" || legendPosition === \"right\"\n\n  const axisStyle = {\n    fontSize: \"12px\",\n    fill: \"var(--muted-foreground)\",\n  }\n\n  const axisLabelStyle = {\n    fontSize: \"11px\",\n    fill: \"var(--muted-foreground)\",\n  }\n\n  // Expand chart margins when axis labels are present to avoid clipping\n  const marginBottom = xLabel ? 28 : 8\n  const marginLeft = yLabel ? 8 : 8\n  // Sized from the actual formatted tick values (not a fixed guess) so\n  // abbreviated currency (\"R$ 800,0 mi\") never wraps or clips — see\n  // lib/chart-axis-width.ts.\n  const yAxisValues = [0, ...series.flatMap((s) => s.data.map((p) => p.y))]\n  const yAxisWidth = measureAxisWidth(yAxisValues, yFormatter ?? fmt, {\n    padding: yLabel ? 52 : 32,\n  })\n  const yAxisLabelOffset = yLabel ? 0 : 8\n\n  if (loading) {\n    return (\n      <ScatterChartSkeleton\n        height={height}\n        hasTitle={!!title}\n        hasSubtitle={!!subtitle}\n        hasFooter={!!footer}\n        className={className}\n      />\n    )\n  }\n\n  if (series.length === 0) {\n    return (\n      <div\n        className={cn(chartWrapperVariants(), className)}\n        data-slot=\"scatter-chart\"\n        {...props}\n      >\n        {(title || subtitle) && (\n          <div\n            className={chartHeaderVariants()}\n            data-slot=\"scatter-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=\"scatter-chart-empty\"\n          style={{ height }}\n        >\n          <div className=\"flex size-10 items-center justify-center rounded-full bg-muted\">\n            <Crosshair 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=\"scatter-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=\"scatter-chart\"\n      {...props}\n    >\n      {(title || subtitle) && (\n        <div className={chartHeaderVariants()} data-slot=\"scatter-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=\"scatter-chart-chart\"\n      >\n        <RechartsScatterChart\n          margin={{ top: 8, right: 16, bottom: marginBottom, left: marginLeft }}\n        >\n          {showGrid && (\n            <CartesianGrid\n              strokeDasharray=\"3 3\"\n              stroke=\"var(--border)\"\n              vertical\n              horizontal\n            />\n          )}\n\n          <XAxis\n            type=\"number\"\n            dataKey=\"x\"\n            name={xLabel ?? \"X\"}\n            domain={xDomain}\n            tick={axisStyle}\n            tickLine={false}\n            axisLine={{ stroke: \"var(--border)\" }}\n            tickFormatter={(v: number) => (xFormatter ? xFormatter(v) : fmt(v))}\n            label={\n              xLabel\n                ? {\n                    value: xLabel,\n                    position: \"insideBottom\",\n                    offset: -16,\n                    style: axisLabelStyle,\n                  }\n                : undefined\n            }\n          />\n\n          <YAxis\n            type=\"number\"\n            dataKey=\"y\"\n            name={yLabel ?? \"Y\"}\n            tick={axisStyle}\n            tickLine={false}\n            axisLine={{ stroke: \"var(--border)\" }}\n            tickFormatter={(v: number) => (yFormatter ? yFormatter(v) : fmt(v))}\n            width={yAxisWidth}\n            label={\n              yLabel\n                ? {\n                    value: yLabel,\n                    angle: -90,\n                    position: \"insideLeft\",\n                    offset: yAxisLabelOffset,\n                    style: { ...axisLabelStyle, textAnchor: \"middle\" },\n                  }\n                : undefined\n            }\n          />\n\n          {hasBubble && <ZAxis type=\"number\" dataKey=\"z\" range={bubbleRange} />}\n\n          {showTooltip && (\n            <Tooltip\n              cursor={{ strokeDasharray: \"3 3\", stroke: \"var(--border)\" }}\n              content={\n                <ChartTooltip\n                  xLabel={xLabel}\n                  yLabel={yLabel}\n                  xFormatter={xFormatter}\n                  yFormatter={yFormatter}\n                  fmt={fmt}\n                />\n              }\n            />\n          )}\n\n          {/* Data series */}\n          {enrichedSeries.map((s) => (\n            <Scatter\n              key={s.name}\n              name={s.name}\n              data={s.enrichedData}\n              fill={s.fill}\n              fillOpacity={0.85}\n              shape={s.shape ?? \"circle\"}\n            />\n          ))}\n\n          {/* Trend lines — one per visible series */}\n          {showTrendLine &&\n            enrichedSeries.map((s) => {\n              const reg = linearRegression(s.data)\n              if (!reg) return null\n              const pts = trendLinePoints(s.data, reg.slope, reg.intercept)\n              return (\n                <Scatter\n                  key={`${s.name}__trend`}\n                  data={pts}\n                  fill=\"transparent\"\n                  line={{\n                    stroke: s.fill,\n                    strokeWidth: 1.5,\n                    strokeDasharray: \"5 3\",\n                    strokeOpacity: 0.7,\n                  }}\n                  legendType=\"none\"\n                  shape={TrendDot}\n                  isAnimationActive={false}\n                />\n              )\n            })}\n        </RechartsScatterChart>\n      </ResponsiveContainer>\n\n      {showLegend && (\n        <ChartLegend\n          payload={legendPayload}\n          hiddenSeries={hiddenSeries}\n          onToggle={toggleSeries}\n          vertical={isVerticalLegend}\n        />\n      )}\n\n      {showBrush && (\n        <ContinuousBrush\n          min={globalXMin}\n          max={globalXMax}\n          low={brushX[0]}\n          high={brushX[1]}\n          onChange={(lo, hi) => setBrushX([lo, hi])}\n          formatter={xFormatter}\n          fmt={fmt}\n          locale={locale}\n        />\n      )}\n\n      {footer && (\n        <div className={chartFooterVariants()} data-slot=\"scatter-chart-footer\">\n          {footer}\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}
