---
title: "Chart · Base UI — StyleX Blocks"
description: "Composable area, line, bar, sparkline, and category-bar data visualizations powered by TanStack Charts and StyleX."
url: "https://stylexblocks.com/components/base-ui/chart/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Chart

Composable area, line, bar, sparkline, and category-bar data visualizations powered by TanStack Charts and StyleX.

- Behavior engine: Base UI
- Also available for: [Ark UI](https://stylexblocks.com/components/ark-ui/chart.md), [UI SDK](https://stylexblocks.com/components/ui-sdk/chart.md)
- Category: Display
- HTML page: https://stylexblocks.com/components/base-ui/chart/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init --style base-ui
```

Then add the item as source you own:

```sh
npx stylexblocks add chart
```

Equivalent: `npx shadcn add @stylexblocks/chart`. Registry item JSON: https://stylexblocks.com/r/base-ui/chart.json

## Usage

```tsx
import { AreaChart } from "#components/ui/base-ui/chart.tsx";

const data = [
  { month: "Jan", Revenue: 4200, Expenses: 2800 },
  { month: "Feb", Revenue: 4850, Expenses: 3100 },
  { month: "Mar", Revenue: 5400, Expenses: 2950 },
  { month: "Apr", Revenue: 6150, Expenses: 3400 },
  { month: "May", Revenue: 7100, Expenses: 3650 },
  { month: "Jun", Revenue: 8300, Expenses: 4100 },
];

export function Example() {
  return (
    <AreaChart
      data={data}
      index="month"
      categories={["Revenue", "Expenses"]}
      colors={["blue", "emerald"]}
      valueFormatter={(value) => `$${value.toLocaleString()}`}
    />
  );
}
```

## Examples

### Reference line & zoomed Y-domain

Overlay a dashed horizontal `referenceLine` threshold with an optional label and narrow the vertical scale via `yDomain` so tight variance stays legible.

```tsx
import { AreaChart, LineChart, BarChart, Sparkline, CategoryBar } from "#components/ui/base-ui/chart.tsx";

export function RevenueTargetChart({ data }: { data: Record<string, unknown>[] }) {
  return (
    <AreaChart
      data={data}
      index="month"
      categories={["Revenue"]}
      colors={["emerald"]}
      height={210}
      yDomain={[3500, 9000]}
      referenceLine={{ value: 6000, label: "Target $6k", color: "amber" }}
      valueFormatter={(value) => `$${value.toLocaleString()}`}
    />
  );
}
```

### Line chart

Multi-series trends with optional point markers, crosshair hover tooltips, and click-to-toggle legend items.

```tsx
import { AreaChart, LineChart, BarChart, Sparkline, CategoryBar } from "#components/ui/base-ui/chart.tsx";

export function TrafficLineChart({ data }: { data: Record<string, unknown>[] }) {
  return (
    <LineChart
      data={data}
      index="day"
      categories={["Organic", "Direct", "Referral"]}
      colors={["indigo", "cyan", "amber"]}
      curve="monotone"
      showDots
      height={220}
    />
  );
}
```

### Bar chart (grouped & stacked)

Switch between side-by-side grouped bars and stacked bars in vertical or horizontal layouts.

```tsx
import { AreaChart, LineChart, BarChart, Sparkline, CategoryBar } from "#components/ui/base-ui/chart.tsx";

export function RevenueBarCharts({ data }: { data: Record<string, unknown>[] }) {
  return (
    <>
      <BarChart
        data={data}
        index="quarter"
        categories={["Enterprise", "SelfServe", "Usage"]}
        colors={["blue", "emerald", "violet"]}
        type="grouped"
        valueFormatter={(v) => `$${v}k`}
      />
      <BarChart
        data={data}
        index="quarter"
        categories={["Enterprise", "SelfServe", "Usage"]}
        colors={["blue", "emerald", "violet"]}
        type="stacked"
        layout="horizontal"
        valueFormatter={(v) => `$${v}k`}
      />
    </>
  );
}
```

### Sparklines in KPI cards

Axis-free inline line and area sparklines with optional hover tooltips for compact metric tiles.

```tsx
import { AreaChart, LineChart, BarChart, Sparkline, CategoryBar } from "#components/ui/base-ui/chart.tsx";

export function KpiSparkline({ data }: { data: Record<string, unknown>[] }) {
  return (
    <Sparkline
      data={data}
      index="day"
      categories={["value"]}
      colors={["emerald"]}
      variant="area"
      showTooltip
      height={42}
    />
  );
}
```

### Category bar

Proportional multi-segment horizontal bar with an optional target marker pin and inline summary legend.

```tsx
import { AreaChart, LineChart, BarChart, Sparkline, CategoryBar } from "#components/ui/base-ui/chart.tsx";

export function QuotaCategoryBar() {
  return (
    <CategoryBar
      values={[42, 26, 18, 14]}
      labels={["Closed Won", "Commit", "Best Case", "Remaining"]}
      colors={["emerald", "blue", "amber", "slate"]}
      markerValue={75}
      valueFormatter={(value) => `${value}%`}
    />
  );
}
```

## Source

`components/ui/base-ui/chart.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import {
  areaY,
  barX,
  barY,
  defineChart,
  dot,
  group,
  lineY,
  ruleY,
  stack,
  text,
  whenFocused,
  type ChartCurve,
} from "@tanstack/charts";
import { crosshair } from "@tanstack/charts/crosshair";
import { decorative } from "@tanstack/charts/mark/decorative";
import { Chart } from "@tanstack/charts/react/tooltip";
import { scaleBand } from "@tanstack/charts/scales/band";
import { scaleLinear } from "@tanstack/charts/scales/linear";
import { scaleOrdinal } from "@tanstack/charts/scales/ordinal";
import { tooltip } from "@tanstack/charts/tooltip";
import { useCallback, useMemo, useState } from "react";
import { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";
import { semanticShadows } from "@stylexblocks/ui/semantic-tokens/shadows.stylex.ts";
import { fontSizes } from "@stylexblocks/ui/tokens/font-sizes.stylex.ts";
import { fontWeights } from "@stylexblocks/ui/tokens/font-weights.stylex.ts";
import { fonts } from "@stylexblocks/ui/tokens/fonts.stylex.ts";
import { lineHeights } from "@stylexblocks/ui/tokens/line-heights.stylex.ts";
import { radii } from "@stylexblocks/ui/tokens/radii.stylex.ts";
import { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";
import type { StyleOverrideProps } from "#lib/recipe-props.ts";

// ============= PALETTE =============

/** Named StyleX-token chart colors with high contrast across light & dark themes. */
export const chartColors = {
  blue: semanticColors.blueSolid,
  emerald: semanticColors.emeraldSolid,
  amber: semanticColors.amberSolid,
  violet: semanticColors.violetSolid,
  rose: semanticColors.roseSolid,
  cyan: semanticColors.cyanSolid,
  indigo: semanticColors.indigoSolid,
  teal: semanticColors.tealSolid,
  orange: semanticColors.orangeSolid,
  slate: semanticColors.graySolid,
} as const;

export type ChartColorName = keyof typeof chartColors;

/** Default 6-color sequence used when `colors` is omitted or shorter than `categories`. */
export const DEFAULT_CHART_COLORS: readonly ChartColorName[] = [
  "blue",
  "emerald",
  "amber",
  "violet",
  "rose",
  "cyan",
] as const;

/**
 * Resolves a named chart color (e.g. `"emerald"`), passes through arbitrary CSS
 * colors / custom properties, or falls back to `DEFAULT_CHART_COLORS[index]`.
 */
export function resolveChartColor(color: string | undefined, index = 0): string {
  if (color && color in chartColors) {
    return chartColors[color as ChartColorName];
  }
  if (color && color.trim().length > 0) {
    return color;
  }
  const safeIndex =
    ((index % DEFAULT_CHART_COLORS.length) + DEFAULT_CHART_COLORS.length) %
    DEFAULT_CHART_COLORS.length;
  return chartColors[DEFAULT_CHART_COLORS[safeIndex]!];
}

// ============= CURVE GENERATORS =============

export type ChartCurveType = "linear" | "monotone" | "step";

type Point2D = readonly [number, number];

function computeMonotoneControls(
  points: readonly Point2D[],
): Array<readonly [number, number, number, number]> {
  const n = points.length;
  if (n < 2) return [];

  const slopes: number[] = [];
  for (let i = 0; i < n - 1; i++) {
    const dx = points[i + 1]![0] - points[i]![0];
    const dy = points[i + 1]![1] - points[i]![1];
    slopes.push(dx === 0 ? 0 : dy / dx);
  }

  const tangents = new Array<number>(n).fill(0);
  if (n === 2) {
    tangents[0] = slopes[0]!;
    tangents[1] = slopes[0]!;
  } else {
    for (let i = 1; i < n - 1; i++) {
      const s0 = slopes[i - 1]!;
      const s1 = slopes[i]!;
      if (s0 * s1 <= 0) {
        tangents[i] = 0;
      } else {
        const h0 = points[i]![0] - points[i - 1]![0];
        const h1 = points[i + 1]![0] - points[i]![0];
        const p = (s0 * h1 + s1 * h0) / (h0 + h1);
        tangents[i] =
          (Math.sign(s0) + Math.sign(s1)) *
          Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p));
      }
    }
    const clampEndpoint = (t: number, s: number) => {
      if (t * s <= 0) return 0;
      if (Math.abs(t) > 3 * Math.abs(s)) return 3 * s;
      return t;
    };
    tangents[0] = clampEndpoint((3 * slopes[0]! - tangents[1]!) / 2, slopes[0]!);
    tangents[n - 1] = clampEndpoint(
      (3 * slopes[n - 2]! - tangents[n - 2]!) / 2,
      slopes[n - 2]!,
    );
  }

  const segments: Array<readonly [number, number, number, number]> = [];
  for (let i = 0; i < n - 1; i++) {
    const p0 = points[i]!;
    const p1 = points[i + 1]!;
    const dx = (p1[0] - p0[0]) / 3;
    segments.push([
      p0[0] + dx,
      p0[1] + dx * tangents[i]!,
      p1[0] - dx,
      p1[1] - dx * tangents[i + 1]!,
    ]);
  }
  return segments;
}

const MONOTONE_CURVE: ChartCurve = {
  line(points) {
    if (points.length === 0) return "";
    const first = points[0]!;
    if (points.length === 1) return `M${first[0]},${first[1]}`;
    const controls = computeMonotoneControls(points);
    let d = `M${first[0]},${first[1]}`;
    for (let i = 0; i < controls.length; i++) {
      const [c1x, c1y, c2x, c2y] = controls[i]!;
      const p1 = points[i + 1]!;
      d += `C${c1x},${c1y},${c2x},${c2y},${p1[0]},${p1[1]}`;
    }
    return d;
  },
  area(top, bottom) {
    if (top.length === 0 || bottom.length === 0) return "";
    const firstTop = top[0]!;
    const lastBottom = bottom[bottom.length - 1]!;
    if (top.length === 1) {
      return `M${firstTop[0]},${firstTop[1]}L${lastBottom[0]},${lastBottom[1]}Z`;
    }
    const topControls = computeMonotoneControls(top);
    const bottomControls = computeMonotoneControls(bottom);
    let d = `M${firstTop[0]},${firstTop[1]}`;
    for (let i = 0; i < topControls.length; i++) {
      const [c1x, c1y, c2x, c2y] = topControls[i]!;
      const p1 = top[i + 1]!;
      d += `C${c1x},${c1y},${c2x},${c2y},${p1[0]},${p1[1]}`;
    }
    d += `L${lastBottom[0]},${lastBottom[1]}`;
    for (let i = bottomControls.length - 1; i >= 0; i--) {
      const [c1x, c1y, c2x, c2y] = bottomControls[i]!;
      const p0 = bottom[i]!;
      d += `C${c2x},${c2y},${c1x},${c1y},${p0[0]},${p0[1]}`;
    }
    return `${d}Z`;
  },
};

const STEP_CURVE: ChartCurve = {
  line(points) {
    if (points.length === 0) return "";
    const first = points[0]!;
    let d = `M${first[0]},${first[1]}`;
    for (let i = 1; i < points.length; i++) {
      const p = points[i]!;
      d += `H${p[0]}V${p[1]}`;
    }
    return d;
  },
  area(top, bottom) {
    if (top.length === 0 || bottom.length === 0) return "";
    const firstTop = top[0]!;
    const lastBottom = bottom[bottom.length - 1]!;
    let d = `M${firstTop[0]},${firstTop[1]}`;
    for (let i = 1; i < top.length; i++) {
      const p = top[i]!;
      d += `H${p[0]}V${p[1]}`;
    }
    d += `L${lastBottom[0]},${lastBottom[1]}`;
    for (let i = bottom.length - 1; i >= 1; i--) {
      const prev = bottom[i - 1]!;
      d += `V${prev[1]}H${prev[0]}`;
    }
    return `${d}Z`;
  },
};

function resolveCurve(curve: ChartCurveType | undefined): ChartCurve | undefined {
  if (curve === "monotone") return MONOTONE_CURVE;
  if (curve === "step") return STEP_CURVE;
  return undefined;
}

// ============= NUMERIC & AXIS HELPERS =============

const DEFAULT_NUMBER_FORMATTER = new Intl.NumberFormat(undefined, {
  maximumFractionDigits: 2,
});

function defaultValueFormatter(value: number): string {
  return DEFAULT_NUMBER_FORMATTER.format(value);
}

function defaultCompactFormatter(value: number): string {
  const abs = Math.abs(value);
  if (abs >= 1_000_000) return `${Number((value / 1_000_000).toFixed(1))}M`;
  if (abs >= 10_000) return `${Number((value / 1_000).toFixed(1))}k`;
  return DEFAULT_NUMBER_FORMATTER.format(value);
}

function toFiniteNumber(raw: unknown): number | null {
  if (typeof raw === "number" && Number.isFinite(raw)) return raw;
  return null;
}

function niceStep(rawStep: number): number {
  if (!Number.isFinite(rawStep) || rawStep <= 0) return 1;
  const exponent = Math.floor(Math.log10(rawStep));
  const magnitude = 10 ** exponent;
  const normalized = rawStep / magnitude;
  if (normalized <= 1) return 1 * magnitude;
  if (normalized <= 2) return 2 * magnitude;
  if (normalized <= 2.5) return 2.5 * magnitude;
  if (normalized <= 5) return 5 * magnitude;
  return 10 * magnitude;
}

function computeNumericAxis(
  values: ReadonlyArray<number>,
  includeZero = true,
): { min: number; max: number; ticks: number[] } {
  if (values.length === 0) {
    return { min: 0, max: 100, ticks: [0, 25, 50, 75, 100] };
  }
  let dataMin = Number.POSITIVE_INFINITY;
  let dataMax = Number.NEGATIVE_INFINITY;
  for (const v of values) {
    if (v < dataMin) dataMin = v;
    if (v > dataMax) dataMax = v;
  }
  if (includeZero) {
    dataMin = Math.min(0, dataMin);
    dataMax = Math.max(0, dataMax);
  }
  if (dataMin === dataMax) {
    const pad = dataMax === 0 ? 10 : Math.abs(dataMax) * 0.2;
    dataMin = includeZero && dataMin >= 0 ? 0 : dataMin - pad;
    dataMax = dataMax + pad;
  }

  const step = niceStep((dataMax - dataMin) / 4);
  const niceMin = Math.floor(dataMin / step) * step;
  const niceMax = Math.ceil(dataMax / step) * step;
  const ticks: number[] = [];
  const count = Math.min(8, Math.max(2, Math.round((niceMax - niceMin) / step)));
  for (let i = 0; i <= count; i++) {
    const tick = Number((niceMin + i * step).toFixed(10));
    ticks.push(Object.is(tick, -0) ? 0 : tick);
  }
  return {
    min: ticks[0] ?? niceMin,
    max: ticks[ticks.length - 1] ?? niceMax,
    ticks,
  };
}

function computeDomainAxis(
  minRaw: number,
  maxRaw: number,
): { min: number; max: number; ticks: number[] } {
  let min = minRaw;
  let max = maxRaw;
  if (!Number.isFinite(min) || !Number.isFinite(max)) {
    return { min: 0, max: 100, ticks: [0, 25, 50, 75, 100] };
  }
  if (min > max) [min, max] = [max, min];
  if (min === max) {
    const pad = max === 0 ? 10 : Math.abs(max) * 0.2;
    min -= pad;
    max += pad;
  }

  const step = niceStep((max - min) / 4);
  const firstTick = Math.ceil(min / step) * step;
  const ticks: number[] = [];
  for (let v = firstTick; v <= max + step * 1e-9 && ticks.length < 8; v += step) {
    const tick = Number(v.toFixed(10));
    ticks.push(Object.is(tick, -0) ? 0 : tick);
  }
  if (ticks.length < 2) {
    const mid = Number(((min + max) / 2).toFixed(10));
    return { min, max, ticks: [min, Object.is(mid, -0) ? 0 : mid, max] };
  }
  return { min, max, ticks };
}

function computeSlotTicks(length: number): number[] {
  if (length <= 0) return [0];
  if (length === 1) return [0];
  if (length <= 7) {
    return Array.from({ length }, (_, i) => i);
  }
  const last = length - 1;
  const segments = 4;
  const result = new Set<number>([0, last]);
  for (let i = 1; i < segments; i++) {
    result.add(Math.round((last * i) / segments));
  }
  return Array.from(result).sort((a, b) => a - b);
}

const CHART_THEME = {
  foreground: semanticColors.fg,
  muted: semanticColors.fgMuted,
  grid: semanticColors.fg,
  background: "transparent",
} as const;

// ============= STYLES =============

const styles = stylex.create({
  root: {
    color: semanticColors.fg,
    display: "flex",
    flexDirection: "column",
    fontFamily: fonts.body,
    gap: spacing._3,
    width: "100%",
  },
  chartHost: {
    width: "100%",
    "--ts-chart-tooltip-background": "transparent",
    "--ts-chart-tooltip-border": "none",
    "--ts-chart-tooltip-border-radius": "0px",
    "--ts-chart-tooltip-padding": "0px",
    "--ts-chart-tooltip-shadow": "none",
  },
  emptyState: {
    alignItems: "center",
    backgroundColor: semanticColors.bgMuted,
    borderColor: semanticColors.borderSubtle,
    borderRadius: radii.md,
    borderStyle: "dashed",
    borderWidth: "1px",
    color: semanticColors.fgMuted,
    display: "flex",
    fontSize: fontSizes.xs,
    justifyContent: "center",
    width: "100%",
  },
  emptyHeight: (height: number) => ({
    height: `${height}px`,
  }),
  tooltipCard: {
    backgroundColor: semanticColors.bgElevated,
    borderColor: semanticColors.border,
    borderRadius: radii.lg,
    borderStyle: "solid",
    borderWidth: "1px",
    boxShadow: semanticShadows.md,
    color: semanticColors.fg,
    display: "flex",
    flexDirection: "column",
    fontFamily: fonts.body,
    gap: spacing._1_5,
    minWidth: "10.5rem",
    paddingBlock: spacing._2_5,
    paddingInline: spacing._3,
  },
  tooltipTitle: {
    color: semanticColors.fgMuted,
    fontSize: fontSizes.xs,
    fontWeight: fontWeights.medium,
    lineHeight: lineHeights.xs,
  },
  tooltipRows: {
    display: "flex",
    flexDirection: "column",
    gap: spacing._1,
  },
  tooltipRow: {
    alignItems: "center",
    borderRadius: radii.sm,
    display: "flex",
    fontSize: fontSizes.xs,
    gap: spacing._3,
    justifyContent: "space-between",
    marginInline: `calc(-1 * ${spacing._1_5})`,
    paddingBlock: "0.125rem",
    paddingInline: spacing._1_5,
  },
  tooltipRowPrimary: {
    backgroundColor: semanticColors.interactionHover,
  },
  tooltipLead: {
    alignItems: "center",
    color: semanticColors.fg,
    display: "flex",
    gap: spacing._2,
  },
  tooltipValue: {
    color: semanticColors.fg,
    fontFamily: fonts.mono,
    fontVariantNumeric: "tabular-nums",
    fontWeight: fontWeights.semibold,
  },
  tooltipReference: {
    borderTopColor: semanticColors.borderSubtle,
    borderTopStyle: "solid",
    borderTopWidth: "1px",
    color: semanticColors.fgMuted,
    fontFamily: fonts.mono,
    fontSize: fontSizes.xs,
    fontVariantNumeric: "tabular-nums",
    lineHeight: lineHeights.xs,
    paddingTop: spacing._1_5,
  },
  legendRow: {
    alignItems: "center",
    display: "flex",
    flexWrap: "wrap",
    gap: spacing._4,
  },
  legendAlignStart: {
    justifyContent: "flex-start",
  },
  legendAlignCenter: {
    justifyContent: "center",
  },
  legendAlignEnd: {
    justifyContent: "flex-end",
  },
  legendItem: {
    alignItems: "center",
    color: semanticColors.fgMuted,
    display: "inline-flex",
    fontFamily: fonts.body,
    fontSize: fontSizes.xs,
    fontWeight: fontWeights.medium,
    gap: spacing._1_5,
    lineHeight: lineHeights.xs,
  },
  legendButton: {
    alignItems: "center",
    backgroundColor: {
      default: "transparent",
      ":hover": semanticColors.interactionHover,
    },
    borderRadius: radii.sm,
    borderStyle: "none",
    borderWidth: 0,
    color: {
      default: semanticColors.fgMuted,
      ":hover": semanticColors.fg,
    },
    cursor: "pointer",
    display: "inline-flex",
    fontFamily: fonts.body,
    fontSize: fontSizes.xs,
    fontWeight: fontWeights.medium,
    gap: spacing._1_5,
    lineHeight: lineHeights.xs,
    outlineColor: semanticColors.accentFocusRing,
    outlineOffset: "2px",
    paddingBlock: spacing._0_5,
    paddingInline: spacing._1_5,
    marginInline: `calc(-1 * ${spacing._1_5})`,
    transitionDuration: "150ms",
    transitionProperty: "opacity, background-color, color",
  },
  legendHidden: {
    opacity: 0.4,
    textDecorationLine: "line-through",
  },
  swatch: {
    borderRadius: "2px",
    display: "inline-block",
    flexShrink: 0,
    height: "0.625rem",
    width: "0.625rem",
  },
  swatchColor: (color: string) => ({
    backgroundColor: color,
  }),
  sparklineRoot: {
    display: "block",
    width: "100%",
  },
  categoryBarRoot: {
    color: semanticColors.fg,
    display: "flex",
    flexDirection: "column",
    fontFamily: fonts.body,
    gap: spacing._2_5,
    width: "100%",
  },
  categoryBarTrackWrap: {
    alignItems: "center",
    display: "flex",
    position: "relative",
    width: "100%",
  },
  categoryBarTrack: {
    backgroundColor: semanticColors.bgMuted,
    borderRadius: radii.full,
    display: "flex",
    gap: "2px",
    height: "0.5rem",
    overflow: "hidden",
    width: "100%",
  },
  categoryBarSegment: (widthPct: number, color: string) => ({
    backgroundColor: color,
    height: "100%",
    width: `${widthPct}%`,
    transitionDuration: "200ms",
    transitionProperty: "width",
  }),
  categoryBarMarker: (leftPct: number) => ({
    backgroundColor: semanticColors.fg,
    borderRadius: radii.full,
    bottom: "-3px",
    boxShadow: `0 0 0 2px ${semanticColors.bgSurface}`,
    left: `calc(${leftPct}% - 1px)`,
    pointerEvents: "none",
    position: "absolute",
    top: "-3px",
    width: "2px",
  }),
  categoryBarLabels: {
    alignItems: "center",
    display: "flex",
    flexWrap: "wrap",
    gap: spacing._4,
  },
  categoryBarLabelItem: {
    alignItems: "center",
    display: "inline-flex",
    fontSize: fontSizes.xs,
    gap: spacing._1_5,
    lineHeight: lineHeights.xs,
  },
  categoryBarLabelText: {
    color: semanticColors.fgMuted,
    fontWeight: fontWeights.medium,
  },
  categoryBarLabelValue: {
    color: semanticColors.fg,
    fontFamily: fonts.mono,
    fontVariantNumeric: "tabular-nums",
    fontWeight: fontWeights.semibold,
  },
});

const legendAlignMap = {
  start: styles.legendAlignStart,
  center: styles.legendAlignCenter,
  end: styles.legendAlignEnd,
} as const;

// ============= SHARED TOOLTIP BODY =============

export interface ChartReferenceLine {
  value: number;
  label?: string;
  color?: string;
}

interface TooltipSeriesEntry {
  id: string;
  label: string;
  series: string;
  value: number;
}

function ChartTooltipCard({
  title,
  entries,
  primaryId,
  colorBySeries,
  formatValue,
  referenceLine,
}: {
  title: string;
  entries: ReadonlyArray<TooltipSeriesEntry>;
  primaryId?: string;
  colorBySeries: ReadonlyMap<string, string>;
  formatValue: (value: number) => string;
  referenceLine?: ChartReferenceLine;
}) {
  // Deduplicate by series in case multiple marks emit points for the same x slot
  const unique: TooltipSeriesEntry[] = [];
  const seen = new Set<string>();
  for (const entry of entries) {
    if (seen.has(entry.series)) continue;
    seen.add(entry.series);
    unique.push(entry);
  }
  if (unique.length === 0) return null;

  let referenceReadout: string | null = null;
  if (referenceLine && Number.isFinite(referenceLine.value)) {
    const refLabel = referenceLine.label ?? formatValue(referenceLine.value);
    if (unique.length === 1) {
      const diff = unique[0]!.value - referenceLine.value;
      const sign = diff > 0 ? "+" : diff < 0 ? "−" : "";
      referenceReadout = `${sign}${formatValue(Math.abs(diff))} vs ${refLabel}`;
    } else {
      referenceReadout = referenceLine.label
        ? `${referenceLine.label}: ${formatValue(referenceLine.value)}`
        : `Ref: ${formatValue(referenceLine.value)}`;
    }
  }

  return (
    <div {...stylex.props(styles.tooltipCard)}>
      {title ? <div {...stylex.props(styles.tooltipTitle)}>{title}</div> : null}
      <div {...stylex.props(styles.tooltipRows)}>
        {unique.map((entry, idx) => {
          const swatchColor =
            colorBySeries.get(entry.series) ?? resolveChartColor(undefined, idx);
          const isPrimary = primaryId !== undefined && primaryId === entry.id;
          return (
            <div
              key={entry.id}
              {...stylex.props(
                styles.tooltipRow,
                isPrimary && styles.tooltipRowPrimary,
              )}
            >
              <span {...stylex.props(styles.tooltipLead)}>
                <span
                  {...stylex.props(styles.swatch, styles.swatchColor(swatchColor))}
                />
                <span>{entry.series}</span>
              </span>
              <span {...stylex.props(styles.tooltipValue)}>
                {formatValue(entry.value)}
              </span>
            </div>
          );
        })}
      </div>
      {referenceReadout ? (
        <div {...stylex.props(styles.tooltipReference)}>{referenceReadout}</div>
      ) : null}
    </div>
  );
}

// ============= HOOK: TOGGLEABLE SERIES =============

function useSeriesVisibility() {
  const [hiddenKeys, setHiddenKeys] = useState<ReadonlySet<string>>(
    () => new Set<string>(),
  );
  const toggleSeries = useCallback((name: string) => {
    setHiddenKeys((prev) => {
      const next = new Set(prev);
      if (next.has(name)) next.delete(name);
      else next.add(name);
      return next;
    });
  }, []);
  return { hiddenKeys, toggleSeries };
}

// ============= CHART LEGEND =============

export interface ChartLegendItem {
  name: string;
  color: string;
}

export interface ChartLegendProps extends StyleOverrideProps {
  items: ReadonlyArray<ChartLegendItem>;
  hiddenKeys?: ReadonlySet<string>;
  onToggle?: (name: string) => void;
  align?: "start" | "center" | "end";
  ariaLabel?: string;
}

/**
 * Interactive or static series legend strip. When `onToggle` is supplied,
 * items render as toggle buttons with `aria-pressed` state.
 */
export function ChartLegend({
  items,
  hiddenKeys,
  onToggle,
  align = "start",
  ariaLabel = "Chart legend",
  palette,
  style,
}: ChartLegendProps) {
  if (items.length === 0) return null;

  return (
    <div
      role="group"
      aria-label={ariaLabel}
      {...stylex.props(palette, styles.legendRow, legendAlignMap[align], style)}
    >
      {items.map((item, idx) => {
        const resolved = resolveChartColor(item.color, idx);
        const isHidden = hiddenKeys?.has(item.name) ?? false;
        if (onToggle) {
          return (
            <button
              key={item.name}
              type="button"
              aria-pressed={!isHidden}
              onClick={() => onToggle(item.name)}
              {...stylex.props(
                styles.legendButton,
                isHidden && styles.legendHidden,
              )}
            >
              <span
                {...stylex.props(styles.swatch, styles.swatchColor(resolved))}
              />
              <span>{item.name}</span>
            </button>
          );
        }
        return (
          <span
            key={item.name}
            {...stylex.props(styles.legendItem, isHidden && styles.legendHidden)}
          >
            <span
              {...stylex.props(styles.swatch, styles.swatchColor(resolved))}
            />
            <span>{item.name}</span>
          </span>
        );
      })}
    </div>
  );
}
ChartLegend.displayName = "ChartLegend";

// ============= AREA CHART =============

export interface AreaChartProps extends StyleOverrideProps {
  data: ReadonlyArray<Record<string, unknown>>;
  index: string;
  categories: ReadonlyArray<string>;
  colors?: ReadonlyArray<string>;
  height?: number;
  type?: "default" | "stacked";
  curve?: ChartCurveType;
  showLegend?: boolean;
  showGrid?: boolean;
  showTooltip?: boolean;
  showXAxis?: boolean;
  showYAxis?: boolean;
  valueFormatter?: (value: number) => string;
  connectNulls?: boolean;
  referenceLine?: ChartReferenceLine;
  yDomain?: readonly [number, number];
  ariaLabel?: string;
}

interface AreaRow {
  id: string;
  slot: number;
  label: string;
  series: string;
  value: number | null;
  y0: number | null;
  y1: number | null;
}

/**
 * Multi-series area chart supporting overlapping (`default`) and cumulative
 * (`stacked`) layouts, smooth/linear/step curves, hover tooltips, optional
 * horizontal reference lines, custom Y-axis domains, and an interactive
 * toggleable legend.
 */
export function AreaChart({
  data,
  index,
  categories,
  colors,
  height = 240,
  type = "default",
  curve = "monotone",
  showLegend = true,
  showGrid = true,
  showTooltip = true,
  showXAxis = true,
  showYAxis = true,
  valueFormatter,
  connectNulls = false,
  referenceLine,
  yDomain,
  ariaLabel = "Area chart",
  palette,
  style,
}: AreaChartProps) {
  const { hiddenKeys, toggleSeries } = useSeriesVisibility();
  const formatValue = valueFormatter ?? defaultValueFormatter;
  const formatAxisValue = valueFormatter ?? defaultCompactFormatter;

  const refValue = referenceLine?.value;
  const refLabel = referenceLine?.label;
  const refColor = referenceLine?.color;
  const yDomainMin = yDomain?.[0];
  const yDomainMax = yDomain?.[1];

  const legendItems = useMemo<ChartLegendItem[]>(
    () =>
      categories.map((name, idx) => ({
        name,
        color: resolveChartColor(colors?.[idx], idx),
      })),
    [categories, colors],
  );

  const colorBySeries = useMemo(
    () => new Map(legendItems.map((item) => [item.name, item.color])),
    [legendItems],
  );

  const activeCategories = useMemo(
    () => categories.filter((name) => !hiddenKeys.has(name)),
    [categories, hiddenKeys],
  );

  const labels = useMemo(
    () => data.map((row, slot) => String(row[index] ?? slot)),
    [data, index],
  );

  const { rows, yAxis } = useMemo(() => {
    const out: AreaRow[] = [];
    const extentValues: number[] = [];

    if (type === "stacked") {
      const posBase = new Array<number>(data.length).fill(0);
      const negBase = new Array<number>(data.length).fill(0);

      for (const series of activeCategories) {
        for (let slot = 0; slot < data.length; slot++) {
          const val = toFiniteNumber(data[slot]?.[series]);
          if (val === null) {
            if (!connectNulls) {
              out.push({
                id: `${series}-${slot}`,
                slot,
                label: labels[slot] ?? String(slot),
                series,
                value: null,
                y0: null,
                y1: null,
              });
            }
            continue;
          }
          let y0: number;
          let y1: number;
          if (val >= 0) {
            y0 = posBase[slot]!;
            y1 = y0 + val;
            posBase[slot] = y1;
          } else {
            y1 = negBase[slot]!;
            y0 = y1 + val;
            negBase[slot] = y0;
          }
          extentValues.push(y0, y1);
          out.push({
            id: `${series}-${slot}`,
            slot,
            label: labels[slot] ?? String(slot),
            series,
            value: val,
            y0,
            y1,
          });
        }
      }
    } else {
      for (const series of activeCategories) {
        for (let slot = 0; slot < data.length; slot++) {
          const val = toFiniteNumber(data[slot]?.[series]);
          if (val === null) {
            if (!connectNulls) {
              out.push({
                id: `${series}-${slot}`,
                slot,
                label: labels[slot] ?? String(slot),
                series,
                value: null,
                y0: null,
                y1: null,
              });
            }
            continue;
          }
          extentValues.push(val);
          out.push({
            id: `${series}-${slot}`,
            slot,
            label: labels[slot] ?? String(slot),
            series,
            value: val,
            y0: 0,
            y1: val,
          });
        }
      }
    }

    if (refValue !== undefined && Number.isFinite(refValue)) {
      extentValues.push(refValue);
    }

    const computedAxis =
      yDomainMin !== undefined && yDomainMax !== undefined
        ? computeDomainAxis(yDomainMin, yDomainMax)
        : computeNumericAxis(extentValues, true);

    if (type !== "stacked") {
      const baseline = Math.min(computedAxis.max, Math.max(computedAxis.min, 0));
      if (baseline !== 0) {
        for (const row of out) {
          if (row.y0 !== null) row.y0 = baseline;
        }
      }
    }

    return { rows: out, yAxis: computedAxis };
  }, [activeCategories, connectNulls, data, labels, refValue, type, yDomainMax, yDomainMin]);

  const xTicks = useMemo(() => computeSlotTicks(data.length), [data.length]);

  const definition = useMemo(() => {
    const resolvedCurve = resolveCurve(curve);
    const maxSlot = Math.max(1, data.length - 1);
    const domain = legendItems.map((item) => item.name);
    const range = legendItems.map((item) => item.color);

    const hasRefLine = refValue !== undefined && Number.isFinite(refValue);
    const resolvedRefColor = refColor
      ? resolveChartColor(refColor)
      : semanticColors.borderEmphasized;
    const resolvedRefLabelColor = refColor
      ? resolvedRefColor
      : semanticColors.fgMuted;
    const isRefNearTop =
      hasRefLine &&
      yAxis.max > yAxis.min &&
      (yAxis.max - refValue) / (yAxis.max - yAxis.min) < 0.16;

    const longestYTick = yAxis.ticks.reduce(
      (max, tick) => Math.max(max, formatAxisValue(tick).length),
      0,
    );
    const leftMargin = showYAxis
      ? Math.min(84, Math.max(48, longestYTick * 7 + 12))
      : 8;

    const marks =
      activeCategories.length > 0 && rows.length > 0
        ? [
            decorative(
              areaY(rows, {
                id: "area-fill",
                x: "slot",
                y1: "y0",
                y2: "y1",
                z: "series",
                color: "series",
                key: "id",
                fillOpacity: type === "stacked" ? 0.28 : 0.18,
                curve: resolvedCurve,
              }),
            ),
            ...(hasRefLine
              ? [
                  decorative(
                    ruleY([refValue], {
                      id: "area-reference-line",
                      stroke: resolvedRefColor,
                      strokeDasharray: "4 4",
                      strokeOpacity: 0.85,
                      strokeWidth: 1.25,
                    }),
                  ),
                ]
              : []),
            lineY(rows, {
              id: "area-line",
              x: "slot",
              y: "y1",
              z: "series",
              color: "series",
              key: "id",
              strokeWidth: 2,
              curve: resolvedCurve,
            }),
            ...(hasRefLine && refLabel
              ? [
                  decorative(
                    text(
                      [
                        {
                          slot: maxSlot,
                          value: refValue,
                          label: refLabel,
                        },
                      ],
                      {
                        id: "area-reference-label",
                        x: "slot",
                        y: "value",
                        text: "label",
                        anchor: "end",
                        dx: -4,
                        dy: isRefNearTop ? 12 : -8,
                        fontSize: 11,
                        fontWeight: 500,
                        fill: resolvedRefLabelColor,
                      },
                    ),
                  ),
                ]
              : []),
            ...(showTooltip
              ? [
                  whenFocused(
                    dot(rows, {
                      id: "area-focus-dots",
                      x: "slot",
                      y: "y1",
                      z: "series",
                      color: "series",
                      key: "id",
                      r: 4,
                      stroke: semanticColors.bgSurface,
                      strokeWidth: 2,
                    }),
                    { match: "x" },
                  ),
                  crosshair({
                    x: {
                      stroke: semanticColors.borderEmphasized,
                      strokeDasharray: "3 3",
                      strokeWidth: 1,
                    },
                    y: false,
                  }),
                ]
              : []),
          ]
        : [];

    return defineChart({
      marks,
      scales: {
        x: {
          scale: () => scaleLinear().domain([0, maxSlot]),
          axis: showXAxis
            ? {
                line: false,
                ticks: {
                  size: 0,
                  values: xTicks,
                  format: (v) => labels[Math.round(Number(v))] ?? "",
                },
              }
            : false,
          grid: false,
        },
        y: {
          scale: () => scaleLinear().domain([yAxis.min, yAxis.max]),
          grid: showGrid,
          axis: showYAxis
            ? {
                line: false,
                ticks: {
                  size: 0,
                  values: yAxis.ticks,
                  format: (v) => formatAxisValue(Number(v)),
                },
              }
            : false,
        },
      },
      color: {
        scale: scaleOrdinal<string, string>().domain(domain).range(range),
      },
      theme: CHART_THEME,
      focus: showTooltip && activeCategories.length > 0 ? "group-x" : false,
      focusRing: false,
      maxFocusDistance: Number.POSITIVE_INFINITY,
      margin: {
        top: 10,
        right: 12,
        bottom: showXAxis ? 26 : 8,
        left: leftMargin,
      },
      ...(showTooltip && activeCategories.length > 0
        ? {
            tooltip: {
              use: tooltip,
              sort: "color-domain" as const,
              offset: 14,
            },
          }
        : {}),
    });
  }, [
    activeCategories.length,
    curve,
    data.length,
    formatAxisValue,
    labels,
    legendItems,
    refColor,
    refLabel,
    refValue,
    rows,
    showGrid,
    showTooltip,
    showXAxis,
    showYAxis,
    type,
    xTicks,
    yAxis,
  ]);

  if (data.length === 0 || categories.length === 0) {
    return (
      <div {...stylex.props(palette, styles.root, style)}>
        <div
          role="img"
          aria-label={ariaLabel}
          {...stylex.props(styles.emptyState, styles.emptyHeight(height))}
        >
          No data available
        </div>
      </div>
    );
  }

  return (
    <div {...stylex.props(palette, styles.root, style)}>
      <div {...stylex.props(styles.chartHost)}>
        <Chart
          definition={definition}
          height={height}
          initialWidth={640}
          ariaLabel={ariaLabel}
          renderTooltipBody={
            showTooltip
              ? ({ points, primaryPoint }) => {
                  const entries: TooltipSeriesEntry[] = [];
                  for (const pt of points) {
                    if (pt.datum.value === null) continue;
                    entries.push({
                      id: pt.datum.id,
                      label: pt.datum.label,
                      series: pt.datum.series,
                      value: pt.datum.value,
                    });
                  }
                  return (
                    <ChartTooltipCard
                      title={entries[0]?.label ?? ""}
                      entries={entries}
                      primaryId={primaryPoint?.datum.id}
                      colorBySeries={colorBySeries}
                      formatValue={formatValue}
                      referenceLine={referenceLine}
                    />
                  );
                }
              : undefined
          }
        />
      </div>

      {showLegend ? (
        <ChartLegend
          items={legendItems}
          hiddenKeys={hiddenKeys}
          onToggle={toggleSeries}
        />
      ) : null}
    </div>
  );
}
AreaChart.displayName = "AreaChart";

// ============= LINE CHART =============

export interface LineChartProps extends StyleOverrideProps {
  data: ReadonlyArray<Record<string, unknown>>;
  index: string;
  categories: ReadonlyArray<string>;
  colors?: ReadonlyArray<string>;
  height?: number;
  curve?: ChartCurveType;
  showDots?: boolean;
  showLegend?: boolean;
  showGrid?: boolean;
  showTooltip?: boolean;
  showXAxis?: boolean;
  showYAxis?: boolean;
  valueFormatter?: (value: number) => string;
  connectNulls?: boolean;
  referenceLine?: ChartReferenceLine;
  yDomain?: readonly [number, number];
  ariaLabel?: string;
}

interface LineRow {
  id: string;
  slot: number;
  label: string;
  series: string;
  value: number | null;
}

/**
 * Multi-series line chart with optional data-point markers, curve styles,
 * horizontal reference lines, custom Y-axis domains, synchronized vertical
 * crosshair + tooltip, and toggleable legend.
 */
export function LineChart({
  data,
  index,
  categories,
  colors,
  height = 240,
  curve = "linear",
  showDots = false,
  showLegend = true,
  showGrid = true,
  showTooltip = true,
  showXAxis = true,
  showYAxis = true,
  valueFormatter,
  connectNulls = false,
  referenceLine,
  yDomain,
  ariaLabel = "Line chart",
  palette,
  style,
}: LineChartProps) {
  const { hiddenKeys, toggleSeries } = useSeriesVisibility();
  const formatValue = valueFormatter ?? defaultValueFormatter;
  const formatAxisValue = valueFormatter ?? defaultCompactFormatter;

  const refValue = referenceLine?.value;
  const refLabel = referenceLine?.label;
  const refColor = referenceLine?.color;
  const yDomainMin = yDomain?.[0];
  const yDomainMax = yDomain?.[1];

  const legendItems = useMemo<ChartLegendItem[]>(
    () =>
      categories.map((name, idx) => ({
        name,
        color: resolveChartColor(colors?.[idx], idx),
      })),
    [categories, colors],
  );

  const colorBySeries = useMemo(
    () => new Map(legendItems.map((item) => [item.name, item.color])),
    [legendItems],
  );

  const activeCategories = useMemo(
    () => categories.filter((name) => !hiddenKeys.has(name)),
    [categories, hiddenKeys],
  );

  const labels = useMemo(
    () => data.map((row, slot) => String(row[index] ?? slot)),
    [data, index],
  );

  const { rows, yAxis } = useMemo(() => {
    const out: LineRow[] = [];
    const extentValues: number[] = [];

    for (const series of activeCategories) {
      for (let slot = 0; slot < data.length; slot++) {
        const val = toFiniteNumber(data[slot]?.[series]);
        if (val === null) {
          if (!connectNulls) {
            out.push({
              id: `${series}-${slot}`,
              slot,
              label: labels[slot] ?? String(slot),
              series,
              value: null,
            });
          }
          continue;
        }
        extentValues.push(val);
        out.push({
          id: `${series}-${slot}`,
          slot,
          label: labels[slot] ?? String(slot),
          series,
          value: val,
        });
      }
    }

    if (refValue !== undefined && Number.isFinite(refValue)) {
      extentValues.push(refValue);
    }

    const computedAxis =
      yDomainMin !== undefined && yDomainMax !== undefined
        ? computeDomainAxis(yDomainMin, yDomainMax)
        : computeNumericAxis(extentValues, true);

    return { rows: out, yAxis: computedAxis };
  }, [activeCategories, connectNulls, data, labels, refValue, yDomainMax, yDomainMin]);

  const xTicks = useMemo(() => computeSlotTicks(data.length), [data.length]);

  const definition = useMemo(() => {
    const resolvedCurve = resolveCurve(curve);
    const maxSlot = Math.max(1, data.length - 1);
    const domain = legendItems.map((item) => item.name);
    const range = legendItems.map((item) => item.color);

    const hasRefLine = refValue !== undefined && Number.isFinite(refValue);
    const resolvedRefColor = refColor
      ? resolveChartColor(refColor)
      : semanticColors.borderEmphasized;
    const resolvedRefLabelColor = refColor
      ? resolvedRefColor
      : semanticColors.fgMuted;
    const isRefNearTop =
      hasRefLine &&
      yAxis.max > yAxis.min &&
      (yAxis.max - refValue) / (yAxis.max - yAxis.min) < 0.16;

    const longestYTick = yAxis.ticks.reduce(
      (max, tick) => Math.max(max, formatAxisValue(tick).length),
      0,
    );
    const leftMargin = showYAxis
      ? Math.min(84, Math.max(48, longestYTick * 7 + 12))
      : 8;

    const marks =
      activeCategories.length > 0 && rows.length > 0
        ? [
            ...(hasRefLine
              ? [
                  decorative(
                    ruleY([refValue], {
                      id: "line-reference-line",
                      stroke: resolvedRefColor,
                      strokeDasharray: "4 4",
                      strokeOpacity: 0.85,
                      strokeWidth: 1.25,
                    }),
                  ),
                ]
              : []),
            lineY(rows, {
              id: "line-series",
              x: "slot",
              y: "value",
              z: "series",
              color: "series",
              key: "id",
              strokeWidth: 2,
              curve: resolvedCurve,
            }),
            ...(showDots
              ? [
                  decorative(
                    dot(rows, {
                      id: "line-dots",
                      x: "slot",
                      y: "value",
                      z: "series",
                      color: "series",
                      key: "id",
                      r: 3.5,
                      stroke: semanticColors.bgSurface,
                      strokeWidth: 1.5,
                    }),
                  ),
                ]
              : []),
            ...(hasRefLine && refLabel
              ? [
                  decorative(
                    text(
                      [
                        {
                          slot: maxSlot,
                          value: refValue,
                          label: refLabel,
                        },
                      ],
                      {
                        id: "line-reference-label",
                        x: "slot",
                        y: "value",
                        text: "label",
                        anchor: "end",
                        dx: -4,
                        dy: isRefNearTop ? 12 : -8,
                        fontSize: 11,
                        fontWeight: 500,
                        fill: resolvedRefLabelColor,
                      },
                    ),
                  ),
                ]
              : []),
            ...(showTooltip
              ? [
                  whenFocused(
                    dot(rows, {
                      id: "line-focus-dots",
                      x: "slot",
                      y: "value",
                      z: "series",
                      color: "series",
                      key: "id",
                      r: 4.5,
                      stroke: semanticColors.bgSurface,
                      strokeWidth: 2,
                    }),
                    { match: "x" },
                  ),
                  crosshair({
                    x: {
                      stroke: semanticColors.borderEmphasized,
                      strokeDasharray: "3 3",
                      strokeWidth: 1,
                    },
                    y: false,
                  }),
                ]
              : []),
          ]
        : [];

    return defineChart({
      marks,
      scales: {
        x: {
          scale: () => scaleLinear().domain([0, maxSlot]),
          axis: showXAxis
            ? {
                line: false,
                ticks: {
                  size: 0,
                  values: xTicks,
                  format: (v) => labels[Math.round(Number(v))] ?? "",
                },
              }
            : false,
          grid: false,
        },
        y: {
          scale: () => scaleLinear().domain([yAxis.min, yAxis.max]),
          grid: showGrid,
          axis: showYAxis
            ? {
                line: false,
                ticks: {
                  size: 0,
                  values: yAxis.ticks,
                  format: (v) => formatAxisValue(Number(v)),
                },
              }
            : false,
        },
      },
      color: {
        scale: scaleOrdinal<string, string>().domain(domain).range(range),
      },
      theme: CHART_THEME,
      focus: showTooltip && activeCategories.length > 0 ? "group-x" : false,
      focusRing: false,
      maxFocusDistance: Number.POSITIVE_INFINITY,
      margin: {
        top: 10,
        right: 12,
        bottom: showXAxis ? 26 : 8,
        left: leftMargin,
      },
      ...(showTooltip && activeCategories.length > 0
        ? {
            tooltip: {
              use: tooltip,
              sort: "color-domain" as const,
              offset: 14,
            },
          }
        : {}),
    });
  }, [
    activeCategories.length,
    curve,
    data.length,
    formatAxisValue,
    labels,
    legendItems,
    refColor,
    refLabel,
    refValue,
    rows,
    showDots,
    showGrid,
    showTooltip,
    showXAxis,
    showYAxis,
    xTicks,
    yAxis,
  ]);

  if (data.length === 0 || categories.length === 0) {
    return (
      <div {...stylex.props(palette, styles.root, style)}>
        <div
          role="img"
          aria-label={ariaLabel}
          {...stylex.props(styles.emptyState, styles.emptyHeight(height))}
        >
          No data available
        </div>
      </div>
    );
  }

  return (
    <div {...stylex.props(palette, styles.root, style)}>
      <div {...stylex.props(styles.chartHost)}>
        <Chart
          definition={definition}
          height={height}
          initialWidth={640}
          ariaLabel={ariaLabel}
          renderTooltipBody={
            showTooltip
              ? ({ points, primaryPoint }) => {
                  const entries: TooltipSeriesEntry[] = [];
                  for (const pt of points) {
                    if (pt.datum.value === null) continue;
                    entries.push({
                      id: pt.datum.id,
                      label: pt.datum.label,
                      series: pt.datum.series,
                      value: pt.datum.value,
                    });
                  }
                  return (
                    <ChartTooltipCard
                      title={entries[0]?.label ?? ""}
                      entries={entries}
                      primaryId={primaryPoint?.datum.id}
                      colorBySeries={colorBySeries}
                      formatValue={formatValue}
                      referenceLine={referenceLine}
                    />
                  );
                }
              : undefined
          }
        />
      </div>

      {showLegend ? (
        <ChartLegend
          items={legendItems}
          hiddenKeys={hiddenKeys}
          onToggle={toggleSeries}
        />
      ) : null}
    </div>
  );
}
LineChart.displayName = "LineChart";

// ============= BAR CHART =============

export interface BarChartProps extends StyleOverrideProps {
  data: ReadonlyArray<Record<string, unknown>>;
  index: string;
  categories: ReadonlyArray<string>;
  colors?: ReadonlyArray<string>;
  height?: number;
  type?: "default" | "grouped" | "stacked";
  layout?: "vertical" | "horizontal";
  showLegend?: boolean;
  showGrid?: boolean;
  showTooltip?: boolean;
  showXAxis?: boolean;
  showYAxis?: boolean;
  valueFormatter?: (value: number) => string;
  ariaLabel?: string;
}

interface BarRow {
  id: string;
  label: string;
  series: string;
  value: number;
}

/**
 * Categorical bar chart supporting vertical (`barY`) and horizontal (`barX`)
 * orientations, grouped and stacked multi-series modes, StyleX tooltips, and
 * interactive legend toggles.
 */
export function BarChart({
  data,
  index,
  categories,
  colors,
  height = 240,
  type,
  layout = "vertical",
  showLegend = true,
  showGrid = true,
  showTooltip = true,
  showXAxis = true,
  showYAxis = true,
  valueFormatter,
  ariaLabel = "Bar chart",
  palette,
  style,
}: BarChartProps) {
  const { hiddenKeys, toggleSeries } = useSeriesVisibility();
  const formatValue = valueFormatter ?? defaultValueFormatter;
  const formatAxisValue = valueFormatter ?? defaultCompactFormatter;
  const resolvedType = type ?? (categories.length > 1 ? "grouped" : "default");

  const legendItems = useMemo<ChartLegendItem[]>(
    () =>
      categories.map((name, idx) => ({
        name,
        color: resolveChartColor(colors?.[idx], idx),
      })),
    [categories, colors],
  );

  const colorBySeries = useMemo(
    () => new Map(legendItems.map((item) => [item.name, item.color])),
    [legendItems],
  );

  const activeCategories = useMemo(
    () => categories.filter((name) => !hiddenKeys.has(name)),
    [categories, hiddenKeys],
  );

  const { rows, bandLabels, valueAxis } = useMemo(() => {
    const out: BarRow[] = [];
    const uniqueLabels: string[] = [];
    const seenLabels = new Set<string>();
    const extentValues: number[] = [];

    for (let i = 0; i < data.length; i++) {
      const datum = data[i]!;
      const label = String(datum[index] ?? i);
      if (!seenLabels.has(label)) {
        seenLabels.add(label);
        uniqueLabels.push(label);
      }

      let posTotal = 0;
      let negTotal = 0;
      for (const series of activeCategories) {
        const val = toFiniteNumber(datum[series]);
        if (val === null) continue;
        out.push({
          id: `${label}-${series}-${i}`,
          label,
          series,
          value: val,
        });
        if (resolvedType === "stacked") {
          if (val >= 0) posTotal += val;
          else negTotal += val;
        } else {
          extentValues.push(val);
        }
      }
      if (resolvedType === "stacked") {
        extentValues.push(posTotal, negTotal);
      }
    }

    return {
      rows: out,
      bandLabels: uniqueLabels,
      valueAxis: computeNumericAxis(extentValues, true),
    };
  }, [activeCategories, data, index, resolvedType]);

  const { horizontalDefinition, verticalDefinition } = useMemo(() => {
    const domain = legendItems.map((item) => item.name);
    const range = legendItems.map((item) => item.color);
    const isStacked = resolvedType === "stacked";
    const isGrouped = !isStacked && activeCategories.length > 1;
    const barLayout = isStacked
      ? stack()
      : isGrouped
        ? group({ padding: 0.14 })
        : undefined;

    const longestLabel = bandLabels.reduce((max, l) => Math.max(max, l.length), 0);
    const horizontalLeftMargin = Math.min(124, Math.max(64, longestLabel * 7 + 16));

    if (layout === "horizontal") {
      const marks =
        activeCategories.length > 0 && rows.length > 0
          ? [
              barX(rows, {
                id: "bars-x",
                x: "value",
                y: "label",
                z: "series",
                color: "series",
                key: "id",
                layout: barLayout,
                radius: isStacked
                  ? { end: 4, stack: "outer" }
                  : ([0, 4, 4, 0] as const),
                fillOpacity: 0.92,
              }),
            ]
          : [];

      return {
        horizontalDefinition: defineChart({
          marks,
          scales: {
            x: {
              scale: () => scaleLinear().domain([valueAxis.min, valueAxis.max]),
              grid: showGrid,
              axis: showXAxis
                ? {
                    line: false,
                    ticks: {
                      size: 0,
                      values: valueAxis.ticks,
                      format: (v) => formatAxisValue(Number(v)),
                    },
                  }
                : false,
            },
            y: {
              scale: () => scaleBand<string>().domain(bandLabels).padding(0.28),
              grid: false,
              axis: showYAxis
                ? {
                    line: false,
                    ticks: { size: 0 },
                  }
                : false,
            },
          },
          color: {
            scale: scaleOrdinal<string, string>().domain(domain).range(range),
          },
          theme: CHART_THEME,
          focus: showTooltip && activeCategories.length > 0 ? "group-y" : false,
          focusRing: false,
          margin: {
            top: 10,
            right: 16,
            bottom: showXAxis ? 26 : 8,
            left: showYAxis ? horizontalLeftMargin : 8,
          },
          ...(showTooltip && activeCategories.length > 0
            ? {
                tooltip: {
                  use: tooltip,
                  sort: "color-domain" as const,
                  offset: 12,
                },
              }
            : {}),
        }),
        verticalDefinition: null,
      };
    }

    const marks =
      activeCategories.length > 0 && rows.length > 0
        ? [
            barY(rows, {
              id: "bars-y",
              x: "label",
              y: "value",
              z: "series",
              color: "series",
              key: "id",
              layout: barLayout,
              radius: isStacked
                ? { end: 4, stack: "outer" }
                : ([4, 4, 0, 0] as const),
              fillOpacity: 0.92,
            }),
          ]
        : [];

    return {
      horizontalDefinition: null,
      verticalDefinition: defineChart({
        marks,
        scales: {
          x: {
            scale: () => scaleBand<string>().domain(bandLabels).padding(0.28),
            grid: false,
            axis: showXAxis
              ? {
                  line: false,
                  ticks: { size: 0 },
                }
              : false,
          },
          y: {
            scale: () => scaleLinear().domain([valueAxis.min, valueAxis.max]),
            grid: showGrid,
            axis: showYAxis
              ? {
                  line: false,
                  ticks: {
                    size: 0,
                    values: valueAxis.ticks,
                    format: (v) => formatAxisValue(Number(v)),
                  },
                }
              : false,
          },
        },
        color: {
          scale: scaleOrdinal<string, string>().domain(domain).range(range),
        },
        theme: CHART_THEME,
        focus: showTooltip && activeCategories.length > 0 ? "group-x" : false,
        focusRing: false,
        margin: {
          top: 10,
          right: 12,
          bottom: showXAxis ? 26 : 8,
          left: showYAxis ? 48 : 8,
        },
        ...(showTooltip && activeCategories.length > 0
          ? {
              tooltip: {
                use: tooltip,
                sort: "color-domain" as const,
                offset: 12,
              },
            }
          : {}),
      }),
    };
  }, [
    activeCategories.length,
    bandLabels,
    formatAxisValue,
    layout,
    legendItems,
    resolvedType,
    rows,
    showGrid,
    showTooltip,
    showXAxis,
    showYAxis,
    valueAxis,
  ]);

  const renderBarTooltip = useCallback(
    ({
      points,
      primaryPoint,
    }: {
      points: ReadonlyArray<{ datum: BarRow }>;
      primaryPoint?: { datum: BarRow } | null;
    }) => {
      const entries: TooltipSeriesEntry[] = points.map((pt) => ({
        id: pt.datum.id,
        label: pt.datum.label,
        series: pt.datum.series,
        value: pt.datum.value,
      }));
      return (
        <ChartTooltipCard
          title={entries[0]?.label ?? ""}
          entries={entries}
          primaryId={primaryPoint?.datum.id}
          colorBySeries={colorBySeries}
          formatValue={formatValue}
        />
      );
    },
    [colorBySeries, formatValue],
  );

  if (data.length === 0 || categories.length === 0) {
    return (
      <div {...stylex.props(palette, styles.root, style)}>
        <div
          role="img"
          aria-label={ariaLabel}
          {...stylex.props(styles.emptyState, styles.emptyHeight(height))}
        >
          No data available
        </div>
      </div>
    );
  }

  return (
    <div {...stylex.props(palette, styles.root, style)}>
      <div {...stylex.props(styles.chartHost)}>
        {horizontalDefinition ? (
          <Chart
            definition={horizontalDefinition}
            height={height}
            initialWidth={640}
            ariaLabel={ariaLabel}
            renderTooltipBody={showTooltip ? renderBarTooltip : undefined}
          />
        ) : verticalDefinition ? (
          <Chart
            definition={verticalDefinition}
            height={height}
            initialWidth={640}
            ariaLabel={ariaLabel}
            renderTooltipBody={showTooltip ? renderBarTooltip : undefined}
          />
        ) : null}
      </div>

      {showLegend ? (
        <ChartLegend
          items={legendItems}
          hiddenKeys={hiddenKeys}
          onToggle={toggleSeries}
        />
      ) : null}
    </div>
  );
}
BarChart.displayName = "BarChart";

// ============= SPARKLINE =============

export interface SparklineProps extends StyleOverrideProps {
  data: ReadonlyArray<Record<string, unknown>>;
  categories: ReadonlyArray<string>;
  index?: string;
  colors?: ReadonlyArray<string>;
  height?: number;
  variant?: "line" | "area";
  curve?: ChartCurveType;
  showTooltip?: boolean;
  valueFormatter?: (value: number) => string;
  ariaLabel?: string;
}

interface SparklineRow {
  id: string;
  slot: number;
  label: string;
  series: string;
  value: number | null;
}

/**
 * Compact axis-free inline trend chart for KPI cards, metrics strips, and table cells.
 */
export function Sparkline({
  data,
  categories,
  index,
  colors,
  height = 40,
  variant = "line",
  curve = "monotone",
  showTooltip = false,
  valueFormatter,
  ariaLabel = "Sparkline trend",
  palette,
  style,
}: SparklineProps) {
  const formatValue = valueFormatter ?? defaultValueFormatter;

  const seriesMeta = useMemo(
    () =>
      categories.map((name, idx) => ({
        name,
        color: resolveChartColor(colors?.[idx], idx),
      })),
    [categories, colors],
  );

  const colorBySeries = useMemo(
    () => new Map(seriesMeta.map((item) => [item.name, item.color])),
    [seriesMeta],
  );

  const { rows, yDomain } = useMemo(() => {
    const out: SparklineRow[] = [];
    let minVal = Number.POSITIVE_INFINITY;
    let maxVal = Number.NEGATIVE_INFINITY;

    for (const series of categories) {
      for (let slot = 0; slot < data.length; slot++) {
        const datum = data[slot]!;
        const val = toFiniteNumber(datum[series]);
        if (val !== null) {
          if (val < minVal) minVal = val;
          if (val > maxVal) maxVal = val;
        }
        out.push({
          id: `${series}-${slot}`,
          slot,
          label: index ? String(datum[index] ?? slot) : String(slot + 1),
          series,
          value: val,
        });
      }
    }

    if (!Number.isFinite(minVal) || !Number.isFinite(maxVal)) {
      return { rows: out, yDomain: [0, 1] as const };
    }
    if (minVal === maxVal) {
      const pad = minVal === 0 ? 1 : Math.abs(minVal) * 0.1;
      return { rows: out, yDomain: [minVal - pad, maxVal + pad] as const };
    }
    const pad = (maxVal - minVal) * 0.08;
    return {
      rows: out,
      yDomain: [minVal - pad, maxVal + pad] as const,
    };
  }, [categories, data, index]);

  const definition = useMemo(() => {
    const resolvedCurve = resolveCurve(curve);
    const maxSlot = Math.max(1, data.length - 1);
    const domain = seriesMeta.map((item) => item.name);
    const range = seriesMeta.map((item) => item.color);

    const marks =
      rows.length > 0
        ? [
            ...(variant === "area"
              ? [
                  decorative(
                    areaY(rows, {
                      id: "spark-area",
                      x: "slot",
                      y1: yDomain[0],
                      y2: "value",
                      z: "series",
                      color: "series",
                      key: "id",
                      fillOpacity: 0.18,
                      curve: resolvedCurve,
                    }),
                  ),
                ]
              : []),
            lineY(rows, {
              id: "spark-line",
              x: "slot",
              y: "value",
              z: "series",
              color: "series",
              key: "id",
              strokeWidth: 1.75,
              curve: resolvedCurve,
            }),
            ...(showTooltip
              ? [
                  whenFocused(
                    dot(rows, {
                      id: "spark-focus-dot",
                      x: "slot",
                      y: "value",
                      z: "series",
                      color: "series",
                      key: "id",
                      r: 3.5,
                      stroke: semanticColors.bgSurface,
                      strokeWidth: 1.5,
                    }),
                    { match: "x" },
                  ),
                ]
              : []),
          ]
        : [];

    return defineChart({
      marks,
      scales: {
        x: {
          scale: () => scaleLinear().domain([0, maxSlot]),
          axis: false,
          grid: false,
        },
        y: {
          scale: () => scaleLinear().domain([yDomain[0], yDomain[1]]),
          axis: false,
          grid: false,
        },
      },
      color: {
        scale: scaleOrdinal<string, string>().domain(domain).range(range),
      },
      theme: CHART_THEME,
      focus: showTooltip ? "group-x" : false,
      focusRing: false,
      maxFocusDistance: Number.POSITIVE_INFINITY,
      margin: { top: 4, right: 2, bottom: 4, left: 2 },
      ...(showTooltip
        ? {
            tooltip: {
              use: tooltip,
              sort: "color-domain" as const,
              offset: 10,
            },
          }
        : {}),
    });
  }, [curve, data.length, rows, seriesMeta, showTooltip, variant, yDomain]);

  if (data.length === 0 || categories.length === 0) {
    return (
      <div
        role="img"
        aria-label={ariaLabel}
        {...stylex.props(palette, styles.sparklineRoot, styles.emptyHeight(height), style)}
      />
    );
  }

  return (
    <div {...stylex.props(palette, styles.sparklineRoot, styles.chartHost, style)}>
      <Chart
        definition={definition}
        height={height}
        initialWidth={200}
        ariaLabel={ariaLabel}
        renderTooltipBody={
          showTooltip
            ? ({ points, primaryPoint }) => {
                const entries: TooltipSeriesEntry[] = [];
                for (const pt of points) {
                  if (pt.datum.value === null) continue;
                  entries.push({
                    id: pt.datum.id,
                    label: pt.datum.label,
                    series: pt.datum.series,
                    value: pt.datum.value,
                  });
                }
                return (
                  <ChartTooltipCard
                    title={index ? (entries[0]?.label ?? "") : ""}
                    entries={entries}
                    primaryId={primaryPoint?.datum.id}
                    colorBySeries={colorBySeries}
                    formatValue={formatValue}
                  />
                );
              }
            : undefined
        }
      />
    </div>
  );
}
Sparkline.displayName = "Sparkline";

// ============= CATEGORY BAR =============

export interface CategoryBarProps extends StyleOverrideProps {
  values: ReadonlyArray<number>;
  labels?: ReadonlyArray<string>;
  colors?: ReadonlyArray<string>;
  markerValue?: number;
  showLabels?: boolean;
  valueFormatter?: (value: number) => string;
  ariaLabel?: string;
}

/**
 * Proportional multi-segment horizontal bar with optional target marker pin
 * and inline summary legend. Built with pure StyleX flex segments.
 */
export function CategoryBar({
  values,
  labels,
  colors,
  markerValue,
  showLabels = true,
  valueFormatter,
  ariaLabel = "Category distribution",
  palette,
  style,
}: CategoryBarProps) {
  const formatValue = valueFormatter ?? defaultValueFormatter;

  const segments = useMemo(() => {
    const safeValues = values.map((v) => (Number.isFinite(v) && v > 0 ? v : 0));
    const total = safeValues.reduce((sum, v) => sum + v, 0);
    return {
      total,
      items: safeValues.map((value, idx) => ({
        value,
        pct: total > 0 ? (value / total) * 100 : 0,
        label: labels?.[idx],
        color: resolveChartColor(colors?.[idx], idx),
      })),
    };
  }, [colors, labels, values]);

  const markerPct =
    markerValue !== undefined && segments.total > 0
      ? Math.min(100, Math.max(0, (markerValue / segments.total) * 100))
      : undefined;

  return (
    <div {...stylex.props(palette, styles.categoryBarRoot, style)}>
      <div
        role="img"
        aria-label={ariaLabel}
        {...stylex.props(styles.categoryBarTrackWrap)}
      >
        <div {...stylex.props(styles.categoryBarTrack)}>
          {segments.items.map((seg, idx) =>
            seg.pct > 0 ? (
              <div
                key={seg.label ?? idx}
                title={
                  seg.label
                    ? `${seg.label}: ${formatValue(seg.value)}`
                    : formatValue(seg.value)
                }
                {...stylex.props(styles.categoryBarSegment(seg.pct, seg.color))}
              />
            ) : null,
          )}
        </div>
        {markerPct !== undefined ? (
          <div
            aria-label={`Target marker: ${formatValue(markerValue!)}`}
            title={formatValue(markerValue!)}
            {...stylex.props(styles.categoryBarMarker(markerPct))}
          />
        ) : null}
      </div>

      {showLabels && segments.items.length > 0 ? (
        <div {...stylex.props(styles.categoryBarLabels)}>
          {segments.items.map((seg, idx) => (
            <div
              key={seg.label ?? idx}
              {...stylex.props(styles.categoryBarLabelItem)}
            >
              <span
                {...stylex.props(styles.swatch, styles.swatchColor(seg.color))}
              />
              {seg.label ? (
                <span {...stylex.props(styles.categoryBarLabelText)}>
                  {seg.label}
                </span>
              ) : null}
              <span {...stylex.props(styles.categoryBarLabelValue)}>
                {formatValue(seg.value)}
              </span>
            </div>
          ))}
        </div>
      ) : null}
    </div>
  );
}
CategoryBar.displayName = "CategoryBar";
```

Credit: Inspired by [Charts](https://saas-ui.dev/docs/charts/overview) from Saas UI
