{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ds-candlestick-chart",
  "title": "Candlestick Chart",
  "description": "A financial candlestick chart with volume bars, moving averages, reference lines, 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",
    "@lema-ds/tokens"
  ],
  "files": [
    {
      "path": "components/ds/ds-candlestick-chart.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport {\n  Bar,\n  Brush,\n  CartesianGrid,\n  ComposedChart,\n  Line,\n  ReferenceLine as RechartsReferenceLine,\n  ResponsiveContainer,\n  Tooltip,\n  XAxis,\n  YAxis,\n} from \"recharts\"\nimport { cva } from \"class-variance-authority\"\nimport { cn } from \"@/lib/utils\"\nimport { Skeleton } from \"@/components/ui/skeleton\"\nimport { CandlestickChart as CandlestickIcon } 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\"\nimport { measureAxisWidth } from \"@/lib/chart-axis-width\"\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport type LegendPosition = \"top\" | \"bottom\" | \"left\" | \"right\"\n\nexport interface CandleDataPoint {\n  date: string\n  open: number\n  high: number\n  low: number\n  close: number\n  volume?: number\n  [key: string]: string | number | undefined\n}\n\nexport interface MovingAverageConfig {\n  period: number\n  /** Defaults to next --chart-N token */\n  color?: string\n  label?: string\n  /** Render as dashed stroke */\n  dashed?: boolean\n}\n\nexport interface CandlestickReferenceLine {\n  value: number\n  label?: string\n  color?: string\n  /** @default true */\n  dashed?: boolean\n}\n\nexport interface CandlestickChartProps extends React.HTMLAttributes<HTMLDivElement> {\n  data: CandleDataPoint[]\n  title?: string\n  subtitle?: string\n  footer?: React.ReactNode\n  height?: number\n  /** Color for bullish candles (close ≥ open). Default: green. */\n  positiveColor?: string\n  /** Color for bearish candles (close < open). Default: red. */\n  negativeColor?: string\n  /** Compute and overlay simple moving average lines */\n  movingAverages?: MovingAverageConfig[]\n  /** Horizontal price reference lines — targets, support/resistance levels */\n  referenceLines?: CandlestickReferenceLine[]\n  /** Render volume bars in the lower section of the chart */\n  showVolume?: boolean\n  showGrid?: boolean\n  showLegend?: boolean\n  /** @default \"bottom\" */\n  legendPosition?: LegendPosition\n  showTooltip?: boolean\n  showBrush?: boolean\n  /** Format price values (Y axis ticks + tooltip) */\n  valueFormatter?: (value: number) => string\n  format?: FormatPreset\n  decimals?: number\n  currency?: string\n  abbreviate?: boolean\n  /** Format date strings (X axis ticks + tooltip header) */\n  dateFormatter?: (date: string) => string\n  /** Show animated skeleton in place of the chart while data loads */\n  loading?: boolean\n  locale?: UILocale\n}\n\n// ── Constants ──────────────────────────────────────────────────────────────\n\nconst POSITIVE_COLOR = \"var(--success)\"\nconst NEGATIVE_COLOR = \"var(--destructive)\"\n\n/** Colors assigned in order to movingAverages when no color is specified */\nconst MA_COLORS = [\n  \"var(--chart-1)\",\n  \"var(--chart-3)\",\n  \"var(--chart-4)\",\n  \"var(--chart-5)\",\n]\n\n// ── Skeleton ───────────────────────────────────────────────────────────────\n\n// 10 candles: alternating up/down, x positions 5..95\nconst CANDLE_DATA = [\n  { x: 5, high: 18, open: 52, close: 38, low: 68 }, // down (close < open)\n  { x: 15, high: 28, open: 40, close: 55, low: 72 }, // up\n  { x: 25, high: 22, open: 58, close: 42, low: 75 }, // down\n  { x: 35, high: 32, open: 44, close: 60, low: 78 }, // up\n  { x: 45, high: 20, open: 55, close: 40, low: 70 }, // down\n  { x: 55, high: 35, open: 42, close: 58, low: 80 }, // up\n  { x: 65, high: 25, open: 60, close: 45, low: 82 }, // down\n  { x: 75, high: 30, open: 48, close: 62, low: 76 }, // up\n  { x: 85, high: 15, open: 62, close: 48, low: 85 }, // down\n  { x: 95, high: 38, open: 45, close: 60, low: 78 }, // up\n]\n\nconst CANDLE_YAXIS_WIDTHS = [28, 20, 24, 18, 22]\nconst CANDLE_XAXIS_WIDTHS = [24, 28, 22, 26, 24, 28, 22, 26, 24, 28]\n\ninterface CandlestickChartSkeletonProps {\n  height?: number\n  hasTitle?: boolean\n  hasSubtitle?: boolean\n  hasFooter?: boolean\n  className?: string\n}\n\nfunction CandlestickChartSkeleton({\n  height = 360,\n  hasTitle = false,\n  hasSubtitle = false,\n  hasFooter = false,\n  className,\n}: CandlestickChartSkeletonProps) {\n  return (\n    <div\n      className={cn(\"flex w-full flex-col\", className)}\n      data-slot=\"candlestick-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          {CANDLE_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 candles */}\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            {/* Horizontal grid lines */}\n            {[25, 50, 75].map((y) => (\n              <line\n                key={y}\n                x1=\"0\"\n                y1={y}\n                x2=\"100\"\n                y2={y}\n                stroke=\"var(--muted)\"\n                strokeWidth=\"0.6\"\n                opacity={0.5}\n                strokeDasharray=\"3 3\"\n              />\n            ))}\n            {/* Candles */}\n            {CANDLE_DATA.map((c, i) => (\n              <g\n                key={i}\n                className=\"motion-safe:animate-pulse\"\n                style={{ animationDelay: `${i * 0.08}s` }}\n              >\n                {/* Wick */}\n                <line\n                  x1={c.x}\n                  y1={c.high}\n                  x2={c.x}\n                  y2={c.low}\n                  stroke=\"var(--muted)\"\n                  strokeWidth=\"1\"\n                />\n                {/* Body */}\n                <rect\n                  x={c.x - 3}\n                  y={Math.min(c.open, c.close)}\n                  width={6}\n                  height={Math.abs(c.close - c.open)}\n                  fill=\"var(--muted)\"\n                  rx={0.5}\n                />\n              </g>\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          {CANDLE_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.08}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\")\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 defaultDateFmt(date: string, locale = \"en-US\"): string {\n  try {\n    const d = new Date(date)\n    if (isNaN(d.getTime())) return date\n    return d.toLocaleDateString(locale, {\n      month: \"short\",\n      day: \"numeric\",\n    })\n  } catch {\n    return date\n  }\n}\n\nfunction fullDateFmt(date: string, locale = \"en-US\"): string {\n  try {\n    const d = new Date(date)\n    if (isNaN(d.getTime())) return date\n    return d.toLocaleDateString(locale, {\n      year: \"numeric\",\n      month: \"short\",\n      day: \"numeric\",\n    })\n  } catch {\n    return date\n  }\n}\n\nfunction computeMA(\n  data: CandleDataPoint[],\n  period: number\n): (number | undefined)[] {\n  return data.map((_, i) => {\n    if (i < period - 1) return undefined\n    const sum = data\n      .slice(i - period + 1, i + 1)\n      .reduce((s, d) => s + d.close, 0)\n    return sum / period\n  })\n}\n\nfunction normalizeMA(\n  raw: MovingAverageConfig[]\n): Required<MovingAverageConfig>[] {\n  return raw.map((ma, i) => ({\n    period: ma.period,\n    color: ma.color ?? MA_COLORS[i % MA_COLORS.length],\n    label: ma.label ?? `MA ${ma.period}`,\n    dashed: ma.dashed ?? false,\n  }))\n}\n\ntype EnrichedPoint = CandleDataPoint &\n  Record<string, string | number | undefined>\n\nfunction enrichData(\n  data: CandleDataPoint[],\n  mas: Required<MovingAverageConfig>[]\n): EnrichedPoint[] {\n  const result: EnrichedPoint[] = data.map((d) => ({ ...d }))\n  mas.forEach((ma) => {\n    const values = computeMA(data, ma.period)\n    values.forEach((v, i) => {\n      result[i][`_ma${ma.period}`] = v\n    })\n  })\n  return result\n}\n\n/** Full high/low range — the bar spans the entire wick */\nconst candleRangeKey = (entry: unknown): [number, number] => {\n  const d = entry as CandleDataPoint\n  return [d.low, d.high]\n}\n\n// ── Candlestick Shape ──────────────────────────────────────────────────────\n\ninterface CandleShapeProps {\n  x?: number\n  y?: number\n  width?: number\n  height?: number\n  payload?: CandleDataPoint\n  positiveColor: string\n  negativeColor: string\n}\n\nfunction CandleShape({\n  x = 0,\n  y = 0,\n  width = 0,\n  height = 0,\n  payload,\n  positiveColor,\n  negativeColor,\n}: CandleShapeProps) {\n  if (!payload || width <= 0 || height <= 0) return null\n\n  const { open, close, high, low } = payload\n  const isUp = close >= open\n  const color = isUp ? positiveColor : negativeColor\n  const center = x + width / 2\n\n  const range = high - low\n  const ratio = range > 0 ? height / range : 0\n\n  // Body rect coordinates within the full wick bar\n  const bodyTop = ratio > 0 ? y + (high - Math.max(open, close)) * ratio : y\n  const bodyBottom = ratio > 0 ? y + (high - Math.min(open, close)) * ratio : y\n  const bodyH = Math.max(bodyBottom - bodyTop, 1.5)\n\n  // Body width — leave 1px inset on each side\n  const bx = x + 1\n  const bw = Math.max(width - 2, 2)\n\n  return (\n    <g>\n      {/* Wick — thin vertical line covering the full high/low range */}\n      <line\n        x1={center}\n        y1={y}\n        x2={center}\n        y2={y + height}\n        stroke={color}\n        strokeWidth={1.5}\n        strokeLinecap=\"round\"\n      />\n      {/* Body — fills between open and close */}\n      <rect\n        x={bx}\n        y={bodyTop}\n        width={bw}\n        height={bodyH}\n        fill={isUp ? \"transparent\" : color}\n        stroke={color}\n        strokeWidth={1.5}\n        rx={1}\n      />\n    </g>\n  )\n}\n\n// ── Volume Bar Shape ───────────────────────────────────────────────────────\n\ninterface VolumeShapeProps {\n  x?: number\n  y?: number\n  width?: number\n  height?: number\n  payload?: CandleDataPoint\n  positiveColor: string\n  negativeColor: string\n}\n\nfunction VolumeShape({\n  x = 0,\n  y = 0,\n  width = 0,\n  height = 0,\n  payload,\n  positiveColor,\n  negativeColor,\n}: VolumeShapeProps) {\n  if (!payload || width <= 0 || height <= 0) return null\n  const isUp = payload.close >= payload.open\n  const color = isUp ? positiveColor : negativeColor\n  return (\n    <rect\n      x={x + 1}\n      y={y}\n      width={Math.max(width - 2, 2)}\n      height={height}\n      fill={color}\n      fillOpacity={0.3}\n      rx={1}\n    />\n  )\n}\n\n// ── Custom Tooltip ─────────────────────────────────────────────────────────\n\nfunction CandleTooltip({\n  active,\n  payload,\n  positiveColor,\n  negativeColor,\n  valueFmt,\n  locale: localeProp,\n}: {\n  active?: boolean\n  payload?: Array<{\n    payload: EnrichedPoint\n    name?: string\n    value?: unknown\n    color?: string\n    strokeDasharray?: string\n  }>\n  positiveColor: string\n  negativeColor: string\n  valueFmt: (v: number) => string\n  locale?: UILocale\n}) {\n  const locale = useUILocale(localeProp)\n  if (!active || !payload?.length) return null\n\n  const candle = payload.find((p) => Array.isArray(p.value))?.payload as\n    CandleDataPoint | undefined\n  if (!candle) return null\n\n  const isUp = candle.close >= candle.open\n  const color = isUp ? positiveColor : negativeColor\n  const change = candle.close - candle.open\n  const changePct = candle.open !== 0 ? (change / candle.open) * 100 : 0\n  const sign = change >= 0 ? \"+\" : \"\"\n\n  // MA line entries\n  const maEntries = payload.filter(\n    (p) => !Array.isArray(p.value) && p.name && p.name.startsWith(\"MA \")\n  )\n\n  return (\n    <div className=\"min-w-44 rounded-lg border border-border bg-card px-3 py-2.5 shadow-md\">\n      {/* Header: date + change badge */}\n      <div className=\"mb-2 flex items-center justify-between gap-3\">\n        <p className=\"text-xs font-semibold text-foreground\">\n          {fullDateFmt(candle.date, locale)}\n        </p>\n        <span\n          className=\"rounded px-1.5 py-0.5 text-xs font-semibold tabular-nums\"\n          style={{ backgroundColor: `${color}22`, color }}\n        >\n          {sign}\n          {valueFmt(change)} ({sign}\n          {changePct.toFixed(2)}%)\n        </span>\n      </div>\n\n      {/* OHLC */}\n      <div className=\"flex flex-col gap-0.5\">\n        {[\n          {\n            label: UI_I18N[locale].candlestick.open,\n            value: candle.open,\n            extra: false,\n          },\n          {\n            label: UI_I18N[locale].candlestick.high,\n            value: candle.high,\n            extra: false,\n          },\n          {\n            label: UI_I18N[locale].candlestick.low,\n            value: candle.low,\n            extra: false,\n          },\n          {\n            label: UI_I18N[locale].candlestick.close,\n            value: candle.close,\n            extra: true,\n          },\n        ].map(({ label, value, extra }) => (\n          <div key={label} className=\"flex items-center gap-2\">\n            <span\n              className=\"w-8 text-xs\"\n              style={{ color: extra ? color : undefined }}\n            >\n              <span\n                className={extra ? \"font-semibold\" : \"text-muted-foreground\"}\n              >\n                {label}\n              </span>\n            </span>\n            <span\n              className=\"ml-auto text-xs tabular-nums\"\n              style={{\n                color: extra ? color : undefined,\n                fontWeight: extra ? 600 : 400,\n              }}\n            >\n              {valueFmt(value)}\n            </span>\n          </div>\n        ))}\n      </div>\n\n      {/* Volume */}\n      {candle.volume !== undefined && (\n        <div className=\"mt-1.5 flex items-center justify-between border-t border-border pt-1.5\">\n          <span className=\"text-xs text-muted-foreground\">\n            {UI_I18N[locale].candlestick.volume}\n          </span>\n          <span className=\"text-xs text-foreground tabular-nums\">\n            {formatChartValue(candle.volume, { locale })}\n          </span>\n        </div>\n      )}\n\n      {/* MA values */}\n      {maEntries.length > 0 && (\n        <div className=\"mt-1.5 flex flex-col gap-0.5 border-t border-border pt-1.5\">\n          {maEntries.map((ma) => (\n            <div key={ma.name} className=\"flex items-center gap-2\">\n              <svg width=\"12\" height=\"6\" className=\"shrink-0\">\n                <line\n                  x1=\"0\"\n                  y1=\"3\"\n                  x2=\"12\"\n                  y2=\"3\"\n                  stroke={ma.color}\n                  strokeWidth={1.5}\n                  strokeDasharray={ma.strokeDasharray ? \"4 2\" : undefined}\n                  strokeLinecap=\"round\"\n                />\n              </svg>\n              <span className=\"text-xs text-muted-foreground\">{ma.name}</span>\n              <span className=\"ml-auto text-xs font-semibold text-foreground tabular-nums\">\n                {typeof ma.value === \"number\" ? valueFmt(ma.value) : \"—\"}\n              </span>\n            </div>\n          ))}\n        </div>\n      )}\n    </div>\n  )\n}\n\n// ── Custom Legend ──────────────────────────────────────────────────────────\n\ninterface LegendPayloadEntry {\n  value: string\n  color: string\n  payload?: { strokeDasharray?: string }\n}\n\nfunction ChartLegend({\n  payload,\n  hiddenSeries,\n  onToggle,\n  positiveColor,\n  negativeColor,\n  vertical = false,\n  locale: localeProp,\n}: {\n  payload?: LegendPayloadEntry[]\n  hiddenSeries?: Set<string>\n  onToggle?: (name: string) => void\n  positiveColor: string\n  negativeColor: string\n  vertical?: boolean\n  locale?: UILocale\n}) {\n  const locale = useUILocale(localeProp)\n  const maItems = payload ?? []\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-5 pt-3\"\n      )}\n    >\n      {/* Static bull/bear indicators */}\n      {[\n        {\n          label: UI_I18N[locale].candlestick.bullish,\n          color: positiveColor,\n          hollow: true,\n        },\n        {\n          label: UI_I18N[locale].candlestick.bearish,\n          color: negativeColor,\n          hollow: false,\n        },\n      ].map(({ label, color, hollow }) => (\n        <div key={label} className=\"flex items-center gap-1.5 px-1 py-0.5\">\n          <svg width=\"10\" height=\"10\" className=\"shrink-0\">\n            <rect\n              x=\"0\"\n              y=\"0\"\n              width=\"10\"\n              height=\"10\"\n              rx=\"1\"\n              fill={hollow ? \"transparent\" : color}\n              stroke={color}\n              strokeWidth=\"1.5\"\n            />\n          </svg>\n          <span className=\"text-xs text-muted-foreground\">{label}</span>\n        </div>\n      ))}\n\n      {/* Toggleable MA line items */}\n      {maItems.map((entry, i) => {\n        const isDashed = !!entry.payload?.strokeDasharray\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            <svg width=\"16\" height=\"8\" className=\"shrink-0\">\n              <line\n                x1=\"0\"\n                y1=\"4\"\n                x2=\"16\"\n                y2=\"4\"\n                stroke={entry.color}\n                strokeWidth={2}\n                strokeDasharray={isDashed ? \"4 2\" : undefined}\n                strokeLinecap=\"round\"\n              />\n            </svg>\n            <span className=\"text-xs text-muted-foreground\">{entry.value}</span>\n          </div>\n        )\n      })}\n    </div>\n  )\n}\n\n// ── Reference Line Label ───────────────────────────────────────────────────\n\nfunction ReferenceLineLabel({\n  viewBox,\n  label,\n  color,\n}: {\n  viewBox?: { x?: number; width?: number; y?: number }\n  label: string\n  color: string\n}) {\n  const x = (viewBox?.x ?? 0) + (viewBox?.width ?? 0)\n  const y = viewBox?.y ?? 0\n  const pad = 6\n  const estW = label.length * 6 + pad * 2\n  return (\n    <g>\n      <rect\n        x={x - estW - 4}\n        y={y - 10}\n        width={estW}\n        height={16}\n        rx={4}\n        fill={color}\n        fillOpacity={0.12}\n      />\n      <text\n        x={x - estW / 2 - 4}\n        y={y + 3}\n        textAnchor=\"middle\"\n        fontSize={10}\n        fontWeight={600}\n        fill={color}\n      >\n        {label}\n      </text>\n    </g>\n  )\n}\n\n// ── Brush Handle ───────────────────────────────────────────────────────────\n\nfunction BrushHandle(props: {\n  x?: number\n  y?: number\n  width?: number\n  height?: number\n}): React.ReactElement {\n  const { x = 0, y = 0, width = 8, height = 30 } = props\n  const midY = y + height / 2\n  return (\n    <g>\n      <rect\n        x={x}\n        y={y + 5}\n        width={width}\n        height={height - 10}\n        rx={3}\n        fill=\"var(--card)\"\n        stroke=\"var(--border)\"\n        strokeWidth={1.5}\n      />\n      <line\n        x1={x + 2}\n        y1={midY - 3}\n        x2={x + width - 2}\n        y2={midY - 3}\n        stroke=\"var(--muted-foreground)\"\n        strokeWidth={1}\n        opacity={0.5}\n      />\n      <line\n        x1={x + 2}\n        y1={midY + 3}\n        x2={x + width - 2}\n        y2={midY + 3}\n        stroke=\"var(--muted-foreground)\"\n        strokeWidth={1}\n        opacity={0.5}\n      />\n    </g>\n  )\n}\n\n// ── CandlestickChart ───────────────────────────────────────────────────────\n\nexport function CandlestickChart({\n  data,\n  title,\n  subtitle,\n  footer,\n  height = 360,\n  positiveColor = POSITIVE_COLOR,\n  negativeColor = NEGATIVE_COLOR,\n  movingAverages,\n  referenceLines,\n  showVolume = false,\n  showGrid = true,\n  showLegend = false,\n  legendPosition = \"bottom\",\n  showTooltip = true,\n  showBrush = false,\n  valueFormatter,\n  format,\n  decimals,\n  currency,\n  abbreviate,\n  dateFormatter,\n  loading = false,\n  locale: localeProp,\n  className,\n  ...props\n}: CandlestickChartProps) {\n  const locale = useUILocale(localeProp)\n  // Hooks must be called unconditionally before any early returns\n  const valueFmt = 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  const dateFmt = React.useCallback(\n    (d: string) => dateFormatter?.(d) ?? defaultDateFmt(d, locale),\n    [dateFormatter, locale]\n  )\n\n  const resolvedMAs = React.useMemo(\n    () => normalizeMA(movingAverages ?? []),\n    [movingAverages]\n  )\n  const enrichedData = React.useMemo(\n    () => enrichData(data, resolvedMAs),\n    [data, resolvedMAs]\n  )\n\n  const legendPayload = React.useMemo(\n    () =>\n      resolvedMAs.map((ma) => ({\n        value: ma.label,\n        color: ma.color,\n        payload: { strokeDasharray: ma.dashed ? \"5 3\" : undefined },\n      })),\n    [resolvedMAs]\n  )\n\n  const maxVolume = React.useMemo(\n    () => Math.max(...data.map((d) => d.volume ?? 0)),\n    [data]\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)) {\n        next.delete(name)\n      } else {\n        next.add(name)\n      }\n      return next\n    })\n  }, [])\n\n  const axisStyle = { fontSize: \"12px\", fill: \"var(--muted-foreground)\" }\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 priceAxisWidth = measureAxisWidth(\n    [0, ...data.flatMap((d) => [d.high, d.low, d.open, d.close])],\n    valueFmt,\n    { min: 56 }\n  )\n\n  if (loading) {\n    return (\n      <CandlestickChartSkeleton\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=\"candlestick-chart\"\n        {...props}\n      >\n        {(title || subtitle) && (\n          <div\n            className={chartHeaderVariants()}\n            data-slot=\"candlestick-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=\"candlestick-chart-empty\"\n          style={{ height }}\n        >\n          <div className=\"flex size-10 items-center justify-center rounded-full bg-muted\">\n            <CandlestickIcon 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=\"candlestick-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=\"candlestick-chart\"\n      {...props}\n    >\n      {(title || subtitle) && (\n        <div\n          className={chartHeaderVariants()}\n          data-slot=\"candlestick-chart-header\"\n        >\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=\"candlestick-chart-chart\"\n      >\n        <ComposedChart\n          data={enrichedData}\n          margin={{ top: 8, right: 8, bottom: 4, left: 4 }}\n          barCategoryGap=\"20%\"\n          barGap={0}\n        >\n          {showGrid && (\n            <CartesianGrid\n              strokeDasharray=\"3 3\"\n              stroke=\"var(--border)\"\n              vertical={false}\n            />\n          )}\n\n          <XAxis\n            dataKey=\"date\"\n            tick={axisStyle}\n            axisLine={false}\n            tickLine={false}\n            dy={6}\n            tickFormatter={dateFmt}\n          />\n\n          {/* Price Y axis */}\n          <YAxis\n            yAxisId=\"price\"\n            tick={axisStyle}\n            axisLine={false}\n            tickLine={false}\n            tickFormatter={valueFmt}\n            width={priceAxisWidth}\n            domain={[\"auto\", \"auto\"]}\n          />\n\n          {/* Volume Y axis — inflated domain pushes bars to the bottom ~20% */}\n          {showVolume && maxVolume > 0 && (\n            <YAxis yAxisId=\"vol\" domain={[0, maxVolume * 5]} hide />\n          )}\n\n          {showTooltip && (\n            <Tooltip\n              content={(p) => (\n                <CandleTooltip\n                  active={p.active}\n                  payload={p.payload as never}\n                  positiveColor={positiveColor}\n                  negativeColor={negativeColor}\n                  valueFmt={valueFmt}\n                  locale={locale}\n                />\n              )}\n              cursor={{ fill: \"var(--muted)\", opacity: 0.15 }}\n            />\n          )}\n\n          {/* Reference lines */}\n          {referenceLines?.map((rl, i) => (\n            <RechartsReferenceLine\n              key={i}\n              yAxisId=\"price\"\n              y={rl.value}\n              stroke={rl.color ?? \"var(--muted-foreground)\"}\n              strokeDasharray={rl.dashed !== false ? \"4 3\" : undefined}\n              strokeWidth={1.5}\n              label={\n                rl.label\n                  ? (labelProps: {\n                      viewBox?: { x?: number; width?: number; y?: number }\n                    }) => (\n                      <ReferenceLineLabel\n                        key={`rl-${i}`}\n                        viewBox={labelProps.viewBox}\n                        label={rl.label!}\n                        color={rl.color ?? \"var(--muted-foreground)\"}\n                      />\n                    )\n                  : undefined\n              }\n            />\n          ))}\n\n          {/* Volume bars — rendered first so candles appear on top */}\n          {showVolume && maxVolume > 0 && (\n            <Bar\n              yAxisId=\"vol\"\n              dataKey=\"volume\"\n              isAnimationActive={false}\n              legendType=\"none\"\n              shape={(shapeProps: unknown) => {\n                const p = shapeProps as VolumeShapeProps & {\n                  payload?: CandleDataPoint\n                }\n                return (\n                  <VolumeShape\n                    {...p}\n                    positiveColor={positiveColor}\n                    negativeColor={negativeColor}\n                  />\n                )\n              }}\n            />\n          )}\n\n          {/* Moving average lines */}\n          {resolvedMAs.map((ma) => (\n            <Line\n              key={ma.period}\n              yAxisId=\"price\"\n              type=\"monotone\"\n              dataKey={`_ma${ma.period}`}\n              name={ma.label}\n              stroke={ma.color}\n              strokeWidth={1.5}\n              strokeDasharray={ma.dashed ? \"5 3\" : undefined}\n              dot={false}\n              connectNulls\n              isAnimationActive={false}\n              hide={hiddenSeries.has(ma.label)}\n            />\n          ))}\n\n          {/* Candlestick bars — rendered last to appear above volume */}\n          <Bar\n            yAxisId=\"price\"\n            dataKey={candleRangeKey}\n            isAnimationActive={false}\n            legendType=\"none\"\n            shape={(shapeProps: unknown) => {\n              const p = shapeProps as CandleShapeProps & {\n                payload?: CandleDataPoint\n              }\n              return (\n                <CandleShape\n                  {...p}\n                  positiveColor={positiveColor}\n                  negativeColor={negativeColor}\n                />\n              )\n            }}\n          />\n\n          {showBrush && (\n            <Brush\n              dataKey=\"date\"\n              height={30}\n              stroke=\"var(--border)\"\n              fill=\"var(--card)\"\n              travellerWidth={8}\n              traveller={(<BrushHandle />) as React.ReactElement<SVGElement>}\n              tickFormatter={() => \"\"}\n            />\n          )}\n        </ComposedChart>\n      </ResponsiveContainer>\n\n      {showLegend && (\n        <ChartLegend\n          payload={legendPayload}\n          hiddenSeries={hiddenSeries}\n          onToggle={toggleSeries}\n          positiveColor={positiveColor}\n          negativeColor={negativeColor}\n          vertical={legendPosition === \"left\" || legendPosition === \"right\"}\n          locale={locale}\n        />\n      )}\n\n      {footer && (\n        <div\n          className={chartFooterVariants()}\n          data-slot=\"candlestick-chart-footer\"\n        >\n          {footer}\n        </div>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}
