# Chart

One chart in a chat card: a trend with its previous period dashed behind it, bars grouped or stacked, or a donut breakdown. A headline carries the latest number and its change; hover or tap reads any point.

{/* Generated by scripts/build-ui-catalog.mjs from src/ui-catalog/. Do not edit. */}

One chart in a chat card: a trend with its previous period dashed behind it, bars grouped or stacked, or a donut breakdown. A headline carries the latest number and its change; hover or tap reads any point.

## When to use it

**Use it when:** The answer is a shape, not one number: a trend over time (line), amounts per period or channel (bars, grouped or stacked), or how a whole splits up (donut). One to three series, plus a previous period to compare against.

**Use something else when:** A few headline numbers without their history (KPI tiles). Exact values to look up or sort (table). More than three series, or a full report with findings (report canvas).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `displayed()` | `FUNCTION_TOOL_DISPLAYED` | As soon as the chart shows. The agent goes on; it already has every number from execute. |

## States

Besides its data, the template draws these as itself, with `mountState()`. Pick one on the preview with **State**.

| State | When it shows |
| --- | --- |
| Loading | While the card loads again in place, for example after Try again. While execute runs, the SDK shows its own loader. |
| Empty | execute found no data for the period. The card says so and the agent explains why. |
| Error | execute returned the failure as data, so the agent can explain it. Try again loads in place. |

```ts
mountState({ root, head, title: "…", state: { kind: "error", text: "…", retry } });
```

The hosted action and the in-page handler below show each case. The state types are `LoadingState`, `EmptyState` and `ErrorState` in fs-kit.

## Data

### ChartData

| Field | Type | Notes |
| --- | --- | --- |
| `type` | `"line" \| "bar" \| "donut"` | line: a trend over time. bar: amounts per period or category. donut: parts of one whole. |
| `title` | `string` |  |
| `subtitle` (optional) | `string` |  |
| `icon` (optional) | `IconName` | Default: chart, bars or pie, by type. |
| `labels` | `string[]` | The x-axis labels, oldest first. On a donut, the slice names. |
| `series` | `ChartSeries[]` | 1 to 3 series plus one compare series; more are cut. A donut draws its first series, up to 5 slices (the rest become Other). |
| `stacked` (optional) | `boolean` | Bars only: stack the series instead of grouping them. Values should be 0 or more. |
| `format` (optional) | `NumberFormat` | How the axis, the tooltip and the headline format values. |
| `headline` (optional) | `ChartHeadline` | The number above the chart, with its change. |
| `footnote` (optional) | `string` | Short note on the left of the footer, e.g. "Excludes refunds". |
| `link` (optional) | `{ label: string; href: string }` | A footer link to the full report in your app. |

### ChartSeries

| Field | Type | Notes |
| --- | --- | --- |
| `name` | `string` | The legend and tooltip name, e.g. "2026" or "Organic". |
| `values` | `number[]` | One value per label, in the same order. |
| `compare` (optional) | `boolean` | A comparison series (last year, last period, a target): muted and dashed, never stacked. At most one. |

### ChartHeadline

| Field | Type | Notes |
| --- | --- | --- |
| `value` (optional) | `number \| string` | The big number. Default: the last period's value (summed when stacked), or a donut's total. |
| `label` (optional) | `string` | What the number is, e.g. "Revenue in November". Default: the last label, or "Total" on a donut. |
| `delta` (optional) | `number` | Change in percent. Default: the last period against the compare series, or the period before. |
| `good` (optional) | `boolean` | false when up is bad (costs, churn). Default: up is good. |
| `vs` (optional) | `string` | What the change is against, e.g. "vs Nov 2025". |

## Install

Copy the template and the shared kit into your code: `agent/ui/` in an agent repo, or anywhere in your app. The template imports only `./fs-kit.js`. Then wire it up from the hosted action or the in-page handler.

- Hosted action: [TypeScript](/ui-catalog/files/ts/usage/chart.hosted.ts), [JavaScript](/ui-catalog/files/js/usage/chart.hosted.js)
- In-page handler: [TypeScript](/ui-catalog/files/ts/usage/chart.component.ts), [JavaScript](/ui-catalog/files/js/usage/chart.component.js)
- chart: [TypeScript](/ui-catalog/files/ts/chart.ts), [JavaScript](/ui-catalog/files/js/chart.js)
- fs-kit: [TypeScript](/ui-catalog/files/ts/fs-kit.ts), [JavaScript](/ui-catalog/files/js/fs-kit.js)

The hosted action needs an agent repo with one folder per action (`agent/actions/<action_key>/index.ts`). If your repo keeps its actions in `agent/actions/index.ts`, use the in-page handler: it runs the same template in your app.

All templates in machine-readable form: [/ui-catalog/catalog.json](/ui-catalog/catalog.json).

## Code

### Hosted action

```ts title="agent/actions/show_revenue_trend/index.ts"
// agent/actions/show_revenue_trend/index.ts: a hosted action.
// Copy the template (chart.ts) and fs-kit.ts into agent/ui/.

type Result = ChartData | { error: string };

export async function execute(args: { months?: number }, ctx: ActionContext): Promise<Result> {
  const res = await ctx.fetch(`/api/revenue/monthly?months=${args.months ?? 12}&compare=previous-year`);
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `The revenue report didn't load (${res.status}). Nothing changed.` };
  const r = await res.json();
  // Return every number the chart draws: the agent reads this, not the chart.
  return {
    type: "line",
    title: "Revenue by month",
    subtitle: r.periodLabel,
    labels: r.months.map((m: any) => m.label),
    series: [
      { name: String(r.year), values: r.months.map((m: any) => m.revenue) },
      { name: String(r.year - 1), values: r.months.map((m: any) => m.previousRevenue), compare: true },
    ],
    format: { style: "currency", currency: r.currency },
    headline: { value: r.latest, label: `Revenue in ${r.latestMonth}`, delta: r.latestDelta, vs: `vs ${r.latestMonth} ${r.year - 1}` },
  };
}

// Read-only in every case: the card reports displayed(result), so the agent reads the data and goes on.
export function render(result: Result, ctx: RenderContext) {
  const { root, head } = ctx.card;
  if ("error" in result) {
    mountState({ root, head, title: "Revenue by month", state: { kind: "error", text: result.error } });
  } else if (result.labels.length === 0) {
    mountState({ root, head, title: result.title, state: { kind: "empty", icon: "chart", title: "No revenue in this period", text: "Paid invoices show up here once they settle." } });
  } else {
    mount({ root, head, data: result, api: { displayed: () => ctx.card.displayed(result) } });
    return;
  }
  ctx.card.displayed(result); // the agent reads what it shows, or the error to explain
}
```

```js title="agent/actions/show_revenue_trend/index.js"
// agent/actions/show_revenue_trend/index.js: a hosted action.
// Copy the template (chart.ts) and fs-kit.ts into agent/ui/.

export async function execute(args, ctx) {
  const res = await ctx.fetch(`/api/revenue/monthly?months=${args.months ?? 12}&compare=previous-year`);
  // A failure goes back as data: the agent explains it, and the card shows it.
  if (!res.ok) return { error: `The revenue report didn't load (${res.status}). Nothing changed.` };
  const r = await res.json();
  // Return every number the chart draws: the agent reads this, not the chart.
  return {
    type: "line",
    title: "Revenue by month",
    subtitle: r.periodLabel,
    labels: r.months.map((m) => m.label),
    series: [
      { name: String(r.year), values: r.months.map((m) => m.revenue) },
      { name: String(r.year - 1), values: r.months.map((m) => m.previousRevenue), compare: true },
    ],
    format: { style: "currency", currency: r.currency },
    headline: { value: r.latest, label: `Revenue in ${r.latestMonth}`, delta: r.latestDelta, vs: `vs ${r.latestMonth} ${r.year - 1}` },
  };
}

// Read-only in every case: the card reports displayed(result), so the agent reads the data and goes on.
export function render(result, ctx) {
  const { root, head } = ctx.card;
  if ("error" in result) {
    mountState({ root, head, title: "Revenue by month", state: { kind: "error", text: result.error } });
  } else if (result.labels.length === 0) {
    mountState({ root, head, title: result.title, state: { kind: "empty", icon: "chart", title: "No revenue in this period", text: "Paid invoices show up here once they settle." } });
  } else {
    mount({ root, head, data: result, api: { displayed: () => ctx.card.displayed(result) } });
    return;
  }
  ctx.card.displayed(result); // the agent reads what it shows, or the error to explain
}
```

### In-page handler

```ts title="in-page handler.ts"
// An in-page action handler: the template runs in your page.

type Result = ChartData | { error: string };

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    show_revenue_trend: {
      // Return every number the chart draws: the agent reads this, not the chart.
      // A failure goes back as data too, so the agent can explain it.
      execute: async ({ months }: { months?: number }): Promise<Result> =>
        loadRevenueTrend(months).catch(() => ({ error: "The revenue report didn't load. Nothing changed." })),

      // Read-only: declares readyState only. The agent goes on as soon as the card reports it's shown.
      renderComponent: ({ data, host, header, readyState }: ComponentContext<Result>) => {
        // Once: on desktop a second readyState (after Retry) would start a new agent turn.
        const shown = once(readyState);
        const show = (result: Result): void => {
          if (!("error" in result)) return void mount({ root: host, head: header, data: result, api: { displayed: () => shown(result) } });
          mountState({
            root: host, head: header, title: "Revenue by month",
            state: {
              kind: "error", text: result.error,
              // Retry in the card: bones while it loads, then the chart (or the error again).
              retry: async () => {
                mountState({ root: host, head: header, title: "Revenue by month", state: { kind: "loading", label: "Loading revenue…" } });
                show(await loadRevenueTrend().catch(() => ({ error: "Still not loading. Try again in a minute." })));
              },
            },
          });
          shown(result);
        };
        show(data);
      },
    },
  });
});
```

```js title="in-page handler.js"
// An in-page action handler: the template runs in your page.

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    show_revenue_trend: {
      // Return every number the chart draws: the agent reads this, not the chart.
      // A failure goes back as data too, so the agent can explain it.
      execute: async ({ months }) =>
        loadRevenueTrend(months).catch(() => ({ error: "The revenue report didn't load. Nothing changed." })),

      // Read-only: declares readyState only. The agent goes on as soon as the card reports it's shown.
      renderComponent: ({ data, host, header, readyState }) => {
        // Once: on desktop a second readyState (after Retry) would start a new agent turn.
        const shown = once(readyState);
        const show = (result) => {
          if (!("error" in result)) return void mount({ root: host, head: header, data: result, api: { displayed: () => shown(result) } });
          mountState({
            root: host, head: header, title: "Revenue by month",
            state: {
              kind: "error", text: result.error,
              // Retry in the card: bones while it loads, then the chart (or the error again).
              retry: async () => {
                mountState({ root: host, head: header, title: "Revenue by month", state: { kind: "loading", label: "Loading revenue…" } });
                show(await loadRevenueTrend().catch(() => ({ error: "Still not loading. Try again in a minute." })));
              },
            },
          });
          shown(result);
        };
        show(data);
      },
    },
  });
});
```

### chart

```ts title="agent/ui/chart.ts"
// Template: chart. A read-only chat card with one chart: a trend over time (line), amounts per period (bars, grouped or stacked) or a breakdown (donut).

export const meta = {
  id: "chart",
  title: "Chart",
  surface: "card",
  kind: "read-only",
  mobile: "same",
  whenToUse: "The answer is a shape, not one number: a trend over time (line), amounts per period or channel (bars, grouped or stacked), or how a whole splits up (donut). One to three series, plus a previous period to compare against.",
  whenNotToUse: "A few headline numbers without their history (KPI tiles). Exact values to look up or sort (table). More than three series, or a full report with findings (report canvas).",
};

const CSS = `
.fsk-ch { container-type: inline-size; }
.fsk-ch .fsk-head > div { flex: 1; min-width: 0; }
.fsk-ch .fsk-ch-hl { display: flex; flex-direction: column; gap: 3px; margin: -2px 0 12px; }
.fsk-ch .fsk-ch-hl-row { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; }
.fsk-ch .fsk-ch-value { font-size: 1.72em; font-weight: 600; letter-spacing: -0.02em; line-height: 1.12; white-space: nowrap; }
.fsk-ch .fsk-ch-hl-meta { font-size: .86em; color: var(--k-text-2); }
.fsk-ch .fsk-ch-delta { display: inline-flex; align-items: center; gap: 2px; padding: 1px 6px 1px 4px; border-radius: 999px; font-size: .79em; font-weight: 600; line-height: 1.5; white-space: nowrap; }
.fsk-ch .fsk-ch-delta--good { color: var(--k-success); background: color-mix(in srgb, var(--k-success) 12%, var(--k-paper)); }
.fsk-ch .fsk-ch-delta--bad { color: var(--k-error); background: color-mix(in srgb, var(--k-error) 12%, var(--k-paper)); }
.fsk-ch .fsk-ch-delta--flat { color: var(--k-text-2); background: var(--k-hover); }

/* Series colors: all derived from the theme's primary, so every brand gets its own palette. */
.fsk-ch .fsk-ch-s0 { color: var(--k-primary); }
.fsk-ch .fsk-ch-s1 { color: color-mix(in oklab, var(--k-primary) 52%, var(--k-text)); }
.fsk-ch .fsk-ch-s2 { color: color-mix(in oklch, var(--k-primary) 45%, var(--k-warning)); }
.fsk-ch .fsk-ch-s3 { color: color-mix(in oklab, var(--k-primary) 40%, var(--k-paper)); }
.fsk-ch .fsk-ch-s4 { color: color-mix(in oklab, var(--k-text-2) 55%, var(--k-paper)); }
.fsk-ch .fsk-ch-cmp { color: color-mix(in srgb, var(--k-text-2) 72%, var(--k-paper)); }

/* Legend: each key shows or hides its series. */
.fsk-ch .fsk-ch-legend { display: flex; flex-wrap: wrap; gap: 2px; margin: -4px 0 6px -8px; }
.fsk-ch .fsk-ch-key {
  appearance: none; display: inline-flex; align-items: center; gap: 7px; min-height: 28px; padding: 0 8px;
  border: 0; border-radius: var(--k-r-md); background: none; color: var(--k-text-2); font: inherit; font-size: .86em; cursor: pointer;
  transition: background .15s, color .15s;
}
.fsk-ch .fsk-ch-key:hover { background: var(--k-hover); color: var(--k-text); }
.fsk-ch .fsk-ch-key:focus-visible { outline: 2px solid var(--k-primary); outline-offset: -2px; }
.fsk-ch .fsk-ch-key[aria-pressed="false"] { color: color-mix(in srgb, var(--k-text-2) 62%, var(--k-paper)); text-decoration: line-through; text-decoration-thickness: 1px; }
.fsk-ch .fsk-ch-key[aria-disabled="true"] { cursor: default; }
.fsk-ch .fsk-ch-key[aria-disabled="true"]:hover { background: none; color: var(--k-text-2); }
.fsk-ch .fsk-ch-sw { flex: none; display: inline-block; width: 10px; height: 10px; border-radius: min(var(--k-r), 3px); background: currentColor; transition: background .15s, box-shadow .15s; }
.fsk-ch[data-type="line"] .fsk-ch-key .fsk-ch-sw { width: 14px; height: 3px; border-radius: 2px; }
.fsk-ch .fsk-ch-key .fsk-ch-sw.fsk-ch-cmp, .fsk-ch .fsk-ch-tip .fsk-ch-sw.fsk-ch-cmp {
  width: 14px; height: 2px; border-radius: 0; background: repeating-linear-gradient(90deg, currentColor 0 4px, transparent 4px 7px);
}
.fsk-ch .fsk-ch-key[aria-pressed="false"] .fsk-ch-sw { background: transparent; box-shadow: inset 0 0 0 1.5px currentColor; }

/* Plot */
.fsk-ch .fsk-ch-plot { position: relative; height: 172px; margin: 0 -2px; touch-action: pan-y; border-radius: var(--k-r-md); -webkit-tap-highlight-color: transparent; }
.fsk-ch .fsk-ch-plot:focus { outline: none; }
.fsk-ch .fsk-ch-plot:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 4px; }
.fsk-ch .fsk-ch-svg { display: block; overflow: visible; }
.fsk-ch .fsk-ch-svg text { fill: var(--k-text-2); font-size: 11px; font-family: inherit; font-variant-numeric: tabular-nums; font-feature-settings: "tnum"; }
.fsk-ch .fsk-ch-grid line { stroke: color-mix(in srgb, var(--k-divider) 75%, var(--k-paper)); shape-rendering: crispEdges; }
.fsk-ch .fsk-ch-grid line.fsk-ch-base { stroke: var(--k-border); }
.fsk-ch .fsk-ch-bar { fill: currentColor; transition: opacity .15s; }
.fsk-ch .fsk-ch-bar.fsk-ch-dim { opacity: .42; }
.fsk-ch .fsk-ch-mark { stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-dasharray: 3 3; fill: none; transition: opacity .15s; }
.fsk-ch .fsk-ch-mark.fsk-ch-dim { opacity: .42; }
.fsk-ch .fsk-ch-mark-bg { stroke: var(--k-paper); stroke-width: 5; stroke-linecap: round; opacity: .9; }
.fsk-ch .fsk-ch-line { fill: none; stroke: currentColor; stroke-width: 2.25; stroke-linecap: round; stroke-linejoin: round; }
.fsk-ch .fsk-ch-line--cmp { stroke-width: 1.75; stroke-dasharray: 4 4; }
.fsk-ch .fsk-ch-halo { fill: currentColor; opacity: .16; }
.fsk-ch .fsk-ch-end { fill: currentColor; stroke: var(--k-paper); stroke-width: 2; }
.fsk-ch .fsk-ch-dot { fill: var(--k-paper); stroke: currentColor; stroke-width: 2.25; }
.fsk-ch .fsk-ch-band { fill: var(--k-hover); }
.fsk-ch .fsk-ch-cross { stroke: var(--k-text-2); stroke-opacity: .45; stroke-width: 1; shape-rendering: crispEdges; }
.fsk-ch .fsk-ch-none { margin: 0; display: grid; place-items: center; height: 100%; color: var(--k-text-2); font-size: .86em; }

.fsk-ch .fsk-ch-tip {
  position: absolute; top: 0; left: 0; z-index: 2; pointer-events: none; display: grid; gap: 4px; min-width: 132px;
  padding: 8px 10px; border: 1px solid var(--k-border); border-radius: var(--k-r-md);
  background: color-mix(in srgb, var(--k-paper) 94%, transparent); -webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px);
  box-shadow: var(--k-shadow); font-size: .79em; line-height: 1.35; white-space: nowrap;
  transition: left .14s var(--k-ease), top .14s var(--k-ease);
}
.fsk-ch .fsk-ch-tip strong { font-weight: 600; margin-bottom: 1px; }
.fsk-ch .fsk-ch-tip-row { display: flex; align-items: center; gap: 6px; color: var(--k-text-2); }
.fsk-ch .fsk-ch-tip-row b { margin-left: auto; padding-left: 14px; color: var(--k-text); font-weight: 600; }
.fsk-ch .fsk-ch-tip-total { margin-top: 2px; padding-top: 5px; border-top: 1px solid var(--k-divider); }
.fsk-ch .fsk-ch-tip .fsk-ch-delta { justify-self: start; margin-top: 2px; }

/* Donut */
.fsk-ch .fsk-ch-donut { display: grid; grid-template-columns: 132px minmax(0, 1fr); align-items: center; gap: 14px; padding: 2px 0 2px; }
.fsk-ch .fsk-ch-ring { position: relative; width: 132px; height: 132px; }
.fsk-ch .fsk-ch-ring svg { display: block; width: 100%; height: 100%; overflow: visible; transform: rotate(-90deg); }
.fsk-ch .fsk-ch-track { fill: none; stroke: var(--k-sunken); stroke-width: 13; }
.fsk-ch .fsk-ch-slice { fill: none; stroke: currentColor; stroke-width: 13; cursor: pointer; transition: opacity .18s, stroke-width .22s var(--k-ease); }
.fsk-ch .fsk-ch-ring[data-sel] .fsk-ch-slice { opacity: .26; }
.fsk-ch .fsk-ch-ring[data-sel] .fsk-ch-slice.fsk-ch-on { opacity: 1; stroke-width: 16; }
.fsk-ch .fsk-ch-center { position: absolute; inset: 0; display: grid; place-content: center; justify-items: center; gap: 1px; padding: 26px; text-align: center; pointer-events: none; }
.fsk-ch .fsk-ch-center b { font-size: 1.43em; font-weight: 600; letter-spacing: -0.02em; line-height: 1.1; }
.fsk-ch .fsk-ch-center span { max-width: 76px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: .79em; color: var(--k-text-2); }
.fsk-ch .fsk-ch-slices { display: flex; flex-direction: column; gap: 1px; min-width: 0; margin: 0 -6px 0 0; padding: 0; list-style: none; }
.fsk-ch .fsk-ch-row {
  appearance: none; display: grid; grid-template-columns: 10px minmax(0, 1fr) auto; align-items: center; column-gap: 8px; width: 100%;
  min-height: 34px; padding: 3px 6px; border: 0; border-radius: var(--k-r-md); background: none; color: inherit; font: inherit; text-align: left; cursor: pointer;
  transition: background .15s, opacity .15s;
}
.fsk-ch .fsk-ch-row:hover, .fsk-ch .fsk-ch-row[aria-pressed="true"] { background: var(--k-hover); }
.fsk-ch .fsk-ch-row:focus-visible { outline: 2px solid var(--k-primary); outline-offset: -2px; }
.fsk-ch .fsk-ch-row-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: .93em; }
.fsk-ch .fsk-ch-row-share { font-size: .93em; font-weight: 600; }
.fsk-ch .fsk-ch-row-val { grid-column: 2 / 4; margin-top: -2px; font-size: .79em; color: var(--k-text-2); }
.fsk-ch .fsk-ch-slices[data-sel] .fsk-ch-row[aria-pressed="false"] { opacity: .55; }

.fsk-ch .fsk-ch-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 10px; padding-top: 8px; border-top: 1px solid var(--k-divider); font-size: .86em; color: var(--k-text-2); }
.fsk-ch .fsk-ch-foot .fsk-btn--link { margin-right: -4px; }
.fsk-ch .fsk-ch-foot .fsk-btn--link:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }

/* Entrance, once: lines draw, bars grow, the ring sweeps. Reduced motion skips all of it (BASE_CSS). */
.fsk-ch .fsk-ch-anim .fsk-ch-bar { transform-box: fill-box; transform-origin: 50% 100%; animation: fsk-ch-grow .62s var(--k-ease) both; animation-delay: calc(var(--i, 0) * 28ms); }
.fsk-ch .fsk-ch-anim .fsk-ch-line--main { stroke-dasharray: 1; animation: fsk-ch-draw 1.05s var(--k-ease) both; }
.fsk-ch .fsk-ch-anim .fsk-ch-area, .fsk-ch .fsk-ch-anim .fsk-ch-line--cmp, .fsk-ch .fsk-ch-anim .fsk-ch-end, .fsk-ch .fsk-ch-anim .fsk-ch-halo, .fsk-ch .fsk-ch-anim .fsk-ch-mark, .fsk-ch .fsk-ch-anim .fsk-ch-mark-bg { animation: fsk-ch-fade .6s .4s ease-out both; }
.fsk-ch .fsk-ch-anim .fsk-ch-slice { animation: fsk-ch-arc .5s var(--k-ease) both; animation-delay: calc(var(--i, 0) * 90ms); }
@keyframes fsk-ch-grow { from { transform: scaleY(0); } }
@keyframes fsk-ch-draw { from { stroke-dashoffset: 1; } to { stroke-dashoffset: 0; } }
@keyframes fsk-ch-fade { from { opacity: 0; } }
@keyframes fsk-ch-arc { from { stroke-dasharray: 0 100; } }

/* Loading: the card's own shape (headline, then bars on an axis). */
.fsk-ch .fsk-ch-sk-hl { display: flex; align-items: center; gap: 8px; margin: 0 0 8px; }
.fsk-ch .fsk-ch-sk-plot { display: flex; align-items: flex-end; gap: 8px; height: 150px; padding: 8px 0 0 30px; border-bottom: 1px solid var(--k-divider); }
.fsk-ch .fsk-ch-sk-plot > span { flex: 1; display: flex; align-items: flex-end; height: 100%; }
.fsk-ch .fsk-ch-sk-plot .fsk-bone { border-radius: max(2px, calc(var(--k-r) * .75)) max(2px, calc(var(--k-r) * .75)) 0 0; }
.fsk-ch .fsk-ch-sk-axis { display: flex; justify-content: space-between; padding: 8px 0 0 30px; }

@container (max-width: 290px) {
  .fsk-ch .fsk-ch-donut { grid-template-columns: minmax(0, 1fr); justify-items: center; gap: 10px; }
  .fsk-ch .fsk-ch-slices { width: 100%; margin: 0; }
}
.fsk-ch[data-surface="mobile"] .fsk-ch-key, .fsk-ch[data-surface="mobile"] .fsk-ch-row, .fsk-ch[data-surface="mobile"] .fsk-ch-foot .fsk-btn--link { min-height: 44px; }
.fsk-ch[data-surface="mobile"] .fsk-ch-plot { height: 184px; }
.fsk-ch[data-surface="mobile"] .fsk-ch-legend { gap: 0; margin: -10px 0 0 -6px; }
.fsk-ch[data-surface="mobile"] .fsk-ch-key { padding: 0 6px; gap: 6px; }
`;

export interface ChartSeries {
  /** The legend and tooltip name, e.g. "2026" or "Organic". */
  name: string;
  /** One value per label, in the same order. */
  values: number[];
  /** A comparison series (last year, last period, a target): muted and dashed, never stacked. At most one. */
  compare?: boolean;
}

export interface ChartHeadline {
  /** The big number. Default: the last period's value (summed when stacked), or a donut's total. */
  value?: number | string;
  /** What the number is, e.g. "Revenue in November". Default: the last label, or "Total" on a donut. */
  label?: string;
  /** Change in percent. Default: the last period against the compare series, or the period before. */
  delta?: number;
  /** false when up is bad (costs, churn). Default: up is good. */
  good?: boolean;
  /** What the change is against, e.g. "vs Nov 2025". */
  vs?: string;
}

export interface ChartData {
  /** line: a trend over time. bar: amounts per period or category. donut: parts of one whole. */
  type: "line" | "bar" | "donut";
  title: string;
  subtitle?: string;
  /** Default: chart, bars or pie, by type. */
  icon?: IconName;
  /** The x-axis labels, oldest first. On a donut, the slice names. */
  labels: string[];
  /** 1 to 3 series plus one compare series; more are cut. A donut draws its first series, up to 5 slices (the rest become Other). */
  series: ChartSeries[];
  /** Bars only: stack the series instead of grouping them. Values should be 0 or more. */
  stacked?: boolean;
  /** How the axis, the tooltip and the headline format values. */
  format?: NumberFormat;
  /** The number above the chart, with its change. */
  headline?: ChartHeadline;
  /** Short note on the left of the footer, e.g. "Excludes refunds". */
  footnote?: string;
  /** A footer link to the full report in your app. */
  link?: { label: string; href: string };
}

export interface ChartProps {
  root: HTMLElement;
  head: StyleHost;
  data: ChartData;
  api?: CardApi;
  /** "mobile": a taller plot and 44px legend keys. Otherwise the same card. */
  surface?: "desktop" | "mobile";
}

let seq = 0;
const r1 = (n: number): number => Math.round(n * 10) / 10;
const sum = (xs: number[]): number => xs.reduce((a, b) => a + b, 0);
const at = (s: ChartSeries | undefined, i: number): number => {
  const v = s?.values[i];
  return typeof v === "number" && Number.isFinite(v) ? v : 0;
};

/** Up to three series to draw, then the first compare series. */
function pickSeries(all: ChartSeries[]): ChartSeries[] {
  const main = all.filter((s) => !s.compare).slice(0, 3);
  const cmp = all.find((s) => s.compare);
  return cmp ? [...main, cmp] : main;
}

function seriesClass(series: ChartSeries[], index: number): string {
  if (series[index].compare) return "fsk-ch-cmp";
  return `fsk-ch-s${series.slice(0, index).filter((x) => !x.compare).length}`;
}

/** 1, 2, 2.5 or 5 steps that cover lo..hi. */
function niceScale(lo: number, hi: number, count: number): number[] {
  if (hi === lo) hi = lo + 1;
  const raw = (hi - lo) / count;
  const mag = 10 ** Math.floor(Math.log10(raw));
  const step = ([1, 2, 2.5, 5, 10].find((m) => m * mag >= raw) ?? 10) * mag;
  const ticks: number[] = [];
  for (let k = Math.floor(lo / step); k <= Math.ceil(hi / step); k++) ticks.push(Math.round(k * step * 1e6) / 1e6);
  return ticks;
}

function axisFormat(v: number, f: NumberFormat = {}): string {
  if (f.style === "percent") return new Intl.NumberFormat(undefined, { style: "percent", maximumFractionDigits: 0 }).format(v / 100);
  const opts: Intl.NumberFormatOptions = { notation: "compact", maximumFractionDigits: 2 };
  if (f.style === "currency") Object.assign(opts, { style: "currency", currency: f.currency ?? "USD" });
  return new Intl.NumberFormat(undefined, opts).format(v);
}

/** A bar with its top corners rounded by the theme radius. */
function barPath(x: number, w: number, base: number, top: number, r: number): string {
  if (top >= base) return `M${r1(x)} ${r1(base)}h${r1(w)}V${r1(top)}H${r1(x)}Z`;
  const rr = Math.min(r, base - top, w / 2);
  return `M${r1(x)} ${r1(base)}V${r1(top + rr)}Q${r1(x)} ${r1(top)} ${r1(x + rr)} ${r1(top)}H${r1(x + w - rr)}Q${r1(x + w)} ${r1(top)} ${r1(x + w)} ${r1(top + rr)}V${r1(base)}Z`;
}

/** A smooth line that never overshoots the data (monotone cubic, as in d3's curveMonotoneX). */
function smoothPath(pts: [number, number][]): string {
  const n = pts.length;
  if (n < 3) return pts.map(([x, y], i) => `${i ? "L" : "M"}${r1(x)} ${r1(y)}`).join("");
  const t: number[] = new Array(n).fill(0);
  for (let i = 1; i < n - 1; i++) {
    const h0 = pts[i][0] - pts[i - 1][0], h1 = pts[i + 1][0] - pts[i][0];
    const s0 = (pts[i][1] - pts[i - 1][1]) / h0, s1 = (pts[i + 1][1] - pts[i][1]) / h1;
    const p = (s0 * h1 + s1 * h0) / (h0 + h1);
    t[i] = (Math.sign(s0) + Math.sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;
  }
  const end = (a: number, b: number, tb: number): number => {
    const hh = pts[b][0] - pts[a][0];
    return hh ? (3 * (pts[b][1] - pts[a][1]) / hh - tb) / 2 : tb;
  };
  t[0] = end(0, 1, t[1]);
  t[n - 1] = end(n - 2, n - 1, t[n - 2]);
  let d = `M${r1(pts[0][0])} ${r1(pts[0][1])}`;
  for (let i = 0; i < n - 1; i++) {
    const [x0, y0] = pts[i], [x1, y1] = pts[i + 1];
    const dx = (x1 - x0) / 3;
    d += `C${r1(x0 + dx)} ${r1(y0 + t[i] * dx)} ${r1(x1 - dx)} ${r1(y1 - t[i + 1] * dx)} ${r1(x1)} ${r1(y1)}`;
  }
  return d;
}

interface Headline {
  value: number | string;
  label: string;
  delta?: number;
  good: boolean;
  vs?: string;
}

function headlineOf(data: ChartData, series: ChartSeries[]): Headline | null {
  const hd = data.headline ?? {};
  const main = series.filter((s) => !s.compare);
  const cmp = series.find((s) => s.compare);
  const n = data.labels.length;
  if (data.type === "donut") {
    const total = sum(data.labels.map((_, i) => Math.max(0, at(main[0], i))));
    return { value: hd.value ?? total, label: hd.label ?? "Total", delta: hd.delta, good: hd.good ?? true, vs: hd.vs };
  }
  if (!n || !main.length) return null;
  const point = (i: number): number => (data.type === "bar" && data.stacked ? sum(main.map((s) => at(s, i))) : at(main[0], i));
  const last = point(n - 1);
  const base = cmp ? at(cmp, n - 1) : n > 1 ? point(n - 2) : 0;
  const auto = base ? Math.round(((last - base) / Math.abs(base)) * 1000) / 10 : undefined;
  return {
    value: hd.value ?? last,
    label: hd.label ?? data.labels[n - 1],
    delta: hd.delta ?? auto,
    good: hd.good ?? true,
    vs: hd.vs ?? (cmp ? `vs ${cmp.name}` : n > 1 ? `vs ${data.labels[n - 2]}` : undefined),
  };
}

function deltaPill(delta: number, good: boolean): HTMLElement {
  const sign = Math.sign(delta);
  const tone = sign === 0 ? "flat" : (sign > 0) === good ? "good" : "bad";
  return h("span", { class: `fsk-ch-delta fsk-ch-delta--${tone} fsk-num`, "aria-hidden": "true" },
    sign !== 0 && icon(sign > 0 ? "up" : "down", 12), `${Math.abs(delta)}%`);
}

function saidDelta(delta: number | undefined, vs?: string): string {
  if (delta == null) return "";
  return `, ${delta === 0 ? "no change" : `${delta > 0 ? "up" : "down"} ${Math.abs(delta)}%`}${vs ? ` ${vs}` : ""}`;
}

function headlineBlock(hl: Headline, format: NumberFormat | undefined): HTMLElement {
  const valueEl = h("span", { class: "fsk-ch-value fsk-num", "aria-hidden": "true" });
  countUp(valueEl, hl.value, format);
  return h("div", { class: "fsk-ch-hl", role: "group", "aria-label": `${hl.label}: ${formatValue(hl.value, format)}${saidDelta(hl.delta, hl.vs)}` },
    h("div", { class: "fsk-ch-hl-row" }, valueEl, hl.delta != null && deltaPill(hl.delta, hl.good)),
    h("span", { class: "fsk-ch-hl-meta", "aria-hidden": "true" }, [hl.label, hl.vs].filter(Boolean).join(" · ")));
}

/** What a screen reader hears for the chart; the full numbers follow in a hidden table. */
function summary(data: ChartData, series: ChartSeries[]): string {
  const f = (v: number): string => formatValue(v, data.format);
  const n = data.labels.length;
  const s = series.find((x) => !x.compare);
  if (!n || !s) return `${data.title}: no data.`;
  if (data.type === "donut") {
    const total = sum(data.labels.map((_, i) => Math.max(0, at(s, i)))) || 1;
    return `Donut chart: ${data.title}. ` + data.labels.map((l, i) => `${l} ${Math.round((Math.max(0, at(s, i)) / total) * 100)}% (${f(at(s, i))})`).join(", ")
      + ". The numbers are in the table that follows.";
  }
  let hi = 0, lo = 0;
  for (let i = 0; i < n; i++) { if (at(s, i) > at(s, hi)) hi = i; if (at(s, i) < at(s, lo)) lo = i; }
  const first = at(s, 0), last = at(s, n - 1);
  const change = first ? Math.round(((last - first) / Math.abs(first)) * 100) : null;
  const others = series.filter((x) => x !== s).map((x) => x.name);
  const kind = data.type === "line" ? "Line chart" : data.stacked ? "Stacked bar chart" : "Bar chart";
  return `${kind}: ${data.title}, ${data.labels[0]} to ${data.labels[n - 1]}. ${s.name} is highest in ${data.labels[hi]} (${f(at(s, hi))}) and lowest in ${data.labels[lo]} (${f(at(s, lo))})`
    + (change != null && n > 1 ? `, ${change >= 0 ? "up" : "down"} ${Math.abs(change)}% over the period.` : ".")
    + (others.length ? ` Also shows ${others.join(" and ")}.` : "") + " The numbers are in the table that follows.";
}

function dataTable(data: ChartData, series: ChartSeries[]): HTMLElement {
  const f = (v: number): string => formatValue(v, data.format);
  if (data.type === "donut") {
    const s = series.find((x) => !x.compare);
    const total = sum(data.labels.map((_, i) => Math.max(0, at(s, i)))) || 1;
    return h("table", { class: "fsk-sr" }, h("caption", {}, data.title),
      h("thead", {}, h("tr", {}, h("th", { scope: "col" }, "Slice"), h("th", { scope: "col" }, "Value"), h("th", { scope: "col" }, "Share"))),
      h("tbody", {}, data.labels.map((l, i) => h("tr", {}, h("th", { scope: "row" }, l), h("td", {}, f(at(s, i))),
        h("td", {}, `${Math.round((Math.max(0, at(s, i)) / total) * 100)}%`)))));
  }
  return h("table", { class: "fsk-sr" }, h("caption", {}, data.title),
    h("thead", {}, h("tr", {}, h("th", { scope: "col" }, "Period"), series.map((s) => h("th", { scope: "col" }, s.name)))),
    h("tbody", {}, data.labels.map((l, i) => h("tr", {}, h("th", { scope: "row" }, l), series.map((s) => h("td", {}, f(at(s, i))))))));
}

interface Drawn {
  showAt(i: number): void;
  hide(): void;
}

/** Draws a line or bar chart at the box's real size, so text never stretches. Called again on resize and on legend changes. */
function drawCartesian(box: HTMLElement, data: ChartData, all: ChartSeries[], off: Set<number>, animate: boolean): Drawn {
  const doc = box.ownerDocument;
  const win = doc.defaultView ?? window;
  const cs = win.getComputedStyle(box);
  const W = Math.max(200, Math.floor(box.clientWidth));
  const H = Math.max(120, Math.floor(box.clientHeight));
  const n = data.labels.length;
  const bar = data.type === "bar";
  const shown = all.map((s, i) => ({ s, i, cls: seriesClass(all, i) })).filter((x) => !off.has(x.i));
  const main = shown.filter((x) => !x.s.compare);
  const cmp = shown.find((x) => x.s.compare);
  const stacked = bar && !!data.stacked && main.length > 1;
  const totals = data.labels.map((_, i) => sum(main.map((x) => Math.max(0, at(x.s, i)))));
  const values = stacked ? [...totals, ...(cmp ? data.labels.map((_, i) => at(cmp.s, i)) : [])] : shown.flatMap((x) => data.labels.map((_, i) => at(x.s, i)));
  const tip = h("div", { class: "fsk-ch-tip", hidden: true, "aria-hidden": "true" });
  if (!n || !values.length) {
    box.replaceChildren(h("p", { class: "fsk-ch-none" }, "No data for this period."));
    return { showAt() {}, hide() {} };
  }

  // Text is measured in the card's own font, so labels are spaced by their real width.
  const ctx = doc.createElement("canvas").getContext("2d");
  const font = `11px ${cs.fontFamily}`;
  const measure = (t: string): number => {
    if (!ctx) return t.length * 6.4;
    ctx.font = font;
    return ctx.measureText(t).width + 1;
  };

  let lo = Math.min(...values), hi = Math.max(...values);
  if (bar || (lo >= 0 && lo < hi * 0.5)) lo = Math.min(0, lo);
  if (bar) hi = Math.max(0, hi);
  const pad = { top: 10, right: bar ? 0 : 8, bottom: 24, left: 0 };
  // The tightest nice scale whose gridlines stay at least 26px apart, so y labels never touch.
  const ph0 = H - pad.top - pad.bottom;
  const ticks = [5, 4, 3, 2].map((c) => niceScale(lo, hi, c)).filter((t) => ph0 / (t.length - 1) >= 26)
    .sort((a, b) => (a[a.length - 1] - a[0]) - (b[b.length - 1] - b[0]) || a.length - b.length)[0] ?? niceScale(lo, hi, 1);
  const t0 = ticks[0], t1 = ticks[ticks.length - 1];
  const tickText = ticks.map((t) => axisFormat(t, data.format));
  pad.left = Math.ceil(Math.max(...tickText.map(measure))) + 10;
  const pw = Math.max(40, W - pad.left - pad.right), ph = Math.max(40, H - pad.top - pad.bottom);
  const Y = (v: number): number => pad.top + ph - ((v - t0) / (t1 - t0 || 1)) * ph;
  const band = pw / n;
  const X = (i: number): number => (bar ? pad.left + band * (i + 0.5) : pad.left + (n === 1 ? pw / 2 : (i / (n - 1)) * pw));
  const zero = Y(Math.max(t0, Math.min(0, t1)));
  const radius = parseFloat(cs.getPropertyValue("--k-r")) || 0;

  const svg = h<SVGSVGElement>("svg", { class: `fsk-ch-svg${animate ? " fsk-ch-anim" : ""}`, width: W, height: H, viewBox: `0 0 ${W} ${H}`, "aria-hidden": "true", focusable: "false" });
  const grid = h<SVGElement>("g", { class: "fsk-ch-grid" });
  ticks.forEach((t, i) => {
    const y = Math.round(Y(t)) + 0.5;
    grid.append(
      h("line", { x1: pad.left, x2: W - pad.right, y1: y, y2: y, class: t === 0 || (i === 0 && bar) ? "fsk-ch-base" : null }),
      h("text", { x: pad.left - 10, y, dy: "0.32em", "text-anchor": "end" }, tickText[i]));
  });

  // X labels: thinned from the end (the latest period always keeps its label), then any that would touch are dropped.
  const widths = data.labels.map(measure);
  const step = bar ? band : n > 1 ? pw / (n - 1) : pw;
  const every = Math.max(1, Math.ceil((Math.max(...widths) + 12) / step));
  let leftEdge = Infinity;
  for (let i = n - 1; i >= 0; i--) {
    if ((n - 1 - i) % every) continue;
    const w = widths[i];
    const cx = Math.min(W - w / 2, Math.max(w / 2, X(i)));
    if (cx + w / 2 + 8 > leftEdge) continue;
    leftEdge = cx - w / 2;
    grid.append(h("text", { x: r1(cx), y: H - 6, "text-anchor": "middle" }, data.labels[i]));
  }

  const hover = bar
    ? h<SVGElement>("rect", { class: "fsk-ch-band", x: 0, y: pad.top, width: r1(band), height: ph, rx: Math.min(radius * 1.5, 8), visibility: "hidden" })
    : h<SVGElement>("line", { class: "fsk-ch-cross", x1: 0, x2: 0, y1: pad.top, y2: pad.top + ph, visibility: "hidden" });
  const marks = h<SVGElement>("g", {});
  const byIndex: SVGElement[][] = data.labels.map(() => []);
  const dots: { el: SVGElement; s: ChartSeries }[] = [];
  let groupW = 0;

  if (bar) {
    const ns = stacked ? 1 : Math.max(1, main.length);
    groupW = Math.min(band * (ns > 1 ? 0.78 : 0.6), ns * (stacked ? 36 : 28));
    const gap = ns > 1 ? Math.min(2, groupW * 0.05) : 0;
    const bw = (groupW - gap * (ns - 1)) / ns;
    const r = Math.min(radius, bw / 2.5, 6);
    data.labels.forEach((_, i) => {
      const x0 = X(i) - groupW / 2;
      if (stacked) {
        let acc = 0;
        const segs = main.filter((x) => at(x.s, i) > 0);
        segs.forEach((x, k) => {
          const base = Y(acc), top = Y(acc + at(x.s, i));
          acc += at(x.s, i);
          const b = k ? base - 1.5 : base; // a hairline of paper between segments
          const d = k === segs.length - 1 ? barPath(x0, bw, b, top, r) : barPath(x0, bw, b, Math.min(top, b - 0.5), 0);
          const el = h<SVGElement>("path", { class: `fsk-ch-bar ${x.cls}`, d, style: { "--i": i * 1 + k * 0.5 } });
          byIndex[i].push(el);
          marks.append(el);
        });
      } else {
        main.forEach((x, si) => {
          const el = h<SVGElement>("path", { class: `fsk-ch-bar ${x.cls}`, d: barPath(x0 + si * (bw + gap), bw, zero, Y(at(x.s, i)), r), style: { "--i": i } });
          byIndex[i].push(el);
          marks.append(el);
        });
      }
      if (cmp) {
        const y = r1(Y(at(cmp.s, i)));
        const ends = { x1: r1(x0 - 4), x2: r1(x0 + groupW + 4), y1: y, y2: y };
        const el = h<SVGElement>("line", { class: `fsk-ch-mark ${cmp.cls}`, ...ends });
        byIndex[i].push(el);
        marks.append(h("line", { class: "fsk-ch-mark-bg", ...ends }), el); // a paper halo keeps the dashes legible over bars
      }
    });
  } else {
    // The compare line goes under the others; the lead series gets the soft area and the end dot.
    const order = [...shown].sort((a, b) => Number(!!b.s.compare) - Number(!!a.s.compare));
    const lead = main[0];
    for (const x of order) {
      const g = h<SVGElement>("g", { class: x.cls });
      const pts = data.labels.map((_, i): [number, number] => [X(i), Y(at(x.s, i))]);
      const d = smoothPath(pts);
      if (x === lead && n > 1) {
        const id = `fsk-ch-grad-${++seq}`;
        g.append(
          h("defs", {}, h("linearGradient", { id, x1: 0, y1: 0, x2: 0, y2: 1 },
            h("stop", { offset: "0%", "stop-color": "currentColor", "stop-opacity": main.length > 1 ? 0.12 : 0.22 }),
            h("stop", { offset: "100%", "stop-color": "currentColor", "stop-opacity": 0 }))),
          h("path", { class: "fsk-ch-area", d: `${d}L${r1(pts[n - 1][0])} ${pad.top + ph}L${r1(pts[0][0])} ${pad.top + ph}Z`, fill: `url(#${id})` }));
      }
      g.append(h("path", { class: `fsk-ch-line fsk-ch-line--${x.s.compare ? "cmp" : "main"}`, d, pathLength: x.s.compare ? null : 1 }));
      if (!x.s.compare) {
        const [ex, ey] = pts[n - 1];
        if (x === lead) g.append(h("circle", { class: "fsk-ch-halo", cx: r1(ex), cy: r1(ey), r: 7.5 }));
        g.append(h("circle", { class: "fsk-ch-end", cx: r1(ex), cy: r1(ey), r: x === lead ? 4 : 3 }));
      }
      const dot = h<SVGElement>("circle", { class: "fsk-ch-dot", cx: 0, cy: 0, r: 4.25, visibility: "hidden" });
      g.append(dot);
      dots.push({ el: dot, s: x.s });
      marks.append(g);
    }
  }

  // Pointer and keyboard readout. Screen readers get the same numbers from the hidden table.
  const f = (v: number): string => formatValue(v, data.format);
  const hide = (): void => {
    tip.hidden = true;
    hover.setAttribute("visibility", "hidden");
    dots.forEach((d) => d.el.setAttribute("visibility", "hidden"));
    byIndex.forEach((els) => els.forEach((el) => el.classList.remove("fsk-ch-dim")));
  };
  const showAt = (i: number): void => {
    if (i < 0 || i >= n) { hide(); return; }
    const x = X(i);
    if (bar) hover.setAttribute("x", String(r1(pad.left + band * i)));
    else { hover.setAttribute("x1", String(Math.round(x) + 0.5)); hover.setAttribute("x2", String(Math.round(x) + 0.5)); }
    hover.setAttribute("visibility", "visible");
    dots.forEach((d) => { d.el.setAttribute("cx", String(r1(x))); d.el.setAttribute("cy", String(r1(Y(at(d.s, i))))); d.el.setAttribute("visibility", "visible"); });
    byIndex.forEach((els, k) => els.forEach((el) => el.classList.toggle("fsk-ch-dim", k !== i)));
    const rows = shown.map((x) => h("span", { class: "fsk-ch-tip-row" }, h("i", { class: `fsk-ch-sw ${x.cls}` }), x.s.name, h("b", { class: "fsk-num" }, f(at(x.s, i)))));
    const total = stacked && h("span", { class: "fsk-ch-tip-row fsk-ch-tip-total" }, "Total", h("b", { class: "fsk-num" }, f(totals[i])));
    let change: HTMLElement | null = null;
    if (cmp && main.length && (stacked || main.length === 1)) {
      const now = stacked ? totals[i] : at(main[0].s, i), then = at(cmp.s, i);
      if (then) change = h<HTMLElement>("span", { class: "fsk-ch-tip-row" }, deltaPill(Math.round(((now - then) / Math.abs(then)) * 1000) / 10, data.headline?.good ?? true), `vs ${cmp.s.name}`);
    }
    tip.replaceChildren(h("strong", {}, data.labels[i]), ...rows, ...[total, change].filter((x): x is HTMLElement => !!x));
    tip.hidden = false;
    const tw = tip.offsetWidth, th = tip.offsetHeight;
    const reach = bar ? groupW / 2 + 8 : 14;
    const left = x + reach + tw <= W ? x + reach : Math.max(0, x - reach - tw);
    // Keep the readout off the point it describes: below it when the point is high, above when low.
    const py = main.length ? Y(stacked ? totals[i] : at(main[0].s, i)) : pad.top;
    const top = py < pad.top + ph / 2 ? Math.min(H - th, pad.top + ph - th) : 0;
    tip.style.left = `${Math.round(left)}px`;
    tip.style.top = `${Math.round(Math.max(0, top))}px`;
  };
  const indexAt = (clientX: number): number => {
    const px = clientX - svg.getBoundingClientRect().left - pad.left;
    return Math.max(0, Math.min(n - 1, bar ? Math.floor(px / band) : Math.round((px / pw) * (n - 1))));
  };
  const hit = h<SVGElement>("rect", { x: Math.max(0, pad.left - 6), y: 0, width: pw + 6 + pad.right, height: pad.top + ph, fill: "transparent" });
  hit.addEventListener("pointermove", (e: PointerEvent) => showAt(indexAt(e.clientX)));
  hit.addEventListener("pointerdown", (e: PointerEvent) => showAt(indexAt(e.clientX)));
  hit.addEventListener("pointerleave", (e: PointerEvent) => { if (e.pointerType === "mouse") hide(); });

  svg.append(grid, hover, marks, hit);
  box.replaceChildren(svg, tip);
  return { showAt, hide };
}

function cartesian(data: ChartData, series: ChartSeries[], win: Window): { el: HTMLElement; dispose(): void } {
  const off = new Set<number>();
  const n = data.labels.length;
  const box = h("div", { class: "fsk-ch-plot", role: "img", tabindex: 0, "aria-label": summary(data, series) });
  let chart: Drawn | null = null;
  let cur = -1;
  let width = 0;
  let first = true;
  const paint = (force = false): void => {
    const w = box.clientWidth;
    if (!w || (!force && Math.abs(w - width) < 1)) return;
    width = w;
    chart = drawCartesian(box, data, series, off, first);
    first = false;
    if (cur >= 0) chart.showAt(cur);
  };

  const keys = series.length > 1 ? series.map((s, i) => h<HTMLButtonElement>("button", {
    class: "fsk-ch-key", type: "button", "aria-pressed": "true",
    onclick: () => {
      const mainShown = series.filter((x, k) => !x.compare && !off.has(k)).length;
      if (!off.has(i) && !s.compare && mainShown <= 1) return; // one series always stays
      if (off.has(i)) off.delete(i); else off.add(i);
      syncKeys();
      paint(true);
    },
  }, h("i", { class: `fsk-ch-sw ${seriesClass(series, i)}`, "aria-hidden": "true" }), s.name)) : [];
  const syncKeys = (): void => {
    const mainShown = series.filter((x, k) => !x.compare && !off.has(k)).length;
    keys.forEach((k, i) => {
      k.setAttribute("aria-pressed", String(!off.has(i)));
      const last = !series[i].compare && !off.has(i) && mainShown <= 1;
      k.setAttribute("aria-disabled", last ? "true" : "false");
      k.title = last ? "At least one series stays on" : off.has(i) ? `Show ${series[i].name}` : `Hide ${series[i].name}`;
    });
  };
  syncKeys();

  box.addEventListener("keydown", (e: KeyboardEvent) => {
    if (!chart || !n) return;
    let i = cur < 0 ? n - 1 : cur;
    if (e.key === "ArrowLeft") i = Math.max(0, i - 1);
    else if (e.key === "ArrowRight") i = Math.min(n - 1, i + 1);
    else if (e.key === "Home") i = 0;
    else if (e.key === "End") i = n - 1;
    else if (e.key === "Escape") { cur = -1; chart.hide(); return; }
    else return;
    e.preventDefault();
    cur = i;
    chart.showAt(i);
  });
  box.addEventListener("focus", () => { if (box.matches(":focus-visible") && chart && n) { cur = n - 1; chart.showAt(cur); } });
  box.addEventListener("blur", () => { cur = -1; chart?.hide(); });
  // A tap elsewhere puts the touch readout away. composedPath() sees through the SDK's shadow root.
  const away = (e: PointerEvent): void => { if (e.pointerType !== "mouse" && !e.composedPath().includes(box)) { cur = -1; chart?.hide(); } };
  box.ownerDocument.addEventListener("pointerdown", away);

  let frame = 0;
  const ro = typeof ResizeObserver === "function" ? new ResizeObserver(() => { win.cancelAnimationFrame(frame); frame = win.requestAnimationFrame(() => paint()); }) : null;
  ro?.observe(box);
  win.requestAnimationFrame(() => paint());

  const el = h("div", { class: "fsk-ch-body" },
    keys.length > 0 && h("div", { class: "fsk-ch-legend", role: "group", "aria-label": "Series" }, keys),
    box,
    dataTable(data, series));
  return { el, dispose: () => { ro?.disconnect(); win.cancelAnimationFrame(frame); box.ownerDocument.removeEventListener("pointerdown", away); } };
}

function donut(data: ChartData, series: ChartSeries[]): { el: HTMLElement; dispose(): void } {
  const s = series.find((x) => !x.compare);
  let slices = data.labels.map((label, i) => ({ label, value: Math.max(0, at(s, i)), other: false })).filter((x) => x.value > 0);
  if (slices.length > 5) slices = [...slices.slice(0, 4), { label: "Other", value: sum(slices.slice(4).map((x) => x.value)), other: true }];
  const total = sum(slices.map((x) => x.value));
  const f = (v: number): string => formatValue(v, data.format);
  const pct = (v: number): string => `${total ? Math.round((v / total) * 100) : 0}%`;
  const box = h("div", { class: "fsk-ch-ring", role: "img", "aria-label": summary(data, series) });
  if (!total) {
    box.append(h("p", { class: "fsk-ch-none" }, "No data."));
    return { el: h("div", { class: "fsk-ch-donut" }, box), dispose: () => {} };
  }

  const C = 50, R = 42;
  const gap = slices.length > 1 ? 1.2 : 0;
  let startAt = 0;
  const arcs = slices.map((x, i) => {
    const share = (x.value / total) * 100;
    const len = Math.max(0.4, share - gap);
    const arc = h<SVGElement>("circle", {
      class: `fsk-ch-slice fsk-ch-s${x.other ? 4 : i}`, cx: C, cy: C, r: R, pathLength: 100,
      "stroke-dasharray": `${r1(len)} ${r1(100 - len)}`, "stroke-dashoffset": r1(-(startAt + gap / 2)), style: { "--i": i },
      onpointerenter: () => preview(i), onpointerleave: () => preview(sel), onclick: () => select(sel === i ? -1 : i),
    }, h("title", {}, `${x.label}: ${f(x.value)} (${pct(x.value)})`));
    startAt += share;
    return arc;
  });
  const svg = h<SVGSVGElement>("svg", { viewBox: "0 0 100 100", class: "fsk-ch-anim", "aria-hidden": "true", focusable: "false" },
    h("circle", { class: "fsk-ch-track", cx: C, cy: C, r: R }), arcs);
  const big = h("b", { class: "fsk-num" });
  const small = h("span", {});
  box.append(svg, h("div", { class: "fsk-ch-center", "aria-hidden": "true" }, big, small));

  const rows = slices.map((x, i) => h<HTMLButtonElement>("button", {
    class: "fsk-ch-row", type: "button", "aria-pressed": "false",
    onpointerenter: () => preview(i), onpointerleave: () => preview(sel), onfocus: () => preview(i), onblur: () => preview(sel),
    onclick: () => select(sel === i ? -1 : i),
  },
    h("i", { class: `fsk-ch-sw fsk-ch-s${x.other ? 4 : i}`, "aria-hidden": "true" }),
    h("span", { class: "fsk-ch-row-name" }, x.label),
    h("span", { class: "fsk-ch-row-share fsk-num" }, pct(x.value)),
    h("span", { class: "fsk-ch-row-val fsk-num" }, f(x.value))));
  const list = h("div", { class: "fsk-ch-slices", role: "group", "aria-label": "Slices" }, rows);

  // The center shows the leading slice, or the one hovered or picked.
  const lead = slices.reduce((b, x, i) => (x.value > slices[b].value ? i : b), 0);
  let sel = -1;
  function preview(i: number): void {
    const k = i < 0 ? lead : i;
    big.textContent = pct(slices[k].value);
    small.textContent = slices[k].label;
    if (i < 0) box.removeAttribute("data-sel"); else box.setAttribute("data-sel", String(i));
    arcs.forEach((a, j) => a.classList.toggle("fsk-ch-on", j === i));
    if (i < 0) list.removeAttribute("data-sel"); else list.setAttribute("data-sel", "");
  }
  function select(i: number): void {
    sel = i;
    rows.forEach((r, j) => r.setAttribute("aria-pressed", String(j === i)));
    preview(i);
  }
  preview(-1);

  return { el: h("div", { class: "fsk-ch-donut" }, box, list, dataTable(data, series)), dispose: () => {} };
}

const TYPE_ICON: Record<ChartData["type"], IconName> = { line: "chart", bar: "bars", donut: "pie" };

/** Read-only: draws the chart and reports "displayed", so the agent doesn't wait. The agent already has the numbers from execute. */
export function mount({ root, head, data, api, surface = "desktop" }: ChartProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-ch", CSS);
  const win = root.ownerDocument.defaultView ?? window;
  const series = pickSeries(data.series);
  const hl = headlineOf(data, series);
  const body = data.type === "donut" ? donut(data, series) : cartesian(data, series, win);

  const card = h("section", { class: "fsk fsk-card fsk-ch", "data-type": data.type, "data-surface": surface, "aria-label": data.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip", "aria-hidden": "true" }, icon(data.icon ?? TYPE_ICON[data.type], 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle))),
    hl && headlineBlock(hl, data.format),
    body.el,
    (data.footnote || data.link) && h("footer", { class: "fsk-ch-foot" },
      h("span", {}, data.footnote ?? ""),
      data.link && h("a", { class: "fsk-btn fsk-btn--link", href: data.link.href, target: "_top" }, data.link.label, icon("chevron", 14))));

  root.replaceChildren(card);
  api?.displayed?.(); // read-only: shown, the agent doesn't wait
  return () => { body.dispose(); root.replaceChildren(); };
}

/** The states this card draws besides its data. */
export const states: StateKind[] = ["loading", "empty", "error"];

const SK_BARS = [46, 58, 52, 66, 61, 74, 70, 84];

/** Loading (a headline and bars on an axis), empty or error, drawn as this card. Read-only: report displayed() yourself if the agent shouldn't wait. */
export function mountState({ root, head, state, title, subtitle, surface = "desktop" }: StateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-ch", CSS);
  const skeleton = (): HTMLElement => h("div", {},
    h("div", { class: "fsk-ch-sk-hl" }, bone("38%", "24px"), bone("44px", "16px", { cls: "fsk-bone--round", i: 1 })),
    bone("30%", "9px", { i: 2 }),
    h("div", { class: "fsk-ch-sk-plot" }, SK_BARS.map((v, i) => h("span", {}, bone("100%", `${v}%`, { i: i + 2 })))),
    h("div", { class: "fsk-ch-sk-axis" }, [0, 1, 2, 3].map((i) => bone("26px", "8px", { i: i + 3 }))));
  const card = stateCard({ state, cls: "fsk-ch", icon: "chart", title, subtitle, surface, skeleton });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

export const fixtures: Record<string, ChartData> = {
  default: {
    type: "line",
    title: "Revenue by month",
    subtitle: "Jan to Nov 2026 · all plans",
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov"],
    series: [
      { name: "2026", values: [118400, 124900, 131200, 128700, 139500, 146800, 152300, 149900, 161700, 172400, 184200] },
      { name: "2025", values: [96200, 99800, 104500, 108100, 111900, 115300, 118700, 121400, 126900, 131800, 138600], compare: true },
    ],
    format: { style: "currency" },
    headline: { value: 184200, label: "Revenue in November", delta: 32.9, vs: "vs Nov 2025" },
    footnote: "Excludes refunds",
    link: { label: "Open report", href: "/reports/revenue?by=month" },
  },
  signups: {
    type: "bar",
    stacked: true,
    title: "Signups by channel",
    subtitle: "Last 8 weeks",
    labels: ["Sep 29", "Oct 6", "Oct 13", "Oct 20", "Oct 27", "Nov 3", "Nov 10", "Nov 17"],
    series: [
      { name: "Organic", values: [412, 438, 451, 470, 462, 495, 521, 548] },
      { name: "Paid", values: [210, 236, 198, 254, 281, 266, 302, 318] },
      { name: "Referral", values: [88, 94, 101, 97, 112, 126, 131, 149] },
      { name: "Last year", values: [610, 640, 655, 690, 705, 720, 760, 790], compare: true },
    ],
    headline: { value: 1015, label: "Signups, week of Nov 17", delta: 6.4, vs: "vs the week before" },
  },
  planMix: {
    type: "donut",
    title: "Accounts by plan",
    subtitle: "Paying accounts · November",
    labels: ["Pro", "Business", "Starter", "Enterprise", "Legacy"],
    series: [{ name: "Accounts", values: [1046, 684, 438, 312, 96] }],
    headline: { label: "Paying accounts", delta: 4.8, vs: "vs October" },
    link: { label: "Open accounts", href: "/accounts?status=paying" },
  },
};
```

```js title="agent/ui/chart.js"
// Template: chart. A read-only chat card with one chart: a trend over time (line), amounts per period (bars, grouped or stacked) or a breakdown (donut).

export const meta = {
  id: "chart",
  title: "Chart",
  surface: "card",
  kind: "read-only",
  mobile: "same",
  whenToUse: "The answer is a shape, not one number: a trend over time (line), amounts per period or channel (bars, grouped or stacked), or how a whole splits up (donut). One to three series, plus a previous period to compare against.",
  whenNotToUse: "A few headline numbers without their history (KPI tiles). Exact values to look up or sort (table). More than three series, or a full report with findings (report canvas).",
};

const CSS = `
.fsk-ch { container-type: inline-size; }
.fsk-ch .fsk-head > div { flex: 1; min-width: 0; }
.fsk-ch .fsk-ch-hl { display: flex; flex-direction: column; gap: 3px; margin: -2px 0 12px; }
.fsk-ch .fsk-ch-hl-row { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; }
.fsk-ch .fsk-ch-value { font-size: 1.72em; font-weight: 600; letter-spacing: -0.02em; line-height: 1.12; white-space: nowrap; }
.fsk-ch .fsk-ch-hl-meta { font-size: .86em; color: var(--k-text-2); }
.fsk-ch .fsk-ch-delta { display: inline-flex; align-items: center; gap: 2px; padding: 1px 6px 1px 4px; border-radius: 999px; font-size: .79em; font-weight: 600; line-height: 1.5; white-space: nowrap; }
.fsk-ch .fsk-ch-delta--good { color: var(--k-success); background: color-mix(in srgb, var(--k-success) 12%, var(--k-paper)); }
.fsk-ch .fsk-ch-delta--bad { color: var(--k-error); background: color-mix(in srgb, var(--k-error) 12%, var(--k-paper)); }
.fsk-ch .fsk-ch-delta--flat { color: var(--k-text-2); background: var(--k-hover); }

/* Series colors: all derived from the theme's primary, so every brand gets its own palette. */
.fsk-ch .fsk-ch-s0 { color: var(--k-primary); }
.fsk-ch .fsk-ch-s1 { color: color-mix(in oklab, var(--k-primary) 52%, var(--k-text)); }
.fsk-ch .fsk-ch-s2 { color: color-mix(in oklch, var(--k-primary) 45%, var(--k-warning)); }
.fsk-ch .fsk-ch-s3 { color: color-mix(in oklab, var(--k-primary) 40%, var(--k-paper)); }
.fsk-ch .fsk-ch-s4 { color: color-mix(in oklab, var(--k-text-2) 55%, var(--k-paper)); }
.fsk-ch .fsk-ch-cmp { color: color-mix(in srgb, var(--k-text-2) 72%, var(--k-paper)); }

/* Legend: each key shows or hides its series. */
.fsk-ch .fsk-ch-legend { display: flex; flex-wrap: wrap; gap: 2px; margin: -4px 0 6px -8px; }
.fsk-ch .fsk-ch-key {
  appearance: none; display: inline-flex; align-items: center; gap: 7px; min-height: 28px; padding: 0 8px;
  border: 0; border-radius: var(--k-r-md); background: none; color: var(--k-text-2); font: inherit; font-size: .86em; cursor: pointer;
  transition: background .15s, color .15s;
}
.fsk-ch .fsk-ch-key:hover { background: var(--k-hover); color: var(--k-text); }
.fsk-ch .fsk-ch-key:focus-visible { outline: 2px solid var(--k-primary); outline-offset: -2px; }
.fsk-ch .fsk-ch-key[aria-pressed="false"] { color: color-mix(in srgb, var(--k-text-2) 62%, var(--k-paper)); text-decoration: line-through; text-decoration-thickness: 1px; }
.fsk-ch .fsk-ch-key[aria-disabled="true"] { cursor: default; }
.fsk-ch .fsk-ch-key[aria-disabled="true"]:hover { background: none; color: var(--k-text-2); }
.fsk-ch .fsk-ch-sw { flex: none; display: inline-block; width: 10px; height: 10px; border-radius: min(var(--k-r), 3px); background: currentColor; transition: background .15s, box-shadow .15s; }
.fsk-ch[data-type="line"] .fsk-ch-key .fsk-ch-sw { width: 14px; height: 3px; border-radius: 2px; }
.fsk-ch .fsk-ch-key .fsk-ch-sw.fsk-ch-cmp, .fsk-ch .fsk-ch-tip .fsk-ch-sw.fsk-ch-cmp {
  width: 14px; height: 2px; border-radius: 0; background: repeating-linear-gradient(90deg, currentColor 0 4px, transparent 4px 7px);
}
.fsk-ch .fsk-ch-key[aria-pressed="false"] .fsk-ch-sw { background: transparent; box-shadow: inset 0 0 0 1.5px currentColor; }

/* Plot */
.fsk-ch .fsk-ch-plot { position: relative; height: 172px; margin: 0 -2px; touch-action: pan-y; border-radius: var(--k-r-md); -webkit-tap-highlight-color: transparent; }
.fsk-ch .fsk-ch-plot:focus { outline: none; }
.fsk-ch .fsk-ch-plot:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 4px; }
.fsk-ch .fsk-ch-svg { display: block; overflow: visible; }
.fsk-ch .fsk-ch-svg text { fill: var(--k-text-2); font-size: 11px; font-family: inherit; font-variant-numeric: tabular-nums; font-feature-settings: "tnum"; }
.fsk-ch .fsk-ch-grid line { stroke: color-mix(in srgb, var(--k-divider) 75%, var(--k-paper)); shape-rendering: crispEdges; }
.fsk-ch .fsk-ch-grid line.fsk-ch-base { stroke: var(--k-border); }
.fsk-ch .fsk-ch-bar { fill: currentColor; transition: opacity .15s; }
.fsk-ch .fsk-ch-bar.fsk-ch-dim { opacity: .42; }
.fsk-ch .fsk-ch-mark { stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-dasharray: 3 3; fill: none; transition: opacity .15s; }
.fsk-ch .fsk-ch-mark.fsk-ch-dim { opacity: .42; }
.fsk-ch .fsk-ch-mark-bg { stroke: var(--k-paper); stroke-width: 5; stroke-linecap: round; opacity: .9; }
.fsk-ch .fsk-ch-line { fill: none; stroke: currentColor; stroke-width: 2.25; stroke-linecap: round; stroke-linejoin: round; }
.fsk-ch .fsk-ch-line--cmp { stroke-width: 1.75; stroke-dasharray: 4 4; }
.fsk-ch .fsk-ch-halo { fill: currentColor; opacity: .16; }
.fsk-ch .fsk-ch-end { fill: currentColor; stroke: var(--k-paper); stroke-width: 2; }
.fsk-ch .fsk-ch-dot { fill: var(--k-paper); stroke: currentColor; stroke-width: 2.25; }
.fsk-ch .fsk-ch-band { fill: var(--k-hover); }
.fsk-ch .fsk-ch-cross { stroke: var(--k-text-2); stroke-opacity: .45; stroke-width: 1; shape-rendering: crispEdges; }
.fsk-ch .fsk-ch-none { margin: 0; display: grid; place-items: center; height: 100%; color: var(--k-text-2); font-size: .86em; }

.fsk-ch .fsk-ch-tip {
  position: absolute; top: 0; left: 0; z-index: 2; pointer-events: none; display: grid; gap: 4px; min-width: 132px;
  padding: 8px 10px; border: 1px solid var(--k-border); border-radius: var(--k-r-md);
  background: color-mix(in srgb, var(--k-paper) 94%, transparent); -webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px);
  box-shadow: var(--k-shadow); font-size: .79em; line-height: 1.35; white-space: nowrap;
  transition: left .14s var(--k-ease), top .14s var(--k-ease);
}
.fsk-ch .fsk-ch-tip strong { font-weight: 600; margin-bottom: 1px; }
.fsk-ch .fsk-ch-tip-row { display: flex; align-items: center; gap: 6px; color: var(--k-text-2); }
.fsk-ch .fsk-ch-tip-row b { margin-left: auto; padding-left: 14px; color: var(--k-text); font-weight: 600; }
.fsk-ch .fsk-ch-tip-total { margin-top: 2px; padding-top: 5px; border-top: 1px solid var(--k-divider); }
.fsk-ch .fsk-ch-tip .fsk-ch-delta { justify-self: start; margin-top: 2px; }

/* Donut */
.fsk-ch .fsk-ch-donut { display: grid; grid-template-columns: 132px minmax(0, 1fr); align-items: center; gap: 14px; padding: 2px 0 2px; }
.fsk-ch .fsk-ch-ring { position: relative; width: 132px; height: 132px; }
.fsk-ch .fsk-ch-ring svg { display: block; width: 100%; height: 100%; overflow: visible; transform: rotate(-90deg); }
.fsk-ch .fsk-ch-track { fill: none; stroke: var(--k-sunken); stroke-width: 13; }
.fsk-ch .fsk-ch-slice { fill: none; stroke: currentColor; stroke-width: 13; cursor: pointer; transition: opacity .18s, stroke-width .22s var(--k-ease); }
.fsk-ch .fsk-ch-ring[data-sel] .fsk-ch-slice { opacity: .26; }
.fsk-ch .fsk-ch-ring[data-sel] .fsk-ch-slice.fsk-ch-on { opacity: 1; stroke-width: 16; }
.fsk-ch .fsk-ch-center { position: absolute; inset: 0; display: grid; place-content: center; justify-items: center; gap: 1px; padding: 26px; text-align: center; pointer-events: none; }
.fsk-ch .fsk-ch-center b { font-size: 1.43em; font-weight: 600; letter-spacing: -0.02em; line-height: 1.1; }
.fsk-ch .fsk-ch-center span { max-width: 76px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: .79em; color: var(--k-text-2); }
.fsk-ch .fsk-ch-slices { display: flex; flex-direction: column; gap: 1px; min-width: 0; margin: 0 -6px 0 0; padding: 0; list-style: none; }
.fsk-ch .fsk-ch-row {
  appearance: none; display: grid; grid-template-columns: 10px minmax(0, 1fr) auto; align-items: center; column-gap: 8px; width: 100%;
  min-height: 34px; padding: 3px 6px; border: 0; border-radius: var(--k-r-md); background: none; color: inherit; font: inherit; text-align: left; cursor: pointer;
  transition: background .15s, opacity .15s;
}
.fsk-ch .fsk-ch-row:hover, .fsk-ch .fsk-ch-row[aria-pressed="true"] { background: var(--k-hover); }
.fsk-ch .fsk-ch-row:focus-visible { outline: 2px solid var(--k-primary); outline-offset: -2px; }
.fsk-ch .fsk-ch-row-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: .93em; }
.fsk-ch .fsk-ch-row-share { font-size: .93em; font-weight: 600; }
.fsk-ch .fsk-ch-row-val { grid-column: 2 / 4; margin-top: -2px; font-size: .79em; color: var(--k-text-2); }
.fsk-ch .fsk-ch-slices[data-sel] .fsk-ch-row[aria-pressed="false"] { opacity: .55; }

.fsk-ch .fsk-ch-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 10px; padding-top: 8px; border-top: 1px solid var(--k-divider); font-size: .86em; color: var(--k-text-2); }
.fsk-ch .fsk-ch-foot .fsk-btn--link { margin-right: -4px; }
.fsk-ch .fsk-ch-foot .fsk-btn--link:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }

/* Entrance, once: lines draw, bars grow, the ring sweeps. Reduced motion skips all of it (BASE_CSS). */
.fsk-ch .fsk-ch-anim .fsk-ch-bar { transform-box: fill-box; transform-origin: 50% 100%; animation: fsk-ch-grow .62s var(--k-ease) both; animation-delay: calc(var(--i, 0) * 28ms); }
.fsk-ch .fsk-ch-anim .fsk-ch-line--main { stroke-dasharray: 1; animation: fsk-ch-draw 1.05s var(--k-ease) both; }
.fsk-ch .fsk-ch-anim .fsk-ch-area, .fsk-ch .fsk-ch-anim .fsk-ch-line--cmp, .fsk-ch .fsk-ch-anim .fsk-ch-end, .fsk-ch .fsk-ch-anim .fsk-ch-halo, .fsk-ch .fsk-ch-anim .fsk-ch-mark, .fsk-ch .fsk-ch-anim .fsk-ch-mark-bg { animation: fsk-ch-fade .6s .4s ease-out both; }
.fsk-ch .fsk-ch-anim .fsk-ch-slice { animation: fsk-ch-arc .5s var(--k-ease) both; animation-delay: calc(var(--i, 0) * 90ms); }
@keyframes fsk-ch-grow { from { transform: scaleY(0); } }
@keyframes fsk-ch-draw { from { stroke-dashoffset: 1; } to { stroke-dashoffset: 0; } }
@keyframes fsk-ch-fade { from { opacity: 0; } }
@keyframes fsk-ch-arc { from { stroke-dasharray: 0 100; } }

/* Loading: the card's own shape (headline, then bars on an axis). */
.fsk-ch .fsk-ch-sk-hl { display: flex; align-items: center; gap: 8px; margin: 0 0 8px; }
.fsk-ch .fsk-ch-sk-plot { display: flex; align-items: flex-end; gap: 8px; height: 150px; padding: 8px 0 0 30px; border-bottom: 1px solid var(--k-divider); }
.fsk-ch .fsk-ch-sk-plot > span { flex: 1; display: flex; align-items: flex-end; height: 100%; }
.fsk-ch .fsk-ch-sk-plot .fsk-bone { border-radius: max(2px, calc(var(--k-r) * .75)) max(2px, calc(var(--k-r) * .75)) 0 0; }
.fsk-ch .fsk-ch-sk-axis { display: flex; justify-content: space-between; padding: 8px 0 0 30px; }

@container (max-width: 290px) {
  .fsk-ch .fsk-ch-donut { grid-template-columns: minmax(0, 1fr); justify-items: center; gap: 10px; }
  .fsk-ch .fsk-ch-slices { width: 100%; margin: 0; }
}
.fsk-ch[data-surface="mobile"] .fsk-ch-key, .fsk-ch[data-surface="mobile"] .fsk-ch-row, .fsk-ch[data-surface="mobile"] .fsk-ch-foot .fsk-btn--link { min-height: 44px; }
.fsk-ch[data-surface="mobile"] .fsk-ch-plot { height: 184px; }
.fsk-ch[data-surface="mobile"] .fsk-ch-legend { gap: 0; margin: -10px 0 0 -6px; }
.fsk-ch[data-surface="mobile"] .fsk-ch-key { padding: 0 6px; gap: 6px; }
`;

let seq = 0;
const r1 = (n) => Math.round(n * 10) / 10;
const sum = (xs) => xs.reduce((a, b) => a + b, 0);
const at = (s, i) => {
  const v = s?.values[i];
  return typeof v === "number" && Number.isFinite(v) ? v : 0;
};

/** Up to three series to draw, then the first compare series. */
function pickSeries(all) {
  const main = all.filter((s) => !s.compare).slice(0, 3);
  const cmp = all.find((s) => s.compare);
  return cmp ? [...main, cmp] : main;
}

function seriesClass(series, index) {
  if (series[index].compare) return "fsk-ch-cmp";
  return `fsk-ch-s${series.slice(0, index).filter((x) => !x.compare).length}`;
}

/** 1, 2, 2.5 or 5 steps that cover lo..hi. */
function niceScale(lo, hi, count) {
  if (hi === lo) hi = lo + 1;
  const raw = (hi - lo) / count;
  const mag = 10 ** Math.floor(Math.log10(raw));
  const step = ([1, 2, 2.5, 5, 10].find((m) => m * mag >= raw) ?? 10) * mag;
  const ticks = [];
  for (let k = Math.floor(lo / step); k <= Math.ceil(hi / step); k++) ticks.push(Math.round(k * step * 1e6) / 1e6);
  return ticks;
}

function axisFormat(v, f = {}) {
  if (f.style === "percent") return new Intl.NumberFormat(undefined, { style: "percent", maximumFractionDigits: 0 }).format(v / 100);
  const opts = { notation: "compact", maximumFractionDigits: 2 };
  if (f.style === "currency") Object.assign(opts, { style: "currency", currency: f.currency ?? "USD" });
  return new Intl.NumberFormat(undefined, opts).format(v);
}

/** A bar with its top corners rounded by the theme radius. */
function barPath(x, w, base, top, r) {
  if (top >= base) return `M${r1(x)} ${r1(base)}h${r1(w)}V${r1(top)}H${r1(x)}Z`;
  const rr = Math.min(r, base - top, w / 2);
  return `M${r1(x)} ${r1(base)}V${r1(top + rr)}Q${r1(x)} ${r1(top)} ${r1(x + rr)} ${r1(top)}H${r1(x + w - rr)}Q${r1(x + w)} ${r1(top)} ${r1(x + w)} ${r1(top + rr)}V${r1(base)}Z`;
}

/** A smooth line that never overshoots the data (monotone cubic, as in d3's curveMonotoneX). */
function smoothPath(pts) {
  const n = pts.length;
  if (n < 3) return pts.map(([x, y], i) => `${i ? "L" : "M"}${r1(x)} ${r1(y)}`).join("");
  const t = new Array(n).fill(0);
  for (let i = 1; i < n - 1; i++) {
    const h0 = pts[i][0] - pts[i - 1][0], h1 = pts[i + 1][0] - pts[i][0];
    const s0 = (pts[i][1] - pts[i - 1][1]) / h0, s1 = (pts[i + 1][1] - pts[i][1]) / h1;
    const p = (s0 * h1 + s1 * h0) / (h0 + h1);
    t[i] = (Math.sign(s0) + Math.sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;
  }
  const end = (a, b, tb) => {
    const hh = pts[b][0] - pts[a][0];
    return hh ? (3 * (pts[b][1] - pts[a][1]) / hh - tb) / 2 : tb;
  };
  t[0] = end(0, 1, t[1]);
  t[n - 1] = end(n - 2, n - 1, t[n - 2]);
  let d = `M${r1(pts[0][0])} ${r1(pts[0][1])}`;
  for (let i = 0; i < n - 1; i++) {
    const [x0, y0] = pts[i], [x1, y1] = pts[i + 1];
    const dx = (x1 - x0) / 3;
    d += `C${r1(x0 + dx)} ${r1(y0 + t[i] * dx)} ${r1(x1 - dx)} ${r1(y1 - t[i + 1] * dx)} ${r1(x1)} ${r1(y1)}`;
  }
  return d;
}

function headlineOf(data, series) {
  const hd = data.headline ?? {};
  const main = series.filter((s) => !s.compare);
  const cmp = series.find((s) => s.compare);
  const n = data.labels.length;
  if (data.type === "donut") {
    const total = sum(data.labels.map((_, i) => Math.max(0, at(main[0], i))));
    return { value: hd.value ?? total, label: hd.label ?? "Total", delta: hd.delta, good: hd.good ?? true, vs: hd.vs };
  }
  if (!n || !main.length) return null;
  const point = (i) => (data.type === "bar" && data.stacked ? sum(main.map((s) => at(s, i))) : at(main[0], i));
  const last = point(n - 1);
  const base = cmp ? at(cmp, n - 1) : n > 1 ? point(n - 2) : 0;
  const auto = base ? Math.round(((last - base) / Math.abs(base)) * 1000) / 10 : undefined;
  return {
    value: hd.value ?? last,
    label: hd.label ?? data.labels[n - 1],
    delta: hd.delta ?? auto,
    good: hd.good ?? true,
    vs: hd.vs ?? (cmp ? `vs ${cmp.name}` : n > 1 ? `vs ${data.labels[n - 2]}` : undefined),
  };
}

function deltaPill(delta, good) {
  const sign = Math.sign(delta);
  const tone = sign === 0 ? "flat" : (sign > 0) === good ? "good" : "bad";
  return h("span", { class: `fsk-ch-delta fsk-ch-delta--${tone} fsk-num`, "aria-hidden": "true" },
    sign !== 0 && icon(sign > 0 ? "up" : "down", 12), `${Math.abs(delta)}%`);
}

function saidDelta(delta, vs) {
  if (delta == null) return "";
  return `, ${delta === 0 ? "no change" : `${delta > 0 ? "up" : "down"} ${Math.abs(delta)}%`}${vs ? ` ${vs}` : ""}`;
}

function headlineBlock(hl, format) {
  const valueEl = h("span", { class: "fsk-ch-value fsk-num", "aria-hidden": "true" });
  countUp(valueEl, hl.value, format);
  return h("div", { class: "fsk-ch-hl", role: "group", "aria-label": `${hl.label}: ${formatValue(hl.value, format)}${saidDelta(hl.delta, hl.vs)}` },
    h("div", { class: "fsk-ch-hl-row" }, valueEl, hl.delta != null && deltaPill(hl.delta, hl.good)),
    h("span", { class: "fsk-ch-hl-meta", "aria-hidden": "true" }, [hl.label, hl.vs].filter(Boolean).join(" · ")));
}

/** What a screen reader hears for the chart; the full numbers follow in a hidden table. */
function summary(data, series) {
  const f = (v) => formatValue(v, data.format);
  const n = data.labels.length;
  const s = series.find((x) => !x.compare);
  if (!n || !s) return `${data.title}: no data.`;
  if (data.type === "donut") {
    const total = sum(data.labels.map((_, i) => Math.max(0, at(s, i)))) || 1;
    return `Donut chart: ${data.title}. ` + data.labels.map((l, i) => `${l} ${Math.round((Math.max(0, at(s, i)) / total) * 100)}% (${f(at(s, i))})`).join(", ")
      + ". The numbers are in the table that follows.";
  }
  let hi = 0, lo = 0;
  for (let i = 0; i < n; i++) { if (at(s, i) > at(s, hi)) hi = i; if (at(s, i) < at(s, lo)) lo = i; }
  const first = at(s, 0), last = at(s, n - 1);
  const change = first ? Math.round(((last - first) / Math.abs(first)) * 100) : null;
  const others = series.filter((x) => x !== s).map((x) => x.name);
  const kind = data.type === "line" ? "Line chart" : data.stacked ? "Stacked bar chart" : "Bar chart";
  return `${kind}: ${data.title}, ${data.labels[0]} to ${data.labels[n - 1]}. ${s.name} is highest in ${data.labels[hi]} (${f(at(s, hi))}) and lowest in ${data.labels[lo]} (${f(at(s, lo))})`
    + (change != null && n > 1 ? `, ${change >= 0 ? "up" : "down"} ${Math.abs(change)}% over the period.` : ".")
    + (others.length ? ` Also shows ${others.join(" and ")}.` : "") + " The numbers are in the table that follows.";
}

function dataTable(data, series) {
  const f = (v) => formatValue(v, data.format);
  if (data.type === "donut") {
    const s = series.find((x) => !x.compare);
    const total = sum(data.labels.map((_, i) => Math.max(0, at(s, i)))) || 1;
    return h("table", { class: "fsk-sr" }, h("caption", {}, data.title),
      h("thead", {}, h("tr", {}, h("th", { scope: "col" }, "Slice"), h("th", { scope: "col" }, "Value"), h("th", { scope: "col" }, "Share"))),
      h("tbody", {}, data.labels.map((l, i) => h("tr", {}, h("th", { scope: "row" }, l), h("td", {}, f(at(s, i))),
        h("td", {}, `${Math.round((Math.max(0, at(s, i)) / total) * 100)}%`)))));
  }
  return h("table", { class: "fsk-sr" }, h("caption", {}, data.title),
    h("thead", {}, h("tr", {}, h("th", { scope: "col" }, "Period"), series.map((s) => h("th", { scope: "col" }, s.name)))),
    h("tbody", {}, data.labels.map((l, i) => h("tr", {}, h("th", { scope: "row" }, l), series.map((s) => h("td", {}, f(at(s, i))))))));
}

/** Draws a line or bar chart at the box's real size, so text never stretches. Called again on resize and on legend changes. */
function drawCartesian(box, data, all, off, animate) {
  const doc = box.ownerDocument;
  const win = doc.defaultView ?? window;
  const cs = win.getComputedStyle(box);
  const W = Math.max(200, Math.floor(box.clientWidth));
  const H = Math.max(120, Math.floor(box.clientHeight));
  const n = data.labels.length;
  const bar = data.type === "bar";
  const shown = all.map((s, i) => ({ s, i, cls: seriesClass(all, i) })).filter((x) => !off.has(x.i));
  const main = shown.filter((x) => !x.s.compare);
  const cmp = shown.find((x) => x.s.compare);
  const stacked = bar && !!data.stacked && main.length > 1;
  const totals = data.labels.map((_, i) => sum(main.map((x) => Math.max(0, at(x.s, i)))));
  const values = stacked ? [...totals, ...(cmp ? data.labels.map((_, i) => at(cmp.s, i)) : [])] : shown.flatMap((x) => data.labels.map((_, i) => at(x.s, i)));
  const tip = h("div", { class: "fsk-ch-tip", hidden: true, "aria-hidden": "true" });
  if (!n || !values.length) {
    box.replaceChildren(h("p", { class: "fsk-ch-none" }, "No data for this period."));
    return { showAt() {}, hide() {} };
  }

  // Text is measured in the card's own font, so labels are spaced by their real width.
  const ctx = doc.createElement("canvas").getContext("2d");
  const font = `11px ${cs.fontFamily}`;
  const measure = (t) => {
    if (!ctx) return t.length * 6.4;
    ctx.font = font;
    return ctx.measureText(t).width + 1;
  };

  let lo = Math.min(...values), hi = Math.max(...values);
  if (bar || (lo >= 0 && lo < hi * 0.5)) lo = Math.min(0, lo);
  if (bar) hi = Math.max(0, hi);
  const pad = { top: 10, right: bar ? 0 : 8, bottom: 24, left: 0 };
  // The tightest nice scale whose gridlines stay at least 26px apart, so y labels never touch.
  const ph0 = H - pad.top - pad.bottom;
  const ticks = [5, 4, 3, 2].map((c) => niceScale(lo, hi, c)).filter((t) => ph0 / (t.length - 1) >= 26)
    .sort((a, b) => (a[a.length - 1] - a[0]) - (b[b.length - 1] - b[0]) || a.length - b.length)[0] ?? niceScale(lo, hi, 1);
  const t0 = ticks[0], t1 = ticks[ticks.length - 1];
  const tickText = ticks.map((t) => axisFormat(t, data.format));
  pad.left = Math.ceil(Math.max(...tickText.map(measure))) + 10;
  const pw = Math.max(40, W - pad.left - pad.right), ph = Math.max(40, H - pad.top - pad.bottom);
  const Y = (v) => pad.top + ph - ((v - t0) / (t1 - t0 || 1)) * ph;
  const band = pw / n;
  const X = (i) => (bar ? pad.left + band * (i + 0.5) : pad.left + (n === 1 ? pw / 2 : (i / (n - 1)) * pw));
  const zero = Y(Math.max(t0, Math.min(0, t1)));
  const radius = parseFloat(cs.getPropertyValue("--k-r")) || 0;

  const svg = h("svg", { class: `fsk-ch-svg${animate ? " fsk-ch-anim" : ""}`, width: W, height: H, viewBox: `0 0 ${W} ${H}`, "aria-hidden": "true", focusable: "false" });
  const grid = h("g", { class: "fsk-ch-grid" });
  ticks.forEach((t, i) => {
    const y = Math.round(Y(t)) + 0.5;
    grid.append(
      h("line", { x1: pad.left, x2: W - pad.right, y1: y, y2: y, class: t === 0 || (i === 0 && bar) ? "fsk-ch-base" : null }),
      h("text", { x: pad.left - 10, y, dy: "0.32em", "text-anchor": "end" }, tickText[i]));
  });

  // X labels: thinned from the end (the latest period always keeps its label), then any that would touch are dropped.
  const widths = data.labels.map(measure);
  const step = bar ? band : n > 1 ? pw / (n - 1) : pw;
  const every = Math.max(1, Math.ceil((Math.max(...widths) + 12) / step));
  let leftEdge = Infinity;
  for (let i = n - 1; i >= 0; i--) {
    if ((n - 1 - i) % every) continue;
    const w = widths[i];
    const cx = Math.min(W - w / 2, Math.max(w / 2, X(i)));
    if (cx + w / 2 + 8 > leftEdge) continue;
    leftEdge = cx - w / 2;
    grid.append(h("text", { x: r1(cx), y: H - 6, "text-anchor": "middle" }, data.labels[i]));
  }

  const hover = bar
    ? h("rect", { class: "fsk-ch-band", x: 0, y: pad.top, width: r1(band), height: ph, rx: Math.min(radius * 1.5, 8), visibility: "hidden" })
    : h("line", { class: "fsk-ch-cross", x1: 0, x2: 0, y1: pad.top, y2: pad.top + ph, visibility: "hidden" });
  const marks = h("g", {});
  const byIndex = data.labels.map(() => []);
  const dots = [];
  let groupW = 0;

  if (bar) {
    const ns = stacked ? 1 : Math.max(1, main.length);
    groupW = Math.min(band * (ns > 1 ? 0.78 : 0.6), ns * (stacked ? 36 : 28));
    const gap = ns > 1 ? Math.min(2, groupW * 0.05) : 0;
    const bw = (groupW - gap * (ns - 1)) / ns;
    const r = Math.min(radius, bw / 2.5, 6);
    data.labels.forEach((_, i) => {
      const x0 = X(i) - groupW / 2;
      if (stacked) {
        let acc = 0;
        const segs = main.filter((x) => at(x.s, i) > 0);
        segs.forEach((x, k) => {
          const base = Y(acc), top = Y(acc + at(x.s, i));
          acc += at(x.s, i);
          const b = k ? base - 1.5 : base; // a hairline of paper between segments
          const d = k === segs.length - 1 ? barPath(x0, bw, b, top, r) : barPath(x0, bw, b, Math.min(top, b - 0.5), 0);
          const el = h("path", { class: `fsk-ch-bar ${x.cls}`, d, style: { "--i": i * 1 + k * 0.5 } });
          byIndex[i].push(el);
          marks.append(el);
        });
      } else {
        main.forEach((x, si) => {
          const el = h("path", { class: `fsk-ch-bar ${x.cls}`, d: barPath(x0 + si * (bw + gap), bw, zero, Y(at(x.s, i)), r), style: { "--i": i } });
          byIndex[i].push(el);
          marks.append(el);
        });
      }
      if (cmp) {
        const y = r1(Y(at(cmp.s, i)));
        const ends = { x1: r1(x0 - 4), x2: r1(x0 + groupW + 4), y1: y, y2: y };
        const el = h("line", { class: `fsk-ch-mark ${cmp.cls}`, ...ends });
        byIndex[i].push(el);
        marks.append(h("line", { class: "fsk-ch-mark-bg", ...ends }), el); // a paper halo keeps the dashes legible over bars
      }
    });
  } else {
    // The compare line goes under the others; the lead series gets the soft area and the end dot.
    const order = [...shown].sort((a, b) => Number(!!b.s.compare) - Number(!!a.s.compare));
    const lead = main[0];
    for (const x of order) {
      const g = h("g", { class: x.cls });
      const pts = data.labels.map((_, i) => [X(i), Y(at(x.s, i))]);
      const d = smoothPath(pts);
      if (x === lead && n > 1) {
        const id = `fsk-ch-grad-${++seq}`;
        g.append(
          h("defs", {}, h("linearGradient", { id, x1: 0, y1: 0, x2: 0, y2: 1 },
            h("stop", { offset: "0%", "stop-color": "currentColor", "stop-opacity": main.length > 1 ? 0.12 : 0.22 }),
            h("stop", { offset: "100%", "stop-color": "currentColor", "stop-opacity": 0 }))),
          h("path", { class: "fsk-ch-area", d: `${d}L${r1(pts[n - 1][0])} ${pad.top + ph}L${r1(pts[0][0])} ${pad.top + ph}Z`, fill: `url(#${id})` }));
      }
      g.append(h("path", { class: `fsk-ch-line fsk-ch-line--${x.s.compare ? "cmp" : "main"}`, d, pathLength: x.s.compare ? null : 1 }));
      if (!x.s.compare) {
        const [ex, ey] = pts[n - 1];
        if (x === lead) g.append(h("circle", { class: "fsk-ch-halo", cx: r1(ex), cy: r1(ey), r: 7.5 }));
        g.append(h("circle", { class: "fsk-ch-end", cx: r1(ex), cy: r1(ey), r: x === lead ? 4 : 3 }));
      }
      const dot = h("circle", { class: "fsk-ch-dot", cx: 0, cy: 0, r: 4.25, visibility: "hidden" });
      g.append(dot);
      dots.push({ el: dot, s: x.s });
      marks.append(g);
    }
  }

  // Pointer and keyboard readout. Screen readers get the same numbers from the hidden table.
  const f = (v) => formatValue(v, data.format);
  const hide = () => {
    tip.hidden = true;
    hover.setAttribute("visibility", "hidden");
    dots.forEach((d) => d.el.setAttribute("visibility", "hidden"));
    byIndex.forEach((els) => els.forEach((el) => el.classList.remove("fsk-ch-dim")));
  };
  const showAt = (i) => {
    if (i < 0 || i >= n) { hide(); return; }
    const x = X(i);
    if (bar) hover.setAttribute("x", String(r1(pad.left + band * i)));
    else { hover.setAttribute("x1", String(Math.round(x) + 0.5)); hover.setAttribute("x2", String(Math.round(x) + 0.5)); }
    hover.setAttribute("visibility", "visible");
    dots.forEach((d) => { d.el.setAttribute("cx", String(r1(x))); d.el.setAttribute("cy", String(r1(Y(at(d.s, i))))); d.el.setAttribute("visibility", "visible"); });
    byIndex.forEach((els, k) => els.forEach((el) => el.classList.toggle("fsk-ch-dim", k !== i)));
    const rows = shown.map((x) => h("span", { class: "fsk-ch-tip-row" }, h("i", { class: `fsk-ch-sw ${x.cls}` }), x.s.name, h("b", { class: "fsk-num" }, f(at(x.s, i)))));
    const total = stacked && h("span", { class: "fsk-ch-tip-row fsk-ch-tip-total" }, "Total", h("b", { class: "fsk-num" }, f(totals[i])));
    let change = null;
    if (cmp && main.length && (stacked || main.length === 1)) {
      const now = stacked ? totals[i] : at(main[0].s, i), then = at(cmp.s, i);
      if (then) change = h("span", { class: "fsk-ch-tip-row" }, deltaPill(Math.round(((now - then) / Math.abs(then)) * 1000) / 10, data.headline?.good ?? true), `vs ${cmp.s.name}`);
    }
    tip.replaceChildren(h("strong", {}, data.labels[i]), ...rows, ...[total, change].filter((x) => !!x));
    tip.hidden = false;
    const tw = tip.offsetWidth, th = tip.offsetHeight;
    const reach = bar ? groupW / 2 + 8 : 14;
    const left = x + reach + tw <= W ? x + reach : Math.max(0, x - reach - tw);
    // Keep the readout off the point it describes: below it when the point is high, above when low.
    const py = main.length ? Y(stacked ? totals[i] : at(main[0].s, i)) : pad.top;
    const top = py < pad.top + ph / 2 ? Math.min(H - th, pad.top + ph - th) : 0;
    tip.style.left = `${Math.round(left)}px`;
    tip.style.top = `${Math.round(Math.max(0, top))}px`;
  };
  const indexAt = (clientX) => {
    const px = clientX - svg.getBoundingClientRect().left - pad.left;
    return Math.max(0, Math.min(n - 1, bar ? Math.floor(px / band) : Math.round((px / pw) * (n - 1))));
  };
  const hit = h("rect", { x: Math.max(0, pad.left - 6), y: 0, width: pw + 6 + pad.right, height: pad.top + ph, fill: "transparent" });
  hit.addEventListener("pointermove", (e) => showAt(indexAt(e.clientX)));
  hit.addEventListener("pointerdown", (e) => showAt(indexAt(e.clientX)));
  hit.addEventListener("pointerleave", (e) => { if (e.pointerType === "mouse") hide(); });

  svg.append(grid, hover, marks, hit);
  box.replaceChildren(svg, tip);
  return { showAt, hide };
}

function cartesian(data, series, win) {
  const off = new Set();
  const n = data.labels.length;
  const box = h("div", { class: "fsk-ch-plot", role: "img", tabindex: 0, "aria-label": summary(data, series) });
  let chart = null;
  let cur = -1;
  let width = 0;
  let first = true;
  const paint = (force = false) => {
    const w = box.clientWidth;
    if (!w || (!force && Math.abs(w - width) < 1)) return;
    width = w;
    chart = drawCartesian(box, data, series, off, first);
    first = false;
    if (cur >= 0) chart.showAt(cur);
  };

  const keys = series.length > 1 ? series.map((s, i) => h("button", {
    class: "fsk-ch-key", type: "button", "aria-pressed": "true",
    onclick: () => {
      const mainShown = series.filter((x, k) => !x.compare && !off.has(k)).length;
      if (!off.has(i) && !s.compare && mainShown <= 1) return; // one series always stays
      if (off.has(i)) off.delete(i); else off.add(i);
      syncKeys();
      paint(true);
    },
  }, h("i", { class: `fsk-ch-sw ${seriesClass(series, i)}`, "aria-hidden": "true" }), s.name)) : [];
  const syncKeys = () => {
    const mainShown = series.filter((x, k) => !x.compare && !off.has(k)).length;
    keys.forEach((k, i) => {
      k.setAttribute("aria-pressed", String(!off.has(i)));
      const last = !series[i].compare && !off.has(i) && mainShown <= 1;
      k.setAttribute("aria-disabled", last ? "true" : "false");
      k.title = last ? "At least one series stays on" : off.has(i) ? `Show ${series[i].name}` : `Hide ${series[i].name}`;
    });
  };
  syncKeys();

  box.addEventListener("keydown", (e) => {
    if (!chart || !n) return;
    let i = cur < 0 ? n - 1 : cur;
    if (e.key === "ArrowLeft") i = Math.max(0, i - 1);
    else if (e.key === "ArrowRight") i = Math.min(n - 1, i + 1);
    else if (e.key === "Home") i = 0;
    else if (e.key === "End") i = n - 1;
    else if (e.key === "Escape") { cur = -1; chart.hide(); return; }
    else return;
    e.preventDefault();
    cur = i;
    chart.showAt(i);
  });
  box.addEventListener("focus", () => { if (box.matches(":focus-visible") && chart && n) { cur = n - 1; chart.showAt(cur); } });
  box.addEventListener("blur", () => { cur = -1; chart?.hide(); });
  // A tap elsewhere puts the touch readout away. composedPath() sees through the SDK's shadow root.
  const away = (e) => { if (e.pointerType !== "mouse" && !e.composedPath().includes(box)) { cur = -1; chart?.hide(); } };
  box.ownerDocument.addEventListener("pointerdown", away);

  let frame = 0;
  const ro = typeof ResizeObserver === "function" ? new ResizeObserver(() => { win.cancelAnimationFrame(frame); frame = win.requestAnimationFrame(() => paint()); }) : null;
  ro?.observe(box);
  win.requestAnimationFrame(() => paint());

  const el = h("div", { class: "fsk-ch-body" },
    keys.length > 0 && h("div", { class: "fsk-ch-legend", role: "group", "aria-label": "Series" }, keys),
    box,
    dataTable(data, series));
  return { el, dispose: () => { ro?.disconnect(); win.cancelAnimationFrame(frame); box.ownerDocument.removeEventListener("pointerdown", away); } };
}

function donut(data, series) {
  const s = series.find((x) => !x.compare);
  let slices = data.labels.map((label, i) => ({ label, value: Math.max(0, at(s, i)), other: false })).filter((x) => x.value > 0);
  if (slices.length > 5) slices = [...slices.slice(0, 4), { label: "Other", value: sum(slices.slice(4).map((x) => x.value)), other: true }];
  const total = sum(slices.map((x) => x.value));
  const f = (v) => formatValue(v, data.format);
  const pct = (v) => `${total ? Math.round((v / total) * 100) : 0}%`;
  const box = h("div", { class: "fsk-ch-ring", role: "img", "aria-label": summary(data, series) });
  if (!total) {
    box.append(h("p", { class: "fsk-ch-none" }, "No data."));
    return { el: h("div", { class: "fsk-ch-donut" }, box), dispose: () => {} };
  }

  const C = 50, R = 42;
  const gap = slices.length > 1 ? 1.2 : 0;
  let startAt = 0;
  const arcs = slices.map((x, i) => {
    const share = (x.value / total) * 100;
    const len = Math.max(0.4, share - gap);
    const arc = h("circle", {
      class: `fsk-ch-slice fsk-ch-s${x.other ? 4 : i}`, cx: C, cy: C, r: R, pathLength: 100,
      "stroke-dasharray": `${r1(len)} ${r1(100 - len)}`, "stroke-dashoffset": r1(-(startAt + gap / 2)), style: { "--i": i },
      onpointerenter: () => preview(i), onpointerleave: () => preview(sel), onclick: () => select(sel === i ? -1 : i),
    }, h("title", {}, `${x.label}: ${f(x.value)} (${pct(x.value)})`));
    startAt += share;
    return arc;
  });
  const svg = h("svg", { viewBox: "0 0 100 100", class: "fsk-ch-anim", "aria-hidden": "true", focusable: "false" },
    h("circle", { class: "fsk-ch-track", cx: C, cy: C, r: R }), arcs);
  const big = h("b", { class: "fsk-num" });
  const small = h("span", {});
  box.append(svg, h("div", { class: "fsk-ch-center", "aria-hidden": "true" }, big, small));

  const rows = slices.map((x, i) => h("button", {
    class: "fsk-ch-row", type: "button", "aria-pressed": "false",
    onpointerenter: () => preview(i), onpointerleave: () => preview(sel), onfocus: () => preview(i), onblur: () => preview(sel),
    onclick: () => select(sel === i ? -1 : i),
  },
    h("i", { class: `fsk-ch-sw fsk-ch-s${x.other ? 4 : i}`, "aria-hidden": "true" }),
    h("span", { class: "fsk-ch-row-name" }, x.label),
    h("span", { class: "fsk-ch-row-share fsk-num" }, pct(x.value)),
    h("span", { class: "fsk-ch-row-val fsk-num" }, f(x.value))));
  const list = h("div", { class: "fsk-ch-slices", role: "group", "aria-label": "Slices" }, rows);

  // The center shows the leading slice, or the one hovered or picked.
  const lead = slices.reduce((b, x, i) => (x.value > slices[b].value ? i : b), 0);
  let sel = -1;
  function preview(i) {
    const k = i < 0 ? lead : i;
    big.textContent = pct(slices[k].value);
    small.textContent = slices[k].label;
    if (i < 0) box.removeAttribute("data-sel"); else box.setAttribute("data-sel", String(i));
    arcs.forEach((a, j) => a.classList.toggle("fsk-ch-on", j === i));
    if (i < 0) list.removeAttribute("data-sel"); else list.setAttribute("data-sel", "");
  }
  function select(i) {
    sel = i;
    rows.forEach((r, j) => r.setAttribute("aria-pressed", String(j === i)));
    preview(i);
  }
  preview(-1);

  return { el: h("div", { class: "fsk-ch-donut" }, box, list, dataTable(data, series)), dispose: () => {} };
}

const TYPE_ICON = { line: "chart", bar: "bars", donut: "pie" };

/** Read-only: draws the chart and reports "displayed", so the agent doesn't wait. The agent already has the numbers from execute. */
export function mount({ root, head, data, api, surface = "desktop" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-ch", CSS);
  const win = root.ownerDocument.defaultView ?? window;
  const series = pickSeries(data.series);
  const hl = headlineOf(data, series);
  const body = data.type === "donut" ? donut(data, series) : cartesian(data, series, win);

  const card = h("section", { class: "fsk fsk-card fsk-ch", "data-type": data.type, "data-surface": surface, "aria-label": data.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip", "aria-hidden": "true" }, icon(data.icon ?? TYPE_ICON[data.type], 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, data.title), data.subtitle && h("p", { class: "fsk-sub" }, data.subtitle))),
    hl && headlineBlock(hl, data.format),
    body.el,
    (data.footnote || data.link) && h("footer", { class: "fsk-ch-foot" },
      h("span", {}, data.footnote ?? ""),
      data.link && h("a", { class: "fsk-btn fsk-btn--link", href: data.link.href, target: "_top" }, data.link.label, icon("chevron", 14))));

  root.replaceChildren(card);
  api?.displayed?.(); // read-only: shown, the agent doesn't wait
  return () => { body.dispose(); root.replaceChildren(); };
}

/** The states this card draws besides its data. */
export const states = ["loading", "empty", "error"];

const SK_BARS = [46, 58, 52, 66, 61, 74, 70, 84];

/** Loading (a headline and bars on an axis), empty or error, drawn as this card. Read-only: report displayed() yourself if the agent shouldn't wait. */
export function mountState({ root, head, state, title, subtitle, surface = "desktop" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-ch", CSS);
  const skeleton = () => h("div", {},
    h("div", { class: "fsk-ch-sk-hl" }, bone("38%", "24px"), bone("44px", "16px", { cls: "fsk-bone--round", i: 1 })),
    bone("30%", "9px", { i: 2 }),
    h("div", { class: "fsk-ch-sk-plot" }, SK_BARS.map((v, i) => h("span", {}, bone("100%", `${v}%`, { i: i + 2 })))),
    h("div", { class: "fsk-ch-sk-axis" }, [0, 1, 2, 3].map((i) => bone("26px", "8px", { i: i + 3 }))));
  const card = stateCard({ state, cls: "fsk-ch", icon: "chart", title, subtitle, surface, skeleton });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

export const fixtures = {
  default: {
    type: "line",
    title: "Revenue by month",
    subtitle: "Jan to Nov 2026 · all plans",
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov"],
    series: [
      { name: "2026", values: [118400, 124900, 131200, 128700, 139500, 146800, 152300, 149900, 161700, 172400, 184200] },
      { name: "2025", values: [96200, 99800, 104500, 108100, 111900, 115300, 118700, 121400, 126900, 131800, 138600], compare: true },
    ],
    format: { style: "currency" },
    headline: { value: 184200, label: "Revenue in November", delta: 32.9, vs: "vs Nov 2025" },
    footnote: "Excludes refunds",
    link: { label: "Open report", href: "/reports/revenue?by=month" },
  },
  signups: {
    type: "bar",
    stacked: true,
    title: "Signups by channel",
    subtitle: "Last 8 weeks",
    labels: ["Sep 29", "Oct 6", "Oct 13", "Oct 20", "Oct 27", "Nov 3", "Nov 10", "Nov 17"],
    series: [
      { name: "Organic", values: [412, 438, 451, 470, 462, 495, 521, 548] },
      { name: "Paid", values: [210, 236, 198, 254, 281, 266, 302, 318] },
      { name: "Referral", values: [88, 94, 101, 97, 112, 126, 131, 149] },
      { name: "Last year", values: [610, 640, 655, 690, 705, 720, 760, 790], compare: true },
    ],
    headline: { value: 1015, label: "Signups, week of Nov 17", delta: 6.4, vs: "vs the week before" },
  },
  planMix: {
    type: "donut",
    title: "Accounts by plan",
    subtitle: "Paying accounts · November",
    labels: ["Pro", "Business", "Starter", "Enterprise", "Legacy"],
    series: [{ name: "Accounts", values: [1046, 684, 438, 312, 96] }],
    headline: { label: "Paying accounts", delta: 4.8, vs: "vs October" },
    link: { label: "Open accounts", href: "/accounts?status=paying" },
  },
};
```

### fs-kit (shared by every template)

TypeScript: /ui-catalog/files/ts/fs-kit.ts, JavaScript: /ui-catalog/files/js/fs-kit.js
