# Lollipop chart: ChartslibraryUI files for your AI tool

A ranked list drawn as thin stems with a dot at each value, lighter than bars. Free under the MIT license. Source: https://chartslibraryui.com/charts/lollipop-chart

## Instructions for the AI assistant

The person who gave you this file wants this chart in their app or dashboard. They may not be a developer, so do the work for them and explain only what they need to do.

1. Create every file under "Files" at the path shown, with the exact content. Don't rewrite, shorten or "simplify" them: they handle missing data, formatting, dark mode, keyboard navigation and the table view.
2. Import the theme once in the app's root layout or entry file: `import "@/components/charts/core/charts.css";` (change the `@/` alias to match the project, or use a relative path).
3. Render `<LollipopChart />` as in the example below, with the person's real data instead of the sample. Ask for their data if you don't have it.
4. If the project is not React (or React 18+), say so and stop instead of converting the code.
5. If the environment needs everything in a single file (for example a chat artifact or canvas), combine the files into one: keep all the code, drop the local imports between them, and put the CSS in a `<style>` element.

Data rules: an array of row objects plus the keys to read. Use `null` for a missing value, never 0. Percentages are fractions (0.12 = 12%). Use `favorable="down"` for costs, churn and latency. Give the chart a title that states the takeaway and a subtitle with the unit and period. Never add a second y-axis.

## About this chart

**Use for:** Ranking many items with similar values; Scores or rates per team, region or product; Comparing items to a target or the average.

**Avoid when:** Values are parts of a total (use stacked-bar-chart instead); You compare two values per item (use dumbbell-chart instead); Only a few items with very different sizes (use horizontal-bar-chart instead).

**Data it needs:** Rows with a label key and one numeric value key.

```ts
[{ team: "Support", score: 72 }, ...]
```

## Example

`./sample-data` is not included: use the person's data, or a few rows in the shape above if they want a demo first.

```tsx
import { LollipopChart } from "@/components/charts/lollipop-chart";
import { csatByTeam } from "./sample-data";

export function Example() {
  return (
    <LollipopChart
      title="Billing and Onboarding lead on satisfaction; Reporting trails"
      subtitle="Customer satisfaction score by support team, last 90 days, out of 100"
      data={csatByTeam}
      label="team"
      value="score"
      highlight={["Billing", "Onboarding", "Reporting"]}
    />
  );
}
```

## Files

### components/charts/lollipop-chart.tsx

```tsx
"use client";
// lollipop-chart.tsx · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com

import { useMemo, type PointerEvent } from "react";
import { AXIS_FONT, XGrid } from "./core/axis";
import { color as tokens } from "./core/color";
import { readNum, type Issue, type Row } from "./core/data";
import { formatValue, labelFormatter, tickFormatter, type FormatInput } from "./core/format";
import { ChartFrame, ChartTooltip, localPoint, useActiveIndex, type FrameProps } from "./core/frame";
import { bandScale, linearScale, valueDomain } from "./core/scale";
import { textWidth, truncate } from "./core/text";
import { useWords } from "./core/words";

export interface LollipopChartProps extends FrameProps {
  /** Rows to draw, one object per row. See the Data section for the shape. */
  data: Row[];
  /** Key of the item name. */
  label: string;
  /** Key of the value. */
  value: string;
  /** Number format for values: "currency", "percent", "integer", "compact" or a format object. */
  format?: FormatInput;
  /** Sort rows by value. Default "desc". */
  sort?: "none" | "asc" | "desc";
  /** Item names to draw in colour; the rest are grey. Default: all in colour. */
  highlight?: string | string[];
  /** Draw a reference line at this value, e.g. a target or the average. */
  reference?: { value: number; label: string };
  /** Print the value at the end of each stem. Default true. */
  showValues?: boolean;
}

type Item = { name: string; value: number };

/**
 * A ranked list drawn as thin stems with a dot at the value. Lighter than bars when many items have similar
 * values, so the eye goes to the ends, not the ink.
 */
export function LollipopChart({ data, label, value, format, sort = "desc", highlight, reference, showValues = true, height: hProp, ...frame }: LollipopChartProps) {
  const { items, issues } = useMemo(() => {
    const issues: Issue[] = [];
    if (!Array.isArray(data) || !data.length) return { items: [] as Item[], issues: [{ level: "error", message: "No data to display." }] as Issue[] };
    let items: Item[] = [];
    let skipped = 0;
    for (const r of data) {
      const n = readNum(r?.[value]);
      if (n.state === "invalid") issues.push({ level: "error", message: `"${r?.[label]}" has a non-numeric value.` });
      else if (n.value === null) skipped++;
      else items.push({ name: String(r?.[label] ?? ""), value: n.value });
    }
    if (skipped) issues.push({ level: "note", message: `${skipped} item(s) without a value are not drawn.` });
    if (sort !== "none") items = [...items].sort((a, b) => (sort === "desc" ? b.value - a.value : a.value - b.value));
    return { items, issues };
  }, [data, label, value, sort]);
  const hl = highlight ? new Set(Array.isArray(highlight) ? highlight : [highlight]) : null;
  const height = hProp ?? Math.max(120, items.length * 30 + 30);
  const f = (v: unknown) => formatValue(v as number, format, { context: "table" });
  const table = { columns: [{ key: "name", label }, { key: "value", label: value, align: "right" as const, format: f }], rows: items };
  const summary = `Lollipop chart of ${items.length} items. ${items.map((i) => `${i.name} ${formatValue(i.value, format)}`).join("; ")}.`;
  return (
    <ChartFrame {...frame} height={height} issues={issues} table={table} summary={summary}>
      {({ width }) => <Inner {...{ width, height, items, format, hl, reference, showValues }} />}
    </ChartFrame>
  );
}

function Inner(p: { width: number; height: number; items: Item[]; format?: FormatInput; hl: Set<string> | null; reference?: { value: number; label: string }; showValues: boolean }) {
  const L = useWords();
  const { width, height, items } = p;
  const { active, setActive, keyProps } = useActiveIndex(items.length, { describe: (i) => ({ label: String(items[i].name) }) });
  const labelW = Math.min(Math.max(...items.map((i) => textWidth(i.name, AXIS_FONT)), 20) + 18, width * 0.32);
  const lf = labelFormatter(p.format, items.map((i) => i.value));
  const valueW = p.showValues ? Math.max(...items.map((i) => textWidth(lf(i.value), AXIS_FONT)), 0) + 10 : 8;
  const top = 4;
  const bottom = height - 22;
  const values = items.map((i) => i.value).concat(p.reference ? [p.reference.value] : []);
  const { domain, ticks } = valueDomain(values, { includeZero: true, ticks: Math.max(3, Math.floor((width - labelW - valueW) / 90)) });
  const ft = tickFormatter(p.format, ticks);
  const sx = linearScale(domain, [labelW, width - valueW]);
  const band = bandScale(items.length, [top, bottom], { paddingInner: 0, paddingOuter: 0 });
  const onMove = (e: PointerEvent<SVGRectElement>) => setActive(band.indexAt(localPoint(e).y + top));
  return (
    <>
      <svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Lollipop chart. Use arrow keys to read items." {...keyProps}>
        <XGrid ticks={ticks} x={sx} y0={top} y1={bottom} format={ft} labelY={bottom + 16} />
        {p.reference && (
          <g aria-hidden>
            <line x1={sx(p.reference.value)} x2={sx(p.reference.value)} y1={top} y2={bottom} style={{ stroke: "var(--clui-ink-2)" }} strokeDasharray="3 3" />
            <text x={sx(p.reference.value) + 4} y={top + 9} className="clui-label" style={{ fill: "var(--clui-ink-2)" }}>
              {p.reference.label}
            </text>
          </g>
        )}
        {items.map((it, i) => {
          const cy = band(i) + band.bandwidth / 2;
          const on = !p.hl || p.hl.has(it.name);
          const fill = on ? tokens.series(0) : tokens.context;
          return (
            <g key={i} className={`clui-mark${active !== null && active !== i ? " clui-dim" : ""}`}>
              <text x={labelW - 10} y={cy} dy="0.32em" textAnchor="end" className="clui-tick" style={{ fill: "var(--clui-ink)" }}>
                {truncate(it.name, labelW - 10, AXIS_FONT)}
              </text>
              <line x1={sx(0)} x2={sx(it.value)} y1={cy} y2={cy} style={{ stroke: fill }} strokeWidth={2} />
              <circle cx={sx(it.value)} cy={cy} r={5} style={{ fill, stroke: "var(--clui-surface)" }} strokeWidth={2} />
              {p.showValues && (
                <text x={sx(it.value) + (it.value < 0 ? -9 : 9)} y={cy} dy="0.32em" textAnchor={it.value < 0 ? "end" : "start"} className="clui-label">
                  {lf(it.value)}
                </text>
              )}
            </g>
          );
        })}
        <rect x={0} y={top} width={width} height={Math.max(0, bottom - top)} fill="transparent" onPointerMove={onMove} onPointerLeave={() => setActive(null)} />
      </svg>
      {active !== null && items[active] && (
        <ChartTooltip
          x={sx(items[active].value)}
          y={band(active) + band.bandwidth / 2}
          width={width}
          height={height}
          data={{
            title: items[active].name,
            rows: [
              { label: L.value, value: formatValue(items[active].value, p.format, { context: "tooltip" }), color: tokens.series(0), shape: "dot", strong: true },
              { label: L.rank, value: `${active + 1} ${L.of} ${items.length}` },
            ],
          }}
        />
      )}
    </>
  );
}
```

### components/charts/core/axis.tsx

```tsx
// core/axis.tsx · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com
"use client";

import type { ReactNode, SVGProps } from "react";
import { textWidth, thinLabels, truncate } from "./text";

export const AXIS_FONT = 11;
export const LABEL_FONT = 11;

/** Width needed for a column of y-axis labels. */
export function axisWidth(labels: string[], fontSize = AXIS_FONT, pad = 8) {
  return Math.ceil(Math.max(0, ...labels.map((l) => textWidth(l, fontSize)))) + pad;
}

/** Horizontal hairline gridlines with labels on the left. The zero line is drawn stronger. */
export function YGrid({
  ticks,
  y,
  x0,
  x1,
  format,
  labels = true,
}: {
  ticks: number[];
  y: (v: number) => number;
  x0: number;
  x1: number;
  format: (v: number) => string;
  labels?: boolean;
}) {
  return (
    <g className="clui-axis" aria-hidden>
      {ticks.map((t) => {
        const py = Math.round(y(t)) + 0.5;
        return (
          <g key={t}>
            <line
              x1={x0}
              x2={x1}
              y1={py}
              y2={py}
              style={{ stroke: t === 0 ? "var(--clui-axis)" : "var(--clui-grid)" }}
              shapeRendering="crispEdges"
            />
            {labels && (
              <text x={x0 - 8} y={py} dy="0.32em" textAnchor="end" className="clui-tick">
                {format(t)}
              </text>
            )}
          </g>
        );
      })}
    </g>
  );
}

/** Vertical hairline gridlines with labels underneath (horizontal bar charts, scatter x axis). */
export function XGrid({
  ticks,
  x,
  y0,
  y1,
  format,
  labels = true,
  labelY,
}: {
  ticks: number[];
  x: (v: number) => number;
  y0: number;
  y1: number;
  format: (v: number) => string;
  labels?: boolean;
  labelY?: number;
}) {
  const positions = ticks.map((t) => x(t));
  const texts = ticks.map((t) => format(t));
  const keep = thinLabels(positions, texts, AXIS_FONT, 8);
  return (
    <g className="clui-axis" aria-hidden>
      {ticks.map((t, i) => {
        const px = Math.round(positions[i]) + 0.5;
        return (
          <g key={t}>
            <line
              x1={px}
              x2={px}
              y1={y0}
              y2={y1}
              style={{ stroke: t === 0 ? "var(--clui-axis)" : "var(--clui-grid)" }}
              shapeRendering="crispEdges"
            />
            {labels && keep[i] && (
              <text x={px} y={labelY ?? y1 + 16} textAnchor="middle" className="clui-tick">
                {texts[i]}
              </text>
            )}
          </g>
        );
      })}
    </g>
  );
}

/**
 * Category or date labels along the bottom. Labels are thinned so they never overlap; hidden labels stay
 * available in the tooltip and the table.
 */
export function XLabels({
  positions,
  labels,
  y,
  maxLabelWidth = 120,
  anchorEnds = false,
  x0,
  x1,
  ticks = false,
  tickTop,
}: {
  positions: number[];
  labels: string[];
  y: number;
  maxLabelWidth?: number;
  /** Align first/last label to the plot edges so they don't overflow. */
  anchorEnds?: boolean;
  x0?: number;
  x1?: number;
  ticks?: boolean;
  tickTop?: number;
}) {
  const shown = labels.map((l) => truncate(l, maxLabelWidth, AXIS_FONT));
  const widths = shown.map((l) => textWidth(l, AXIS_FONT));
  // Where a label would overflow the plot edge, anchor it to the edge; thin using the shifted centres.
  const anchors = positions.map((px, i): "start" | "middle" | "end" => {
    if (anchorEnds && x0 !== undefined && px - widths[i] / 2 < x0) return "start";
    if (anchorEnds && x1 !== undefined && px + widths[i] / 2 > x1) return "end";
    return "middle";
  });
  const textX = positions.map((px, i) =>
    anchors[i] === "start" ? Math.max(px - 4, x0 ?? px) : anchors[i] === "end" ? Math.min(px + 4, x1 ?? px) : px,
  );
  const centres = textX.map((tx, i) =>
    anchors[i] === "start" ? tx + widths[i] / 2 : anchors[i] === "end" ? tx - widths[i] / 2 : tx,
  );
  const keep = thinLabels(centres, shown, AXIS_FONT, 12);
  return (
    <g className="clui-axis" aria-hidden>
      {positions.map((px, i) => {
        if (!keep[i]) return null;
        const anchor = anchors[i];
        const tx = textX[i];
        return (
          <g key={i}>
            {ticks && tickTop !== undefined && (
              <line x1={px} x2={px} y1={tickTop} y2={tickTop + 4} style={{ stroke: "var(--clui-axis)" }} />
            )}
            <text x={tx} y={y} textAnchor={anchor} className="clui-tick">
              {shown[i]}
              {shown[i] !== labels[i] && <title>{labels[i]}</title>}
            </text>
          </g>
        );
      })}
    </g>
  );
}

/** Shaded region marking forecast or partial periods, with a label at the top. */
export function PeriodShade({
  x0,
  x1,
  top,
  bottom,
  label,
  kind = "forecast",
}: {
  x0: number;
  x1: number;
  top: number;
  bottom: number;
  label?: string;
  kind?: "forecast" | "partial";
}) {
  if (x1 <= x0) return null;
  return (
    <g aria-hidden>
      <rect
        x={x0}
        y={top}
        width={x1 - x0}
        height={bottom - top}
        style={{ fill: kind === "forecast" ? "var(--clui-forecast-bg)" : "var(--clui-partial-bg)" }}
      />
      <line x1={x0} x2={x0} y1={top} y2={bottom} style={{ stroke: "var(--clui-axis)" }} strokeDasharray="2 3" />
      {label && (
        <text x={x0 + 6} y={top + 12} className="clui-annot">
          {label}
        </text>
      )}
    </g>
  );
}

/** A labelled horizontal reference line (target, average, threshold). */
export function RefLine({
  y,
  x0,
  x1,
  label,
  align = "end",
}: {
  y: number;
  x0: number;
  x1: number;
  label?: ReactNode;
  align?: "start" | "end";
}) {
  return (
    <g aria-hidden>
      <line x1={x0} x2={x1} y1={y} y2={y} style={{ stroke: "var(--clui-ink-2)" }} strokeDasharray="4 3" />
      {label && (
        <text
          x={align === "end" ? x1 : x0}
          y={y - 5}
          textAnchor={align === "end" ? "end" : "start"}
          className="clui-annot clui-halo"
        >
          {label}
        </text>
      )}
    </g>
  );
}

/** Text with a surface-coloured halo so it stays readable over marks. */
export function HaloText(props: SVGProps<SVGTextElement>) {
  return <text {...props} className={["clui-halo", props.className].filter(Boolean).join(" ")} />;
}

/**
 * Place end labels for lines without overlap. Returns adjusted y positions (sorted greedy spacing). If the labels
 * would need to move more than `maxShift`, returns null: fall back to the legend instead.
 */
export function placeEndLabels(ys: number[], minGap = 14, top = 0, bottom = Infinity, maxShift = 28): number[] | null {
  const order = ys.map((y, i) => ({ y, i })).sort((a, b) => a.y - b.y);
  const placed = order.map((o) => o.y);
  for (let k = 1; k < placed.length; k++) if (placed[k] - placed[k - 1] < minGap) placed[k] = placed[k - 1] + minGap;
  const overflow = placed[placed.length - 1] - bottom;
  if (overflow > 0) for (let k = 0; k < placed.length; k++) placed[k] -= overflow;
  for (let k = 0; k < placed.length; k++) placed[k] = Math.max(top, placed[k]);
  for (let k = 1; k < placed.length; k++) if (placed[k] - placed[k - 1] < minGap) placed[k] = placed[k - 1] + minGap;
  const out = new Array<number>(ys.length);
  let worst = 0;
  order.forEach((o, k) => {
    out[o.i] = placed[k];
    worst = Math.max(worst, Math.abs(placed[k] - o.y));
  });
  return worst > maxShift ? null : out;
}
```

### components/charts/core/bars.tsx

```tsx
// core/bars.tsx · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com
"use client";

/**
 * Shared engine for bar and column charts: single, grouped, stacked and 100% stacked, vertical or horizontal.
 * Bars always start at zero. Bars are at most 24px thick, with a rounded data end and a square baseline.
 */

import { useMemo, type PointerEvent } from "react";
import { AXIS_FONT, RefLine, XGrid, XLabels, YGrid, axisWidth } from "./axis";
import { PALETTE_SIZE, seriesColors, toneColor, toneOf, type Favorable } from "./color";
import { checkRows, column, type Issue, type Row } from "./data";
import { formatValue, labelFormatter, tickFormatter, type FormatInput } from "./format";
import {
  ChartFrame,
  ChartTooltip,
  localPoint,
  useActiveIndex,
  useSeriesToggle,
  type FrameProps,
  type LegendItem,
  type TooltipRow,
} from "./frame";
import { barPath } from "./path";
import { bandScale, linearScale, valueDomain } from "./scale";
import { textWidth, truncate } from "./text";
import { normalizeSeries, type Reference, type SeriesInput } from "./series";
import type { ChartWords } from "./words";
import { useWords } from "./words";

export interface BarChartBaseProps extends FrameProps {
  data: Row[];
  /** Key of the category label in each row. */
  x: string;
  series: SeriesInput[];
  format?: FormatInput;
  /** Category values to emphasise (single series). Others are grey. */
  highlight?: string | string[];
  /** Sort categories by value (single series) or total (stacked). */
  sort?: "none" | "asc" | "desc";
  /** Value labels at bar ends. "auto" shows them when they fit. */
  labels?: boolean | "auto";
  /** First category that is an incomplete period; drawn lighter and marked. */
  partialFrom?: string;
  /** Categories that are forecasts; drawn hollow and marked. */
  forecastFrom?: string;
  references?: Reference[];
  /** Colour bars by sign using `favorable` (diverging bars). */
  colorBySign?: boolean;
  favorable?: Favorable;
  /** Show the legend. Default: on for 2+ series. */
  legend?: boolean;
  /** Max bar thickness in px. */
  maxBarSize?: number;
}

export type BarLayout = "single" | "grouped" | "stacked" | "stacked100";

const GAP = 2;

export function BarsChart(
  props: BarChartBaseProps & { layout: BarLayout; orientation: "vertical" | "horizontal"; summaryName?: string },
) {
  const L = useWords(props.words);
  const {
    data,
    x,
    series: seriesInput,
    format,
    highlight,
    sort = "none",
    labels = "auto",
    partialFrom,
    forecastFrom,
    references = [],
    colorBySign = false,
    favorable = "up",
    legend,
    maxBarSize = 24,
    layout,
    orientation,
    summaryName,
    height: heightProp,
    ...frame
  } = props;
  const series = useMemo(() => normalizeSeries(seriesInput), [seriesInput]);
  const keys = series.map((s) => s.key);
  const toggle = useSeriesToggle(keys);
  const visible = series.filter((s) => !toggle.hidden.has(s.key));
  const stacked = layout === "stacked" || layout === "stacked100";

  const keySig = keys.join("|");
  const prep = useMemo(() => {
    const issues: Issue[] = checkRows(data, { xKey: x, valueKeys: keys, maxSeries: PALETTE_SIZE, allowMissing: false });
    let rows = Array.isArray(data) ? [...data] : [];
    if (layout === "stacked100") {
      const neg = rows.some((r) => keys.some((k) => typeof r?.[k] === "number" && (r[k] as number) < 0));
      if (neg)
        issues.push({ level: "error", message: "100% stacked bars can't show negative values. Use stacked or grouped bars." });
    }
    if (sort !== "none") {
      const val = (r: Row) => keys.reduce((a, k) => a + (typeof r?.[k] === "number" ? (r[k] as number) : 0), 0);
      rows = rows.sort((a, b) => (sort === "asc" ? val(a) - val(b) : val(b) - val(a)));
    }
    const cols = Object.fromEntries(keys.map((k) => [k, column(rows, k).values]));
    return { issues, rows, cols };
  }, [data, x, keySig, sort, layout]); // eslint-disable-line react-hooks/exhaustive-deps
  const { issues, rows, cols } = prep;
  const n = rows.length;
  const cats = rows.map((r) => String(r?.[x] ?? ""));

  const horizontal = orientation === "horizontal";
  const rowSize = layout === "grouped" ? Math.min(maxBarSize, 20) * visible.length + 14 : Math.min(maxBarSize, 22) + 12;
  const height = heightProp ?? (horizontal ? Math.max(120, n * rowSize + 30) : 280);

  const colors = seriesColors(series);
  const hl = highlight === undefined ? null : new Set(Array.isArray(highlight) ? highlight : [highlight]);

  const partialIndex = partialFrom !== undefined ? cats.indexOf(String(partialFrom)) : -1;
  const forecastIndex = forecastFrom !== undefined ? cats.indexOf(String(forecastFrom)) : -1;

  // per category segments
  const visibleSig = visible.map((s) => s.key).join("|");
  const segs = useMemo(() => {
    return rows.map((_, i) => {
      const total = visible.reduce((a, s) => a + Math.max(0, cols[s.key][i] ?? 0), 0);
      let pos = 0;
      let neg = 0;
      return visible.map((s, j) => {
        let v = cols[s.key][i];
        if (v === null) return { key: s.key, j, v: null as number | null, a: 0, b: 0, raw: null as number | null };
        const raw = v;
        if (layout === "stacked100") v = total === 0 ? 0 : v / total;
        if (!stacked) return { key: s.key, j, v, a: 0, b: v, raw };
        if (v >= 0) {
          const a = pos;
          pos += v;
          return { key: s.key, j, v, a, b: pos, raw };
        }
        const a = neg;
        neg += v;
        return { key: s.key, j, v, a, b: neg, raw };
      });
    });
  }, [rows, cols, visibleSig, layout]); // eslint-disable-line react-hooks/exhaustive-deps

  const values: number[] = [];
  for (const cat of segs) for (const s of cat) if (s.v !== null) values.push(s.a, s.b);
  for (const r of references) values.push(r.value);

  const legendItems: LegendItem[] =
    legend === false || (legend === undefined && series.length < 2)
      ? []
      : series.map((s) => ({ key: s.key, label: s.label!, color: colors[s.key], shape: "square" }));
  if (colorBySign && legend !== false && series.length === 1) {
    legendItems.push(
      { key: "__good", label: favorable === "down" ? "Decrease (favorable)" : "Increase (favorable)", color: "var(--clui-good)" },
      { key: "__bad", label: favorable === "down" ? "Increase (unfavorable)" : "Decrease (unfavorable)", color: "var(--clui-bad)" },
    );
  }

  const fmtTable = (v: unknown) => formatValue(v as number, format, { context: "table" });
  const table = {
    columns: [
      { key: "__x", label: x },
      ...series.map((s) => ({ key: s.key, label: s.label!, align: "right" as const, format: fmtTable })),
      ...(stacked && series.length > 1 ? [{ key: "__total", label: L.total, align: "right" as const, format: fmtTable }] : []),
    ],
    rows: rows.map((r, i) => ({
      __x: cats[i],
      ...Object.fromEntries(series.map((s) => [s.key, cols[s.key][i]])),
      __total: series.reduce((a, s) => a + (cols[s.key][i] ?? 0), 0),
    })),
  };

  const summary = (() => {
    if (!n) return "Bar chart with no data.";
    const s0 = series[0];
    const vals = cols[s0?.key] ?? [];
    let maxI = 0;
    let minI = 0;
    vals.forEach((v, i) => {
      if ((v ?? -Infinity) > (vals[maxI] ?? -Infinity)) maxI = i;
      if ((v ?? Infinity) < (vals[minI] ?? Infinity)) minI = i;
    });
    return `${summaryName ?? "Bar chart"} of ${series.map((s) => s.label).join(", ")} across ${n} categories. ${
      s0?.label
    } is highest for ${cats[maxI]} (${formatValue(vals[maxI], format)}) and lowest for ${cats[minI]} (${formatValue(
      vals[minI],
      format,
    )}). Use arrow keys to read values.`;
  })();

  return (
    <ChartFrame
      {...frame}
      height={height}
      issues={issues}
      table={table}
      summary={summary}
      legend={legendItems}
      legendHidden={toggle.hidden}
      onLegendToggle={series.length > 1 ? toggle.toggle : undefined}
      onLegendHover={(k) => toggle.setFocus(k && !k.startsWith("__") ? k : null)}
    >
      {({ width }) => {
        const p = {
          width,
          height,
          n,
          cats,
          rows,
          segs,
          values,
          visible,
          colors,
          hl,
          layout,
          stacked,
          format,
          labels,
          partialIndex,
          forecastIndex,
          references,
          colorBySign,
          favorable,
          maxBarSize,
          focus: toggle.focus,
          rawCols: cols,
        };
        return horizontal ? <HorizontalPlot {...p} /> : <VerticalPlot {...p} />;
      }}
    </ChartFrame>
  );
}

type Seg = { key: string; j: number; v: number | null; a: number; b: number; raw: number | null };

interface PlotP {
  width: number;
  height: number;
  n: number;
  cats: string[];
  rows: Row[];
  segs: Seg[][];
  values: number[];
  visible: { key: string; label?: string }[];
  colors: Record<string, string>;
  hl: Set<string> | null;
  layout: BarLayout;
  stacked: boolean;
  format?: FormatInput;
  labels: boolean | "auto";
  partialIndex: number;
  forecastIndex: number;
  references: Reference[];
  colorBySign: boolean;
  favorable: Favorable;
  maxBarSize: number;
  focus: string | null;
  rawCols: Record<string, (number | null)[]>;
}

function fillFor(p: PlotP, seg: Seg, cat: string) {
  if (p.colorBySign) return toneColor(toneOf(seg.raw, p.favorable));
  if (p.hl && p.visible.length === 1) return p.hl.has(cat) ? p.colors[seg.key] : "var(--clui-context)";
  return p.colors[seg.key];
}

function tooltipFor(p: PlotP, i: number, L: ChartWords) {
  const rows: TooltipRow[] = p.segs[i].map((s) => ({
    label: p.visible[s.j].label ?? s.key,
    value: formatValue(s.raw, p.format, { context: "tooltip" }),
    note:
      p.layout === "stacked100" && s.v !== null ? `(${formatValue(s.v, { kind: "percent", decimals: 0 })})` : undefined,
    color: fillFor(p, s, p.cats[i]),
    shape: "square",
  }));
  if (p.stacked && p.visible.length > 1) {
    rows.reverse();
    rows.push({
      label: L.total,
      value: formatValue(
        p.segs[i].reduce((a, s) => a + (s.raw ?? 0), 0),
        p.format,
        { context: "tooltip" },
      ),
      strong: true,
    });
  }
  const tags = [
    p.partialIndex >= 0 && i >= p.partialIndex ? "Partial period" : null,
    p.forecastIndex >= 0 && i >= p.forecastIndex ? L.forecast : null,
  ].filter(Boolean);
  return { title: p.cats[i], rows, footer: tags.length ? tags.join(" · ") : undefined };
}

/** One label formatter per plot so every bar label shares a magnitude. */
function labelFmt(p: PlotP) {
  return labelFormatter(p.format, p.segs.map((cat) => cat.reduce((a, s) => a + (s.raw ?? 0), 0)));
}

function markStyle(p: PlotP, i: number, fill: string) {
  const forecast = p.forecastIndex >= 0 && i >= p.forecastIndex;
  const partial = p.partialIndex >= 0 && i >= p.partialIndex;
  if (forecast) return { fill: "transparent", stroke: fill, strokeWidth: 1.5, strokeDasharray: "3 2" };
  if (partial) return { fill, opacity: 0.45 };
  return { fill };
}

function VerticalPlot(p: PlotP) {
  const L = useWords();
  const fmtLabel = labelFmt(p);
  const { width, height, n, cats } = p;
  const { active, setActive, keyProps } = useActiveIndex(n, { describe: (i) => ({ label: cats[i], row: p.rows[i] }) });
  const tickCount = Math.max(2, Math.min(6, Math.floor(height / 50)));
  const { domain, ticks } = valueDomain(p.values, {
    includeZero: true,
    ticks: tickCount,
    domain: p.layout === "stacked100" ? [0, 1] : undefined,
  });
  const yFmt = p.layout === "stacked100" ? { kind: "percent" as const, decimals: 0 } : p.format;
  const fmtTick = tickFormatter(yFmt, ticks);
  const left = axisWidth(ticks.map(fmtTick));
  const right = width - 8;
  const hasMarkerRow = p.partialIndex >= 0 || p.forecastIndex >= 0;
  const top = hasMarkerRow ? 22 : 16;
  const bottom = height - 24;
  const y = linearScale(domain, [bottom, top]);
  const band = bandScale(n, [left, right], { paddingInner: 0.3, paddingOuter: 0.15 });
  const groups = p.layout === "grouped" ? p.visible.length : 1;
  const groupW = Math.min(band.bandwidth, p.maxBarSize * groups + GAP * (groups - 1));
  const barW = Math.max(1, (groupW - GAP * (groups - 1)) / groups);
  const zeroY = y(0);

  const mixedSigns = p.stacked && p.segs.some((cat) => cat.some((s) => (s.v ?? 0) < 0) && cat.some((s) => (s.v ?? 0) > 0));
  const labelFits =
    p.labels === true ||
    (p.labels === "auto" &&
      p.layout !== "grouped" &&
      p.layout !== "stacked100" &&
      !mixedSigns &&
      n <= 16 &&
      cats.every((_, i) => {
        const total = p.segs[i].reduce((a, s) => a + (s.raw ?? 0), 0);
        return textWidth(fmtLabel(total), 10.5) <= band.step - 4;
      }));

  const onMove = (e: PointerEvent<SVGRectElement>) => setActive(band.indexAt(localPoint(e).x + left));

  return (
    <>
      <svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Bar chart. Use arrow keys to read values." {...keyProps}>
        <YGrid ticks={ticks} y={y} x0={left} x1={right} format={fmtTick} />
        <XLabels
          positions={cats.map((_, i) => band(i) + band.bandwidth / 2)}
          labels={cats}
          y={bottom + 17}
          maxLabelWidth={Math.max(40, band.step * 3)}
          anchorEnds
          x0={left - 8}
          x1={width}
        />
        {hasMarkerRow &&
          (() => {
            const mi = Math.min(...[p.partialIndex, p.forecastIndex].filter((v) => v >= 0));
            return (
              <text x={right} y={11} textAnchor="end" className="clui-annot">
                {mi === p.forecastIndex ? "Forecast (outlined)" : "Partial period (faded)"}
              </text>
            );
          })()}
        {active !== null && (
          <rect x={band(active) - (band.step - band.bandwidth) / 2} y={top} width={band.step} height={bottom - top} style={{ fill: "var(--clui-grid)", opacity: 0.6 }} />
        )}
        {p.segs.map((cat, i) => {
          const cx = band(i) + (band.bandwidth - groupW) / 2;
          const outer = (s: Seg) => {
            if (!p.stacked) return true;
            const sameSide = cat.filter((o) => o.v !== null && o.v !== 0 && Math.sign(o.v) === Math.sign(s.v ?? 0));
            return sameSide[sameSide.length - 1] === s;
          };
          return (
            <g key={i}>
              {cat.map((s) => {
                if (s.v === null || s.a === s.b) return null;
                const bx = p.layout === "grouped" ? cx + s.j * (barW + GAP) : cx;
                const w = p.layout === "grouped" ? barW : groupW;
                const ya = y(s.a);
                const yb = y(s.b);
                const up = s.b > s.a || (s.b === s.a && s.v >= 0);
                const isOuter = outer(s);
                // 2px surface gap between stacked segments
                const gapA = p.stacked && s.a !== 0 ? GAP / 2 : 0;
                const gapB = p.stacked && !isOuter ? GAP / 2 : 0;
                let y0 = Math.min(ya, yb);
                let h = Math.abs(yb - ya);
                if (up) {
                  y0 += gapB;
                  h -= gapA + gapB;
                } else {
                  y0 += gapA;
                  h -= gapA + gapB;
                }
                h = Math.max(h, s.v !== 0 ? 1 : 0);
                const fill = fillFor(p, s, cats[i]);
                const style = markStyle(p, i, fill);
                const d = isOuter ? barPath(bx, y0, w, h, 4, up ? "up" : "down") : `M${bx},${y0}h${w}v${h}h${-w}Z`;
                const dim = p.focus !== null && p.focus !== s.key;
                return <path key={s.key} d={d} style={style} className={`clui-mark${dim ? " clui-dim" : ""}`} />;
              })}
              {labelFits &&
                (() => {
                  const total = cat.reduce((a, s) => a + (s.raw ?? 0), 0);
                  if (cat.every((s) => s.v === null)) return null;
                  const end = p.stacked ? (total >= 0 ? Math.max(0, ...cat.map((s) => s.b)) : Math.min(0, ...cat.map((s) => s.b))) : total;
                  const ly = total >= 0 ? y(end) - 5 : y(end) + 13;
                  return (
                    <text x={band(i) + band.bandwidth / 2} y={ly} textAnchor="middle" className="clui-label">
                      {fmtLabel(total)}
                    </text>
                  );
                })()}
            </g>
          );
        })}
        <line x1={left} x2={right} y1={Math.round(zeroY) + 0.5} y2={Math.round(zeroY) + 0.5} style={{ stroke: "var(--clui-axis)" }} />
        {p.references.map((r, i) => (
          <RefLine key={i} y={y(r.value)} x0={left} x1={right} label={r.label} />
        ))}
        <rect
          x={left}
          y={0}
          width={Math.max(0, right - left)}
          height={bottom}
          fill="transparent"
          onPointerMove={onMove}
          onPointerDown={onMove}
          onPointerLeave={() => setActive(null)}
        />
      </svg>
      {active !== null && (
        <ChartTooltip
          x={band(active) + band.bandwidth / 2}
          y={y(Math.max(0, ...p.segs[active].map((s) => s.b)))}
          width={width}
          height={height}
          data={tooltipFor(p, active, L)}
        />
      )}
    </>
  );
}

function HorizontalPlot(p: PlotP) {
  const L = useWords();
  const fmtLabel = labelFmt(p);
  const { width, height, n, cats } = p;
  const { active, setActive, keyProps } = useActiveIndex(n, { describe: (i) => ({ label: cats[i], row: p.rows[i] }) });
  const labelCol = Math.min(Math.max(...cats.map((c) => textWidth(c, AXIS_FONT)), 20) + 12, Math.max(80, width * 0.38));
  const left = labelCol;
  const hasNeg = p.values.some((v) => v < 0);
  const showAxis = p.labels === false || p.layout === "grouped" || p.layout === "stacked100";
  const labelRoom = showAxis ? 10 : 56;
  const right = width - labelRoom;
  const top = 4;
  const bottom = showAxis ? height - 22 : height - 4;
  const tickCount = Math.max(2, Math.min(6, Math.floor((right - left) / 90)));
  const { domain, ticks } = valueDomain(p.values, {
    includeZero: true,
    ticks: tickCount,
    domain: p.layout === "stacked100" ? [0, 1] : undefined,
  });
  const xFmt = p.layout === "stacked100" ? { kind: "percent" as const, decimals: 0 } : p.format;
  const fmtTick = tickFormatter(xFmt, ticks);
  // with negative values, leave room for labels on the left of negative bars
  const negRoom = hasNeg && !showAxis ? 52 : 0;
  const xs = linearScale(domain, [left + negRoom, right]);
  const band = bandScale(n, [top, bottom], { paddingInner: 0.3, paddingOuter: 0.1 });
  const groups = p.layout === "grouped" ? p.visible.length : 1;
  const groupH = Math.min(band.bandwidth, p.maxBarSize * groups + GAP * (groups - 1));
  const barH = Math.max(1, (groupH - GAP * (groups - 1)) / groups);
  const zeroX = xs(0);
  const onMove = (e: PointerEvent<SVGRectElement>) => setActive(band.indexAt(localPoint(e).y));

  return (
    <>
      <svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Bar chart. Use arrow keys to read values." {...keyProps}>
        {showAxis && <XGrid ticks={ticks} x={xs} y0={top} y1={bottom} format={fmtTick} />}
        {active !== null && (
          <rect x={0} y={band(active) - (band.step - band.bandwidth) / 2} width={width} height={band.step} style={{ fill: "var(--clui-grid)", opacity: 0.6 }} />
        )}
        {cats.map((c, i) => (
          <text key={i} x={left - 10} y={band(i) + band.bandwidth / 2} dy="0.32em" textAnchor="end" className="clui-tick" style={{ fill: "var(--clui-ink)" }}>
            {truncate(c, left - 14, AXIS_FONT)}
            <title>{c}</title>
          </text>
        ))}
        {p.segs.map((cat, i) => {
          const cy = band(i) + (band.bandwidth - groupH) / 2;
          const outer = (s: Seg) => {
            if (!p.stacked) return true;
            const same = cat.filter((o) => o.v !== null && o.v !== 0 && Math.sign(o.v) === Math.sign(s.v ?? 0));
            return same[same.length - 1] === s;
          };
          const total = cat.reduce((a, s) => a + (s.raw ?? 0), 0);
          const endVal = p.stacked ? (total >= 0 ? Math.max(0, ...cat.map((s) => s.b)) : Math.min(0, ...cat.map((s) => s.b))) : total;
          return (
            <g key={i}>
              {cat.map((s) => {
                if (s.v === null || s.a === s.b) return null;
                const by = p.layout === "grouped" ? cy + s.j * (barH + GAP) : cy;
                const h = p.layout === "grouped" ? barH : groupH;
                const xa = xs(s.a);
                const xb = xs(s.b);
                const rightward = s.b >= s.a;
                const isOuter = outer(s);
                const gapA = p.stacked && s.a !== 0 ? GAP / 2 : 0;
                const gapB = p.stacked && !isOuter ? GAP / 2 : 0;
                let x0 = Math.min(xa, xb);
                let w = Math.abs(xb - xa);
                if (rightward) {
                  x0 += gapA;
                  w -= gapA + gapB;
                } else {
                  x0 += gapB;
                  w -= gapA + gapB;
                }
                w = Math.max(w, 1);
                const fill = fillFor(p, s, cats[i]);
                const d = isOuter ? barPath(x0, by, w, h, 4, rightward ? "right" : "left") : `M${x0},${by}h${w}v${h}h${-w}Z`;
                const dim = p.focus !== null && p.focus !== s.key;
                return <path key={s.key} d={d} style={markStyle(p, i, fill)} className={`clui-mark${dim ? " clui-dim" : ""}`} />;
              })}
              {!showAxis && cat.some((s) => s.v !== null) && (
                <text
                  x={endVal >= 0 ? xs(endVal) + 6 : xs(endVal) - 6}
                  y={band(i) + band.bandwidth / 2}
                  dy="0.32em"
                  textAnchor={endVal >= 0 ? "start" : "end"}
                  className="clui-label"
                >
                  {fmtLabel(total)}
                </text>
              )}
            </g>
          );
        })}
        <line x1={Math.round(zeroX) + 0.5} x2={Math.round(zeroX) + 0.5} y1={top} y2={bottom} style={{ stroke: "var(--clui-axis)" }} />
        {p.references.map((r, i) => (
          <g key={i} aria-hidden>
            <line x1={xs(r.value)} x2={xs(r.value)} y1={top} y2={bottom} style={{ stroke: "var(--clui-ink-2)" }} strokeDasharray="4 3" />
            {r.label && (
              <text x={xs(r.value) + 4} y={bottom - 4} className="clui-annot clui-halo">
                {r.label}
              </text>
            )}
          </g>
        ))}
        <rect x={0} y={top} width={width} height={bottom - top} fill="transparent" onPointerMove={onMove} onPointerDown={onMove} onPointerLeave={() => setActive(null)} />
      </svg>
      {active !== null && (
        <ChartTooltip
          x={Math.min(right, xs(Math.max(0, ...p.segs[active].map((s) => s.b))))}
          y={band(active) + band.bandwidth / 2}
          width={width}
          height={height}
          data={tooltipFor(p, active, L)}
        />
      )}
    </>
  );
}
```

### components/charts/core/charts.css

```css
/* ChartslibraryUI 1.1.0 · MIT License */
/*
 * ChartslibraryUI chart theme. Import once, e.g. in your root layout:
 *   import "@/components/charts/core/charts.css";
 *
 * Everything is a CSS variable. To re-brand, override the --clui-* tokens on .clui (or a parent scope).
 * Dark mode follows `.dark` or `[data-theme="dark"]` on any ancestor (next-themes, shadcn, Tailwind),
 * or set mode="dark" | "light" | "auto" on a chart. Wrap a region in .clui-light / .clui-dark to force a mode.
 *
 * The categorical order (s1-s8) is validated for colour-vision deficiency on adjacent pairs in both modes.
 * Keep the order if you swap hues, and re-validate.
 */

.clui,
.clui-light {
  --clui-font: inherit;
  --clui-surface: #ffffff;
  --clui-ink: #191919;
  --clui-ink-2: #5e5e5e;
  --clui-ink-3: #858585;
  --clui-grid: #ececec;
  --clui-axis: #c2c2c2;
  --clui-border: rgba(11, 11, 11, 0.1);
  --clui-context: #b9b9b9;
  --clui-context-soft: #e2e2e2;
  --clui-total: #4b4b4b;
  --clui-neutral: #a3a3a3;
  --clui-s1: #257de0;
  --clui-s2: #f47230;
  --clui-s3: #00b894;
  --clui-s4: #f2a600;
  --clui-s5: #ee7fac;
  --clui-s6: #008a17;
  --clui-s7: #6a4ce2;
  --clui-s8: #ec4647;
  --clui-s1-ink: #ffffff;
  --clui-s2-ink: #191919;
  --clui-s3-ink: #0b0b0b;
  --clui-s4-ink: #0b0b0b;
  --clui-s5-ink: #0b0b0b;
  --clui-s6-ink: #ffffff;
  --clui-s7-ink: #ffffff;
  --clui-s8-ink: #ffffff;
  --clui-good: #0a9b20;
  --clui-bad: #dc3c3d;
  --clui-good-text: #006c10;
  --clui-bad-text: #b3261e;
  --clui-forecast-bg: rgba(25, 25, 25, 0.035);
  --clui-partial-bg: rgba(25, 25, 25, 0.025);
  --clui-tooltip-bg: #ffffff;
  --clui-tooltip-shadow: 0 1px 2px rgba(0, 0, 0, 0.06), 0 6px 20px rgba(0, 0, 0, 0.08);
  /* sequential (blue), light -> dark */
  --clui-seq-1: #e3effd;
  --clui-seq-2: #b6d5f8;
  --clui-seq-3: #84b9f3;
  --clui-seq-4: #519ced;
  --clui-seq-5: #257de0;
  --clui-seq-6: #1b64be;
  --clui-seq-7: #0e3d7e;
  --clui-seq-ink-1: #191919;
  --clui-seq-ink-2: #191919;
  --clui-seq-ink-3: #191919;
  --clui-seq-ink-4: #191919;
  --clui-seq-ink-5: #ffffff;
  --clui-seq-ink-6: #ffffff;
  --clui-seq-ink-7: #ffffff;
  /* diverging (red <- grey -> blue) */
  --clui-div-n3: #b3262a;
  --clui-div-n2: #e3615f;
  --clui-div-n1: #f5b9b5;
  --clui-div-0: #efefef;
  --clui-div-p1: #b3d3f7;
  --clui-div-p2: #519ced;
  --clui-div-p3: #1b64be;
  --clui-div-ink-n3: #ffffff;
  --clui-div-ink-n2: #191919;
  --clui-div-ink-n1: #191919;
  --clui-div-ink-0: #191919;
  --clui-div-ink-p1: #191919;
  --clui-div-ink-p2: #191919;
  --clui-div-ink-p3: #ffffff;
  color-scheme: light;
}

.dark .clui,
[data-theme="dark"] .clui,
.clui[data-mode="dark"],
.clui-dark,
.clui-dark .clui {
  --clui-surface: #191919;
  --clui-ink: #efefef;
  --clui-ink-2: #a6a6a6;
  --clui-ink-3: #7f7f7f;
  --clui-grid: #2b2b2b;
  --clui-axis: #4a4a4a;
  --clui-border: rgba(255, 255, 255, 0.1);
  --clui-context: #5f5f5f;
  --clui-context-soft: #363636;
  --clui-total: #c9c9c9;
  --clui-neutral: #6f6f6f;
  --clui-s1: #338ced;
  --clui-s2: #e76624;
  --clui-s3: #00a888;
  --clui-s4: #d28e05;
  --clui-s5: #e24d8b;
  --clui-s6: #0aac23;
  --clui-s7: #9887ef;
  --clui-s8: #eb6263;
  --clui-s1-ink: #0b0b0b;
  --clui-s2-ink: #0b0b0b;
  --clui-s3-ink: #0b0b0b;
  --clui-s4-ink: #0b0b0b;
  --clui-s5-ink: #0b0b0b;
  --clui-s6-ink: #0b0b0b;
  --clui-s7-ink: #0b0b0b;
  --clui-s8-ink: #0b0b0b;
  --clui-good: #19b032;
  --clui-bad: #eb6263;
  --clui-good-text: #53c556;
  --clui-bad-text: #f28b8b;
  --clui-forecast-bg: rgba(255, 255, 255, 0.045);
  --clui-partial-bg: rgba(255, 255, 255, 0.03);
  --clui-tooltip-bg: #232323;
  --clui-tooltip-shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.45);
  --clui-seq-1: #1c2a3c;
  --clui-seq-2: #1d3f6b;
  --clui-seq-3: #1b5aa6;
  --clui-seq-4: #2f7fd9;
  --clui-seq-5: #5aa3ee;
  --clui-seq-6: #93c2f5;
  --clui-seq-7: #cfe4fb;
  --clui-seq-ink-1: #efefef;
  --clui-seq-ink-2: #efefef;
  --clui-seq-ink-3: #efefef;
  --clui-seq-ink-4: #ffffff;
  --clui-seq-ink-5: #0b0b0b;
  --clui-seq-ink-6: #0b0b0b;
  --clui-seq-ink-7: #0b0b0b;
  --clui-div-n3: #f08a89;
  --clui-div-n2: #c2474a;
  --clui-div-n1: #6b2c2d;
  --clui-div-0: #333333;
  --clui-div-p1: #1f4677;
  --clui-div-p2: #2f7fd9;
  --clui-div-p3: #8bbcf5;
  --clui-div-ink-n3: #0b0b0b;
  --clui-div-ink-n2: #ffffff;
  --clui-div-ink-n1: #efefef;
  --clui-div-ink-0: #efefef;
  --clui-div-ink-p1: #efefef;
  --clui-div-ink-p2: #ffffff;
  --clui-div-ink-p3: #0b0b0b;
  color-scheme: dark;
}

/* Forced light inside a dark page (declared after dark so it wins). */
.clui-light .clui,
.clui[data-mode="light"] {
  --clui-surface: #ffffff;
  --clui-ink: #191919;
  --clui-ink-2: #5e5e5e;
  --clui-ink-3: #858585;
  --clui-grid: #ececec;
  --clui-axis: #c2c2c2;
  --clui-border: rgba(11, 11, 11, 0.1);
  --clui-context: #b9b9b9;
  --clui-context-soft: #e2e2e2;
  --clui-total: #4b4b4b;
  --clui-neutral: #a3a3a3;
  --clui-s1: #257de0;
  --clui-s2: #f47230;
  --clui-s3: #00b894;
  --clui-s4: #f2a600;
  --clui-s5: #ee7fac;
  --clui-s6: #008a17;
  --clui-s7: #6a4ce2;
  --clui-s8: #ec4647;
  --clui-s1-ink: #ffffff;
  --clui-s2-ink: #191919;
  --clui-s3-ink: #0b0b0b;
  --clui-s4-ink: #0b0b0b;
  --clui-s5-ink: #0b0b0b;
  --clui-s6-ink: #ffffff;
  --clui-s7-ink: #ffffff;
  --clui-s8-ink: #ffffff;
  --clui-good: #0a9b20;
  --clui-bad: #dc3c3d;
  --clui-good-text: #006c10;
  --clui-bad-text: #b3261e;
  --clui-forecast-bg: rgba(25, 25, 25, 0.035);
  --clui-partial-bg: rgba(25, 25, 25, 0.025);
  --clui-tooltip-bg: #ffffff;
  --clui-tooltip-shadow: 0 1px 2px rgba(0, 0, 0, 0.06), 0 6px 20px rgba(0, 0, 0, 0.08);
  --clui-seq-1: #e3effd;
  --clui-seq-2: #b6d5f8;
  --clui-seq-3: #84b9f3;
  --clui-seq-4: #519ced;
  --clui-seq-5: #257de0;
  --clui-seq-6: #1b64be;
  --clui-seq-7: #0e3d7e;
  --clui-seq-ink-1: #191919;
  --clui-seq-ink-2: #191919;
  --clui-seq-ink-3: #191919;
  --clui-seq-ink-4: #191919;
  --clui-seq-ink-5: #ffffff;
  --clui-seq-ink-6: #ffffff;
  --clui-seq-ink-7: #ffffff;
  --clui-div-n3: #b3262a;
  --clui-div-n2: #e3615f;
  --clui-div-n1: #f5b9b5;
  --clui-div-0: #efefef;
  --clui-div-p1: #b3d3f7;
  --clui-div-p2: #519ced;
  --clui-div-p3: #1b64be;
  --clui-div-ink-n3: #ffffff;
  --clui-div-ink-n2: #191919;
  --clui-div-ink-n1: #191919;
  --clui-div-ink-0: #191919;
  --clui-div-ink-p1: #191919;
  --clui-div-ink-p2: #191919;
  --clui-div-ink-p3: #ffffff;
  color-scheme: light;
}

@media (prefers-color-scheme: dark) {
  .clui[data-mode="auto"] {
    --clui-surface: #191919;
    --clui-ink: #efefef;
    --clui-ink-2: #a6a6a6;
    --clui-ink-3: #7f7f7f;
    --clui-grid: #2b2b2b;
    --clui-axis: #4a4a4a;
    --clui-border: rgba(255, 255, 255, 0.1);
    --clui-context: #5f5f5f;
    --clui-context-soft: #363636;
    --clui-total: #c9c9c9;
    --clui-neutral: #6f6f6f;
    --clui-s1: #338ced;
    --clui-s2: #e76624;
    --clui-s3: #00a888;
    --clui-s4: #d28e05;
    --clui-s5: #e24d8b;
    --clui-s6: #0aac23;
    --clui-s7: #9887ef;
    --clui-s8: #eb6263;
    --clui-s1-ink: #0b0b0b;
    --clui-s2-ink: #0b0b0b;
    --clui-s3-ink: #0b0b0b;
    --clui-s4-ink: #0b0b0b;
    --clui-s5-ink: #0b0b0b;
    --clui-s6-ink: #0b0b0b;
    --clui-s7-ink: #0b0b0b;
    --clui-s8-ink: #0b0b0b;
  --clui-s1-ink: #0b0b0b;
  --clui-s2-ink: #0b0b0b;
  --clui-s3-ink: #0b0b0b;
  --clui-s4-ink: #0b0b0b;
  --clui-s5-ink: #0b0b0b;
  --clui-s6-ink: #0b0b0b;
  --clui-s7-ink: #0b0b0b;
  --clui-s8-ink: #0b0b0b;
    --clui-good: #19b032;
    --clui-bad: #eb6263;
    --clui-good-text: #53c556;
    --clui-bad-text: #f28b8b;
    --clui-forecast-bg: rgba(255, 255, 255, 0.045);
    --clui-partial-bg: rgba(255, 255, 255, 0.03);
    --clui-tooltip-bg: #232323;
    --clui-seq-1: #1c2a3c;
    --clui-seq-2: #1d3f6b;
    --clui-seq-3: #1b5aa6;
    --clui-seq-4: #2f7fd9;
    --clui-seq-5: #5aa3ee;
    --clui-seq-6: #93c2f5;
    --clui-seq-7: #cfe4fb;
    --clui-seq-ink-4: #ffffff;
    --clui-seq-ink-5: #0b0b0b;
    --clui-seq-ink-6: #0b0b0b;
    --clui-seq-ink-7: #0b0b0b;
    --clui-div-n3: #f08a89;
    --clui-div-n2: #c2474a;
    --clui-div-n1: #6b2c2d;
    --clui-div-0: #333333;
    --clui-div-p1: #1f4677;
    --clui-div-p2: #2f7fd9;
    --clui-div-p3: #8bbcf5;
    color-scheme: dark;
  }
}

/* ---------- frame ---------- */

.clui {
  margin: 0;
  font-family: var(--clui-font);
  color: var(--clui-ink);
  min-width: 0;
  position: relative;
  -webkit-font-smoothing: antialiased;
}
.clui *,
.clui *::before,
.clui *::after {
  box-sizing: border-box;
}
.clui-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 10px;
}
.clui-head-text {
  min-width: 0;
}
.clui-title {
  margin: 0;
  font-size: 15px;
  line-height: 1.3;
  font-weight: 600;
  letter-spacing: -0.01em;
  color: var(--clui-ink);
}
.clui-subtitle {
  margin: 2px 0 0;
  font-size: 12.5px;
  line-height: 1.4;
  color: var(--clui-ink-2);
}
.clui-toolbar {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
}
/* Charts with an onSelect handler: marks are clickable. */
.clui svg[data-selectable] {
  cursor: pointer;
}

.clui-tool {
  font: inherit;
  font-size: 11px;
  line-height: 1;
  padding: 5px 8px;
  border-radius: 6px;
  border: 1px solid var(--clui-border);
  background: transparent;
  color: var(--clui-ink-2);
  cursor: pointer;
}
.clui-tool:hover {
  color: var(--clui-ink);
  border-color: var(--clui-axis);
}
.clui-tool[aria-pressed="true"] {
  color: var(--clui-ink);
  background: var(--clui-grid);
}
.clui-tool:focus-visible,
.clui-legend-btn:focus-visible,
.clui svg:focus-visible,
.clui-table-wrap:focus-visible {
  outline: 2px solid var(--clui-s1);
  outline-offset: 2px;
  border-radius: 4px;
}
.clui svg:focus:not(:focus-visible) {
  outline: none;
}

.clui-legend {
  display: flex;
  flex-wrap: wrap;
  gap: 4px 14px;
  list-style: none;
  margin: 0 0 10px;
  padding: 0;
  font-size: 12px;
  color: var(--clui-ink-2);
}
.clui-legend li {
  display: flex;
}
.clui-legend-item,
.clui-legend-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font: inherit;
  color: inherit;
}
.clui-legend-btn {
  background: none;
  border: 0;
  padding: 0;
  cursor: pointer;
}
.clui-legend-btn[data-off] {
  opacity: 0.45;
  text-decoration: line-through;
}
.clui-key {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 2px;
  flex-shrink: 0;
}
.clui-key-line {
  width: 14px;
  height: 2px;
  border-radius: 1px;
}
.clui-key-dot {
  border-radius: 50%;
  width: 8px;
  height: 8px;
}
.clui-key-ring {
  border-radius: 50%;
  width: 9px;
  height: 9px;
  background: transparent;
  border: 2px solid;
}
.clui-key-band {
  width: 14px;
  height: 8px;
  opacity: 0.35;
}

.clui-plot {
  position: relative;
  width: 100%;
}
.clui-plot svg {
  display: block;
  overflow: visible;
}
.clui-tick {
  font-size: 11px;
  fill: var(--clui-ink-2);
  font-variant-numeric: tabular-nums;
}
.clui-annot {
  font-size: 11px;
  fill: var(--clui-ink-2);
}
.clui-label {
  font-size: 11px;
  fill: var(--clui-ink);
  font-variant-numeric: tabular-nums;
}
.clui-label-strong {
  font-size: 11.5px;
  font-weight: 600;
  fill: var(--clui-ink);
}
.clui-halo {
  paint-order: stroke;
  stroke: var(--clui-surface);
  stroke-width: 3px;
  stroke-linejoin: round;
}
.clui-mark {
  transition: opacity 120ms ease;
}
.clui-dim {
  opacity: 0.25;
}

.clui-tooltip {
  position: absolute;
  z-index: 10;
  pointer-events: none;
  min-width: 140px;
  max-width: 280px;
  padding: 8px 10px;
  border-radius: 8px;
  background: var(--clui-tooltip-bg);
  border: 1px solid var(--clui-border);
  box-shadow: var(--clui-tooltip-shadow);
  font-size: 12px;
  line-height: 1.35;
  color: var(--clui-ink);
}
.clui-tooltip-title {
  font-weight: 600;
  margin-bottom: 4px;
}
.clui-tooltip table {
  border-collapse: collapse;
  width: 100%;
}
.clui-tooltip td {
  padding: 1.5px 0;
  vertical-align: middle;
}
.clui-tooltip-label {
  color: var(--clui-ink-2);
  padding-right: 14px !important;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 170px;
}
.clui-tooltip-label > span:last-child {
  margin-left: 6px;
}
.clui-tooltip-value {
  text-align: right;
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
}
.clui-tooltip tr[data-strong] td {
  font-weight: 600;
  color: var(--clui-ink);
}
.clui-tooltip-note {
  color: var(--clui-ink-2);
  font-weight: 400;
}
.clui-tooltip-footer {
  margin-top: 5px;
  padding-top: 5px;
  border-top: 1px solid var(--clui-border);
  color: var(--clui-ink-2);
  font-size: 11px;
}

.clui-foot {
  display: flex;
  flex-direction: column;
  gap: 2px;
  margin-top: 10px;
  font-size: 11px;
  line-height: 1.4;
  color: var(--clui-ink-2);
}
.clui-note[data-level="warning"] {
  color: var(--clui-ink);
}
.clui-source {
  color: var(--clui-ink-3);
}

.clui-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  gap: 6px;
  padding: 16px;
  border: 1px dashed var(--clui-axis);
  border-radius: 8px;
  color: var(--clui-ink-2);
  font-size: 12px;
}
.clui-message-title {
  font-weight: 600;
  font-size: 13px;
  color: var(--clui-ink);
}
.clui-message ul {
  margin: 0;
  padding: 0;
  list-style: none;
  max-width: 520px;
}

.clui-table-wrap {
  overflow: auto;
  border: 1px solid var(--clui-border);
  border-radius: 8px;
}
.clui-table {
  border-collapse: collapse;
  width: 100%;
  font-size: 12px;
  font-variant-numeric: tabular-nums;
}
.clui-table th,
.clui-table td {
  padding: 6px 10px;
  border-bottom: 1px solid var(--clui-grid);
  text-align: left;
  white-space: nowrap;
}
.clui-table thead th {
  position: sticky;
  top: 0;
  background: var(--clui-surface);
  color: var(--clui-ink-2);
  font-weight: 500;
}
.clui-table tbody th {
  font-weight: 500;
}
.clui-table [data-align="right"] {
  text-align: right;
}

.clui-sr {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}

/* KPI tiles */
.clui-kpi-row {
  display: grid;
  gap: 12px;
  grid-template-columns: repeat(auto-fit, minmax(var(--clui-kpi-min, 180px), 1fr));
}
.clui-kpi {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 14px 16px;
  border: 1px solid var(--clui-border);
  border-radius: 10px;
  background: var(--clui-surface);
  min-width: 0;
  container-type: inline-size;
}
.clui-kpi-label {
  font-size: 12.5px;
  color: var(--clui-ink-2);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.clui-kpi-value {
  font-size: 26px;
  line-height: 1.15;
  font-weight: 600;
  letter-spacing: -0.02em;
  white-space: nowrap;
}
.clui-kpi-delta {
  font-size: 12px;
  font-variant-numeric: tabular-nums;
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  align-items: baseline;
}
.clui-kpi-delta-muted {
  color: var(--clui-ink-2);
}
.clui-kpi-foot {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 8px;
}
.clui-kpi-delta > span:first-child {
  white-space: nowrap;
}
/* Narrow tiles: the sparkline moves under the numbers instead of squeezing them. */
@container (max-width: 260px) {
  .clui-kpi-foot {
    flex-direction: column;
    align-items: stretch;
  }
  .clui-kpi-spark {
    width: 100% !important;
  }
}

@media (prefers-reduced-motion: reduce) {
  .clui * {
    transition: none !important;
    animation: none !important;
  }
}

@media (forced-colors: active) {
  .clui-key {
    forced-color-adjust: none;
  }
}
```

### components/charts/core/color.ts

```ts
// core/color.ts · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com
/**
 * Colour roles. Every colour is a CSS variable defined in charts.css, so light/dark and brand changes happen in CSS.
 *
 * Rules
 * - Categorical colours are assigned in a fixed order and never cycled. Past 8 series, extra series are grey.
 * - Emphasis by default: when `highlight` is given, highlighted series take accent colours and the rest are grey.
 * - Good / bad colour follows business direction (`favorable`), not the sign of the number.
 */

export const PALETTE_SIZE = 8;

export const color = {
  series: (i: number) => (i < PALETTE_SIZE ? `var(--clui-s${i + 1})` : "var(--clui-context)"),
  /** Text colour for a label placed inside a fill of series colour i. */
  seriesInk: (i: number) => (i < PALETTE_SIZE ? `var(--clui-s${i + 1}-ink)` : "var(--clui-ink)"),
  accent: "var(--clui-s1)",
  context: "var(--clui-context)",
  contextSoft: "var(--clui-context-soft)",
  ink: "var(--clui-ink)",
  ink2: "var(--clui-ink-2)",
  ink3: "var(--clui-ink-3)",
  grid: "var(--clui-grid)",
  axis: "var(--clui-axis)",
  surface: "var(--clui-surface)",
  good: "var(--clui-good)",
  bad: "var(--clui-bad)",
  goodText: "var(--clui-good-text)",
  badText: "var(--clui-bad-text)",
  neutral: "var(--clui-neutral)",
  total: "var(--clui-total)",
  forecast: "var(--clui-forecast-bg)",
  seq: (step: number) => `var(--clui-seq-${Math.max(1, Math.min(7, step))})`,
  seqInk: (step: number) => `var(--clui-seq-ink-${Math.max(1, Math.min(7, step))})`,
  div: (step: number) => `var(--clui-div-${step < 0 ? `n${Math.min(3, -step)}` : step > 0 ? `p${Math.min(3, step)}` : "0"})`,
  divInk: (step: number) =>
    `var(--clui-div-ink-${step < 0 ? `n${Math.min(3, -step)}` : step > 0 ? `p${Math.min(3, step)}` : "0"})`,
};

export interface SeriesLike {
  key: string;
  color?: string;
}

/**
 * Resolve each series' colour. Colour follows the series' position in the declared list (not its rank or visibility); series with an explicit
 * colour don't use up a slot,
 * so toggling a series never repaints the others.
 */
export function seriesColors(series: SeriesLike[], highlight?: string | string[]): Record<string, string> {
  const hl = highlight === undefined ? null : new Set(Array.isArray(highlight) ? highlight : [highlight]);
  const out: Record<string, string> = {};
  let slot = 0;
  series.forEach((s) => {
    if (s.color) out[s.key] = s.color;
    else if (hl) out[s.key] = hl.has(s.key) ? color.series(slot++) : color.context;
    else out[s.key] = color.series(slot++);
  });
  return out;
}

// ---------- direction ----------

export type Favorable = "up" | "down" | "none";
export type Tone = "good" | "bad" | "neutral";

/** Is this change good? `favorable: "down"` for costs, churn, latency. Zero and "none" are neutral. */
export function toneOf(delta: number | null | undefined, favorable: Favorable = "up"): Tone {
  if (delta === null || delta === undefined || !Number.isFinite(delta) || delta === 0 || favorable === "none")
    return "neutral";
  const up = delta > 0;
  return (favorable === "up") === up ? "good" : "bad";
}

export const toneColor = (tone: Tone) => (tone === "good" ? color.good : tone === "bad" ? color.bad : color.neutral);
export const toneText = (tone: Tone) =>
  tone === "good" ? color.goodText : tone === "bad" ? color.badText : color.ink2;

/** Arrow follows the sign; colour (applied separately) follows `favorable`. */
export const arrowGlyph = (delta: number | null | undefined) =>
  delta === null || delta === undefined || !Number.isFinite(delta) || delta === 0 ? "" : delta > 0 ? "▲" : "▼";

/** Word for screen readers and tables, so tone never depends on colour alone. */
export const toneWord = (tone: Tone) => (tone === "good" ? "favorable" : tone === "bad" ? "unfavorable" : "no change");
```

### components/charts/core/data.ts

```ts
// core/data.ts · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com
/**
 * Data checks. Charts never silently "fix" data: invalid input becomes an error message drawn on the chart,
 * and questionable input (missing values, duplicates, too many series) becomes a visible footnote.
 */

export type IssueLevel = "error" | "warning" | "note";

export interface Issue {
  level: IssueLevel;
  message: string;
}

export type Row = Record<string, unknown>;

export function isNum(v: unknown): v is number {
  return typeof v === "number" && Number.isFinite(v);
}

/** Read a numeric cell: finite numbers pass, null/undefined are "missing", anything else is "invalid". */
export function readNum(v: unknown): { value: number | null; state: "ok" | "missing" | "invalid" } {
  if (v === null || v === undefined) return { value: null, state: "missing" };
  if (typeof v === "number") {
    if (Number.isFinite(v)) return { value: v, state: "ok" };
    if (Number.isNaN(v)) return { value: null, state: "missing" };
    return { value: null, state: "invalid" };
  }
  return { value: null, state: "invalid" };
}

const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;

/** Extract a numeric column with counts of missing / invalid cells. */
export function column(rows: Row[], key: string) {
  let missing = 0;
  let invalid = 0;
  const invalidRows: number[] = [];
  const values = rows.map((row, i) => {
    const r = readNum(row?.[key]);
    if (r.state === "missing") missing++;
    if (r.state === "invalid") {
      invalid++;
      invalidRows.push(i);
    }
    return r.value;
  });
  return { values, missing, invalid, invalidRows };
}

/** Standard checks for row-based charts. Returns issues; callers add chart-specific ones. */
export function checkRows(
  rows: unknown,
  opts: { name?: string; xKey?: string; valueKeys: string[]; allowMissing?: boolean; maxSeries?: number },
): Issue[] {
  const issues: Issue[] = [];
  if (!Array.isArray(rows)) return [{ level: "error", message: "`data` must be an array of rows." }];
  if (rows.length === 0) return [{ level: "error", message: "No data to display." }];
  if (opts.valueKeys.length === 0)
    return [{ level: "error", message: "No series to draw. Pass at least one key." }];
  if (opts.xKey && !rows.some((r) => r && (r as Row)[opts.xKey!] !== undefined)) {
    issues.push({ level: "error", message: `No row has the x key "${opts.xKey}".` });
  }
  for (const key of opts.valueKeys) {
    const present = rows.some((r) => r && key in (r as Row));
    if (!present) {
      issues.push({ level: "error", message: `No row has the key "${key}".` });
      continue;
    }
    const c = column(rows as Row[], key);
    if (c.invalid) {
      const sample = c.invalidRows
        .slice(0, 3)
        .map((i) => JSON.stringify((rows as Row[])[i][key]))
        .join(", ");
      issues.push({
        level: "error",
        message: `"${key}" has ${plural(c.invalid, "non-numeric value")} (${sample}${c.invalid > 3 ? ", …" : ""}). Convert to numbers before charting.`,
      });
    }
    if (c.missing && c.missing === rows.length) {
      issues.push({ level: "warning", message: `"${key}" has no values.` });
    } else if (c.missing && opts.allowMissing !== false) {
      issues.push({
        level: "note",
        message: `"${key}": ${plural(c.missing, "missing value")}, shown as gaps.`,
      });
    } else if (c.missing) {
      issues.push({
        level: "warning",
        message: `"${key}": ${plural(c.missing, "missing value")} not drawn.`,
      });
    }
  }
  if (opts.xKey) {
    const seen = new Map<string, number>();
    for (const r of rows as Row[]) {
      const k = String(r?.[opts.xKey]);
      seen.set(k, (seen.get(k) ?? 0) + 1);
    }
    const dups = [...seen.entries()].filter(([, n]) => n > 1);
    if (dups.length) {
      issues.push({
        level: "warning",
        message: `Duplicate ${opts.xKey} values: ${dups
          .slice(0, 3)
          .map(([k]) => `"${k}"`)
          .join(
            ", ",
          )}${dups.length > 3 ? "…" : ""}. Each row is drawn separately; aggregate first if that is not intended.`,
      });
    }
  }
  if (opts.maxSeries && opts.valueKeys.length > opts.maxSeries) {
    issues.push({
      level: "warning",
      message: `${opts.valueKeys.length} series exceeds the ${opts.maxSeries}-colour palette; series after ${opts.maxSeries} are grey. Consider small multiples or grouping into "Other".`,
    });
  }
  return issues;
}

export const hasError = (issues: Issue[]) => issues.some((i) => i.level === "error");

/** Parse a date-like value to UTC ms. Date-only ISO strings ("2026-03-01") are read as UTC midnight. */
export function parseDate(v: unknown): number | null {
  if (v instanceof Date) return Number.isNaN(v.getTime()) ? null : v.getTime();
  if (typeof v === "number") return Number.isFinite(v) ? v : null;
  if (typeof v !== "string" || !v.trim()) return null;
  const s = v.trim();
  const dateOnly = /^(\d{4})-(\d{2})(?:-(\d{2}))?$/.exec(s);
  if (dateOnly) {
    const [, y, m, d] = dateOnly;
    return Date.UTC(Number(y), Number(m) - 1, d ? Number(d) : 1);
  }
  const t = Date.parse(s);
  return Number.isNaN(t) ? null : t;
}

export function sum(values: (number | null)[]): number {
  let s = 0;
  for (const v of values) if (v !== null && Number.isFinite(v)) s += v;
  return s;
}

export function extent(values: (number | null | undefined)[]): [number, number] | null {
  let lo = Infinity;
  let hi = -Infinity;
  for (const v of values) {
    if (v === null || v === undefined || !Number.isFinite(v)) continue;
    if (v < lo) lo = v;
    if (v > hi) hi = v;
  }
  return lo === Infinity ? null : [lo, hi];
}

/** Quantile of a sorted array (linear interpolation, R-7). */
export function quantile(sorted: number[], p: number): number {
  if (!sorted.length) return NaN;
  const h = (sorted.length - 1) * p;
  const lo = Math.floor(h);
  const hi = Math.ceil(h);
  return sorted[lo] + (sorted[hi] - sorted[lo]) * (h - lo);
}

/** Convert row data to CSV (RFC 4180), guarding against spreadsheet formula injection. */
export function toCSV(columns: { key: string; label: string }[], rows: Row[]): string {
  const cell = (v: unknown) => {
    if (v === null || v === undefined) return "";
    let s = v instanceof Date ? v.toISOString() : String(v);
    // numbers (e.g. -5) are data, not formulas; anything else is checked by its text
    if (typeof v !== "number" && typeof v !== "bigint" && /^[=+\-@\t\r]/.test(s)) s = `'${s}`;
    return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
  };
  const lines = [columns.map((c) => cell(c.label)).join(",")];
  for (const r of rows) lines.push(columns.map((c) => cell(r[c.key])).join(","));
  return lines.join("\r\n");
}
```

### components/charts/core/format.ts

```ts
// core/format.ts · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com
/**
 * Number and date formatting shared by every chart: axes, tooltips, labels, legends, tables and KPI tiles.
 *
 * Conventions
 * - Percent values are fractions: 0.125 -> "12.5%".
 * - Percentage points ("pp") are given in points: 2.3 -> "+2.3 pp".
 * - Negative numbers use a true minus sign (U+2212).
 * - Compact numbers (1.2K, $4.2M) are used from 10,000 upward in "auto" mode. Tables show full values.
 * - A magnitude unit (m, bn, k...) means the value is already scaled, so it is never re-compacted:
 *   { kind: "currency", unit: "m" } formats 1000 as "$1,000m", never "$1.0Km".
 */

export type FormatKind = "number" | "integer" | "currency" | "percent" | "pp";

export interface FormatSpec {
  kind?: FormatKind;
  /** "auto" (default) compacts from 10,000 up outside tables; true always compacts; false never. */
  compact?: boolean | "auto";
  /** Fixed number of decimals. Overrides the automatic choice. */
  decimals?: number;
  /** ISO 4217 code for kind "currency". Default "USD". */
  currency?: string;
  /** Unit written after the number, e.g. "trips", "ms", "m" (already in millions). */
  unit?: string;
  /** Always show a sign (+/−). Default true for "pp", false otherwise. */
  signed?: boolean;
  /** BCP 47 locale. Default "en-US". */
  locale?: string;
}

export type FormatPreset = FormatKind | "compact" | "currency-compact";
export type FormatInput = FormatPreset | FormatSpec | ((value: number) => string);

/** Where a value is written. Tables show more precision and no auto-compaction. */
export type FormatContext = "axis" | "label" | "tooltip" | "table";

const MINUS = "−";
const MAGNITUDE_UNITS = new Set(["k", "K", "m", "M", "mm", "MM", "bn", "b", "B", "tn", "T"]);
const TIGHT_UNITS = new Set(["x", "×", "%", "‰", "°"]);

export function resolveFormat(input?: FormatInput): FormatSpec | ((value: number) => string) {
  if (typeof input === "function") return input;
  if (!input) return { kind: "number" };
  if (typeof input === "string") {
    switch (input) {
      case "compact":
        return { kind: "number", compact: true };
      case "currency-compact":
        return { kind: "currency", compact: true };
      default:
        return { kind: input };
    }
  }
  return { kind: "number", ...input };
}

interface Magnitude {
  divisor: number;
  suffix: string;
}

const MAGNITUDES: Magnitude[] = [
  { divisor: 1e12, suffix: "T" },
  { divisor: 1e9, suffix: "B" },
  { divisor: 1e6, suffix: "M" },
  { divisor: 1e3, suffix: "K" },
];

function magnitudeFor(abs: number): Magnitude {
  for (const m of MAGNITUDES) if (abs >= m.divisor * 0.9995) return m;
  return { divisor: 1, suffix: "" };
}

function isMagnitudeUnit(unit?: string) {
  return !!unit && MAGNITUDE_UNITS.has(unit);
}

function shouldCompact(spec: FormatSpec, abs: number, context: FormatContext) {
  if (spec.kind === "percent" || spec.kind === "pp") return false;
  if (isMagnitudeUnit(spec.unit)) return false;
  const c = spec.compact ?? "auto";
  if (c === true) return abs >= 1000 || context !== "table";
  if (c === false) return false;
  return context !== "table" && abs >= 10_000;
}

function defaultDecimals(spec: FormatSpec, scaledAbs: number, compacted: boolean, context: FormatContext) {
  if (spec.decimals !== undefined) return spec.decimals;
  switch (spec.kind) {
    case "integer":
      return compacted ? (scaledAbs < 100 ? 1 : 0) : 0;
    case "percent":
      return 1;
    case "pp":
      return 1;
    default: {
      if (compacted) return scaledAbs < 100 ? 1 : 0;
      // whole numbers are written whole: "$40", not "$40.0"
      if (Number.isInteger(scaledAbs)) return 0;
      if (context === "table" || context === "tooltip") {
        if (scaledAbs >= 1000) return 0;
        if (scaledAbs >= 100) return 1;
        return 2;
      }
      if (scaledAbs >= 100) return 0;
      if (scaledAbs >= 10) return 1;
      return 2;
    }
  }
}

function appendUnit(text: string, unit?: string) {
  if (!unit) return text;
  if (TIGHT_UNITS.has(unit) || isMagnitudeUnit(unit)) return text + unit;
  return `${text} ${unit}`;
}

/** Intl formatting with our suffix inserted after the numeric part (handles "4,2 M €" style locales). */
function intlFormat(
  scaled: number,
  spec: FormatSpec,
  decimals: number,
  suffix: string,
  trim: boolean,
  significant?: number,
): string {
  const locale = spec.locale ?? "en-US";
  const opts: Intl.NumberFormatOptions = significant
    ? { maximumSignificantDigits: significant }
    : { minimumFractionDigits: trim ? 0 : decimals, maximumFractionDigits: decimals };
  if (spec.kind === "currency") {
    opts.style = "currency";
    opts.currency = spec.currency ?? "USD";
  }
  const parts = new Intl.NumberFormat(locale, opts).formatToParts(scaled);
  let lastNumeric = -1;
  parts.forEach((p, i) => {
    if (p.type === "integer" || p.type === "fraction" || p.type === "decimal" || p.type === "group") lastNumeric = i;
  });
  let out = "";
  parts.forEach((p, i) => {
    out += p.type === "minusSign" ? MINUS : p.value;
    if (i === lastNumeric) out += suffix;
  });
  return out;
}

export interface FormatOptions {
  context?: FormatContext;
  signed?: boolean;
  /** Force a magnitude (used by axes so every tick shares one suffix). */
  magnitude?: Magnitude;
  decimals?: number;
  /** Drop trailing zeros (axes). */
  trim?: boolean;
}

/** Format one value. null/undefined/NaN become an en dash, never "0". */
export function formatValue(value: number | null | undefined, input?: FormatInput, options: FormatOptions = {}): string {
  if (value === null || value === undefined || typeof value !== "number" || Number.isNaN(value)) return "–";
  if (!Number.isFinite(value)) return value > 0 ? "∞" : `${MINUS}∞`;
  const resolved = resolveFormat(input);
  if (typeof resolved === "function") return resolved(value);
  const spec = resolved;
  const context = options.context ?? "label";
  const signed = options.signed ?? spec.signed ?? spec.kind === "pp";

  if (value === 0 && spec.decimals === undefined) {
    // Zero is always written plainly: "0", "$0", "0%", never "$0.0M".
    let z = intlFormat(0, spec, 0, "", true);
    if (spec.kind === "percent") z += "%";
    if (spec.kind === "pp") z = appendUnit(z, "pp");
    return appendUnit(z, isMagnitudeUnit(spec.unit) ? undefined : spec.unit);
  }

  let scaled = value;
  if (spec.kind === "percent") scaled = value * 100;

  const abs = Math.abs(scaled);
  const mag = options.magnitude ?? (shouldCompact(spec, abs, context) ? magnitudeFor(abs) : { divisor: 1, suffix: "" });
  const display = scaled / mag.divisor;
  const decimals = options.decimals ?? defaultDecimals(spec, Math.abs(display), mag.divisor > 1, context);

  // Very small non-zero values must not collapse to "0".
  const tiny = display !== 0 && Math.abs(display) < 0.5 * 10 ** -decimals && spec.decimals === undefined;
  let text = tiny
    ? intlFormat(display, spec, decimals, mag.suffix, true, 2)
    : intlFormat(display, spec, decimals, mag.suffix, !!options.trim);

  // Normalise "−0" / "−0.0"
  if (!/[1-9]/.test(text)) text = text.replace(MINUS, "");

  if (spec.kind === "percent") text += "%";
  if (spec.kind === "pp") text = appendUnit(text, "pp");
  text = appendUnit(text, spec.unit);
  if (signed && value > 0 && /[1-9]/.test(text)) text = `+${text}`;
  return text;
}

/**
 * Build a formatter for a set of axis ticks: one magnitude suffix for the whole axis and the fewest decimals
 * that keep every tick distinct.
 */
export function tickFormatter(input: FormatInput | undefined, ticks: number[]): (v: number) => string {
  const resolved = resolveFormat(input);
  if (typeof resolved === "function") return resolved;
  const spec = resolved;
  const scale = spec.kind === "percent" ? 100 : 1;
  const maxAbs = Math.max(0, ...ticks.map((t) => Math.abs(t * scale)));
  const mag = shouldCompact(spec, maxAbs, "axis") ? magnitudeFor(maxAbs) : { divisor: 1, suffix: "" };
  const zeroFirst = (fn: (v: number) => string) => (v: number) => (v === 0 ? formatValue(0, { ...spec, decimals: undefined }) : fn(v));
  // Ticks are round numbers: they always use the fewest decimals that keep them distinct, even when the
  // format fixes decimals for labels and tooltips ("10 h", not "10.0 h").
  for (let d = 0; d <= 4; d++) {
    const labels = ticks.map((t) => formatValue(t, spec, { context: "axis", magnitude: mag, decimals: d, trim: false }));
    const exact = ticks.every((t) => {
      const s = (t * scale) / mag.divisor;
      return Math.abs(Math.round(s * 10 ** d) - s * 10 ** d) < 1e-6;
    });
    if (new Set(labels).size === labels.length && exact) {
      return zeroFirst((v) => formatValue(v, spec, { context: "axis", magnitude: mag, decimals: d, trim: false }));
    }
  }
  return zeroFirst((v) => formatValue(v, spec, { context: "axis", magnitude: mag, decimals: 2, trim: false }));
}

/** Make a single-context formatter. */
/**
 * Formatter for a set of data labels shown together. If the largest label compacts, every label shares its
 * magnitude ("$17.8K, $4.5K, −$0.7K", never "$17.8K, $4,500, −$700"). Percent, pp, magnitude units and
 * function formats fall back to formatting each value on its own. `delta` writes signed differences.
 */
export function labelFormatter(input: FormatInput | undefined, values: (number | null | undefined)[], opts: { delta?: boolean } = {}) {
  const resolved = resolveFormat(input);
  const single = (v: number | null | undefined) => (opts.delta ? formatDelta(v, input) : formatValue(v, input));
  if (typeof resolved === "function") return single;
  const spec = resolved;
  if (spec.kind === "percent" || spec.kind === "pp") return single;
  const finite = values.filter((v): v is number => typeof v === "number" && Number.isFinite(v));
  const maxAbs = finite.reduce((m, v) => Math.max(m, Math.abs(v)), 0);
  if (!maxAbs || !shouldCompact(spec, maxAbs, "label")) return single;
  const magnitude = magnitudeFor(maxAbs);
  const decimals = spec.decimals ?? (maxAbs / magnitude.divisor >= 100 ? 0 : 1);
  return (v: number | null | undefined) =>
    v === 0 || v === null || v === undefined || !Number.isFinite(v) ? single(v) : formatValue(v, input, { magnitude, decimals, signed: opts.delta });
}

export function formatter(input: FormatInput | undefined, context: FormatContext = "label") {
  return (v: number | null | undefined) => formatValue(v, input, { context });
}

/**
 * Format a difference between two values of the given format.
 * Percent formats express differences in percentage points.
 */
export function formatDelta(delta: number | null | undefined, input?: FormatInput, context: FormatContext = "label") {
  const resolved = resolveFormat(input);
  if (typeof resolved === "function") {
    if (delta === null || delta === undefined || Number.isNaN(delta)) return "–";
    const t = resolved(Math.abs(delta));
    return delta > 0 ? `+${t}` : delta < 0 ? `${MINUS}${t}` : t;
  }
  if (resolved.kind === "percent") {
    return formatValue(delta === null || delta === undefined ? delta : delta * 100, { ...resolved, kind: "pp" }, {
      context,
      signed: true,
    });
  }
  return formatValue(delta, resolved, { context, signed: true });
}

/** Relative change as a signed percentage. Returns "–" when the base is zero or missing. */
export function formatChange(current: number | null | undefined, base: number | null | undefined, decimals = 1) {
  if (current == null || base == null || !Number.isFinite(current) || !Number.isFinite(base) || base === 0) return "–";
  const change = (current - base) / Math.abs(base);
  return formatValue(change, { kind: "percent", decimals }, { signed: true });
}

/** A share of a whole, with "<1%" for tiny non-zero shares rather than a misleading "0%". */
export function formatShare(share: number | null | undefined, decimals = 0) {
  if (share === null || share === undefined || Number.isNaN(share)) return "–";
  if (share > 0 && share * 100 < 0.5 * 10 ** -decimals) return `<${(10 ** -decimals).toString()}%`;
  return formatValue(share, { kind: "percent", decimals });
}

export type DateGrain = "day" | "week" | "month" | "quarter" | "year";

const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

/** Format a timestamp (ms) in UTC at the given grain. */
export function formatDate(ms: number, grain: DateGrain = "day", style: "short" | "long" = "short"): string {
  const d = new Date(ms);
  if (Number.isNaN(d.getTime())) return "–";
  const y = d.getUTCFullYear();
  const m = d.getUTCMonth();
  switch (grain) {
    case "year":
      return String(y);
    case "quarter":
      return `Q${Math.floor(m / 3) + 1} ${y}`;
    case "month":
      return style === "long" ? `${MONTHS[m]} ${y}` : `${MONTHS[m]} ${String(y).slice(2)}`;
    case "week":
    case "day":
    default:
      return style === "long" ? `${MONTHS[m]} ${d.getUTCDate()}, ${y}` : `${MONTHS[m]} ${d.getUTCDate()}`;
  }
}
```

### components/charts/core/frame.tsx

```tsx
// core/frame.tsx · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com
"use client";

import {
  Component,
  useCallback,
  useId,
  useLayoutEffect,
  useEffect,
  useRef,
  useState,
  type CSSProperties,
  type ErrorInfo,
  type KeyboardEvent,
  type PointerEvent,
  type ReactNode,
} from "react";
import { hasError, toCSV, type Issue, type Row } from "./data";
import { ChartScope, useWords, useSelectHandler, type ChartWords, type ChartSelectEvent } from "./words";

export { ChartWordsProvider, DEFAULT_WORDS, useWords, type ChartWords, type ChartSelectEvent } from "./words";

// ---------- size ----------

const useIsoLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;

/** Width of an element, tracked with ResizeObserver. Falls back to `fallback` where ResizeObserver is missing. */
export function useWidth<T extends HTMLElement>(fixed?: number, fallback = 640) {
  const ref = useRef<T>(null);
  const [width, setWidth] = useState(fixed ?? 0);
  useIsoLayoutEffect(() => {
    if (fixed) return setWidth(fixed);
    const el = ref.current;
    if (!el) return;
    if (typeof ResizeObserver === "undefined") return setWidth(el.clientWidth || fallback);
    const measure = () => setWidth(Math.floor(el.clientWidth || el.getBoundingClientRect().width || 0));
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(el);
    return () => ro.disconnect();
  }, [fixed, fallback]);
  return [ref, width] as const;
}

// ---------- legend ----------

export type KeyShape = "line" | "dash" | "square" | "dot" | "ring" | "band";

export interface LegendItem {
  key: string;
  label: string;
  color: string;
  shape?: KeyShape;
}

export function KeySwatch({ color, shape = "square" }: { color: string; shape?: KeyShape }) {
  const s: CSSProperties = { background: color };
  if (shape === "line") return <span className="clui-key clui-key-line" style={s} aria-hidden />;
  if (shape === "dash")
    return (
      <span
        className="clui-key clui-key-line"
        style={{ background: `repeating-linear-gradient(90deg, ${color} 0 4px, transparent 4px 7px)` }}
        aria-hidden
      />
    );
  if (shape === "dot") return <span className="clui-key clui-key-dot" style={s} aria-hidden />;
  if (shape === "ring") return <span className="clui-key clui-key-ring" style={{ borderColor: color }} aria-hidden />;
  if (shape === "band") return <span className="clui-key clui-key-band" style={s} aria-hidden />;
  return <span className="clui-key" style={s} aria-hidden />;
}

export function Legend({
  items,
  hidden,
  onToggle,
  onHover,
}: {
  items: LegendItem[];
  hidden?: Set<string>;
  onToggle?: (key: string) => void;
  onHover?: (key: string | null) => void;
}) {
  const L = useWords();
  if (!items.length) return null;
  return (
    <ul className="clui-legend" aria-label={L.legend}>
      {items.map((it) => {
        const off = hidden?.has(it.key);
        const content = (
          <>
            <KeySwatch color={it.color} shape={it.shape} />
            <span>{it.label}</span>
          </>
        );
        return (
          <li key={it.key} onPointerEnter={() => onHover?.(it.key)} onPointerLeave={() => onHover?.(null)}>
            {onToggle ? (
              <button
                type="button"
                className="clui-legend-btn"
                aria-pressed={!off}
                data-off={off || undefined}
                onClick={() => onToggle(it.key)}
                onFocus={() => onHover?.(it.key)}
                onBlur={() => onHover?.(null)}
                title={`${off ? L.show : L.hide} ${it.label}`}
              >
                {content}
              </button>
            ) : (
              <span className="clui-legend-item">{content}</span>
            )}
          </li>
        );
      })}
    </ul>
  );
}

/** Legend state: hidden series and the hovered (highlighted) series. Colours never change when toggling. */
export function useSeriesToggle(keys: string[]) {
  const [hidden, setHidden] = useState<Set<string>>(() => new Set());
  const [focus, setFocus] = useState<string | null>(null);
  const toggle = useCallback(
    (key: string) =>
      setHidden((prev) => {
        const next = new Set(prev);
        if (next.has(key)) next.delete(key);
        else if (keys.length - next.size > 1) next.add(key); // always keep one series visible
        return next;
      }),
    [keys.length],
  );
  return { hidden, toggle, focus, setFocus };
}

// ---------- tooltip ----------

export interface TooltipRow {
  label: string;
  value: string;
  color?: string;
  shape?: KeyShape;
  strong?: boolean;
  note?: string;
}

export interface TooltipData {
  title?: string;
  rows: TooltipRow[];
  footer?: string;
}

/** Tooltip positioned inside the plot. Flips to the left of the pointer on the right half. */
export function ChartTooltip({
  x,
  y,
  width,
  height,
  data,
}: {
  x: number;
  y: number;
  width: number;
  height: number;
  data: TooltipData | null;
}) {
  if (!data) return null;
  const flip = x > width * 0.55;
  const top = Math.max(8, Math.min(height - 8, y));
  const style: CSSProperties = {
    left: x,
    top,
    transform: `translate(${flip ? "calc(-100% - 14px)" : "14px"}, ${top > height * 0.6 ? "-100%" : top < height * 0.3 ? "0" : "-50%"})`,
  };
  return (
    <div className="clui-tooltip" style={style} role="status" aria-live="polite">
      {data.title && <div className="clui-tooltip-title">{data.title}</div>}
      {data.rows.length > 0 && (
        <table>
          <tbody>
            {data.rows.map((r, i) => (
              <tr key={i} data-strong={r.strong || undefined}>
                <td className="clui-tooltip-label">
                  {r.color && <KeySwatch color={r.color} shape={r.shape} />}
                  <span>{r.label}</span>
                </td>
                <td className="clui-tooltip-value">
                  {r.value}
                  {r.note && <span className="clui-tooltip-note"> {r.note}</span>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
      {data.footer && <div className="clui-tooltip-footer">{data.footer}</div>}
    </div>
  );
}

/** Pointer position relative to the element that received the event. */
export function localPoint(e: PointerEvent<Element>) {
  const rect = (e.currentTarget as Element).getBoundingClientRect();
  return { x: e.clientX - rect.left, y: e.clientY - rect.top };
}

/**
 * The active (hovered or keyboard-focused) item. Spread `keyProps` on the focusable SVG: arrow keys move,
 * Home/End jump, Escape clears.
 */
export function useActiveIndex(
  count: number,
  opts: {
    columns?: number;
    /** What a click on mark i reports to the chart's onSelect (label and data row). */
    describe?: (i: number) => Omit<ChartSelectEvent, "index">;
  } = {},
) {
  const [active, setActive] = useState<number | null>(null);
  const onSelect = useSelectHandler();
  const cols = opts.columns;
  const select = (i: number | null) => {
    if (!onSelect || i === null || i < 0 || i >= count) return;
    onSelect({ index: i, ...opts.describe?.(i) });
  };
  const onKeyDown = (e: KeyboardEvent) => {
    if (!count) return;
    if ((e.key === "Enter" || e.key === " ") && onSelect && active !== null) {
      e.preventDefault();
      select(active);
      return;
    }
    const cur = active ?? -1;
    let next: number | null = cur;
    switch (e.key) {
      case "ArrowRight":
        next = Math.min(count - 1, cur + 1);
        break;
      case "ArrowLeft":
        next = Math.max(0, cur < 0 ? 0 : cur - 1);
        break;
      case "ArrowDown":
        next = cols ? Math.min(count - 1, cur < 0 ? 0 : cur + cols) : Math.min(count - 1, cur + 1);
        break;
      case "ArrowUp":
        next = cols ? Math.max(0, cur - cols) : Math.max(0, cur < 0 ? 0 : cur - 1);
        break;
      case "Home":
        next = 0;
        break;
      case "End":
        next = count - 1;
        break;
      case "Escape":
        next = null;
        break;
      default:
        return;
    }
    e.preventDefault();
    setActive(next);
  };
  const keyProps = {
    tabIndex: 0,
    onKeyDown,
    onBlur: () => setActive(null),
    onClick: onSelect ? () => select(active) : undefined,
    "data-selectable": onSelect ? "" : undefined,
  };
  return { active, setActive, keyProps };
}

// ---------- table ----------

export interface TableColumn {
  key: string;
  label: string;
  align?: "left" | "right";
  /** Display formatter. The raw value is used for CSV. */
  format?: (value: unknown, row: Row) => string;
}

export interface TableData {
  columns: TableColumn[];
  rows: Row[];
  caption?: string;
}

export function DataTable({ table, maxHeight }: { table: TableData; maxHeight?: number }) {
  return (
    <div className="clui-table-wrap" style={maxHeight ? { maxHeight } : undefined} tabIndex={0}>
      <table className="clui-table">
        {table.caption && <caption className="clui-sr">{table.caption}</caption>}
        <thead>
          <tr>
            {table.columns.map((c) => (
              <th key={c.key} scope="col" data-align={c.align ?? "left"}>
                {c.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {table.rows.map((row, i) => (
            <tr key={i}>
              {table.columns.map((c, j) => {
                const v = row[c.key];
                const text = c.format ? c.format(v, row) : v === null || v === undefined ? "–" : String(v);
                return j === 0 ? (
                  <th key={c.key} scope="row" data-align={c.align ?? "left"}>
                    {text}
                  </th>
                ) : (
                  <td key={c.key} data-align={c.align ?? "left"}>
                    {text}
                  </td>
                );
              })}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export function downloadCSV(table: TableData, filename = "chart-data.csv") {
  const csv = toCSV(table.columns, table.rows);
  const blob = new Blob(["﻿" + csv], { type: "text/csv;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

// ---------- messages ----------

export function ChartMessage({ issues, height }: { issues: Issue[]; height: number }) {
  const errors = issues.filter((i) => i.level === "error");
  const empty = errors.length === 1 && errors[0].message === "No data to display.";
  return (
    <div className="clui-message" style={{ minHeight: height }} role="alert" data-kind={empty ? "empty" : "error"}>
      <div className="clui-message-title">{empty ? "No data to display" : "This chart can’t be drawn"}</div>
      {!empty && (
        <ul>
          {errors.slice(0, 4).map((e, i) => (
            <li key={i}>{e.message}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

class ChartBoundary extends Component<{ height: number; children: ReactNode }, { error: Error | null }> {
  state = { error: null as Error | null };
  static getDerivedStateFromError(error: Error) {
    return { error };
  }
  componentDidCatch(error: Error, info: ErrorInfo) {
    if (typeof console !== "undefined") console.error("[chart] render failed", error, info.componentStack);
  }
  render() {
    if (this.state.error)
      return (
        <ChartMessage
          height={this.props.height}
          issues={[{ level: "error", message: `Rendering failed: ${this.state.error.message}` }]}
        />
      );
    return this.props.children;
  }
}

// ---------- frame ----------

export type ChartMode = "light" | "dark" | "auto";

export interface FrameProps {
  /** The takeaway, e.g. "Revenue passed plan in Q3". */
  title?: ReactNode;
  /** What is measured: metric, unit, basis, period. */
  subtitle?: ReactNode;
  /** Data source, shown in the footer. */
  source?: ReactNode;
  /** Extra footnote text. */
  footnote?: ReactNode;
  /** Height of the plot area in px. 0 lets the content set its own height. */
  height?: number;
  /** Fixed width in px. Defaults to the container width. */
  width?: number;
  /** Light/dark override. By default the chart follows `.dark` / `[data-theme="dark"]` on an ancestor. */
  mode?: ChartMode;
  /** Show the table/CSV toolbar. */
  toolbar?: boolean;
  /** Show data notes (missing values, duplicates) under the chart. */
  showNotes?: boolean;
  className?: string;
  style?: CSSProperties;
  /** Heading element for the title. */
  titleAs?: "h2" | "h3" | "h4" | "div";
  /** Translate the words the chart draws itself ("Total", "Forecast", "Table"…). See ChartWordsProvider. */
  words?: Partial<ChartWords>;
  /** Called when someone clicks a mark (or presses Enter on it): its index, label and data row. */
  onSelect?: (e: ChartSelectEvent) => void;
}

export interface ChartFrameProps extends FrameProps {
  legend?: LegendItem[];
  legendHidden?: Set<string>;
  onLegendToggle?: (key: string) => void;
  onLegendHover?: (key: string | null) => void;
  issues?: Issue[];
  table?: TableData;
  /** Screen-reader summary of what the chart shows. */
  summary: string;
  /** Name used for the CSV file. */
  csvName?: string;
  /** Minimum width before the plot scrolls horizontally instead of compressing further. */
  minWidth?: number;
  /** Start in table view. */
  defaultView?: "chart" | "table";
  children: (size: { width: number; height: number }) => ReactNode;
}

export function ChartFrame(props: ChartFrameProps) {
  return (
    <ChartScope labels={props.words} onSelect={props.onSelect}>
      <FrameBody {...props} />
    </ChartScope>
  );
}

function FrameBody(props: ChartFrameProps) {
  const L = useWords();
  const {
    title,
    subtitle,
    source,
    footnote,
    height = 280,
    width: fixedWidth,
    mode,
    toolbar = true,
    showNotes = true,
    className,
    style,
    titleAs: TitleTag = "h3",
    legend,
    legendHidden,
    onLegendToggle,
    onLegendHover,
    issues = [],
    table,
    summary,
    csvName,
    minWidth = 0,
    defaultView = "chart",
    children,
  } = props;
  const [ref, measured] = useWidth<HTMLDivElement>(fixedWidth);
  const [view, setView] = useState<"chart" | "table">(defaultView);
  const id = useId();
  const failed = hasError(issues);
  const notes = issues.filter((i) => i.level !== "error");
  const plotWidth = Math.max(measured, minWidth);

  return (
    <figure
      className={["clui", className].filter(Boolean).join(" ")}
      data-mode={mode}
      style={{ ...(fixedWidth ? { width: fixedWidth } : null), ...style }}
      aria-labelledby={title ? `${id}-t` : undefined}
      aria-describedby={`${id}-s`}
    >
      {(title || subtitle || (toolbar && table && !failed)) && (
        <div className="clui-head">
          <div className="clui-head-text">
            {title && (
              <TitleTag className="clui-title" id={`${id}-t`}>
                {title}
              </TitleTag>
            )}
            {subtitle && <p className="clui-subtitle">{subtitle}</p>}
          </div>
          {toolbar && table && !failed && (
            <div className="clui-toolbar">
              <button
                type="button"
                className="clui-tool"
                aria-pressed={view === "table"}
                onClick={() => setView((v) => (v === "chart" ? "table" : "chart"))}
              >
                {view === "chart" ? L.table : L.chart}
              </button>
              <button
                type="button"
                className="clui-tool"
                onClick={() => downloadCSV(table, csvName ?? (typeof title === "string" ? slug(title) : "chart-data") + ".csv")}
                aria-label={L.downloadCsv}
              >
                {L.csv}
              </button>
            </div>
          )}
        </div>
      )}
      {legend && legend.length > 0 && !failed && view === "chart" && (
        <Legend items={legend} hidden={legendHidden} onToggle={onLegendToggle} onHover={onLegendHover} />
      )}
      <p className="clui-sr" id={`${id}-s`}>
        {summary}
      </p>
      <div
        ref={ref}
        className="clui-plot"
        style={{ minHeight: height || 120, overflowX: minWidth && measured < minWidth ? "auto" : undefined }}
      >
        {failed ? (
          <ChartMessage issues={issues} height={height} />
        ) : view === "table" && table ? (
          <DataTable table={table} maxHeight={Math.max(height, 200)} />
        ) : measured > 0 ? (
          <ChartBoundary height={height}>
            <div style={{ position: "relative", width: plotWidth, height: height || undefined }}>
              {children({ width: plotWidth, height })}
            </div>
          </ChartBoundary>
        ) : (
          <div style={{ height: height || 120 }} aria-hidden />
        )}
      </div>
      {((showNotes && notes.length > 0) || source || footnote) && (
        <figcaption className="clui-foot">
          {showNotes &&
            notes.map((n, i) => (
              <span key={i} className="clui-note" data-level={n.level}>
                {`${n.level === "warning" ? L.check : L.note}: `}
                {n.message}
              </span>
            ))}
          {footnote && <span className="clui-note">{footnote}</span>}
          {source && <span className="clui-source">{L.source}: {source}</span>}
        </figcaption>
      )}
    </figure>
  );
}

function slug(s: string) {
  return (
    s
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/^-|-$/g, "")
      .slice(0, 60) || "chart-data"
  );
}
```

### components/charts/core/path.ts

```ts
// core/path.ts · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com
/** SVG path builders. Points that are null create gaps, so missing data is never interpolated. */

export type Point = [number, number];
export type MaybePoint = Point | null;
export type Curve = "linear" | "monotone" | "step" | "step-before";

const r = (v: number) => Math.round(v * 10) / 10;

/** Split a point list into runs of consecutive non-null points. */
export function segments(points: MaybePoint[]): Point[][] {
  const out: Point[][] = [];
  let run: Point[] = [];
  for (const p of points) {
    if (p && Number.isFinite(p[0]) && Number.isFinite(p[1])) run.push(p);
    else if (run.length) {
      out.push(run);
      run = [];
    }
  }
  if (run.length) out.push(run);
  return out;
}

function monotoneTangents(pts: Point[]): number[] {
  const n = pts.length;
  const m: number[] = [];
  for (let i = 0; i < n - 1; i++) {
    const dx = pts[i + 1][0] - pts[i][0];
    m.push(dx === 0 ? 0 : (pts[i + 1][1] - pts[i][1]) / dx);
  }
  const t: number[] = new Array(n);
  t[0] = m[0];
  t[n - 1] = m[n - 2];
  for (let i = 1; i < n - 1; i++) t[i] = m[i - 1] * m[i] <= 0 ? 0 : (m[i - 1] + m[i]) / 2;
  for (let i = 0; i < n - 1; i++) {
    if (m[i] === 0) {
      t[i] = 0;
      t[i + 1] = 0;
      continue;
    }
    const a = t[i] / m[i];
    const b = t[i + 1] / m[i];
    const s = a * a + b * b;
    if (s > 9) {
      const tau = 3 / Math.sqrt(s);
      t[i] = tau * a * m[i];
      t[i + 1] = tau * b * m[i];
    }
  }
  return t;
}

/** Path commands for one run, without the leading move. */
function runCommands(pts: Point[], curve: Curve): string {
  if (pts.length === 1) return "";
  let d = "";
  if (curve === "step") {
    for (let i = 1; i < pts.length; i++) d += `H${r(pts[i][0])}V${r(pts[i][1])}`;
    return d;
  }
  if (curve === "step-before") {
    for (let i = 1; i < pts.length; i++) d += `V${r(pts[i][1])}H${r(pts[i][0])}`;
    return d;
  }
  if (curve === "monotone" && pts.length > 2) {
    const t = monotoneTangents(pts);
    for (let i = 0; i < pts.length - 1; i++) {
      const [x0, y0] = pts[i];
      const [x1, y1] = pts[i + 1];
      const dx = (x1 - x0) / 3;
      d += `C${r(x0 + dx)},${r(y0 + t[i] * dx)},${r(x1 - dx)},${r(y1 - t[i + 1] * dx)},${r(x1)},${r(y1)}`;
    }
    return d;
  }
  for (let i = 1; i < pts.length; i++) d += `L${r(pts[i][0])},${r(pts[i][1])}`;
  return d;
}

/** A line through the points; nulls break the line. Single isolated points produce no path (draw a dot). */
export function linePath(points: MaybePoint[], curve: Curve = "linear"): string {
  return segments(points)
    .filter((s) => s.length > 1)
    .map((s) => `M${r(s[0][0])},${r(s[0][1])}${runCommands(s, curve)}`)
    .join("");
}

/** Points that have no neighbour on either side; they need a visible dot because a line can't show them. */
export function isolatedPoints(points: MaybePoint[]): Point[] {
  return segments(points)
    .filter((s) => s.length === 1)
    .map((s) => s[0]);
}

/**
 * Area between a top line and a baseline. `base` is a constant y (e.g. the zero line) or a matching list of points
 * (stacked areas). Gaps in either list break the area.
 */
export function areaPath(top: MaybePoint[], base: number | MaybePoint[], curve: Curve = "linear"): string {
  const bottom: MaybePoint[] = typeof base === "number" ? top.map((p) => (p ? [p[0], base] : null)) : base;
  const ok = (p: MaybePoint | undefined): p is Point => !!p && Number.isFinite(p[0]) && Number.isFinite(p[1]);
  const runs: number[][] = [];
  let run: number[] = [];
  top.forEach((p, i) => {
    if (ok(p) && ok(bottom[i])) run.push(i);
    else if (run.length) {
      runs.push(run);
      run = [];
    }
  });
  if (run.length) runs.push(run);
  const bottomCurve: Curve = curve === "step" ? "step-before" : curve === "step-before" ? "step" : curve;
  let d = "";
  for (const idx of runs) {
    if (idx.length < 2) continue;
    const t = idx.map((i) => top[i] as Point);
    const b = idx.map((i) => bottom[i] as Point).reverse();
    d += `M${r(t[0][0])},${r(t[0][1])}${runCommands(t, curve)}`;
    d += `L${r(b[0][0])},${r(b[0][1])}${runCommands(b, bottomCurve)}Z`;
  }
  return d;
}

export type BarEnd = "up" | "down" | "left" | "right";

/**
 * A bar with a rounded data end and a square baseline. (x, y) is the top-left corner. `end` says which side
 * carries the value.
 */
export function barPath(x: number, y: number, w: number, h: number, radius = 4, end: BarEnd = "up"): string {
  if (w <= 0 || h <= 0) return "";
  const rad = Math.max(0, Math.min(radius, end === "up" || end === "down" ? w / 2 : h / 2, end === "up" || end === "down" ? h : w));
  const x1 = x + w;
  const y1 = y + h;
  const a = (ex: number, ey: number) => `A${r(rad)},${r(rad)} 0 0 1 ${r(ex)},${r(ey)}`;
  switch (end) {
    case "up":
      return `M${r(x)},${r(y1)}V${r(y + rad)}${a(x + rad, y)}H${r(x1 - rad)}${a(x1, y + rad)}V${r(y1)}Z`;
    case "down":
      return `M${r(x1)},${r(y)}V${r(y1 - rad)}${a(x1 - rad, y1)}H${r(x + rad)}${a(x, y1 - rad)}V${r(y)}Z`;
    case "right":
      return `M${r(x)},${r(y)}H${r(x1 - rad)}${a(x1, y + rad)}V${r(y1 - rad)}${a(x1 - rad, y1)}H${r(x)}Z`;
    case "left":
      return `M${r(x1)},${r(y1)}H${r(x + rad)}${a(x, y1 - rad)}V${r(y + rad)}${a(x + rad, y)}H${r(x1)}Z`;
  }
}

/** Rectangle with all four corners rounded (cells, tiles, segments). */
export function roundedRect(x: number, y: number, w: number, h: number, radius = 2): string {
  if (w <= 0 || h <= 0) return "";
  const rad = Math.max(0, Math.min(radius, w / 2, h / 2));
  const a = (ex: number, ey: number) => `A${r(rad)},${r(rad)} 0 0 1 ${r(ex)},${r(ey)}`;
  return `M${r(x + rad)},${r(y)}H${r(x + w - rad)}${a(x + w, y + rad)}V${r(y + h - rad)}${a(x + w - rad, y + h)}H${r(
    x + rad,
  )}${a(x, y + h - rad)}V${r(y + rad)}${a(x + rad, y)}Z`;
}

/** Donut / pie sector. Angles in radians, 0 = 12 o'clock, clockwise. */
export function arcPath(cx: number, cy: number, inner: number, outer: number, start: number, end: number): string {
  const sweep = end - start;
  if (sweep <= 0) return "";
  if (sweep >= Math.PI * 2 - 1e-6) {
    // full ring: two halves
    const mid = start + Math.PI;
    return arcPath(cx, cy, inner, outer, start, mid) + arcPath(cx, cy, inner, outer, mid, start + Math.PI * 2 - 1e-6);
  }
  const p = (rad: number, a: number): Point => [cx + rad * Math.sin(a), cy - rad * Math.cos(a)];
  const large = sweep > Math.PI ? 1 : 0;
  const [ox0, oy0] = p(outer, start);
  const [ox1, oy1] = p(outer, end);
  let d = `M${r(ox0)},${r(oy0)}A${r(outer)},${r(outer)} 0 ${large} 1 ${r(ox1)},${r(oy1)}`;
  if (inner > 0) {
    const [ix1, iy1] = p(inner, end);
    const [ix0, iy0] = p(inner, start);
    d += `L${r(ix1)},${r(iy1)}A${r(inner)},${r(inner)} 0 ${large} 0 ${r(ix0)},${r(iy0)}Z`;
  } else {
    d += `L${r(cx)},${r(cy)}Z`;
  }
  return d;
}
```

### components/charts/core/scale.ts

```ts
// core/scale.ts · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com
/** Minimal scales: linear, band, point and UTC time. Pure functions, no dependencies. */
import type { DateGrain } from "./format";

export interface LinearScale {
  (value: number): number;
  domain: [number, number];
  range: [number, number];
  invert(px: number): number;
}

export function linearScale(domain: [number, number], range: [number, number]): LinearScale {
  const [d0, d1] = domain;
  const [r0, r1] = range;
  const span = d1 - d0 || 1;
  const fn = ((v: number) => r0 + ((v - d0) / span) * (r1 - r0)) as LinearScale;
  fn.domain = domain;
  fn.range = range;
  fn.invert = (px: number) => d0 + ((px - r0) / (r1 - r0 || 1)) * span;
  return fn;
}

function tickStep(min: number, max: number, count: number) {
  const raw = Math.abs(max - min) / Math.max(1, count);
  if (raw === 0 || !Number.isFinite(raw)) return 1;
  const power = Math.floor(Math.log10(raw));
  const base = 10 ** power;
  const err = raw / base;
  const mult = err >= 7.5 ? 10 : err >= 3.5 ? 5 : err >= 1.5 ? 2 : 1;
  return mult * base;
}

/** Round numbers covering [min, max], about `count` intervals. */
export function niceTicks(min: number, max: number, count = 5): number[] {
  if (!Number.isFinite(min) || !Number.isFinite(max)) return [0];
  if (min === max) {
    if (min === 0) return [0, 1];
    const pad = Math.abs(min) * 0.1;
    return niceTicks(min - pad, max + pad, count);
  }
  if (min > max) [min, max] = [max, min];
  const step = tickStep(min, max, count);
  const start = Math.floor(min / step) * step;
  const stop = Math.ceil(max / step) * step;
  const ticks: number[] = [];
  const decimals = Math.max(0, -Math.floor(Math.log10(step)) + 1);
  for (let v = start, i = 0; v <= stop + step / 2 && i < 100; v += step, i++) {
    ticks.push(Number(v.toFixed(decimals)) + 0);
  }
  return ticks.map((t) => (Object.is(t, -0) ? 0 : t));
}

export interface ValueDomainOptions {
  /** Force zero into the domain (required for bars, columns and areas). */
  includeZero?: boolean;
  /** Target number of tick intervals. */
  ticks?: number;
  /** Explicit domain; null entries are computed. */
  domain?: [number | null, number | null];
}

/** Compute a nice domain + ticks for a set of values (non-finite values are ignored). */
export function valueDomain(values: number[], opts: ValueDomainOptions = {}) {
  const finite = values.filter((v) => Number.isFinite(v));
  let min = finite.length ? Math.min(...finite) : 0;
  let max = finite.length ? Math.max(...finite) : 1;
  if (opts.includeZero) {
    min = Math.min(0, min);
    max = Math.max(0, max);
  }
  const fixedMin = opts.domain?.[0];
  const fixedMax = opts.domain?.[1];
  if (fixedMin != null) min = fixedMin;
  if (fixedMax != null) max = fixedMax;
  const ticks = niceTicks(min, max, opts.ticks ?? 5);
  const lo = fixedMin ?? ticks[0];
  const hi = fixedMax ?? ticks[ticks.length - 1];
  return { domain: [lo, hi] as [number, number], ticks: ticks.filter((t) => t >= lo - 1e-9 && t <= hi + 1e-9) };
}

export interface BandScale {
  (index: number): number;
  bandwidth: number;
  step: number;
  count: number;
  /** index of the band that contains px, clamped. */
  indexAt(px: number): number;
}

/** Evenly spaced bands for categorical bars. */
export function bandScale(
  count: number,
  range: [number, number],
  opts: { paddingInner?: number; paddingOuter?: number } = {},
): BandScale {
  const inner = opts.paddingInner ?? 0.25;
  const outer = opts.paddingOuter ?? 0.12;
  const [r0, r1] = range;
  const n = Math.max(1, count);
  const step = (r1 - r0) / Math.max(1, n - inner + outer * 2);
  const bandwidth = step * (1 - inner);
  const start = r0 + step * outer;
  const fn = ((i: number) => start + i * step) as BandScale;
  fn.bandwidth = Math.max(0, bandwidth);
  fn.step = step;
  fn.count = count;
  fn.indexAt = (px: number) => Math.max(0, Math.min(count - 1, Math.floor((px - start + (step * inner) / 2) / step)));
  return fn;
}

export interface PointScale {
  (index: number): number;
  step: number;
  count: number;
  indexAt(px: number): number;
}

/** Evenly spaced points for categorical lines (first and last point sit at the edges, with padding). */
export function pointScale(count: number, range: [number, number], padding = 0): PointScale {
  const [r0, r1] = range;
  const n = Math.max(1, count);
  const step = n === 1 ? 0 : (r1 - r0 - padding * 2) / (n - 1);
  const fn = ((i: number) => (n === 1 ? (r0 + r1) / 2 : r0 + padding + i * step)) as PointScale;
  fn.step = step;
  fn.count = count;
  fn.indexAt = (px: number) =>
    n === 1 ? 0 : Math.max(0, Math.min(n - 1, Math.round((px - r0 - padding) / (step || 1))));
  return fn;
}

/** Index of the value in a sorted array nearest to target. */
export function nearestIndex(sorted: number[], target: number): number {
  if (!sorted.length) return -1;
  let lo = 0;
  let hi = sorted.length - 1;
  while (hi - lo > 1) {
    const mid = (lo + hi) >> 1;
    if (sorted[mid] < target) lo = mid;
    else hi = mid;
  }
  return Math.abs(sorted[lo] - target) <= Math.abs(sorted[hi] - target) ? lo : hi;
}

// ---------- time ----------

const DAY = 86_400_000;

interface TimeInterval {
  grain: DateGrain;
  ms: number;
  step: number;
  unit: "day" | "month" | "year";
}

const INTERVALS: TimeInterval[] = [
  { grain: "day", ms: DAY, step: 1, unit: "day" },
  { grain: "day", ms: 2 * DAY, step: 2, unit: "day" },
  { grain: "week", ms: 7 * DAY, step: 7, unit: "day" },
  { grain: "week", ms: 14 * DAY, step: 14, unit: "day" },
  { grain: "month", ms: 30 * DAY, step: 1, unit: "month" },
  { grain: "month", ms: 61 * DAY, step: 2, unit: "month" },
  { grain: "quarter", ms: 91 * DAY, step: 3, unit: "month" },
  { grain: "month", ms: 182 * DAY, step: 6, unit: "month" },
  { grain: "year", ms: 365 * DAY, step: 1, unit: "year" },
  { grain: "year", ms: 730 * DAY, step: 2, unit: "year" },
  { grain: "year", ms: 1826 * DAY, step: 5, unit: "year" },
  { grain: "year", ms: 3652 * DAY, step: 10, unit: "year" },
];

/** Calendar-aligned UTC ticks between min and max (ms). */
export function timeTicks(min: number, max: number, count = 6): { ticks: number[]; grain: DateGrain } {
  if (!Number.isFinite(min) || !Number.isFinite(max) || max <= min) return { ticks: [min], grain: "day" };
  const target = (max - min) / Math.max(1, count);
  const interval = INTERVALS.find((i) => i.ms >= target) ?? INTERVALS[INTERVALS.length - 1];
  const ticks: number[] = [];
  const start = new Date(min);
  let cursor: Date;
  if (interval.unit === "day") {
    cursor = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate()));
    if (interval.step === 7 || interval.step === 14) {
      // align to Monday
      const dow = (cursor.getUTCDay() + 6) % 7;
      cursor = new Date(cursor.getTime() - dow * DAY);
    }
  } else if (interval.unit === "month") {
    const m = Math.floor(start.getUTCMonth() / interval.step) * interval.step;
    cursor = new Date(Date.UTC(start.getUTCFullYear(), m, 1));
  } else {
    const y = Math.floor(start.getUTCFullYear() / interval.step) * interval.step;
    cursor = new Date(Date.UTC(y, 0, 1));
  }
  let guard = 0;
  while (cursor.getTime() <= max && guard++ < 500) {
    if (cursor.getTime() >= min) ticks.push(cursor.getTime());
    if (interval.unit === "day") cursor = new Date(cursor.getTime() + interval.step * DAY);
    else if (interval.unit === "month")
      cursor = new Date(Date.UTC(cursor.getUTCFullYear(), cursor.getUTCMonth() + interval.step, 1));
    else cursor = new Date(Date.UTC(cursor.getUTCFullYear() + interval.step, 0, 1));
  }
  return { ticks, grain: interval.grain };
}

// ---------- colour steps ----------

/** Map a value to a sequential step 1..steps (1 = lowest). Equal-width bins between min and max. */
export function sequentialStep(value: number, min: number, max: number, steps = 7): number {
  if (!Number.isFinite(value)) return 0;
  if (max <= min) return Math.ceil(steps / 2);
  const t = (value - min) / (max - min);
  return Math.max(1, Math.min(steps, Math.floor(t * steps) + 1));
}

/** Map a value to a diverging step -3..3 around `center` (0 = within the neutral band). */
export function divergingStep(value: number, maxAbs: number, center = 0): number {
  if (!Number.isFinite(value) || maxAbs <= 0) return 0;
  const t = (value - center) / maxAbs;
  const a = Math.abs(t);
  const s = a < 1 / 7 ? 0 : a < 3 / 7 ? 1 : a < 5 / 7 ? 2 : 3;
  return t < 0 ? -s : s;
}
```

### components/charts/core/series.tsx

```tsx
// core/series.tsx · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com
"use client";

/**
 * Shared engine for line, area, stacked-area, step and index charts: one x axis (categories or time), one y axis
 * (never two), gaps for missing values, forecast/partial periods, end labels, a crosshair tooltip and keyboard
 * navigation. The public chart files (line-chart.tsx, area-chart.tsx, ...) are thin wrappers around it.
 */

import { useMemo, type PointerEvent } from "react";
import { AXIS_FONT, PeriodShade, RefLine, XLabels, YGrid, axisWidth, placeEndLabels } from "./axis";
import { seriesColors, PALETTE_SIZE } from "./color";
import { checkRows, column, parseDate, type Issue, type Row } from "./data";
import { formatDate, formatValue, tickFormatter, type DateGrain, type FormatInput } from "./format";
import {
  ChartFrame,
  ChartTooltip,
  localPoint,
  useActiveIndex,
  useSeriesToggle,
  type FrameProps,
  type LegendItem,
  type TableData,
  type TooltipRow,
} from "./frame";
import { areaPath, isolatedPoints, linePath, type Curve, type MaybePoint } from "./path";
import { linearScale, nearestIndex, pointScale, timeTicks, valueDomain } from "./scale";
import { textWidth } from "./text";
import { useWords } from "./words";

export interface SeriesDef {
  key: string;
  label?: string;
  /** Any CSS colour. Defaults to the categorical order (or grey context when `highlight` is used). */
  color?: string;
  /** Draw this whole series dashed (e.g. a plan or target line). */
  dashed?: boolean;
}

export type SeriesInput = string | SeriesDef;

export interface Reference {
  value: number;
  label?: string;
}

export interface SeriesChartProps extends FrameProps {
  data: Row[];
  /** Key of the x value in each row. */
  x: string;
  series: SeriesInput[];
  /** "category" treats x as labels (default); "time" reads ISO strings, Date or ms and spaces by real time. */
  xType?: "category" | "time";
  /** Date grain used to label time axes and tooltips. Auto-detected if omitted. */
  grain?: DateGrain;
  /** Y value format, e.g. "currency", { kind: "percent" }, or a function. */
  format?: FormatInput;
  curve?: Curve;
  /** Series key(s) to emphasise; others are drawn as grey context. */
  highlight?: string | string[];
  /** First x value that is a forecast. From there on lines are dashed and the region is shaded. */
  forecastFrom?: string | number | Date;
  /** First x value that is an incomplete period (e.g. month to date). */
  partialFrom?: string | number | Date;
  /** Include zero in the y axis. Default true; set false to zoom in on a rate (lines only). */
  zero?: boolean;
  /** Fixed y domain; null keeps the computed bound. */
  yDomain?: [number | null, number | null];
  references?: Reference[];
  /** Dots on every point. Default: only when there are few points. */
  markers?: boolean;
  /** Series names at the line ends. Default: on when up to 4 series fit. */
  endLabels?: boolean;
  /** Show the legend. Default: on for 2+ series. */
  legend?: boolean;
  /** Click legend entries to hide/show series. Default true for 2+ series. */
  toggleable?: boolean;
}

export type SeriesKind = "line" | "area" | "stacked" | "stacked100";

const DAY = 86_400_000;

function guessGrain(times: number[]): DateGrain {
  if (times.length < 2) return "day";
  const gaps = times
    .slice(1)
    .map((t, i) => t - times[i])
    .filter((g) => g > 0)
    .sort((a, b) => a - b);
  const g = gaps[Math.floor(gaps.length / 2)] ?? DAY;
  if (g >= 360 * DAY) return "year";
  if (g >= 89 * DAY) return "quarter";
  if (g >= 27 * DAY) return "month";
  if (g >= 6.5 * DAY) return "week";
  return "day";
}

export function normalizeSeries(series: SeriesInput[]): SeriesDef[] {
  return (series ?? []).map((s) => (typeof s === "string" ? { key: s, label: s } : { ...s, label: s.label ?? s.key }));
}

/** Index of the first x at or after `from`, or -1. */
function indexFrom(xs: unknown[], times: number[] | null, from: string | number | Date | undefined): number {
  if (from === undefined || from === null) return -1;
  if (times) {
    const t = parseDate(from);
    if (t === null) return -1;
    return times.findIndex((v) => v >= t);
  }
  return xs.findIndex((v) => String(v) === String(from));
}

export function SeriesChart(props: SeriesChartProps & { kind: SeriesKind; summaryName?: string }) {
  const {
    data,
    x,
    series: seriesInput,
    xType = "category",
    format,
    curve = "linear",
    highlight,
    forecastFrom,
    partialFrom,
    zero = true,
    yDomain,
    references = [],
    markers,
    endLabels,
    legend,
    toggleable,
    kind,
    summaryName,
    height = 280,
    ...frame
  } = props;

  const series = useMemo(() => normalizeSeries(seriesInput), [seriesInput]);
  const keys = series.map((s) => s.key);
  const toggle = useSeriesToggle(keys);
  const stacked = kind === "stacked" || kind === "stacked100";

  const keySig = keys.join("|");
  const prepared = useMemo(() => {
    const issues: Issue[] = checkRows(data, {
      xKey: x,
      valueKeys: keys,
      maxSeries: PALETTE_SIZE,
      allowMissing: true,
    });
    const rows = Array.isArray(data) ? data : [];
    let times: number[] | null = null;
    let order = rows.map((_, i) => i);
    if (xType === "time" && rows.length) {
      const parsed = rows.map((r) => parseDate(r?.[x]));
      const bad = parsed.filter((t) => t === null).length;
      if (bad) issues.push({ level: "error", message: `${bad} row(s) have an unreadable date in "${x}".` });
      order = order.filter((i) => parsed[i] !== null).sort((a, b) => parsed[a]! - parsed[b]!);
      times = order.map((i) => parsed[i]!);
    }
    const sorted = order.map((i) => rows[i]);
    const cols = Object.fromEntries(keys.map((k) => [k, column(sorted, k).values]));
    if (stacked) {
      for (const k of keys) {
        if (cols[k].some((v) => v !== null && v < 0)) {
          issues.push({
            level: "error",
            message: `Stacked areas can't show negative values ("${k}" has some). Use a line chart or stacked bars.`,
          });
          break;
        }
      }
    }
    return { issues, rows: sorted, times, cols };
  }, [data, x, keySig, xType, stacked]); // eslint-disable-line react-hooks/exhaustive-deps

  const { issues, rows, times, cols } = prepared;
  const n = rows.length;
  const grain = props.grain ?? (times ? guessGrain(times) : "month");
  const xLabel = (i: number) =>
    times ? formatDate(times[i], grain, "long") : String(rows[i]?.[x] ?? "");

  const colors = seriesColors(series, highlight);
  const visible = series.filter((s) => !toggle.hidden.has(s.key));

  // stacked values: per index, cumulative bottom/top for each visible series. Any missing cell breaks the column.
  const visibleSig = visible.map((s) => s.key).join("|");
  const stack = useMemo(() => {
    if (!stacked) return null;
    const bottoms: Record<string, (number | null)[]> = {};
    const tops: Record<string, (number | null)[]> = {};
    const totals: (number | null)[] = [];
    for (let i = 0; i < n; i++) {
      const vals = visible.map((s) => cols[s.key]?.[i] ?? null);
      const broken = vals.some((v) => v === null);
      const total = broken ? null : vals.reduce<number>((a, b) => a + (b ?? 0), 0);
      totals.push(total);
      let acc = 0;
      visible.forEach((s, j) => {
        bottoms[s.key] ??= [];
        tops[s.key] ??= [];
        if (broken || total === null || (kind === "stacked100" && total === 0)) {
          bottoms[s.key].push(null);
          tops[s.key].push(null);
          return;
        }
        const v = kind === "stacked100" ? vals[j]! / total : vals[j]!;
        bottoms[s.key].push(acc);
        acc += v;
        tops[s.key].push(acc);
      });
    }
    return { bottoms, tops, totals };
  }, [stacked, kind, n, cols, visibleSig]); // eslint-disable-line react-hooks/exhaustive-deps

  const yFormat: FormatInput | undefined = kind === "stacked100" ? { kind: "percent", decimals: 0 } : format;

  const fIndex = indexFrom(rows.map((r) => r?.[x]), times, forecastFrom);
  const pIndex = indexFrom(rows.map((r) => r?.[x]), times, partialFrom);
  const splitAt = fIndex > 0 ? fIndex : pIndex > 0 ? pIndex : -1;

  const allValues: number[] = [];
  if (stack) {
    for (const k of Object.keys(stack.tops)) for (const v of stack.tops[k]) if (v !== null) allValues.push(v);
  } else {
    for (const s of visible) for (const v of cols[s.key] ?? []) if (v !== null) allValues.push(v);
  }
  for (const r of references) allValues.push(r.value);

  const tableData: TableData = {
    columns: [
      { key: "__x", label: x },
      ...series.map((s) => ({
        key: s.key,
        label: s.label!,
        align: "right" as const,
        format: (v: unknown) => formatValue(v as number, format, { context: "table" }),
      })),
    ],
    rows: rows.map((r, i) => ({
      __x: times ? new Date(times[i]).toISOString().slice(0, 10) : r?.[x],
      ...Object.fromEntries(series.map((s) => [s.key, cols[s.key]?.[i] ?? null])),
    })),
  };

  const legendItems: LegendItem[] =
    legend === false || (legend === undefined && series.length < 2)
      ? []
      : series.map((s) => ({
          key: s.key,
          label: s.label!,
          color: colors[s.key],
          shape: stacked || kind === "area" ? "square" : s.dashed ? "dash" : "line",
        }));

  const summary = buildSummary(summaryName ?? kind, series, cols, n, xLabel, format);

  return (
    <ChartFrame
      {...frame}
      height={height}
      issues={issues}
      table={tableData}
      summary={summary}
      legend={legendItems}
      legendHidden={toggle.hidden}
      onLegendToggle={(toggleable ?? series.length > 1) ? toggle.toggle : undefined}
      onLegendHover={toggle.setFocus}
    >
      {({ width }) => (
        <SeriesPlot
          width={width}
          height={height}
          n={n}
          times={times}
          rows={rows}
          x={x}
          grain={grain}
          series={series}
          visible={visible}
          cols={cols}
          stack={stack}
          kind={kind}
          colors={colors}
          curve={curve}
          yFormat={yFormat}
          format={format}
          allValues={allValues}
          zero={zero || kind !== "line"}
          yDomain={kind === "stacked100" ? [0, 1] : yDomain}
          references={references}
          markers={markers}
          endLabels={endLabels}
          fIndex={fIndex}
          pIndex={pIndex}
          splitAt={splitAt}
          xLabel={xLabel}
          focus={toggle.focus}
          highlight={highlight}
        />
      )}
    </ChartFrame>
  );
}

function buildSummary(
  name: string,
  series: SeriesDef[],
  cols: Record<string, (number | null)[]>,
  n: number,
  xLabel: (i: number) => string,
  format?: FormatInput,
) {
  if (!n) return `${name} chart with no data.`;
  const parts = series.slice(0, 4).map((s) => {
    const vals = (cols[s.key] ?? []).filter((v): v is number => v !== null);
    if (!vals.length) return `${s.label}: no values`;
    const first = vals[0];
    const last = vals[vals.length - 1];
    return `${s.label} from ${formatValue(first, format)} to ${formatValue(last, format)} (min ${formatValue(
      Math.min(...vals),
      format,
    )}, max ${formatValue(Math.max(...vals), format)})`;
  });
  return `${name[0].toUpperCase()}${name.slice(1)} chart, ${n} points from ${xLabel(0)} to ${xLabel(n - 1)}. ${parts.join(
    "; ",
  )}.${series.length > 4 ? ` ${series.length - 4} more series in the table view.` : ""} Use arrow keys to read values.`;
}

interface PlotProps {
  width: number;
  height: number;
  n: number;
  times: number[] | null;
  rows: Row[];
  x: string;
  grain: DateGrain;
  series: SeriesDef[];
  visible: SeriesDef[];
  cols: Record<string, (number | null)[]>;
  stack: { bottoms: Record<string, (number | null)[]>; tops: Record<string, (number | null)[]>; totals: (number | null)[] } | null;
  kind: SeriesKind;
  colors: Record<string, string>;
  curve: Curve;
  yFormat?: FormatInput;
  format?: FormatInput;
  allValues: number[];
  zero: boolean;
  yDomain?: [number | null, number | null];
  references: Reference[];
  markers?: boolean;
  endLabels?: boolean;
  fIndex: number;
  pIndex: number;
  splitAt: number;
  xLabel: (i: number) => string;
  focus: string | null;
  highlight?: string | string[];
}

function SeriesPlot(p: PlotProps) {
  const L = useWords();
  const { width, height, n, times, cols, stack, kind, colors, curve, visible } = p;
  const { active, setActive, keyProps } = useActiveIndex(n, { describe: (i) => ({ label: p.xLabel(i), row: p.rows[i] }) });
  const stacked = !!stack;

  const tickCount = Math.max(2, Math.min(6, Math.floor(height / 50)));
  const { domain, ticks } = valueDomain(p.allValues, { includeZero: p.zero, ticks: tickCount, domain: p.yDomain });
  const fmtTick = tickFormatter(p.yFormat, ticks);
  const tickLabels = ticks.map(fmtTick);

  // end labels: names at line ends (lines only, up to 4 visible series, enough width)
  const lastIndex = (key: string) => {
    const vals = stacked ? stack!.tops[key] : cols[key];
    for (let i = (vals?.length ?? 0) - 1; i >= 0; i--) if (vals[i] !== null) return i;
    return -1;
  };
  const wantEnd =
    p.endLabels ?? (kind === "line" && visible.length >= 2 && visible.length <= 4 && width >= 420);
  const endLabelWidth = wantEnd
    ? Math.min(140, Math.max(...visible.map((s) => textWidth(s.label!, AXIS_FONT))) + 14)
    : 0;

  const forecastLabel = p.fIndex > 0 || p.pIndex > 0;
  const top = forecastLabel ? 20 : 8;
  const bottom = height - 24;
  const left = axisWidth(tickLabels);
  const right = width - Math.max(10, endLabelWidth);

  const y = linearScale(domain, [bottom, top]);
  const xs: number[] = (() => {
    if (times && times.length) {
      const t0 = times[0];
      const t1 = times[times.length - 1];
      const sx = linearScale([t0, t1 === t0 ? t0 + 1 : t1], [left + 4, right - 4]);
      return times.map((t) => (t1 === t0 ? (left + right) / 2 : sx(t)));
    }
    const ps = pointScale(n, [left, right], Math.min(24, (right - left) / Math.max(2, n) / 2));
    return Array.from({ length: n }, (_, i) => ps(i));
  })();

  const pts = (vals: (number | null)[] | undefined): MaybePoint[] =>
    (vals ?? []).map((v, i) => (v === null || v === undefined ? null : [xs[i], y(v)]));

  // x axis labels
  let xAxis;
  if (times && times.length > 1) {
    const { ticks: tt, grain: tg } = timeTicks(times[0], times[times.length - 1], Math.max(2, Math.floor((right - left) / 80)));
    const sx = linearScale([times[0], times[times.length - 1]], [left + 4, right - 4]);
    xAxis = (
      <XLabels
        positions={tt.map((t) => sx(t))}
        labels={tt.map((t) => formatDate(t, tg === "week" ? "day" : tg))}
        y={bottom + 17}
        anchorEnds
        x0={left - 8}
        x1={width}
        ticks
        tickTop={bottom}
      />
    );
  } else {
    xAxis = (
      <XLabels
        positions={xs}
        labels={p.rows.map((r, i) => (times ? formatDate(times[i], p.grain) : String(r?.[p.x] ?? "")))}
        y={bottom + 17}
        anchorEnds
        x0={left - 8}
        x1={width}
      />
    );
  }

  const splitX = (idx: number) => (idx <= 0 ? null : (xs[idx - 1] + xs[idx]) / 2);
  const fx = splitX(p.fIndex);
  const px = splitX(p.pIndex);

  const onMove = (e: PointerEvent<SVGRectElement>) => {
    const { x: mx } = localPoint(e);
    const px0 = mx + left;
    setActive(times ? nearestIndex(xs, px0) : nearestIndex(xs, px0));
  };

  const isDim = (key: string) => p.focus !== null && p.focus !== key;
  const hl = p.highlight === undefined ? null : new Set(Array.isArray(p.highlight) ? p.highlight : [p.highlight]);
  // context series first so highlighted ones sit on top
  const drawOrder = [...visible].sort((a, b) => Number(hl?.has(a.key) ?? 0) - Number(hl?.has(b.key) ?? 0));

  const showMarkers = p.markers ?? n <= 12;

  const lines = drawOrder.map((s) => {
    const vals = stacked ? stack!.tops[s.key] : cols[s.key];
    const all = pts(vals);
    const c = colors[s.key];
    const isContext = hl !== null && !hl.has(s.key);
    const strokeW = isContext ? 1.5 : 2;
    const solid = p.splitAt > 0 ? all.map((pt, i) => (i < p.splitAt ? pt : null)) : all;
    const dashed = p.splitAt > 0 ? all.map((pt, i) => (i >= p.splitAt - 1 ? pt : null)) : [];
    const areaFill =
      kind === "line"
        ? null
        : stacked
          ? areaPath(all, pts(stack!.bottoms[s.key]), curve)
          : areaPath(all, y(Math.max(domain[0], Math.min(0, domain[1]))), curve);
    const dots = showMarkers ? all : isolatedPoints(all);
    return (
      <g key={s.key} className={`clui-mark${isDim(s.key) ? " clui-dim" : ""}`}>
        {areaFill && (
          <path d={areaFill} style={{ fill: c, opacity: stacked ? 0.85 : 0.12 }} stroke="none" />
        )}
        {stacked && <path d={linePath(solid, curve)} style={{ stroke: "var(--clui-surface)" }} strokeWidth={1.5} fill="none" />}
        {!stacked && (
          <>
            <path
              d={linePath(solid, curve)}
              style={{ stroke: c }}
              strokeWidth={strokeW}
              fill="none"
              strokeLinejoin="round"
              strokeLinecap="round"
              strokeDasharray={s.dashed ? "5 4" : undefined}
            />
            {dashed.length > 0 && (
              <path
                d={linePath(dashed, curve)}
                style={{ stroke: c }}
                strokeWidth={strokeW}
                fill="none"
                strokeDasharray="4 4"
                strokeLinecap="round"
              />
            )}
          </>
        )}
        {!stacked &&
          dots.map((pt, i) =>
            pt ? (
              <circle
                key={i}
                cx={pt[0]}
                cy={pt[1]}
                r={3.5}
                style={{ fill: c, stroke: "var(--clui-surface)" }}
                strokeWidth={1.5}
              />
            ) : null,
          )}
      </g>
    );
  });

  // end labels
  let endLabelEls = null;
  if (wantEnd && endLabelWidth) {
    const items = visible
      .map((s) => ({ s, i: lastIndex(s.key) }))
      .filter((o) => o.i >= 0)
      .map((o) => {
        const v = stacked ? stack!.tops[o.s.key][o.i]! : cols[o.s.key][o.i]!;
        return { ...o, y: y(v) };
      });
    const placed = placeEndLabels(
      items.map((o) => o.y),
      13,
      top,
      bottom,
    );
    if (placed) {
      endLabelEls = items.map((o, k) => (
        <text
          key={o.s.key}
          x={xs[o.i] + 8}
          y={placed[k]}
          dy="0.32em"
          className={`clui-label clui-halo${isDim(o.s.key) ? " clui-dim" : ""}`}
        >
          {o.s.label}
        </text>
      ));
    }
  }

  // tooltip
  let tip = null;
  if (active !== null && active < n) {
    const order = stacked ? [...visible].reverse() : visible;
    const rows: TooltipRow[] = order.map((s) => {
      const v = cols[s.key]?.[active] ?? null;
      const share =
        kind === "stacked100" && stack && stack.totals[active] ? (v ?? 0) / stack.totals[active]! : null;
      return {
        label: s.label!,
        value: formatValue(v, p.format, { context: "tooltip" }),
        note: share !== null ? `(${formatValue(share, { kind: "percent", decimals: 0 })})` : undefined,
        color: colors[s.key],
        shape: (stacked || kind === "area" ? "square" : "line") as "square" | "line",
      };
    });
    if (stacked && visible.length > 1) {
      rows.push({
        label: L.total,
        value: formatValue(stack!.totals[active], p.format, { context: "tooltip" }),
        strong: true,
      });
    }
    const tags = [
      p.fIndex > 0 && active >= p.fIndex ? L.forecast : null,
      p.pIndex > 0 && active >= p.pIndex ? "Partial period" : null,
    ].filter(Boolean);
    const anyVal = visible.map((s) => (stacked ? stack!.tops[s.key][active] : cols[s.key]?.[active])).find((v) => v !== null && v !== undefined);
    tip = (
      <ChartTooltip
        x={xs[active]}
        y={anyVal !== undefined && anyVal !== null ? y(anyVal) : (top + bottom) / 2}
        width={width}
        height={height}
        data={{ title: p.xLabel(active), rows, footer: tags.length ? tags.join(" · ") : undefined }}
      />
    );
  }

  return (
    <>
      <svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Chart. Use arrow keys to read values." {...keyProps}>
        {fx !== null && <PeriodShade x0={fx} x1={right} top={top - 14} bottom={bottom} label={L.forecast} />}
        {px !== null && (fx === null || px < fx) && (
          <PeriodShade x0={px} x1={fx ?? right} top={top - 14} bottom={bottom} label="Partial" kind="partial" />
        )}
        <YGrid ticks={ticks} y={y} x0={left} x1={right} format={fmtTick} />
        {xAxis}
        {p.references.map((r, i) => (
          <RefLine key={i} y={y(r.value)} x0={left} x1={right} label={r.label} />
        ))}
        {lines}
        {endLabelEls}
        {active !== null && active < n && (
          <g aria-hidden>
            <line x1={xs[active]} x2={xs[active]} y1={top} y2={bottom} style={{ stroke: "var(--clui-axis)" }} />
            {visible.map((s) => {
              const v = stacked ? stack!.tops[s.key][active] : cols[s.key]?.[active];
              if (v === null || v === undefined) return null;
              return (
                <circle
                  key={s.key}
                  cx={xs[active]}
                  cy={y(v)}
                  r={4.5}
                  style={{ fill: colors[s.key], stroke: "var(--clui-surface)" }}
                  strokeWidth={2}
                />
              );
            })}
          </g>
        )}
        <rect
          x={left}
          y={0}
          width={Math.max(0, right - left + (endLabelWidth ? 0 : 10))}
          height={bottom}
          fill="transparent"
          onPointerMove={onMove}
          onPointerDown={onMove}
          onPointerLeave={() => setActive(null)}
        />
      </svg>
      {tip}
    </>
  );
}
```

### components/charts/core/text.ts

```ts
// core/text.ts · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com
/**
 * Deterministic text measurement. An approximation of a typical UI sans-serif, good to within a few pixels. It is
 * the same on the server, in tests and in the browser, which keeps layouts and screenshots stable.
 */

const NARROW = new Set("iljtfrI.,:;'|!()[]{} ".split(""));
const WIDE = new Set("mwMW@%&".split(""));

export function textWidth(text: string, fontSize = 12): number {
  let w = 0;
  for (const ch of text) {
    if (NARROW.has(ch)) w += 0.3;
    else if (WIDE.has(ch)) w += 0.86;
    else if (ch >= "0" && ch <= "9") w += 0.57;
    else if (ch >= "A" && ch <= "Z") w += 0.66;
    else if (ch.charCodeAt(0) > 0x2e80) w += 1; // CJK and similar full-width glyphs
    else w += 0.53;
  }
  return w * fontSize;
}

/** Shorten text with an ellipsis to fit maxWidth. */
export function truncate(text: string, maxWidth: number, fontSize = 12): string {
  if (textWidth(text, fontSize) <= maxWidth) return text;
  const chars = [...text];
  let lo = 0;
  let hi = chars.length;
  while (lo < hi) {
    const mid = Math.ceil((lo + hi) / 2);
    if (textWidth(chars.slice(0, mid).join("") + "…", fontSize) <= maxWidth) lo = mid;
    else hi = mid - 1;
  }
  return lo <= 0 ? "…" : chars.slice(0, lo).join("").trimEnd() + "…";
}

/**
 * Choose which labels to show along an axis so none overlap. Keeps the first and last label where possible
 * and an even stride in between.
 */
export function thinLabels(positions: number[], labels: string[], fontSize = 11, gap = 10): boolean[] {
  const n = positions.length;
  if (n === 0) return [];
  const widths = labels.map((l) => textWidth(l, fontSize));
  for (let stride = 1; stride <= n; stride++) {
    const keep = positions.map((_, i) => i % stride === 0);
    if (stride > 1 && (n - 1) % stride !== 0) {
      // try to keep the last label if it does not collide with the previous kept one
      let lastKept = n - 1 - ((n - 1) % stride);
      const fits =
        positions[n - 1] - widths[n - 1] / 2 - (positions[lastKept] + widths[lastKept] / 2) >= gap;
      if (fits) keep[n - 1] = true;
      else if (lastKept > 0) {
        keep[lastKept] = false;
        keep[n - 1] = true;
        lastKept = n - 1;
      }
    }
    let ok = true;
    let prev = -1;
    for (let i = 0; i < n && ok; i++) {
      if (!keep[i]) continue;
      if (prev >= 0 && positions[i] - widths[i] / 2 - (positions[prev] + widths[prev] / 2) < gap) ok = false;
      prev = i;
    }
    if (ok) return keep;
  }
  return positions.map((_, i) => i === 0);
}
```

### components/charts/core/words.tsx

```tsx
// core/words.tsx · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com
"use client";

import { createContext, useContext, useMemo, type ReactNode } from "react";
import type { Row } from "./data";

/**
 * Words the charts draw themselves (table headers, tooltips, legends, the toolbar). Translate them once for the
 * whole app with <ChartWordsProvider words={…}>, or per chart with the `words` prop. Anything you leave out
 * stays in English. Your own titles, series names and column names are never touched.
 */
export interface ChartWords {
  // toolbar & legend
  table: string;
  chart: string;
  csv: string;
  downloadCsv: string;
  legend: string;
  /** Legend button tooltip, before the series name. */
  show: string;
  hide: string;
  /** Prefix of data notes under the chart. */
  note: string;
  check: string;
  /** Before the data source in the footer. */
  source: string;
  // values
  value: string;
  total: string;
  subtotal: string;
  change: string;
  share: string;
  count: string;
  median: string;
  mean: string;
  range: string;
  low: string;
  high: string;
  min: string;
  max: string;
  rank: string;
  /** "3 of 12" in ranked charts. */
  of: string;
  other: string;
  noData: string;
  // business words
  actual: string;
  forecast: string;
  partial: string;
  plan: string;
  target: string;
  increase: string;
  decrease: string;
  // time & finance
  start: string;
  end: string;
  progress: string;
  today: string;
  open: string;
  close: string;
  volume: string;
}

export const DEFAULT_WORDS: ChartWords = {
  table: "Table",
  chart: "Chart",
  csv: "CSV",
  downloadCsv: "Download data as CSV",
  legend: "Legend",
  show: "Show",
  hide: "Hide",
  note: "Note",
  check: "Check",
  source: "Source",
  value: "Value",
  total: "Total",
  subtotal: "Subtotal",
  change: "Change",
  share: "Share",
  count: "Count",
  median: "Median",
  mean: "Mean",
  range: "Range",
  low: "Low",
  high: "High",
  min: "Min",
  max: "Max",
  rank: "Rank",
  of: "of",
  other: "Other",
  noData: "No data",
  actual: "Actual",
  forecast: "Forecast",
  partial: "Partial",
  plan: "Plan",
  target: "Target",
  increase: "Increase",
  decrease: "Decrease",
  start: "Start",
  end: "End",
  progress: "Progress",
  today: "Today",
  open: "Open",
  close: "Close",
  volume: "Volume",
};

/** What a click (or Enter) on a mark reports. `row` is the data row behind the mark when the chart has one. */
export interface ChartSelectEvent {
  /** Position of the mark in the chart's own order (bar, point, cell, slice…). */
  index: number;
  /** The mark's label as shown in the tooltip, when there is one. */
  label?: string;
  row?: Row;
}

interface ChartContextValue {
  labels: ChartWords;
  onSelect?: (e: ChartSelectEvent) => void;
}

const Ctx = createContext<ChartContextValue>({ labels: DEFAULT_WORDS });

/** Translate the charts' own words for everything inside. Nest it, or use a chart's `words` prop, to override. */
export function ChartWordsProvider({ words, children }: { words: Partial<ChartWords>; children: ReactNode }) {
  const parent = useContext(Ctx);
  const value = useMemo(() => ({ ...parent, labels: { ...parent.labels, ...words } }), [parent, words]);
  return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}

/** Used by ChartFrame: one chart's `words` and `onSelect`, on top of any app-wide provider. */
export function ChartScope({ labels, onSelect, children }: { labels?: Partial<ChartWords>; onSelect?: (e: ChartSelectEvent) => void; children: ReactNode }) {
  const parent = useContext(Ctx);
  const value = useMemo(
    () => ({ labels: labels ? { ...parent.labels, ...labels } : parent.labels, onSelect: onSelect ?? parent.onSelect }),
    [parent, labels, onSelect],
  );
  return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}

/** The labels in effect. Pass a chart's own `words` prop when calling it outside ChartFrame's children. */
export function useWords(override?: Partial<ChartWords>): ChartWords {
  const { labels } = useContext(Ctx);
  return useMemo(() => (override ? { ...labels, ...override } : labels), [labels, override]);
}

/** The chart's select handler, if any. */
export function useSelectHandler(): ((e: ChartSelectEvent) => void) | undefined {
  return useContext(Ctx).onSelect;
}
```

More charts: https://chartslibraryui.com/charts · How to use with AI tools: https://chartslibraryui.com/docs/use-with-ai
