# Report

A report the agent opens beside the chat: headline numbers, one chart, a breakdown and what stands out. The agent explains it and answers follow-ups from the same state; it can't change the numbers.

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

A report the agent opens beside the chat: headline numbers, one chart, a breakdown and what stands out. The agent explains it and answers follow-ups from the same state; it can't change the numbers.

## When to use it

**Use it when:** The user asks how something did over a period and the answer needs room: a few headline numbers, a trend, a breakdown and what stands out. The agent explains it beside the chat and answers follow-ups from the same state.

**Use something else when:** A few numbers that fit in the chat (KPI tiles card). Data the user edits (table or form canvas). Raw exports with hundreds of rows (link to your app). Mobile: the canvas isn't available; use the summary card (mountMobile).

## What the agent receives

| The template calls | The agent gets | When |
| --- | --- | --- |
| `canvas.state` | `Canvas state` | With every message. READ_MODE: the agent reads the numbers and findings and explains them; any change it tries is refused. |
| `canvas.setTitle(title)` | `Canvas title` | When the report draws. The header and the chat card show it. |
| `displayed()` | `FUNCTION_TOOL_DISPLAYED` | Mobile summary card: as soon as it shows. |

## States

Besides its data, the template draws these as itself: `mountState()` on the canvas, `mountMobileState()` in the mobile card. Pick one on the preview with **State**.

| State | When it shows |
| --- | --- |
| Loading | The canvas opens at once while renderCanvas fetches the numbers, and again after Try again. The agent reads the report once it's in the canvas state. |
| Empty | The period has no data yet. The report says so and offers the latest period that has some. |
| Error | The report's data didn't load. execute or renderCanvas got the failure; Try again loads it in place. |

```ts
mountState({ root, head, title: "…", state: { kind: "error", text: "…", retry } });
mountMobileState({ 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

### ReportState

| Field | Type | Notes |
| --- | --- | --- |
| `canvasTitle` (optional) | `string` | The canvas header (setTitle, up to 80 characters). Default: the title. |
| `eyebrow` (optional) | `string` |  |
| `title` | `string` |  |
| `summary` (optional) | `string` | One or two sentences that answer the user's question. |
| `period` (optional) | `string` | The period the numbers cover, such as "Oct 1 to Oct 31, 2026". |
| `updated` (optional) | `string` | When the data was read, such as "8 min ago". |
| `kpis` | `ReportKpi[]` | 2 to 4 headline numbers; more are cut. |
| `chart` (optional) | `ReportChart` |  |
| `table` (optional) | `ReportTable` |  |
| `insights` (optional) | `ReportInsight[]` | 2 to 4 findings, written by the agent or your backend. |

### ReportKpi

| Field | Type | Notes |
| --- | --- | --- |
| `label` | `string` |  |
| `value` | `number \| string` |  |
| `format` (optional) | `NumberFormat` |  |
| `delta` (optional) | `{ value: number; good?: boolean; vs?: string }` | Change in percent vs the previous period. good: false when up is bad (costs, churn). |
| `trend` (optional) | `number[]` | Recent values, oldest first, for the sparkline. |

### ReportChart

| Field | Type | Notes |
| --- | --- | --- |
| `type` | `"bar" \| "line"` | bar for amounts per period or category, line for a trend. |
| `title` | `string` |  |
| `labels` | `string[]` | The x-axis labels, oldest first. |
| `series` | `ReportSeries[]` | 1 to 3 series; more are cut. |
| `format` (optional) | `NumberFormat` | How the axis and the tooltip format values. |

### ReportSeries

| Field | Type | Notes |
| --- | --- | --- |
| `name` | `string` |  |
| `values` | `number[]` | One value per chart label, in the same order. |
| `compare` (optional) | `boolean` | A comparison series (last period, target): drawn muted, dashed on a line chart. |

### ReportTable

| Field | Type | Notes |
| --- | --- | --- |
| `title` | `string` |  |
| `rowLabel` | `string` | The first column's header, such as "Plan" or "Region". |
| `columns` | `ReportColumn[]` |  |
| `rows` | `ReportRow[]` | Sorted the way you want them shown (biggest first). |
| `limit` (optional) | `number` | Rows shown (default 6). The rest show as "N more". |

### ReportColumn

| Field | Type | Notes |
| --- | --- | --- |
| `label` | `string` |  |
| `format` (optional) | `NumberFormat` |  |
| `delta` (optional) | `boolean` | A change column in percent: an arrow, colored by sign. |
| `upIsGood` (optional) | `boolean` | For a change column: false when up is bad (costs, churn). |
| `bar` (optional) | `boolean` | Draws a share bar next to the numbers, scaled to the column's largest value. |

### ReportRow

| Field | Type | Notes |
| --- | --- | --- |
| `label` | `string` |  |
| `values` | `(number \| string)[]` | One value per column, in the same order. |

### ReportInsight

| Field | Type | Notes |
| --- | --- | --- |
| `tone` | `"positive" \| "negative" \| "neutral"` | positive (good news), negative (needs attention) or neutral (context). |
| `title` | `string` | One short line the user can scan. |
| `detail` (optional) | `string` |  |

### ReportActions

| Field | Type | Notes |
| --- | --- | --- |
| `openInApp()` (optional) | `() => void` | Opens the full report in your app. Adds "Open in app" to the header and the table. |

## 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/report-canvas.hosted.ts), [JavaScript](/ui-catalog/files/js/usage/report-canvas.hosted.js)
- In-page handler: [TypeScript](/ui-catalog/files/ts/usage/report-canvas.canvas.ts), [JavaScript](/ui-catalog/files/js/usage/report-canvas.canvas.js)
- report-canvas: [TypeScript](/ui-catalog/files/ts/report-canvas.ts), [JavaScript](/ui-catalog/files/js/report-canvas.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/open_revenue_report/index.ts"
// agent/actions/open_revenue_report/index.ts: a hosted canvas action (desktop).
// Copy the template (report-canvas.ts) and fs-kit.ts into agent/ui/.

type Result = ReportState | { error: string; title: string; month?: string };

// The canvas's first state, and what the agent reads with every message. Keep it under about 3 KB:
// headline numbers, the chart series, the top rows and the findings. The full data stays in your app.
// A failure goes back as data: the agent explains it, and the canvas shows it.
export async function execute(args: { month?: string }, ctx: ActionContext): Promise<Result> {
  return fetchReport(ctx, args.month);
}

async function fetchReport(ctx: ActionContext, month = "current"): Promise<Result> {
  const res = await ctx.fetch(`/api/reports/revenue?month=${encodeURIComponent(month)}`);
  if (!res.ok) return { error: `The reporting service didn't answer (${res.status}). Nothing in your account changed.`, title: "Revenue report", month };
  return { ...(await res.json()), error: null }; // { title, period, kpis, chart, table, insights }
}

export function renderCanvas(ctx: CanvasActionContext) {
  const canvas = liveCanvas(ctx.canvas); // canvas.state follows your setState calls and the agent's edits
  canvas.setType("REPORT");
  canvas.setStatus("READ_MODE"); // the agent explains the numbers; it can't change them
  const at = { root: canvas.root, head: canvas.head, canvas };
  let cleanup: Cleanup = () => {};

  const draw = (): void => {
    cleanup();
    const st = canvas.state;
    if (st.error) {
      cleanup = mountState({ ...at, title: st.title, state: { kind: "error", title: "Couldn't load the revenue report", text: st.error, retry: () => reload(st.month) } });
    } else if (!st.kpis?.length) {
      // No data for the period yet (the month hasn't closed): say so, offer the last full month.
      cleanup = mountState({ ...at, title: st.title, subtitle: st.period, state: { kind: "empty", icon: "calendar",
        title: "This month isn't closed yet", text: "A month's revenue shows up here once its invoices are final.",
        action: { label: "Show last month", onClick: () => reload("previous") } } });
    } else {
      cleanup = mount({ ...at, actions: { openInApp: () => ctx.nav.go("/reports/revenue") } });
    }
  };

  // Bones in the report's shape while it loads, then the report, or the error again.
  async function reload(month?: string): Promise<void> {
    cleanup();
    cleanup = mountState({ ...at, title: canvas.state.title, state: { kind: "loading", label: "Loading the revenue report…" } });
    canvas.setState(await fetchReport(ctx, month)); // error: null on success, so draw() shows the report
    draw();
  }

  draw();
  return () => cleanup();
}
```

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

// The canvas's first state, and what the agent reads with every message. Keep it under about 3 KB:
// headline numbers, the chart series, the top rows and the findings. The full data stays in your app.
// A failure goes back as data: the agent explains it, and the canvas shows it.
export async function execute(args, ctx) {
  return fetchReport(ctx, args.month);
}

async function fetchReport(ctx, month = "current") {
  const res = await ctx.fetch(`/api/reports/revenue?month=${encodeURIComponent(month)}`);
  if (!res.ok) return { error: `The reporting service didn't answer (${res.status}). Nothing in your account changed.`, title: "Revenue report", month };
  return { ...(await res.json()), error: null }; // { title, period, kpis, chart, table, insights }
}

export function renderCanvas(ctx) {
  const canvas = liveCanvas(ctx.canvas); // canvas.state follows your setState calls and the agent's edits
  canvas.setType("REPORT");
  canvas.setStatus("READ_MODE"); // the agent explains the numbers; it can't change them
  const at = { root: canvas.root, head: canvas.head, canvas };
  let cleanup = () => {};

  const draw = () => {
    cleanup();
    const st = canvas.state;
    if (st.error) {
      cleanup = mountState({ ...at, title: st.title, state: { kind: "error", title: "Couldn't load the revenue report", text: st.error, retry: () => reload(st.month) } });
    } else if (!st.kpis?.length) {
      // No data for the period yet (the month hasn't closed): say so, offer the last full month.
      cleanup = mountState({ ...at, title: st.title, subtitle: st.period, state: { kind: "empty", icon: "calendar",
        title: "This month isn't closed yet", text: "A month's revenue shows up here once its invoices are final.",
        action: { label: "Show last month", onClick: () => reload("previous") } } });
    } else {
      cleanup = mount({ ...at, actions: { openInApp: () => ctx.nav.go("/reports/revenue") } });
    }
  };

  // Bones in the report's shape while it loads, then the report, or the error again.
  async function reload(month) {
    cleanup();
    cleanup = mountState({ ...at, title: canvas.state.title, state: { kind: "loading", label: "Loading the revenue report…" } });
    canvas.setState(await fetchReport(ctx, month)); // error: null on success, so draw() shows the report
    draw();
  }

  draw();
  return () => cleanup();
}
```

### In-page handler

```ts title="in-page handler.ts"
// An in-page canvas action (desktop). The SDK leaves canvas actions out on mobile,
// so mobile gets the summary card below.

type Result = ReportState | { error: string; title: string; month?: string };

// The canvas's first state, and what the agent reads: headline numbers, the chart series,
// the top rows and the findings. Summaries, not raw data: keep it under about 3 KB.
// A failure goes back as data too, so the agent can explain it.
const load = (month?: string): Promise<Result> => loadRevenueReport(month)
  .catch(() => ({ error: "The reporting service didn't answer. Nothing in your account changed.", title: "Revenue report", month }));

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    open_revenue_report: {
      execute: async ({ month }: { month?: string }): Promise<Result> => load(month),

      renderCanvas: (sdk: CanvasContext) => {
        const ctx = liveCanvas(sdk); // ctx.state follows your setState calls and the agent's edits
        ctx.setType("REPORT");
        ctx.setStatus("READ_MODE"); // the agent explains the numbers; it can't change them
        const at = { root: ctx.host, head: ctx.header, canvas: ctx };
        let cleanup: Cleanup = () => {};
        const draw = (): void => {
          cleanup();
          const st = ctx.state;
          if (st.error) cleanup = mountState({ ...at, title: st.title, state: { kind: "error", title: "Couldn't load the revenue report", text: st.error, retry: () => reload(st.month) } });
          // No data for the period yet (the month hasn't closed): say so, offer the last full month.
          else if (!st.kpis?.length) cleanup = mountState({ ...at, title: st.title, subtitle: st.period, state: { kind: "empty", icon: "calendar",
            title: "This month isn't closed yet", text: "A month's revenue shows up here once its invoices are final.",
            action: { label: "Show last month", onClick: () => reload("previous") } } });
          else cleanup = mount({ ...at, actions: { openInApp: () => router.push("/reports/revenue") } });
        };
        // Bones while it loads, then the report (or the error again). The agent reads the new state.
        async function reload(month?: string): Promise<void> {
          cleanup();
          cleanup = mountState({ ...at, title: ctx.state.title, state: { kind: "loading", label: "Loading the revenue report…" } });
          const next = await load(month);
          ctx.setState("error" in next ? next : { ...next, error: null });
          draw();
        }
        draw();
        return () => cleanup();
      },
    },

    // Mobile: a summary card with the same data, or the same states as a card.
    show_revenue_summary: {
      execute: async ({ month }: { month?: string }): Promise<Result> => load(month),
      renderComponent: ({ data, host, header, readyState }: ComponentContext<Result>) => {
        const at = { root: host, head: header, title: data.title };
        if ("error" in data) mountMobileState({ ...at, state: { kind: "error", text: data.error } });
        else if (!data.kpis.length) mountMobileState({ ...at, subtitle: data.period, state: { kind: "empty", icon: "calendar", title: "This month isn't closed yet", text: "A month's revenue shows up once its invoices are final." } });
        else return void mountMobile({ root: host, head: header, data, api: { displayed: () => readyState(data) } });
        readyState(data); // read-only: the agent goes on once it's shown
      },
    },
  });
});
```

```js title="in-page handler.js"
// An in-page canvas action (desktop). The SDK leaves canvas actions out on mobile,
// so mobile gets the summary card below.

// The canvas's first state, and what the agent reads: headline numbers, the chart series,
// the top rows and the findings. Summaries, not raw data: keep it under about 3 KB.
// A failure goes back as data too, so the agent can explain it.
const load = (month) => loadRevenueReport(month)
  .catch(() => ({ error: "The reporting service didn't answer. Nothing in your account changed.", title: "Revenue report", month }));

foldspace("when", "ready", () => {
  foldspace.agent({ /* …common setup… */ }).addActionHandlers({
    open_revenue_report: {
      execute: async ({ month }) => load(month),

      renderCanvas: (sdk) => {
        const ctx = liveCanvas(sdk); // ctx.state follows your setState calls and the agent's edits
        ctx.setType("REPORT");
        ctx.setStatus("READ_MODE"); // the agent explains the numbers; it can't change them
        const at = { root: ctx.host, head: ctx.header, canvas: ctx };
        let cleanup = () => {};
        const draw = () => {
          cleanup();
          const st = ctx.state;
          if (st.error) cleanup = mountState({ ...at, title: st.title, state: { kind: "error", title: "Couldn't load the revenue report", text: st.error, retry: () => reload(st.month) } });
          // No data for the period yet (the month hasn't closed): say so, offer the last full month.
          else if (!st.kpis?.length) cleanup = mountState({ ...at, title: st.title, subtitle: st.period, state: { kind: "empty", icon: "calendar",
            title: "This month isn't closed yet", text: "A month's revenue shows up here once its invoices are final.",
            action: { label: "Show last month", onClick: () => reload("previous") } } });
          else cleanup = mount({ ...at, actions: { openInApp: () => router.push("/reports/revenue") } });
        };
        // Bones while it loads, then the report (or the error again). The agent reads the new state.
        async function reload(month) {
          cleanup();
          cleanup = mountState({ ...at, title: ctx.state.title, state: { kind: "loading", label: "Loading the revenue report…" } });
          const next = await load(month);
          ctx.setState("error" in next ? next : { ...next, error: null });
          draw();
        }
        draw();
        return () => cleanup();
      },
    },

    // Mobile: a summary card with the same data, or the same states as a card.
    show_revenue_summary: {
      execute: async ({ month }) => load(month),
      renderComponent: ({ data, host, header, readyState }) => {
        const at = { root: host, head: header, title: data.title };
        if ("error" in data) mountMobileState({ ...at, state: { kind: "error", text: data.error } });
        else if (!data.kpis.length) mountMobileState({ ...at, subtitle: data.period, state: { kind: "empty", icon: "calendar", title: "This month isn't closed yet", text: "A month's revenue shows up once its invoices are final." } });
        else return void mountMobile({ root: host, head: header, data, api: { displayed: () => readyState(data) } });
        readyState(data); // read-only: the agent goes on once it's shown
      },
    },
  });
});
```

### report-canvas

```ts title="agent/ui/report-canvas.ts"
// Template: report-canvas. A read-only REPORT canvas the agent opens beside the chat: headline numbers, one chart, a breakdown table and its findings.

export interface ReportKpi {
  label: string;
  value: number | string;
  format?: NumberFormat;
  /** Change in percent vs the previous period. good: false when up is bad (costs, churn). */
  delta?: { value: number; good?: boolean; vs?: string };
  /** Recent values, oldest first, for the sparkline. */
  trend?: number[];
}

export interface ReportSeries {
  name: string;
  /** One value per chart label, in the same order. */
  values: number[];
  /** A comparison series (last period, target): drawn muted, dashed on a line chart. */
  compare?: boolean;
}

export interface ReportChart {
  /** bar for amounts per period or category, line for a trend. */
  type: "bar" | "line";
  title: string;
  /** The x-axis labels, oldest first. */
  labels: string[];
  /** 1 to 3 series; more are cut. */
  series: ReportSeries[];
  /** How the axis and the tooltip format values. */
  format?: NumberFormat;
}

export interface ReportColumn {
  label: string;
  format?: NumberFormat;
  /** A change column in percent: an arrow, colored by sign. */
  delta?: boolean;
  /** For a change column: false when up is bad (costs, churn). */
  upIsGood?: boolean;
  /** Draws a share bar next to the numbers, scaled to the column's largest value. */
  bar?: boolean;
}

export interface ReportRow {
  label: string;
  /** One value per column, in the same order. */
  values: (number | string)[];
}

export interface ReportTable {
  title: string;
  /** The first column's header, such as "Plan" or "Region". */
  rowLabel: string;
  columns: ReportColumn[];
  /** Sorted the way you want them shown (biggest first). */
  rows: ReportRow[];
  /** Rows shown (default 6). The rest show as "N more". */
  limit?: number;
}

export interface ReportInsight {
  /** positive (good news), negative (needs attention) or neutral (context). */
  tone: "positive" | "negative" | "neutral";
  /** One short line the user can scan. */
  title: string;
  detail?: string;
}

/** What the agent reads with each message. Keep it under about 3 KB: summaries and top rows, not raw data. */
export interface ReportState {
  /** The canvas header (setTitle, up to 80 characters). Default: the title. */
  canvasTitle?: string;
  eyebrow?: string;
  title: string;
  /** One or two sentences that answer the user's question. */
  summary?: string;
  /** The period the numbers cover, such as "Oct 1 to Oct 31, 2026". */
  period?: string;
  /** When the data was read, such as "8 min ago". */
  updated?: string;
  /** 2 to 4 headline numbers; more are cut. */
  kpis: ReportKpi[];
  chart?: ReportChart;
  table?: ReportTable;
  /** 2 to 4 findings, written by the agent or your backend. */
  insights?: ReportInsight[];
}

export interface ReportActions {
  /** Opens the full report in your app. Adds "Open in app" to the header and the table. */
  openInApp?(): void;
}

export const meta = {
  id: "report-canvas",
  title: "Report",
  surface: "canvas",
  canvasType: "REPORT",
  kind: "read-only",
  mobile: "fallback-card",
  whenToUse: "The user asks how something did over a period and the answer needs room: a few headline numbers, a trend, a breakdown and what stands out. The agent explains it beside the chat and answers follow-ups from the same state.",
  whenNotToUse: "A few numbers that fit in the chat (KPI tiles card). Data the user edits (table or form canvas). Raw exports with hundreds of rows (link to your app). Mobile: the canvas isn't available; use the summary card (mountMobile).",
};

const CSS = `
.fsk-rep { min-height: 100%; background: var(--k-paper); container: fsk-rep / inline-size; }
.fsk-rep-inner { max-width: 960px; margin: 0 auto; padding: 28px 32px 48px; }
.fsk-rep-top { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
.fsk-rep-title { margin: 12px 0 8px; font-size: 1.6em; font-weight: 650; letter-spacing: -0.022em; line-height: 1.2; text-wrap: balance; }
.fsk-rep-meta { display: flex; flex-wrap: wrap; gap: 4px 16px; margin: 0; font-size: .86em; color: var(--k-text-2); }
.fsk-rep-meta span { display: inline-flex; align-items: center; gap: 6px; }
.fsk-rep-summary { margin: 16px 0 0; max-width: 66ch; font-size: 1.07em; line-height: 1.55; text-wrap: pretty; }

.fsk-rep-nav {
  position: sticky; top: 0; z-index: 2; display: flex; flex-wrap: wrap; gap: 2px;
  margin: 20px -32px 0; padding: 8px 28px; border-bottom: 1px solid transparent;
  background: color-mix(in srgb, var(--k-paper) 90%, transparent);
  -webkit-backdrop-filter: saturate(1.4) blur(10px); backdrop-filter: saturate(1.4) blur(10px);
  transition: border-color .2s;
}
.fsk-rep-nav[data-stuck] { border-bottom-color: var(--k-divider); }
.fsk-rep-navbtn {
  appearance: none; border: 0; background: none; font: inherit; font-size: .86em; color: var(--k-text-2);
  padding: 5px 10px; border-radius: var(--k-r-md); cursor: pointer; transition: background .15s, color .15s;
}
.fsk-rep-navbtn:hover { background: var(--k-hover); color: var(--k-text); }
.fsk-rep-navbtn[aria-current="true"] { background: var(--k-tint); color: var(--k-primary); font-weight: 600; }
.fsk-rep-navbtn:focus-visible, .fsk-rep-h:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }

.fsk-rep-sec { margin-top: 28px; scroll-margin-top: 56px; }
.fsk-rep-sec--first { margin-top: 20px; }
.fsk-rep-h { display: flex; align-items: center; gap: 8px; margin: 0 0 12px; font-size: 1em; font-weight: 600; letter-spacing: -0.005em; border-radius: 2px; }
.fsk-rep-h .fsk-icon { color: var(--k-text-2); }
.fsk-rep-panel { border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper); }

.fsk-rep-kpis { display: grid; gap: 12px; grid-template-columns: repeat(2, minmax(0, 1fr)); }
.fsk-rep-kpis[data-n="1"] { grid-template-columns: minmax(0, 1fr); }
.fsk-rep-kpis[data-n="3"] > :last-child { grid-column: 1 / -1; }
.fsk-rep-kpi {
  position: relative; display: flex; flex-direction: column; gap: 6px; min-width: 0; overflow: hidden;
  padding: 14px 14px 0; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper);
}
.fsk-rep-kpi-label { font-size: .86em; color: var(--k-text-2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.fsk-rep-kpi-value { font-size: 1.72em; font-weight: 650; letter-spacing: -0.02em; line-height: 1.1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.fsk-rep-kpi-row { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; min-height: 20px; }
.fsk-rep-kpi-vs { font-size: .79em; color: var(--k-text-2); }
.fsk-rep-kpi .fsk-spark { display: block; width: calc(100% + 28px); height: 36px; margin: 4px -14px 0; color: var(--k-primary); }
.fsk-rep-kpi--bad .fsk-spark { color: var(--k-error); }
.fsk-rep-kpi--flat .fsk-spark { color: var(--k-text-2); }
.fsk-rep-delta { display: inline-flex; align-items: center; gap: 2px; padding: 1px 6px 1px 4px; border-radius: 999px; font-size: .79em; font-weight: 600; }
.fsk-rep-delta--good { color: var(--k-success); background: color-mix(in srgb, var(--k-success) 12%, var(--k-paper)); }
.fsk-rep-delta--bad { color: var(--k-error); background: color-mix(in srgb, var(--k-error) 12%, var(--k-paper)); }
.fsk-rep-delta--flat { color: var(--k-text-2); background: var(--k-hover); }

.fsk-rep-chartpanel { padding: 16px 16px 10px; }
.fsk-rep-charthead { display: flex; align-items: baseline; justify-content: space-between; flex-wrap: wrap; gap: 6px 16px; margin-bottom: 10px; }
.fsk-rep-charttitle { margin: 0; font-size: .93em; font-weight: 600; }
.fsk-rep-legend { display: flex; flex-wrap: wrap; gap: 4px 14px; margin: 0; padding: 0; list-style: none; font-size: .79em; color: var(--k-text-2); }
.fsk-rep-legend li { display: inline-flex; align-items: center; gap: 6px; }
.fsk-rep-sw { display: inline-block; flex: none; width: 10px; height: 10px; border-radius: min(var(--k-r), 3px); background: currentColor; }
.fsk-rep-legend--line .fsk-rep-sw { width: 14px; height: 2px; border-radius: 2px; }
.fsk-rep-legend--line .fsk-rep-cmp.fsk-rep-sw { background: repeating-linear-gradient(90deg, currentColor 0 4px, transparent 4px 7px); }
.fsk-rep-chart { position: relative; height: 240px; }
.fsk-rep-svg { display: block; overflow: visible; }
.fsk-rep-svg text { fill: var(--k-text-2); font-size: 11px; font-family: inherit; font-variant-numeric: tabular-nums; }
.fsk-rep-grid line { stroke: var(--k-divider); shape-rendering: crispEdges; }
.fsk-rep-grid line.fsk-rep-base { stroke: var(--k-border); }
.fsk-rep-s0 { color: var(--k-primary); }
.fsk-rep-s1 { color: color-mix(in oklab, var(--k-primary) 50%, var(--k-text)); }
.fsk-rep-s2 { color: color-mix(in oklab, var(--k-primary) 50%, var(--k-warning)); }
.fsk-rep-cmp { color: color-mix(in srgb, var(--k-text-2) 75%, var(--k-paper)); }
.fsk-rep-bar { fill: currentColor; }
.fsk-rep-line { fill: none; stroke: currentColor; stroke-width: 2.25; stroke-linecap: round; stroke-linejoin: round; stroke-dasharray: 1; }
.fsk-rep-line--cmp { stroke-width: 1.75; stroke-dasharray: 4 4; }
.fsk-rep-end { fill: currentColor; stroke: var(--k-paper); stroke-width: 2; }
.fsk-rep-dot { fill: var(--k-paper); stroke: currentColor; stroke-width: 2; }
.fsk-rep-band { fill: var(--k-hover); }
.fsk-rep-guide { stroke: var(--k-border); stroke-dasharray: 3 3; }
.fsk-rep-tip {
  position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none; display: grid; gap: 3px; min-width: 132px;
  padding: 8px 10px; border: 1px solid var(--k-border); border-radius: var(--k-r-md); background: var(--k-paper);
  box-shadow: var(--k-shadow); font-size: .79em; white-space: nowrap;
}
.fsk-rep-tip strong { font-weight: 600; margin-bottom: 1px; }
.fsk-rep-tip-row { display: flex; align-items: center; gap: 6px; color: var(--k-text-2); }
.fsk-rep-tip-row b { margin-left: auto; padding-left: 12px; color: var(--k-text); font-weight: 600; }
.fsk-rep-empty { margin: 0; display: grid; place-items: center; height: 100%; color: var(--k-text-2); font-size: .86em; }
.fsk-rep-anim .fsk-rep-bar { transform-box: fill-box; transform-origin: 50% 100%; animation: fsk-rep-grow .6s var(--k-ease) both; animation-delay: calc(var(--i, 0) * 22ms); }
.fsk-rep-anim .fsk-rep-line:not(.fsk-rep-line--cmp) { animation: fsk-rep-draw 1s var(--k-ease) both; }
.fsk-rep-anim .fsk-rep-area, .fsk-rep-anim .fsk-rep-line--cmp, .fsk-rep-anim .fsk-rep-end { animation: fsk-rep-fade .6s .35s ease-out both; }

.fsk-rep-tablewrap { overflow-x: auto; }
.fsk-rep-table { width: 100%; border-collapse: collapse; font-size: .93em; }
.fsk-rep-table caption { text-align: left; }
.fsk-rep-table th, .fsk-rep-table td { padding: 10px 14px; text-align: left; white-space: nowrap; }
.fsk-rep-table thead th { font-size: .86em; font-weight: 500; color: var(--k-text-2); border-bottom: 1px solid var(--k-border); padding-top: 12px; padding-bottom: 10px; }
.fsk-rep-table tbody th { font-weight: 500; }
.fsk-rep-table tbody tr + tr > * { border-top: 1px solid var(--k-muted-border); }
.fsk-rep-table tbody tr:hover > * { background: var(--k-sunken); }
.fsk-rep-table .fsk-rep-r { text-align: right; }
.fsk-rep-rank { display: inline-block; min-width: 1.6em; color: var(--k-text-2); font-weight: 400; }
.fsk-rep-share { display: inline-flex; align-items: center; justify-content: flex-end; gap: 10px; }
.fsk-rep-track { width: 64px; height: 6px; border-radius: 999px; background: var(--k-hover); overflow: hidden; }
.fsk-rep-fill { display: block; height: 100%; border-radius: inherit; background: var(--k-primary); transform-origin: 0 50%; }
.fsk-rep-enter .fsk-rep-fill { animation: fsk-rep-grow-x .7s .1s var(--k-ease) both; }
.fsk-rep-chg { display: inline-flex; align-items: center; gap: 2px; font-weight: 600; }
.fsk-rep-chg--good { color: var(--k-success); }
.fsk-rep-chg--bad { color: var(--k-error); }
.fsk-rep-chg--flat { color: var(--k-text-2); font-weight: 500; }
.fsk-rep-tfoot { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 8px 8px 14px; border-top: 1px solid var(--k-border); font-size: .86em; color: var(--k-text-2); }

.fsk-rep-ins { display: grid; gap: 10px; margin: 0; padding: 0; list-style: none; }
.fsk-rep-in { display: grid; grid-template-columns: 32px minmax(0, 1fr); gap: 12px; padding: 14px; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper); }
.fsk-rep-in-ico { display: grid; place-items: center; width: 32px; height: 32px; border-radius: var(--k-r-md); }
.fsk-rep-in--positive .fsk-rep-in-ico { color: var(--k-success); background: color-mix(in srgb, var(--k-success) 12%, var(--k-paper)); }
.fsk-rep-in--negative .fsk-rep-in-ico { color: var(--k-error); background: color-mix(in srgb, var(--k-error) 12%, var(--k-paper)); }
.fsk-rep-in--neutral .fsk-rep-in-ico { color: var(--k-text-2); background: var(--k-hover); }
.fsk-rep-in-title { margin: 5px 0 0; font-weight: 600; line-height: 1.35; text-wrap: pretty; }
.fsk-rep-in-detail { margin: 4px 0 0; color: var(--k-text-2); font-size: .93em; text-wrap: pretty; }
.fsk-rep-foot { display: flex; align-items: center; gap: 6px; margin: 28px 0 0; font-size: .86em; color: var(--k-text-2); }

@container fsk-rep (min-width: 600px) {
  .fsk-rep-kpis[data-n="3"] { grid-template-columns: repeat(3, minmax(0, 1fr)); }
  .fsk-rep-kpis[data-n="3"] > :last-child { grid-column: auto; }
}
@container fsk-rep (min-width: 760px) { .fsk-rep-ins { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@container fsk-rep (min-width: 840px) { .fsk-rep-kpis[data-n="4"] { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
@container fsk-rep (max-width: 520px) {
  .fsk-rep-inner { padding: 20px 16px 36px; }
  .fsk-rep-nav { margin: 16px -16px 0; padding: 8px 12px; }
  .fsk-rep-title { font-size: 1.4em; }
  .fsk-rep-top .fsk-btn span { display: none; }
  .fsk-rep-chart { height: 200px; }
  .fsk-rep-chartpanel { padding: 14px 12px 8px; }
  .fsk-rep-table th, .fsk-rep-table td { padding: 9px 10px; }
  .fsk-rep-track { display: none; }
}
@keyframes fsk-rep-grow { from { transform: scaleY(0); } }
@keyframes fsk-rep-grow-x { from { transform: scaleX(0); } }
@keyframes fsk-rep-draw { from { stroke-dashoffset: 1; } to { stroke-dashoffset: 0; } }
@keyframes fsk-rep-fade { from { opacity: 0; } }

/* Mobile summary card */
.fsk-repc .fsk-repc-kpis { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
.fsk-repc .fsk-repc-kpi { display: flex; flex-direction: column; gap: 4px; min-width: 0; padding: 10px 12px; border-radius: var(--k-r-md); background: var(--k-sunken); }
.fsk-repc .fsk-rep-kpi-value { font-size: 1.36em; }
.fsk-repc .fsk-repc-ins { list-style: none; margin: 14px 0 0; padding: 0; display: grid; gap: 10px; }
.fsk-repc .fsk-repc-ins li { display: flex; align-items: flex-start; gap: 10px; }
.fsk-repc .fsk-rep-in-ico { width: 24px; height: 24px; flex: none; }
.fsk-repc .fsk-repc-ins span:last-child { padding-top: 2px; font-size: .93em; line-height: 1.4; }
.fsk-repc .fsk-repc-foot { display: flex; align-items: center; gap: 6px; margin: 14px 0 0; padding-top: 12px; border-top: 1px solid var(--k-divider); font-size: .79em; color: var(--k-text-2); }

/* States (mountState): the report's own page, with a skeleton in its shape or a centered block */
.fsk-rep-st { display: flex; flex-direction: column; }
.fsk-rep-st > .fsk-rep-inner { flex: 1; display: flex; flex-direction: column; width: 100%; }
.fsk-rep-st .fsk-badge { align-self: flex-start; }
.fsk-rep-st .fsk-rep-title .fsk-bone { margin: 4px 0; }
.fsk-rep-st .fsk-rep-summary.fsk-sk-lines { margin-top: 18px; }
.fsk-rep-sk-nav { display: flex; gap: 8px; margin: 22px 0 0; padding: 8px 0 4px; }
.fsk-rep-sk-h { display: flex; align-items: center; gap: 8px; margin: 0 0 14px; }
.fsk-rep-sk-kpi { display: flex; flex-direction: column; gap: 10px; padding: 14px; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); }
.fsk-rep-sk-kpi > .fsk-bone:last-child { margin-top: 6px; }
.fsk-rep-sk-chart { display: flex; flex-direction: column; gap: 14px; }
.fsk-rep-sk-bars { display: flex; align-items: flex-end; gap: 10px; height: 180px; padding: 0 4px; border-bottom: 1px solid var(--k-divider); }
.fsk-rep-sk-bars > .fsk-bone { flex: 1; border-radius: max(2px, calc(var(--k-r) * .75)) max(2px, calc(var(--k-r) * .75)) 0 0; }
.fsk-rep-sk-row { display: flex; align-items: center; gap: 14px; padding: 12px 14px; }
.fsk-rep-sk-row + .fsk-rep-sk-row { border-top: 1px solid var(--k-muted-border); }
.fsk-rep-sk-row > .fsk-bone:nth-child(2) { margin-left: auto; }
.fsk-rep-st-box { flex: 1; display: flex; align-items: center; justify-content: center; padding: 24px 0 12%; }
.fsk-rep-st-panel { width: 100%; max-width: 460px; animation: fsk-in .32s var(--k-ease) both; }
.fsk-rep-st-panel > .fsk-error { padding: 20px; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper); box-shadow: var(--k-shadow); }
.fsk-rep-st-panel > .fsk-empty { padding: 8px 0; }
.fsk-rep-st-panel .fsk-empty-art { width: 60px; height: 60px; }
.fsk-rep-st-panel .fsk-empty-title { font-size: 1.15em; }
.fsk-repc .fsk-repc-kpi .fsk-bone { background: color-mix(in srgb, var(--k-text) 9%, var(--k-sunken)); }
.fsk-repc .fsk-rep-sk-ins { display: grid; gap: 12px; margin: 16px 0 2px; }
.fsk-repc .fsk-rep-sk-ins > div { display: flex; align-items: center; gap: 10px; }
`;

let seq = 0;
const NS = "http://www.w3.org/2000/svg";
type Attrs = Record<string, string | number | null | undefined>;

/** SVG builder for what h() doesn't cover (text). */
function svgEl(doc: Document, tag: string, attrs: Attrs = {}, ...kids: (Node | string)[]): SVGElement {
  const el = doc.createElementNS(NS, tag) as SVGElement;
  for (const [k, v] of Object.entries(attrs)) if (v != null) el.setAttribute(k, String(v));
  el.append(...kids);
  return el;
}

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

const TONES: Record<ReportInsight["tone"], { icon: IconName; sr: string }> = {
  positive: { icon: "up", sr: "Good news: " },
  negative: { icon: "alert", sr: "Needs attention: " },
  neutral: { icon: "info", sr: "Note: " },
};

function deltaTone(d: ReportKpi["delta"]): "good" | "bad" | "flat" {
  if (!d || Math.sign(d.value) === 0) return "flat";
  return (d.good ?? d.value > 0) ? "good" : "bad";
}

/** 0, 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 start = Math.floor(lo / step), end = Math.ceil(hi / step);
  const ticks: number[] = [];
  for (let k = start; k <= end; k++) ticks.push(k * step);
  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", minimumFractionDigits: 0, maximumFractionDigits: 1 };
  if (f.style === "currency") Object.assign(opts, { style: "currency", currency: f.currency ?? "USD" });
  return new Intl.NumberFormat(undefined, opts).format(v);
}

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

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`; // zero or negative: square
  const rr = Math.min(r, base - top);
  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`;
}

/** What a screen reader hears for the chart; the full numbers follow in a hidden table. */
function chartSummary(c: ReportChart): string {
  const s = c.series[0];
  if (!s || !s.values.length) return `${c.title}: no data.`;
  const f = (v: number): string => formatValue(v, c.format);
  let hi = 0, lo = 0;
  s.values.forEach((v, i) => { if (v > s.values[hi]) hi = i; if (v < s.values[lo]) lo = i; });
  const first = s.values[0], last = s.values[s.values.length - 1];
  const change = c.type === "line" && first ? Math.round(((last - first) / Math.abs(first)) * 100) : null;
  const others = c.series.slice(1, 3).map((x) => x.name);
  return `${c.type === "bar" ? "Bar" : "Line"} chart: ${c.title}, ${c.labels[0]} to ${c.labels[c.labels.length - 1]}. ${s.name} is highest in ${c.labels[hi]} (${f(s.values[hi])}) and lowest in ${c.labels[lo]} (${f(s.values[lo])})`
    + (change != null ? `, ${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.";
}

/** Draws the chart at the box's real width, so text never stretches. Called again on resize. */
function drawChart(box: HTMLElement, chart: ReportChart, animate: boolean): void {
  const doc = box.ownerDocument;
  const win = doc.defaultView ?? window;
  const W = Math.max(200, Math.floor(box.clientWidth));
  const H = Math.max(140, Math.floor(box.clientHeight));
  const n = chart.labels.length;
  const series = chart.series.slice(0, 3);
  const values = series.flatMap((s) => s.values.slice(0, n)).filter(Number.isFinite);
  if (!n || !values.length) { box.replaceChildren(h("p", { class: "fsk-rep-empty" }, "No data for this period.")); return; }

  let lo = Math.min(...values), hi = Math.max(...values);
  if (chart.type === "bar" || lo < hi * 0.5) lo = Math.min(0, lo); // bars always start at zero
  if (chart.type === "bar") hi = Math.max(0, hi);
  const ticks = niceScale(lo, hi, H < 210 ? 3 : 4);
  const t0 = ticks[0], t1 = ticks[ticks.length - 1];
  const tickText = ticks.map((t) => axisFormat(t, chart.format));
  const pad = { top: 10, right: chart.type === "line" ? 10 : 2, bottom: 28, left: Math.ceil(Math.max(...tickText.map((t) => t.length)) * 6.4) + 14 };
  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 => (chart.type === "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(win.getComputedStyle(box).getPropertyValue("--k-r")) || 0;

  const svg = svgEl(doc, "svg", { class: `fsk-rep-svg${animate ? " fsk-rep-anim" : ""}`, width: W, height: H, viewBox: `0 0 ${W} ${H}`, "aria-hidden": "true", focusable: "false" });
  const grid = svgEl(doc, "g", { class: "fsk-rep-grid" });
  ticks.forEach((t, i) => {
    const y = Math.round(Y(t)) + 0.5;
    grid.append(
      svgEl(doc, "line", { x1: pad.left, x2: W - pad.right, y1: y, y2: y, class: t === 0 ? "fsk-rep-base" : null }),
      svgEl(doc, "text", { x: pad.left - 8, y, dy: "0.32em", "text-anchor": "end" }, tickText[i]));
  });
  const every = Math.max(1, Math.ceil(n / Math.max(1, Math.floor(pw / 52))));
  chart.labels.forEach((label, i) => {
    if ((n - 1 - i) % every) return; // thin from the end, so the latest period always has its label
    const anchor = chart.type === "line" && i === 0 ? "start" : chart.type === "line" && i === n - 1 ? "end" : "middle";
    grid.append(svgEl(doc, "text", { x: r1(X(i)), y: H - 8, "text-anchor": anchor }, label));
  });

  const hover = chart.type === "bar"
    ? svgEl(doc, "rect", { class: "fsk-rep-band", x: 0, y: pad.top, width: r1(band), height: ph, rx: Math.min(radius, 8), visibility: "hidden" })
    : svgEl(doc, "line", { class: "fsk-rep-guide", x1: 0, x2: 0, y1: pad.top, y2: pad.top + ph, visibility: "hidden" });
  const marks = svgEl(doc, "g", {});
  const dots: SVGElement[][] = [];

  if (chart.type === "bar") {
    const ns = series.length;
    const groupW = Math.min(band * (ns > 1 ? 0.76 : 0.62), ns * 44);
    const gap = ns > 1 ? Math.min(3, groupW * 0.06) : 0;
    const bw = (groupW - gap * (ns - 1)) / ns;
    const r = Math.min(radius, bw / 2.5, 6);
    series.forEach((s, si) => {
      const g = svgEl(doc, "g", { class: seriesClass(series, si) });
      s.values.slice(0, n).forEach((v, i) => {
        g.append(svgEl(doc, "path", { class: "fsk-rep-bar", d: barPath(X(i) - groupW / 2 + si * (bw + gap), bw, zero, Y(v), r), style: `--i:${i}` }));
      });
      marks.append(g);
    });
  } else {
    let lead = true;
    series.forEach((s, si) => {
      const g = svgEl(doc, "g", { class: seriesClass(series, si) });
      const pts = s.values.slice(0, n).map((v, i) => [X(i), Y(v)] as const);
      const d = pts.map(([x, y], i) => `${i ? "L" : "M"}${r1(x)} ${r1(y)}`).join("");
      if (lead && !s.compare && pts.length > 1) {
        const id = `fsk-rep-grad-${++seq}`;
        g.append(
          svgEl(doc, "defs", {}, svgEl(doc, "linearGradient", { id, x1: 0, y1: 0, x2: 0, y2: 1 },
            svgEl(doc, "stop", { offset: "0%", "stop-color": "currentColor", "stop-opacity": 0.2 }),
            svgEl(doc, "stop", { offset: "100%", "stop-color": "currentColor", "stop-opacity": 0 }))),
          svgEl(doc, "path", { class: "fsk-rep-area", d: `${d}L${r1(pts[pts.length - 1][0])} ${pad.top + ph}L${r1(pts[0][0])} ${pad.top + ph}Z`, fill: `url(#${id})` }));
      }
      g.append(svgEl(doc, "path", { class: `fsk-rep-line${s.compare ? " fsk-rep-line--cmp" : ""}`, d, pathLength: s.compare ? null : 1 }));
      if (lead && !s.compare) {
        const [ex, ey] = pts[pts.length - 1];
        g.append(svgEl(doc, "circle", { class: "fsk-rep-end", cx: r1(ex), cy: r1(ey), r: 4 }));
      }
      const ds = pts.map(([x, y]) => svgEl(doc, "circle", { class: "fsk-rep-dot", cx: r1(x), cy: r1(y), r: 4, visibility: "hidden" }));
      g.append(...ds);
      dots.push(ds);
      if (!s.compare) lead = false;
      marks.append(g);
    });
  }

  // Pointer readout. Keyboard and screen reader users get the same numbers from the hidden table.
  const tip = h("div", { class: "fsk-rep-tip", hidden: true, "aria-hidden": "true" });
  const hit = svgEl(doc, "rect", { x: pad.left, y: 0, width: pw, height: pad.top + ph, fill: "transparent" });
  const hide = (): void => {
    tip.hidden = true;
    hover.setAttribute("visibility", "hidden");
    dots.forEach((ds) => ds.forEach((c) => c.setAttribute("visibility", "hidden")));
  };
  const showAt = (i: number): void => {
    if (i < 0 || i >= n) { hide(); return; }
    if (chart.type === "bar") hover.setAttribute("x", String(r1(pad.left + band * i)));
    else { hover.setAttribute("x1", String(r1(X(i)))); hover.setAttribute("x2", String(r1(X(i)))); }
    hover.setAttribute("visibility", "visible");
    dots.forEach((ds) => ds.forEach((c, k) => c.setAttribute("visibility", k === i ? "visible" : "hidden")));
    tip.replaceChildren(h("strong", {}, chart.labels[i]), ...series.map((s, si) => h("span", { class: "fsk-rep-tip-row" },
      h("i", { class: `fsk-rep-sw ${seriesClass(series, si)}` }), s.name, h("b", { class: "fsk-num" }, formatValue(s.values[i], chart.format)))));
    tip.hidden = false;
    const tw = tip.offsetWidth;
    const x = X(i);
    tip.style.left = `${Math.round(x + 14 + tw > W ? Math.max(0, x - 14 - tw) : x + 14)}px`;
  };
  hit.addEventListener("pointermove", (e) => {
    const x = (e as PointerEvent).clientX - svg.getBoundingClientRect().left - pad.left;
    showAt(chart.type === "bar" ? Math.floor(x / band) : Math.round((x / pw) * (n - 1)));
  });
  hit.addEventListener("pointerleave", hide);

  svg.append(grid, hover, marks, hit);
  box.replaceChildren(svg, tip);
}

function kpiTile(m: ReportKpi, animate: boolean): HTMLElement {
  const d = m.delta;
  const tone = deltaTone(d);
  const sign = d ? Math.sign(d.value) : 0;
  const value = formatValue(m.value, m.format);
  const valueEl = h("span", { class: "fsk-rep-kpi-value fsk-num" });
  if (animate) countUp(valueEl, m.value, m.format); else valueEl.textContent = value;
  const said = d ? `, ${sign === 0 ? "no change" : `${sign > 0 ? "up" : "down"} ${Math.abs(d.value)}%`}${d.vs ? ` ${d.vs}` : ""}` : "";
  return h("div", { class: `fsk-rep-kpi fsk-rep-kpi--${tone}`, role: "group", "aria-label": `${m.label}: ${value}${said}` },
    h("span", { class: "fsk-rep-kpi-label", title: m.label }, m.label),
    valueEl,
    d && h("div", { class: "fsk-rep-kpi-row", "aria-hidden": "true" },
      h("span", { class: `fsk-rep-delta fsk-rep-delta--${tone} fsk-num` }, sign !== 0 && icon(sign > 0 ? "up" : "down", 12), sign === 0 ? "0%" : `${Math.abs(d.value)}%`),
      d.vs && h("span", { class: "fsk-rep-kpi-vs" }, d.vs)),
    (m.trend?.length ?? 0) > 1 ? sparkline(m.trend!, { label: `${m.label} trend` }) : h("div", { style: { height: "14px" } }));
}

function tableCell(v: number | string | undefined, col: ReportColumn, max: number): HTMLElement {
  if (typeof v !== "number") return h("td", { class: "fsk-rep-r" }, v ?? "–");
  if (col.delta) {
    const sign = Math.sign(v);
    const tone = sign === 0 ? "flat" : (col.upIsGood ?? true) === sign > 0 ? "good" : "bad";
    return h("td", { class: "fsk-rep-r" }, h("span", { class: `fsk-rep-chg fsk-rep-chg--${tone} fsk-num` },
      sign !== 0 && icon(sign > 0 ? "up" : "down", 12),
      h("span", { class: "fsk-sr" }, sign > 0 ? "up " : sign < 0 ? "down " : ""),
      formatValue(Math.abs(v), { style: "percent", digits: 1 })));
  }
  const text = h("span", { class: "fsk-num" }, formatValue(v, col.format));
  if (!col.bar || max <= 0) return h("td", { class: "fsk-rep-r" }, text);
  return h("td", { class: "fsk-rep-r" }, h("span", { class: "fsk-rep-share" },
    h("span", { class: "fsk-rep-track", "aria-hidden": "true" }, h("span", { class: "fsk-rep-fill", style: { width: `${Math.max(2, (v / max) * 100)}%` } })),
    text));
}

export interface ReportCanvasProps {
  root: HTMLElement;
  head: StyleHost;
  /** The canvas: the in-page renderCanvas ctx or a hosted ctx.canvas. Its state wins over data. */
  canvas?: CanvasApi;
  data?: ReportState;
  actions?: ReportActions;
}

export interface ReportCardProps {
  root: HTMLElement;
  head: StyleHost;
  data: ReportState;
  api?: CardApi;
}

/**
 * Desktop canvas, READ_MODE: the agent reads the state and explains it; it doesn't change it.
 * If your app refreshes the numbers, call canvas.setState and the report redraws.
 */
export function mount({ root, head, canvas, data, actions }: ReportCanvasProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-rep", CSS);
  const doc = root.ownerDocument;
  const win = doc.defaultView ?? window;
  const reduce = !!win.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  let state = structuredClone(canvas?.state ?? data) as ReportState;
  let disposers: (() => void)[] = [];
  let first = true;
  const uid = `fsk-rep-${++seq}`;
  const off = canvas?.onStateChange?.((next) => { state = structuredClone(next) as ReportState; render(); });

  function section(key: string, label: string, ic: IconName, body: Child, extra?: string): HTMLElement {
    return h("section", { class: `fsk-rep-sec${extra ? ` ${extra}` : ""}`, id: `${uid}-${key}`, "data-sec": key, "aria-labelledby": `${uid}-${key}-h` },
      h("h3", { class: "fsk-rep-h", id: `${uid}-${key}-h`, tabindex: "-1" }, icon(ic, 16), label),
      body);
  }

  function chartBlock(c: ReportChart): HTMLElement {
    const series = c.series.slice(0, 3);
    const box = h("div", { class: "fsk-rep-chart", role: "img", "aria-label": chartSummary(c) });
    const block = h("div", { class: "fsk-rep-panel fsk-rep-chartpanel" },
      h("div", { class: "fsk-rep-charthead" },
        h("h4", { class: "fsk-rep-charttitle" }, c.title),
        series.length > 1 && h("ul", { class: `fsk-rep-legend${c.type === "line" ? " fsk-rep-legend--line" : ""}`, "aria-hidden": "true" },
          series.map((s, i) => h("li", {}, h("i", { class: `fsk-rep-sw ${seriesClass(series, i)}` }), s.name)))),
      box,
      h("table", { class: "fsk-sr" },
        h("caption", {}, c.title),
        h("thead", {}, h("tr", {}, h("th", { scope: "col" }, "Period"), series.map((s) => h("th", { scope: "col" }, s.name)))),
        h("tbody", {}, c.labels.map((l, i) => h("tr", {}, h("th", { scope: "row" }, l), series.map((s) => h("td", {}, formatValue(s.values[i], c.format))))))));
    const animate = first;
    let width = 0;
    const paint = (): void => {
      const w = box.clientWidth;
      if (!w || Math.abs(w - width) < 1) return;
      const anim = animate && !width;
      width = w;
      drawChart(box, c, anim);
    };
    let frame = 0;
    const ro = "ResizeObserver" in win ? new win.ResizeObserver(() => { win.cancelAnimationFrame(frame); frame = win.requestAnimationFrame(paint); }) : null;
    ro?.observe(box);
    disposers.push(() => { ro?.disconnect(); win.cancelAnimationFrame(frame); });
    win.requestAnimationFrame(paint);
    return block;
  }

  function tableBlock(t: ReportTable): HTMLElement {
    const limit = t.limit ?? 6;
    const rows = t.rows.slice(0, limit);
    const more = t.rows.length - rows.length;
    const max = t.columns.map((_, ci) => Math.max(0, ...t.rows.map((r) => (typeof r.values[ci] === "number" ? (r.values[ci] as number) : 0))));
    return h("div", { class: "fsk-rep-panel" },
      h("div", { class: "fsk-rep-tablewrap" },
        h("table", { class: "fsk-rep-table" },
          h("caption", { class: "fsk-sr" }, t.title),
          h("thead", {}, h("tr", {},
            h("th", { scope: "col" }, t.rowLabel),
            t.columns.map((c) => h("th", { scope: "col", class: "fsk-rep-r" }, c.label)))),
          h("tbody", {}, rows.map((r, i) => h("tr", {},
            h("th", { scope: "row" }, h("span", { class: "fsk-rep-rank fsk-num", "aria-hidden": "true" }, i + 1), r.label),
            t.columns.map((c, ci) => tableCell(r.values[ci], c, max[ci]))))))),
      more > 0 && h("div", { class: "fsk-rep-tfoot" },
        h("span", {}, `${more} more ${more === 1 ? "row" : "rows"}`),
        actions?.openInApp && h("button", { class: "fsk-btn fsk-btn--link", type: "button", onclick: () => actions.openInApp?.() }, "See all", icon("chevron", 14))));
  }

  function insightsBlock(list: ReportInsight[]): HTMLElement {
    return h("ul", { class: "fsk-rep-ins" }, list.slice(0, 4).map((x) => {
      const t = TONES[x.tone] ?? TONES.neutral;
      return h("li", { class: `fsk-rep-in fsk-rep-in--${x.tone}` },
        h("span", { class: "fsk-rep-in-ico", "aria-hidden": "true" }, icon(t.icon, 16)),
        h("div", {},
          h("p", { class: "fsk-rep-in-title" }, h("span", { class: "fsk-sr" }, t.sr), x.title),
          x.detail && h("p", { class: "fsk-rep-in-detail" }, x.detail)));
    }));
  }

  function wireNav(nav: HTMLElement, sentinel: HTMLElement, sections: HTMLElement[]): void {
    if (!("IntersectionObserver" in win)) return;
    const visible = new Set<string>();
    const mark = (key: string): void => nav.querySelectorAll<HTMLElement>("[data-go]").forEach((b) => b.setAttribute("aria-current", String(b.dataset.go === key)));
    const io = new win.IntersectionObserver((entries) => {
      for (const e of entries) {
        const key = (e.target as HTMLElement).dataset.sec!;
        if (e.isIntersecting) visible.add(key); else visible.delete(key);
      }
      const top = sections.find((s) => visible.has(s.dataset.sec!));
      if (top) mark(top.dataset.sec!);
    }, { rootMargin: "-64px 0px -55% 0px" });
    sections.forEach((s) => io.observe(s));
    const stuck = new win.IntersectionObserver(([e]) => {
      const isStuck = !e.isIntersecting && e.boundingClientRect.top < nav.getBoundingClientRect().top - 2;
      nav.toggleAttribute("data-stuck", isStuck);
    });
    stuck.observe(sentinel);
    disposers.push(() => { io.disconnect(); stuck.disconnect(); });
  }

  function render(): void {
    disposers.forEach((d) => d());
    disposers = [];
    canvas?.setTitle?.((state.canvasTitle ?? state.title).slice(0, 80));
    const kpis = (state.kpis ?? []).slice(0, 4);
    const parts: { key: string; label: string; ic: IconName; body: HTMLElement }[] = [];
    if (kpis.length) parts.push({ key: "overview", label: "Overview", ic: "zap", body: h("div", { class: "fsk-rep-kpis", "data-n": kpis.length }, kpis.map((m) => kpiTile(m, first))) });
    if (state.chart) parts.push({ key: "chart", label: state.chart.type === "line" ? "Trend" : "Chart", ic: state.chart.type === "line" ? "chart" : "bars", body: chartBlock(state.chart) });
    if (state.table) parts.push({ key: "breakdown", label: state.table.title, ic: "table", body: tableBlock(state.table) });
    if (state.insights?.length) parts.push({ key: "insights", label: "Insights", ic: "sparkle", body: insightsBlock(state.insights) });
    const sections = parts.map((p, i) => section(p.key, p.label, p.ic, p.body, i === 0 ? "fsk-rep-sec--first" : undefined));

    const go = (key: string): void => {
      const target = sections.find((s) => s.dataset.sec === key);
      target?.scrollIntoView({ behavior: reduce ? "auto" : "smooth", block: "start" });
      target?.querySelector<HTMLElement>(".fsk-rep-h")?.focus({ preventScroll: true });
    };
    const sentinel = h("div", { "aria-hidden": "true", style: { height: "1px", marginBottom: "-1px" } });
    const nav = parts.length >= 3 && h("nav", { class: "fsk-rep-nav", "aria-label": "Report sections" },
      parts.map((p, i) => h("button", { class: "fsk-rep-navbtn", type: "button", "data-go": p.key, "aria-current": String(i === 0), onclick: () => go(p.key) }, p.key === "breakdown" ? "Breakdown" : p.label)));

    const wrap = h("div", { class: `fsk fsk-rep${first ? " fsk-rep-enter" : ""}` },
      h("article", { class: "fsk-rep-inner", "aria-label": state.title },
        h("header", {},
          h("div", { class: "fsk-rep-top" },
            h("span", { class: "fsk-badge fsk-badge--agent" }, icon("chart", 12), state.eyebrow ?? "Report"),
            actions?.openInApp && h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: () => actions.openInApp?.(), "aria-label": "Open in app" },
              icon("external", 14), h("span", {}, "Open in app"))),
          h("h2", { class: "fsk-rep-title" }, state.title),
          (state.period || state.updated) && h("p", { class: "fsk-rep-meta" },
            state.period && h("span", {}, icon("calendar", 14), state.period),
            state.updated && h("span", {}, icon("clock", 14), `Updated ${state.updated}`)),
          state.summary && h("p", { class: "fsk-rep-summary" }, state.summary)),
        nav && sentinel,
        nav,
        sections,
        h("p", { class: "fsk-rep-foot" }, icon("message", 14), "Ask me about any number in this report.")));
    root.replaceChildren(wrap);
    if (nav) wireNav(nav, sentinel, sections);
    first = false;
  }

  render();
  return () => { off?.(); disposers.forEach((d) => d()); root.replaceChildren(); };
}

/** Mobile has no canvas: a summary card (a chat card action) with the headline numbers and the top findings. */
export function mountMobile({ root, head, data, api }: ReportCardProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-rep", CSS);
  const kpis = (data.kpis ?? []).slice(0, 4);
  root.replaceChildren(h("section", { class: "fsk fsk-card fsk-repc", "aria-label": data.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon("chart", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, data.title), data.period && h("p", { class: "fsk-sub" }, data.period))),
    kpis.length > 0 && h("div", { class: "fsk-repc-kpis" }, kpis.map((m) => {
      const tone = deltaTone(m.delta);
      const sign = m.delta ? Math.sign(m.delta.value) : 0;
      return h("div", { class: "fsk-repc-kpi" },
        h("span", { class: "fsk-rep-kpi-label" }, m.label),
        h("span", { class: "fsk-rep-kpi-value fsk-num" }, formatValue(m.value, m.format)),
        m.delta && h("span", {}, h("span", { class: `fsk-rep-delta fsk-rep-delta--${tone} fsk-num` },
          sign !== 0 && icon(sign > 0 ? "up" : "down", 12),
          h("span", { class: "fsk-sr" }, sign > 0 ? "up " : sign < 0 ? "down " : "no change "),
          `${Math.abs(m.delta.value)}%`)));
    })),
    (data.insights?.length ?? 0) > 0 && h("ul", { class: "fsk-repc-ins" }, data.insights!.slice(0, 3).map((x) => {
      const t = TONES[x.tone] ?? TONES.neutral;
      return h("li", { class: `fsk-rep-in--${x.tone}` },
        h("span", { class: "fsk-rep-in-ico", "aria-hidden": "true" }, icon(t.icon, 14)),
        h("span", {}, h("span", { class: "fsk-sr" }, t.sr), x.title));
    })),
    h("p", { class: "fsk-repc-foot" }, icon("expand", 12), "Open on desktop for the full report.")));
  api?.displayed?.();
  return () => root.replaceChildren();
}

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

/** mountState's props: the kit's StateProps for the canvas. Mobile uses mountMobileState. */
export interface ReportCanvasStateProps extends Omit<StateProps, "surface"> {
  /** The canvas: mountState sets its title. */
  canvas?: CanvasApi;
  /** The canvas header (setTitle, up to 80 characters). Default: the title. */
  canvasTitle?: string;
  /** The badge above the title. Default: "Report". */
  eyebrow?: string;
}

const loadingLabel = (s: CardState): string => (s.kind === "loading" ? s.label ?? "Loading the report…" : "");

/** The report as bones: section tabs, four headline numbers, a chart and the first table rows. */
function reportSkeleton(): Child {
  const heading = (w: string, i: number): HTMLElement => h("div", { class: "fsk-rep-sk-h" }, bone("16px", "16px", { cls: "fsk-bone--box", i }), bone(w, "11px", { i }));
  return [
    h("div", { class: "fsk-rep-sk-nav" }, ["72px", "56px", "84px", "64px"].map((w, i) => bone(w, "26px", { cls: "fsk-bone--box", i }))),
    h("section", { class: "fsk-rep-sec fsk-rep-sec--first" }, heading("80px", 0),
      h("div", { class: "fsk-rep-kpis", "data-n": 4 }, Array.from({ length: 4 }, (_, i) =>
        h("div", { class: "fsk-rep-sk-kpi" }, bone("48%", "9px", { i }), bone("64%", "22px", { i }), bone("38%", "14px", { i }), bone("100%", "26px", { i }))))),
    h("section", { class: "fsk-rep-sec" }, heading("64px", 2),
      h("div", { class: "fsk-rep-panel fsk-rep-chartpanel fsk-rep-sk-chart" }, bone("34%", "11px", { i: 2 }),
        h("div", { class: "fsk-rep-sk-bars" }, [42, 48, 46, 55, 58, 64, 61, 70, 74, 79, 84, 96].map((v, i) => bone("auto", `${v}%`, { i: i % 6 }))))),
    h("section", { class: "fsk-rep-sec" }, heading("110px", 4),
      h("div", { class: "fsk-rep-panel" }, Array.from({ length: 4 }, (_, i) =>
        h("div", { class: "fsk-rep-sk-row" }, bone(`${[30, 26, 22, 24][i]}%`, "10px", { i }), bone("48px", "10px", { i }), bone("72px", "10px", { i }), bone("44px", "10px", { i }))))),
  ];
}

/**
 * Desktop canvas in a state: the report's header (badge, title, period) above the report as bones while it loads,
 * or a centered empty or error block. Returns the cleanup; mount the report once its data is in.
 */
export function mountState({ root, head, state, title, subtitle, canvas, canvasTitle, eyebrow }: ReportCanvasStateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-rep", CSS);
  canvas?.setTitle?.((canvasTitle ?? title ?? "Report").slice(0, 80));
  const loading = state.kind === "loading";
  let dispose = (): void => {};
  let body: Child;
  if (state.kind === "loading") body = h("div", { "aria-hidden": "true" }, reportSkeleton());
  else if (state.kind === "empty") body = h("div", { class: "fsk-rep-st-box" }, h("div", { class: "fsk-rep-st-panel" }, emptyBlock(state)));
  else {
    const e = errorBlock(state);
    dispose = e.dispose;
    body = h("div", { class: "fsk-rep-st-box" }, h("div", { class: "fsk-rep-st-panel" }, e.el));
  }
  root.replaceChildren(h("div", {
    class: "fsk fsk-rep fsk-rep-st", "data-state": state.kind,
    role: loading ? "status" : null, "aria-busy": loading ? "true" : null, "aria-live": loading ? "polite" : null,
  },
    loading && h("span", { class: "fsk-sr" }, loadingLabel(state)),
    h("div", { class: "fsk-rep-inner" },
      h("span", { class: "fsk-badge fsk-badge--agent" }, icon("chart", 12), eyebrow ?? "Report"),
      h("h2", { class: "fsk-rep-title" }, title ?? (loading ? bone("56%", "24px") : "Report")),
      subtitle ? h("p", { class: "fsk-rep-meta" }, h("span", {}, icon("calendar", 14), subtitle)) : loading && h("p", { class: "fsk-rep-meta", "aria-hidden": "true" }, bone("160px", "10px")),
      loading && h("div", { class: "fsk-rep-summary fsk-sk-lines", "aria-hidden": "true" }, bone("94%", "11px"), bone("68%", "11px")),
      body)));
  return () => { dispose(); root.replaceChildren(); };
}

/** Mobile summary card in a state: its header above headline-number bones, or an empty or error block. Read-only: report displayed() yourself. */
export function mountMobileState({ root, head, state, title, subtitle, surface = "mobile" }: StateProps): Cleanup {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-rep", CSS);
  const card = stateCard({
    state: state.kind === "loading" ? { ...state, label: loadingLabel(state) } : state, cls: "fsk-repc", icon: "chart", title, subtitle, surface,
    skeleton: () => [
      h("div", { class: "fsk-repc-kpis" }, Array.from({ length: 4 }, (_, i) =>
        h("div", { class: "fsk-repc-kpi" }, bone("58%", "9px", { i }), bone("72%", "18px", { i }), bone("36%", "12px", { i })))),
      h("div", { class: "fsk-rep-sk-ins" }, Array.from({ length: 3 }, (_, i) =>
        h("div", {}, bone("24px", "24px", { cls: "fsk-bone--box", i }), bone(`${[74, 62, 68][i]}%`, "10px", { i })))),
    ],
  });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

export const fixtures: Record<string, ReportState> = {
  default: {
    canvasTitle: "Revenue report: October 2026",
    eyebrow: "Monthly report",
    title: "Revenue, October 2026",
    summary: "MRR grew 6.2% to $482,300 and beat target for the fourth month in a row. Churn is the one number moving the wrong way.",
    period: "Oct 1 to Oct 31, 2026",
    updated: "8 min ago",
    kpis: [
      { label: "MRR", value: 482300, format: { style: "currency" }, delta: { value: 6.2, vs: "vs Sep" }, trend: [402, 411, 418, 431, 440, 452, 454, 482] },
      { label: "New customers", value: 128, delta: { value: 14, vs: "vs Sep" }, trend: [88, 97, 92, 104, 101, 110, 112, 128] },
      { label: "Net revenue retention", value: 108.4, format: { style: "percent" }, delta: { value: 1.1, vs: "vs Sep" }, trend: [104, 105, 105, 106, 107, 107, 107.2, 108.4] },
      { label: "Churned MRR", value: 9850, format: { style: "currency" }, delta: { value: 18, good: false, vs: "vs Sep" }, trend: [6.1, 6.4, 6.2, 7, 7.4, 8.1, 8.3, 9.85] },
    ],
    chart: {
      type: "line",
      title: "Monthly recurring revenue",
      labels: ["Nov", "Dec", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct"],
      series: [
        { name: "MRR", values: [361000, 368500, 377200, 381900, 392400, 402100, 411300, 418600, 431200, 440900, 454100, 482300] },
        { name: "Target", values: [360000, 370000, 380000, 390000, 400000, 410000, 420000, 430000, 438000, 446000, 452000, 460000], compare: true },
      ],
      format: { style: "currency" },
    },
    table: {
      title: "MRR by region",
      rowLabel: "Region",
      columns: [
        { label: "Customers" },
        { label: "MRR", format: { style: "currency" }, bar: true },
        { label: "Change", delta: true },
      ],
      rows: [
        { label: "North America", values: [1612, 228400, 5.8] },
        { label: "Western Europe", values: [902, 121900, 7.1] },
        { label: "UK and Ireland", values: [388, 54300, 3.9] },
        { label: "Asia Pacific", values: [344, 41700, 16.4] },
        { label: "Nordics", values: [161, 22600, 2.2] },
        { label: "Latin America", values: [128, 13400, -1.5] },
      ],
      limit: 5,
    },
    insights: [
      { tone: "positive", title: "Enterprise upgrades drove most of the growth", detail: "Nine enterprise accounts upgraded and added $18,400 MRR, 65% of this month's net new." },
      { tone: "negative", title: "Churn rose for the third month in a row", detail: "Churned MRR is up 18% vs September, mostly Starter accounts in their first 90 days." },
      { tone: "neutral", title: "Asia Pacific is now your fourth-largest region", detail: "It passed the Nordics after three new annual contracts." },
    ],
  },
  bars: {
    title: "Sign-ups, last 8 weeks",
    period: "Sep 7 to Nov 1, 2026",
    updated: "just now",
    kpis: [
      { label: "Sign-ups", value: 2140, delta: { value: 9.4, vs: "vs prior 8 weeks" } },
      { label: "Activated", value: 46.2, format: { style: "percent" }, delta: { value: -1.8, vs: "vs prior 8 weeks" } },
    ],
    chart: {
      type: "bar",
      title: "Sign-ups per week",
      labels: ["W37", "W38", "W39", "W40", "W41", "W42", "W43", "W44"],
      series: [
        { name: "This year", values: [212, 238, 251, 246, 268, 281, 302, 342] },
        { name: "Last year", values: [190, 201, 214, 222, 219, 240, 251, 262], compare: true },
      ],
    },
    insights: [
      { tone: "positive", title: "Week 44 was your best week this year" },
      { tone: "negative", title: "Fewer new users finish setup on day one" },
    ],
  },
};
```

```js title="agent/ui/report-canvas.js"
// Template: report-canvas. A read-only REPORT canvas the agent opens beside the chat: headline numbers, one chart, a breakdown table and its findings.

export const meta = {
  id: "report-canvas",
  title: "Report",
  surface: "canvas",
  canvasType: "REPORT",
  kind: "read-only",
  mobile: "fallback-card",
  whenToUse: "The user asks how something did over a period and the answer needs room: a few headline numbers, a trend, a breakdown and what stands out. The agent explains it beside the chat and answers follow-ups from the same state.",
  whenNotToUse: "A few numbers that fit in the chat (KPI tiles card). Data the user edits (table or form canvas). Raw exports with hundreds of rows (link to your app). Mobile: the canvas isn't available; use the summary card (mountMobile).",
};

const CSS = `
.fsk-rep { min-height: 100%; background: var(--k-paper); container: fsk-rep / inline-size; }
.fsk-rep-inner { max-width: 960px; margin: 0 auto; padding: 28px 32px 48px; }
.fsk-rep-top { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
.fsk-rep-title { margin: 12px 0 8px; font-size: 1.6em; font-weight: 650; letter-spacing: -0.022em; line-height: 1.2; text-wrap: balance; }
.fsk-rep-meta { display: flex; flex-wrap: wrap; gap: 4px 16px; margin: 0; font-size: .86em; color: var(--k-text-2); }
.fsk-rep-meta span { display: inline-flex; align-items: center; gap: 6px; }
.fsk-rep-summary { margin: 16px 0 0; max-width: 66ch; font-size: 1.07em; line-height: 1.55; text-wrap: pretty; }

.fsk-rep-nav {
  position: sticky; top: 0; z-index: 2; display: flex; flex-wrap: wrap; gap: 2px;
  margin: 20px -32px 0; padding: 8px 28px; border-bottom: 1px solid transparent;
  background: color-mix(in srgb, var(--k-paper) 90%, transparent);
  -webkit-backdrop-filter: saturate(1.4) blur(10px); backdrop-filter: saturate(1.4) blur(10px);
  transition: border-color .2s;
}
.fsk-rep-nav[data-stuck] { border-bottom-color: var(--k-divider); }
.fsk-rep-navbtn {
  appearance: none; border: 0; background: none; font: inherit; font-size: .86em; color: var(--k-text-2);
  padding: 5px 10px; border-radius: var(--k-r-md); cursor: pointer; transition: background .15s, color .15s;
}
.fsk-rep-navbtn:hover { background: var(--k-hover); color: var(--k-text); }
.fsk-rep-navbtn[aria-current="true"] { background: var(--k-tint); color: var(--k-primary); font-weight: 600; }
.fsk-rep-navbtn:focus-visible, .fsk-rep-h:focus-visible { outline: 2px solid var(--k-primary); outline-offset: 2px; }

.fsk-rep-sec { margin-top: 28px; scroll-margin-top: 56px; }
.fsk-rep-sec--first { margin-top: 20px; }
.fsk-rep-h { display: flex; align-items: center; gap: 8px; margin: 0 0 12px; font-size: 1em; font-weight: 600; letter-spacing: -0.005em; border-radius: 2px; }
.fsk-rep-h .fsk-icon { color: var(--k-text-2); }
.fsk-rep-panel { border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper); }

.fsk-rep-kpis { display: grid; gap: 12px; grid-template-columns: repeat(2, minmax(0, 1fr)); }
.fsk-rep-kpis[data-n="1"] { grid-template-columns: minmax(0, 1fr); }
.fsk-rep-kpis[data-n="3"] > :last-child { grid-column: 1 / -1; }
.fsk-rep-kpi {
  position: relative; display: flex; flex-direction: column; gap: 6px; min-width: 0; overflow: hidden;
  padding: 14px 14px 0; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper);
}
.fsk-rep-kpi-label { font-size: .86em; color: var(--k-text-2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.fsk-rep-kpi-value { font-size: 1.72em; font-weight: 650; letter-spacing: -0.02em; line-height: 1.1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.fsk-rep-kpi-row { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; min-height: 20px; }
.fsk-rep-kpi-vs { font-size: .79em; color: var(--k-text-2); }
.fsk-rep-kpi .fsk-spark { display: block; width: calc(100% + 28px); height: 36px; margin: 4px -14px 0; color: var(--k-primary); }
.fsk-rep-kpi--bad .fsk-spark { color: var(--k-error); }
.fsk-rep-kpi--flat .fsk-spark { color: var(--k-text-2); }
.fsk-rep-delta { display: inline-flex; align-items: center; gap: 2px; padding: 1px 6px 1px 4px; border-radius: 999px; font-size: .79em; font-weight: 600; }
.fsk-rep-delta--good { color: var(--k-success); background: color-mix(in srgb, var(--k-success) 12%, var(--k-paper)); }
.fsk-rep-delta--bad { color: var(--k-error); background: color-mix(in srgb, var(--k-error) 12%, var(--k-paper)); }
.fsk-rep-delta--flat { color: var(--k-text-2); background: var(--k-hover); }

.fsk-rep-chartpanel { padding: 16px 16px 10px; }
.fsk-rep-charthead { display: flex; align-items: baseline; justify-content: space-between; flex-wrap: wrap; gap: 6px 16px; margin-bottom: 10px; }
.fsk-rep-charttitle { margin: 0; font-size: .93em; font-weight: 600; }
.fsk-rep-legend { display: flex; flex-wrap: wrap; gap: 4px 14px; margin: 0; padding: 0; list-style: none; font-size: .79em; color: var(--k-text-2); }
.fsk-rep-legend li { display: inline-flex; align-items: center; gap: 6px; }
.fsk-rep-sw { display: inline-block; flex: none; width: 10px; height: 10px; border-radius: min(var(--k-r), 3px); background: currentColor; }
.fsk-rep-legend--line .fsk-rep-sw { width: 14px; height: 2px; border-radius: 2px; }
.fsk-rep-legend--line .fsk-rep-cmp.fsk-rep-sw { background: repeating-linear-gradient(90deg, currentColor 0 4px, transparent 4px 7px); }
.fsk-rep-chart { position: relative; height: 240px; }
.fsk-rep-svg { display: block; overflow: visible; }
.fsk-rep-svg text { fill: var(--k-text-2); font-size: 11px; font-family: inherit; font-variant-numeric: tabular-nums; }
.fsk-rep-grid line { stroke: var(--k-divider); shape-rendering: crispEdges; }
.fsk-rep-grid line.fsk-rep-base { stroke: var(--k-border); }
.fsk-rep-s0 { color: var(--k-primary); }
.fsk-rep-s1 { color: color-mix(in oklab, var(--k-primary) 50%, var(--k-text)); }
.fsk-rep-s2 { color: color-mix(in oklab, var(--k-primary) 50%, var(--k-warning)); }
.fsk-rep-cmp { color: color-mix(in srgb, var(--k-text-2) 75%, var(--k-paper)); }
.fsk-rep-bar { fill: currentColor; }
.fsk-rep-line { fill: none; stroke: currentColor; stroke-width: 2.25; stroke-linecap: round; stroke-linejoin: round; stroke-dasharray: 1; }
.fsk-rep-line--cmp { stroke-width: 1.75; stroke-dasharray: 4 4; }
.fsk-rep-end { fill: currentColor; stroke: var(--k-paper); stroke-width: 2; }
.fsk-rep-dot { fill: var(--k-paper); stroke: currentColor; stroke-width: 2; }
.fsk-rep-band { fill: var(--k-hover); }
.fsk-rep-guide { stroke: var(--k-border); stroke-dasharray: 3 3; }
.fsk-rep-tip {
  position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none; display: grid; gap: 3px; min-width: 132px;
  padding: 8px 10px; border: 1px solid var(--k-border); border-radius: var(--k-r-md); background: var(--k-paper);
  box-shadow: var(--k-shadow); font-size: .79em; white-space: nowrap;
}
.fsk-rep-tip strong { font-weight: 600; margin-bottom: 1px; }
.fsk-rep-tip-row { display: flex; align-items: center; gap: 6px; color: var(--k-text-2); }
.fsk-rep-tip-row b { margin-left: auto; padding-left: 12px; color: var(--k-text); font-weight: 600; }
.fsk-rep-empty { margin: 0; display: grid; place-items: center; height: 100%; color: var(--k-text-2); font-size: .86em; }
.fsk-rep-anim .fsk-rep-bar { transform-box: fill-box; transform-origin: 50% 100%; animation: fsk-rep-grow .6s var(--k-ease) both; animation-delay: calc(var(--i, 0) * 22ms); }
.fsk-rep-anim .fsk-rep-line:not(.fsk-rep-line--cmp) { animation: fsk-rep-draw 1s var(--k-ease) both; }
.fsk-rep-anim .fsk-rep-area, .fsk-rep-anim .fsk-rep-line--cmp, .fsk-rep-anim .fsk-rep-end { animation: fsk-rep-fade .6s .35s ease-out both; }

.fsk-rep-tablewrap { overflow-x: auto; }
.fsk-rep-table { width: 100%; border-collapse: collapse; font-size: .93em; }
.fsk-rep-table caption { text-align: left; }
.fsk-rep-table th, .fsk-rep-table td { padding: 10px 14px; text-align: left; white-space: nowrap; }
.fsk-rep-table thead th { font-size: .86em; font-weight: 500; color: var(--k-text-2); border-bottom: 1px solid var(--k-border); padding-top: 12px; padding-bottom: 10px; }
.fsk-rep-table tbody th { font-weight: 500; }
.fsk-rep-table tbody tr + tr > * { border-top: 1px solid var(--k-muted-border); }
.fsk-rep-table tbody tr:hover > * { background: var(--k-sunken); }
.fsk-rep-table .fsk-rep-r { text-align: right; }
.fsk-rep-rank { display: inline-block; min-width: 1.6em; color: var(--k-text-2); font-weight: 400; }
.fsk-rep-share { display: inline-flex; align-items: center; justify-content: flex-end; gap: 10px; }
.fsk-rep-track { width: 64px; height: 6px; border-radius: 999px; background: var(--k-hover); overflow: hidden; }
.fsk-rep-fill { display: block; height: 100%; border-radius: inherit; background: var(--k-primary); transform-origin: 0 50%; }
.fsk-rep-enter .fsk-rep-fill { animation: fsk-rep-grow-x .7s .1s var(--k-ease) both; }
.fsk-rep-chg { display: inline-flex; align-items: center; gap: 2px; font-weight: 600; }
.fsk-rep-chg--good { color: var(--k-success); }
.fsk-rep-chg--bad { color: var(--k-error); }
.fsk-rep-chg--flat { color: var(--k-text-2); font-weight: 500; }
.fsk-rep-tfoot { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 8px 8px 14px; border-top: 1px solid var(--k-border); font-size: .86em; color: var(--k-text-2); }

.fsk-rep-ins { display: grid; gap: 10px; margin: 0; padding: 0; list-style: none; }
.fsk-rep-in { display: grid; grid-template-columns: 32px minmax(0, 1fr); gap: 12px; padding: 14px; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper); }
.fsk-rep-in-ico { display: grid; place-items: center; width: 32px; height: 32px; border-radius: var(--k-r-md); }
.fsk-rep-in--positive .fsk-rep-in-ico { color: var(--k-success); background: color-mix(in srgb, var(--k-success) 12%, var(--k-paper)); }
.fsk-rep-in--negative .fsk-rep-in-ico { color: var(--k-error); background: color-mix(in srgb, var(--k-error) 12%, var(--k-paper)); }
.fsk-rep-in--neutral .fsk-rep-in-ico { color: var(--k-text-2); background: var(--k-hover); }
.fsk-rep-in-title { margin: 5px 0 0; font-weight: 600; line-height: 1.35; text-wrap: pretty; }
.fsk-rep-in-detail { margin: 4px 0 0; color: var(--k-text-2); font-size: .93em; text-wrap: pretty; }
.fsk-rep-foot { display: flex; align-items: center; gap: 6px; margin: 28px 0 0; font-size: .86em; color: var(--k-text-2); }

@container fsk-rep (min-width: 600px) {
  .fsk-rep-kpis[data-n="3"] { grid-template-columns: repeat(3, minmax(0, 1fr)); }
  .fsk-rep-kpis[data-n="3"] > :last-child { grid-column: auto; }
}
@container fsk-rep (min-width: 760px) { .fsk-rep-ins { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@container fsk-rep (min-width: 840px) { .fsk-rep-kpis[data-n="4"] { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
@container fsk-rep (max-width: 520px) {
  .fsk-rep-inner { padding: 20px 16px 36px; }
  .fsk-rep-nav { margin: 16px -16px 0; padding: 8px 12px; }
  .fsk-rep-title { font-size: 1.4em; }
  .fsk-rep-top .fsk-btn span { display: none; }
  .fsk-rep-chart { height: 200px; }
  .fsk-rep-chartpanel { padding: 14px 12px 8px; }
  .fsk-rep-table th, .fsk-rep-table td { padding: 9px 10px; }
  .fsk-rep-track { display: none; }
}
@keyframes fsk-rep-grow { from { transform: scaleY(0); } }
@keyframes fsk-rep-grow-x { from { transform: scaleX(0); } }
@keyframes fsk-rep-draw { from { stroke-dashoffset: 1; } to { stroke-dashoffset: 0; } }
@keyframes fsk-rep-fade { from { opacity: 0; } }

/* Mobile summary card */
.fsk-repc .fsk-repc-kpis { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
.fsk-repc .fsk-repc-kpi { display: flex; flex-direction: column; gap: 4px; min-width: 0; padding: 10px 12px; border-radius: var(--k-r-md); background: var(--k-sunken); }
.fsk-repc .fsk-rep-kpi-value { font-size: 1.36em; }
.fsk-repc .fsk-repc-ins { list-style: none; margin: 14px 0 0; padding: 0; display: grid; gap: 10px; }
.fsk-repc .fsk-repc-ins li { display: flex; align-items: flex-start; gap: 10px; }
.fsk-repc .fsk-rep-in-ico { width: 24px; height: 24px; flex: none; }
.fsk-repc .fsk-repc-ins span:last-child { padding-top: 2px; font-size: .93em; line-height: 1.4; }
.fsk-repc .fsk-repc-foot { display: flex; align-items: center; gap: 6px; margin: 14px 0 0; padding-top: 12px; border-top: 1px solid var(--k-divider); font-size: .79em; color: var(--k-text-2); }

/* States (mountState): the report's own page, with a skeleton in its shape or a centered block */
.fsk-rep-st { display: flex; flex-direction: column; }
.fsk-rep-st > .fsk-rep-inner { flex: 1; display: flex; flex-direction: column; width: 100%; }
.fsk-rep-st .fsk-badge { align-self: flex-start; }
.fsk-rep-st .fsk-rep-title .fsk-bone { margin: 4px 0; }
.fsk-rep-st .fsk-rep-summary.fsk-sk-lines { margin-top: 18px; }
.fsk-rep-sk-nav { display: flex; gap: 8px; margin: 22px 0 0; padding: 8px 0 4px; }
.fsk-rep-sk-h { display: flex; align-items: center; gap: 8px; margin: 0 0 14px; }
.fsk-rep-sk-kpi { display: flex; flex-direction: column; gap: 10px; padding: 14px; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); }
.fsk-rep-sk-kpi > .fsk-bone:last-child { margin-top: 6px; }
.fsk-rep-sk-chart { display: flex; flex-direction: column; gap: 14px; }
.fsk-rep-sk-bars { display: flex; align-items: flex-end; gap: 10px; height: 180px; padding: 0 4px; border-bottom: 1px solid var(--k-divider); }
.fsk-rep-sk-bars > .fsk-bone { flex: 1; border-radius: max(2px, calc(var(--k-r) * .75)) max(2px, calc(var(--k-r) * .75)) 0 0; }
.fsk-rep-sk-row { display: flex; align-items: center; gap: 14px; padding: 12px 14px; }
.fsk-rep-sk-row + .fsk-rep-sk-row { border-top: 1px solid var(--k-muted-border); }
.fsk-rep-sk-row > .fsk-bone:nth-child(2) { margin-left: auto; }
.fsk-rep-st-box { flex: 1; display: flex; align-items: center; justify-content: center; padding: 24px 0 12%; }
.fsk-rep-st-panel { width: 100%; max-width: 460px; animation: fsk-in .32s var(--k-ease) both; }
.fsk-rep-st-panel > .fsk-error { padding: 20px; border: 1px solid var(--k-border); border-radius: var(--k-r-lg); background: var(--k-paper); box-shadow: var(--k-shadow); }
.fsk-rep-st-panel > .fsk-empty { padding: 8px 0; }
.fsk-rep-st-panel .fsk-empty-art { width: 60px; height: 60px; }
.fsk-rep-st-panel .fsk-empty-title { font-size: 1.15em; }
.fsk-repc .fsk-repc-kpi .fsk-bone { background: color-mix(in srgb, var(--k-text) 9%, var(--k-sunken)); }
.fsk-repc .fsk-rep-sk-ins { display: grid; gap: 12px; margin: 16px 0 2px; }
.fsk-repc .fsk-rep-sk-ins > div { display: flex; align-items: center; gap: 10px; }
`;

let seq = 0;
const NS = "http://www.w3.org/2000/svg";

/** SVG builder for what h() doesn't cover (text). */
function svgEl(doc, tag, attrs = {}, ...kids) {
  const el = doc.createElementNS(NS, tag);
  for (const [k, v] of Object.entries(attrs)) if (v != null) el.setAttribute(k, String(v));
  el.append(...kids);
  return el;
}

const r1 = (v) => Math.round(v * 10) / 10;

const TONES = {
  positive: { icon: "up", sr: "Good news: " },
  negative: { icon: "alert", sr: "Needs attention: " },
  neutral: { icon: "info", sr: "Note: " },
};

function deltaTone(d) {
  if (!d || Math.sign(d.value) === 0) return "flat";
  return (d.good ?? d.value > 0) ? "good" : "bad";
}

/** 0, 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 start = Math.floor(lo / step), end = Math.ceil(hi / step);
  const ticks = [];
  for (let k = start; k <= end; k++) ticks.push(k * step);
  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", minimumFractionDigits: 0, maximumFractionDigits: 1 };
  if (f.style === "currency") Object.assign(opts, { style: "currency", currency: f.currency ?? "USD" });
  return new Intl.NumberFormat(undefined, opts).format(v);
}

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

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`; // zero or negative: square
  const rr = Math.min(r, base - top);
  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`;
}

/** What a screen reader hears for the chart; the full numbers follow in a hidden table. */
function chartSummary(c) {
  const s = c.series[0];
  if (!s || !s.values.length) return `${c.title}: no data.`;
  const f = (v) => formatValue(v, c.format);
  let hi = 0, lo = 0;
  s.values.forEach((v, i) => { if (v > s.values[hi]) hi = i; if (v < s.values[lo]) lo = i; });
  const first = s.values[0], last = s.values[s.values.length - 1];
  const change = c.type === "line" && first ? Math.round(((last - first) / Math.abs(first)) * 100) : null;
  const others = c.series.slice(1, 3).map((x) => x.name);
  return `${c.type === "bar" ? "Bar" : "Line"} chart: ${c.title}, ${c.labels[0]} to ${c.labels[c.labels.length - 1]}. ${s.name} is highest in ${c.labels[hi]} (${f(s.values[hi])}) and lowest in ${c.labels[lo]} (${f(s.values[lo])})`
    + (change != null ? `, ${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.";
}

/** Draws the chart at the box's real width, so text never stretches. Called again on resize. */
function drawChart(box, chart, animate) {
  const doc = box.ownerDocument;
  const win = doc.defaultView ?? window;
  const W = Math.max(200, Math.floor(box.clientWidth));
  const H = Math.max(140, Math.floor(box.clientHeight));
  const n = chart.labels.length;
  const series = chart.series.slice(0, 3);
  const values = series.flatMap((s) => s.values.slice(0, n)).filter(Number.isFinite);
  if (!n || !values.length) { box.replaceChildren(h("p", { class: "fsk-rep-empty" }, "No data for this period.")); return; }

  let lo = Math.min(...values), hi = Math.max(...values);
  if (chart.type === "bar" || lo < hi * 0.5) lo = Math.min(0, lo); // bars always start at zero
  if (chart.type === "bar") hi = Math.max(0, hi);
  const ticks = niceScale(lo, hi, H < 210 ? 3 : 4);
  const t0 = ticks[0], t1 = ticks[ticks.length - 1];
  const tickText = ticks.map((t) => axisFormat(t, chart.format));
  const pad = { top: 10, right: chart.type === "line" ? 10 : 2, bottom: 28, left: Math.ceil(Math.max(...tickText.map((t) => t.length)) * 6.4) + 14 };
  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) => (chart.type === "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(win.getComputedStyle(box).getPropertyValue("--k-r")) || 0;

  const svg = svgEl(doc, "svg", { class: `fsk-rep-svg${animate ? " fsk-rep-anim" : ""}`, width: W, height: H, viewBox: `0 0 ${W} ${H}`, "aria-hidden": "true", focusable: "false" });
  const grid = svgEl(doc, "g", { class: "fsk-rep-grid" });
  ticks.forEach((t, i) => {
    const y = Math.round(Y(t)) + 0.5;
    grid.append(
      svgEl(doc, "line", { x1: pad.left, x2: W - pad.right, y1: y, y2: y, class: t === 0 ? "fsk-rep-base" : null }),
      svgEl(doc, "text", { x: pad.left - 8, y, dy: "0.32em", "text-anchor": "end" }, tickText[i]));
  });
  const every = Math.max(1, Math.ceil(n / Math.max(1, Math.floor(pw / 52))));
  chart.labels.forEach((label, i) => {
    if ((n - 1 - i) % every) return; // thin from the end, so the latest period always has its label
    const anchor = chart.type === "line" && i === 0 ? "start" : chart.type === "line" && i === n - 1 ? "end" : "middle";
    grid.append(svgEl(doc, "text", { x: r1(X(i)), y: H - 8, "text-anchor": anchor }, label));
  });

  const hover = chart.type === "bar"
    ? svgEl(doc, "rect", { class: "fsk-rep-band", x: 0, y: pad.top, width: r1(band), height: ph, rx: Math.min(radius, 8), visibility: "hidden" })
    : svgEl(doc, "line", { class: "fsk-rep-guide", x1: 0, x2: 0, y1: pad.top, y2: pad.top + ph, visibility: "hidden" });
  const marks = svgEl(doc, "g", {});
  const dots = [];

  if (chart.type === "bar") {
    const ns = series.length;
    const groupW = Math.min(band * (ns > 1 ? 0.76 : 0.62), ns * 44);
    const gap = ns > 1 ? Math.min(3, groupW * 0.06) : 0;
    const bw = (groupW - gap * (ns - 1)) / ns;
    const r = Math.min(radius, bw / 2.5, 6);
    series.forEach((s, si) => {
      const g = svgEl(doc, "g", { class: seriesClass(series, si) });
      s.values.slice(0, n).forEach((v, i) => {
        g.append(svgEl(doc, "path", { class: "fsk-rep-bar", d: barPath(X(i) - groupW / 2 + si * (bw + gap), bw, zero, Y(v), r), style: `--i:${i}` }));
      });
      marks.append(g);
    });
  } else {
    let lead = true;
    series.forEach((s, si) => {
      const g = svgEl(doc, "g", { class: seriesClass(series, si) });
      const pts = s.values.slice(0, n).map((v, i) => [X(i), Y(v)]);
      const d = pts.map(([x, y], i) => `${i ? "L" : "M"}${r1(x)} ${r1(y)}`).join("");
      if (lead && !s.compare && pts.length > 1) {
        const id = `fsk-rep-grad-${++seq}`;
        g.append(
          svgEl(doc, "defs", {}, svgEl(doc, "linearGradient", { id, x1: 0, y1: 0, x2: 0, y2: 1 },
            svgEl(doc, "stop", { offset: "0%", "stop-color": "currentColor", "stop-opacity": 0.2 }),
            svgEl(doc, "stop", { offset: "100%", "stop-color": "currentColor", "stop-opacity": 0 }))),
          svgEl(doc, "path", { class: "fsk-rep-area", d: `${d}L${r1(pts[pts.length - 1][0])} ${pad.top + ph}L${r1(pts[0][0])} ${pad.top + ph}Z`, fill: `url(#${id})` }));
      }
      g.append(svgEl(doc, "path", { class: `fsk-rep-line${s.compare ? " fsk-rep-line--cmp" : ""}`, d, pathLength: s.compare ? null : 1 }));
      if (lead && !s.compare) {
        const [ex, ey] = pts[pts.length - 1];
        g.append(svgEl(doc, "circle", { class: "fsk-rep-end", cx: r1(ex), cy: r1(ey), r: 4 }));
      }
      const ds = pts.map(([x, y]) => svgEl(doc, "circle", { class: "fsk-rep-dot", cx: r1(x), cy: r1(y), r: 4, visibility: "hidden" }));
      g.append(...ds);
      dots.push(ds);
      if (!s.compare) lead = false;
      marks.append(g);
    });
  }

  // Pointer readout. Keyboard and screen reader users get the same numbers from the hidden table.
  const tip = h("div", { class: "fsk-rep-tip", hidden: true, "aria-hidden": "true" });
  const hit = svgEl(doc, "rect", { x: pad.left, y: 0, width: pw, height: pad.top + ph, fill: "transparent" });
  const hide = () => {
    tip.hidden = true;
    hover.setAttribute("visibility", "hidden");
    dots.forEach((ds) => ds.forEach((c) => c.setAttribute("visibility", "hidden")));
  };
  const showAt = (i) => {
    if (i < 0 || i >= n) { hide(); return; }
    if (chart.type === "bar") hover.setAttribute("x", String(r1(pad.left + band * i)));
    else { hover.setAttribute("x1", String(r1(X(i)))); hover.setAttribute("x2", String(r1(X(i)))); }
    hover.setAttribute("visibility", "visible");
    dots.forEach((ds) => ds.forEach((c, k) => c.setAttribute("visibility", k === i ? "visible" : "hidden")));
    tip.replaceChildren(h("strong", {}, chart.labels[i]), ...series.map((s, si) => h("span", { class: "fsk-rep-tip-row" },
      h("i", { class: `fsk-rep-sw ${seriesClass(series, si)}` }), s.name, h("b", { class: "fsk-num" }, formatValue(s.values[i], chart.format)))));
    tip.hidden = false;
    const tw = tip.offsetWidth;
    const x = X(i);
    tip.style.left = `${Math.round(x + 14 + tw > W ? Math.max(0, x - 14 - tw) : x + 14)}px`;
  };
  hit.addEventListener("pointermove", (e) => {
    const x = (e).clientX - svg.getBoundingClientRect().left - pad.left;
    showAt(chart.type === "bar" ? Math.floor(x / band) : Math.round((x / pw) * (n - 1)));
  });
  hit.addEventListener("pointerleave", hide);

  svg.append(grid, hover, marks, hit);
  box.replaceChildren(svg, tip);
}

function kpiTile(m, animate) {
  const d = m.delta;
  const tone = deltaTone(d);
  const sign = d ? Math.sign(d.value) : 0;
  const value = formatValue(m.value, m.format);
  const valueEl = h("span", { class: "fsk-rep-kpi-value fsk-num" });
  if (animate) countUp(valueEl, m.value, m.format); else valueEl.textContent = value;
  const said = d ? `, ${sign === 0 ? "no change" : `${sign > 0 ? "up" : "down"} ${Math.abs(d.value)}%`}${d.vs ? ` ${d.vs}` : ""}` : "";
  return h("div", { class: `fsk-rep-kpi fsk-rep-kpi--${tone}`, role: "group", "aria-label": `${m.label}: ${value}${said}` },
    h("span", { class: "fsk-rep-kpi-label", title: m.label }, m.label),
    valueEl,
    d && h("div", { class: "fsk-rep-kpi-row", "aria-hidden": "true" },
      h("span", { class: `fsk-rep-delta fsk-rep-delta--${tone} fsk-num` }, sign !== 0 && icon(sign > 0 ? "up" : "down", 12), sign === 0 ? "0%" : `${Math.abs(d.value)}%`),
      d.vs && h("span", { class: "fsk-rep-kpi-vs" }, d.vs)),
    (m.trend?.length ?? 0) > 1 ? sparkline(m.trend, { label: `${m.label} trend` }) : h("div", { style: { height: "14px" } }));
}

function tableCell(v, col, max) {
  if (typeof v !== "number") return h("td", { class: "fsk-rep-r" }, v ?? "–");
  if (col.delta) {
    const sign = Math.sign(v);
    const tone = sign === 0 ? "flat" : (col.upIsGood ?? true) === sign > 0 ? "good" : "bad";
    return h("td", { class: "fsk-rep-r" }, h("span", { class: `fsk-rep-chg fsk-rep-chg--${tone} fsk-num` },
      sign !== 0 && icon(sign > 0 ? "up" : "down", 12),
      h("span", { class: "fsk-sr" }, sign > 0 ? "up " : sign < 0 ? "down " : ""),
      formatValue(Math.abs(v), { style: "percent", digits: 1 })));
  }
  const text = h("span", { class: "fsk-num" }, formatValue(v, col.format));
  if (!col.bar || max <= 0) return h("td", { class: "fsk-rep-r" }, text);
  return h("td", { class: "fsk-rep-r" }, h("span", { class: "fsk-rep-share" },
    h("span", { class: "fsk-rep-track", "aria-hidden": "true" }, h("span", { class: "fsk-rep-fill", style: { width: `${Math.max(2, (v / max) * 100)}%` } })),
    text));
}

/**
 * Desktop canvas, READ_MODE: the agent reads the state and explains it; it doesn't change it.
 * If your app refreshes the numbers, call canvas.setState and the report redraws.
 */
export function mount({ root, head, canvas, data, actions }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-rep", CSS);
  const doc = root.ownerDocument;
  const win = doc.defaultView ?? window;
  const reduce = !!win.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
  let state = structuredClone(canvas?.state ?? data);
  let disposers = [];
  let first = true;
  const uid = `fsk-rep-${++seq}`;
  const off = canvas?.onStateChange?.((next) => { state = structuredClone(next); render(); });

  function section(key, label, ic, body, extra) {
    return h("section", { class: `fsk-rep-sec${extra ? ` ${extra}` : ""}`, id: `${uid}-${key}`, "data-sec": key, "aria-labelledby": `${uid}-${key}-h` },
      h("h3", { class: "fsk-rep-h", id: `${uid}-${key}-h`, tabindex: "-1" }, icon(ic, 16), label),
      body);
  }

  function chartBlock(c) {
    const series = c.series.slice(0, 3);
    const box = h("div", { class: "fsk-rep-chart", role: "img", "aria-label": chartSummary(c) });
    const block = h("div", { class: "fsk-rep-panel fsk-rep-chartpanel" },
      h("div", { class: "fsk-rep-charthead" },
        h("h4", { class: "fsk-rep-charttitle" }, c.title),
        series.length > 1 && h("ul", { class: `fsk-rep-legend${c.type === "line" ? " fsk-rep-legend--line" : ""}`, "aria-hidden": "true" },
          series.map((s, i) => h("li", {}, h("i", { class: `fsk-rep-sw ${seriesClass(series, i)}` }), s.name)))),
      box,
      h("table", { class: "fsk-sr" },
        h("caption", {}, c.title),
        h("thead", {}, h("tr", {}, h("th", { scope: "col" }, "Period"), series.map((s) => h("th", { scope: "col" }, s.name)))),
        h("tbody", {}, c.labels.map((l, i) => h("tr", {}, h("th", { scope: "row" }, l), series.map((s) => h("td", {}, formatValue(s.values[i], c.format))))))));
    const animate = first;
    let width = 0;
    const paint = () => {
      const w = box.clientWidth;
      if (!w || Math.abs(w - width) < 1) return;
      const anim = animate && !width;
      width = w;
      drawChart(box, c, anim);
    };
    let frame = 0;
    const ro = "ResizeObserver" in win ? new win.ResizeObserver(() => { win.cancelAnimationFrame(frame); frame = win.requestAnimationFrame(paint); }) : null;
    ro?.observe(box);
    disposers.push(() => { ro?.disconnect(); win.cancelAnimationFrame(frame); });
    win.requestAnimationFrame(paint);
    return block;
  }

  function tableBlock(t) {
    const limit = t.limit ?? 6;
    const rows = t.rows.slice(0, limit);
    const more = t.rows.length - rows.length;
    const max = t.columns.map((_, ci) => Math.max(0, ...t.rows.map((r) => (typeof r.values[ci] === "number" ? (r.values[ci]) : 0))));
    return h("div", { class: "fsk-rep-panel" },
      h("div", { class: "fsk-rep-tablewrap" },
        h("table", { class: "fsk-rep-table" },
          h("caption", { class: "fsk-sr" }, t.title),
          h("thead", {}, h("tr", {},
            h("th", { scope: "col" }, t.rowLabel),
            t.columns.map((c) => h("th", { scope: "col", class: "fsk-rep-r" }, c.label)))),
          h("tbody", {}, rows.map((r, i) => h("tr", {},
            h("th", { scope: "row" }, h("span", { class: "fsk-rep-rank fsk-num", "aria-hidden": "true" }, i + 1), r.label),
            t.columns.map((c, ci) => tableCell(r.values[ci], c, max[ci]))))))),
      more > 0 && h("div", { class: "fsk-rep-tfoot" },
        h("span", {}, `${more} more ${more === 1 ? "row" : "rows"}`),
        actions?.openInApp && h("button", { class: "fsk-btn fsk-btn--link", type: "button", onclick: () => actions.openInApp?.() }, "See all", icon("chevron", 14))));
  }

  function insightsBlock(list) {
    return h("ul", { class: "fsk-rep-ins" }, list.slice(0, 4).map((x) => {
      const t = TONES[x.tone] ?? TONES.neutral;
      return h("li", { class: `fsk-rep-in fsk-rep-in--${x.tone}` },
        h("span", { class: "fsk-rep-in-ico", "aria-hidden": "true" }, icon(t.icon, 16)),
        h("div", {},
          h("p", { class: "fsk-rep-in-title" }, h("span", { class: "fsk-sr" }, t.sr), x.title),
          x.detail && h("p", { class: "fsk-rep-in-detail" }, x.detail)));
    }));
  }

  function wireNav(nav, sentinel, sections) {
    if (!("IntersectionObserver" in win)) return;
    const visible = new Set();
    const mark = (key) => nav.querySelectorAll("[data-go]").forEach((b) => b.setAttribute("aria-current", String(b.dataset.go === key)));
    const io = new win.IntersectionObserver((entries) => {
      for (const e of entries) {
        const key = (e.target).dataset.sec;
        if (e.isIntersecting) visible.add(key); else visible.delete(key);
      }
      const top = sections.find((s) => visible.has(s.dataset.sec));
      if (top) mark(top.dataset.sec);
    }, { rootMargin: "-64px 0px -55% 0px" });
    sections.forEach((s) => io.observe(s));
    const stuck = new win.IntersectionObserver(([e]) => {
      const isStuck = !e.isIntersecting && e.boundingClientRect.top < nav.getBoundingClientRect().top - 2;
      nav.toggleAttribute("data-stuck", isStuck);
    });
    stuck.observe(sentinel);
    disposers.push(() => { io.disconnect(); stuck.disconnect(); });
  }

  function render() {
    disposers.forEach((d) => d());
    disposers = [];
    canvas?.setTitle?.((state.canvasTitle ?? state.title).slice(0, 80));
    const kpis = (state.kpis ?? []).slice(0, 4);
    const parts = [];
    if (kpis.length) parts.push({ key: "overview", label: "Overview", ic: "zap", body: h("div", { class: "fsk-rep-kpis", "data-n": kpis.length }, kpis.map((m) => kpiTile(m, first))) });
    if (state.chart) parts.push({ key: "chart", label: state.chart.type === "line" ? "Trend" : "Chart", ic: state.chart.type === "line" ? "chart" : "bars", body: chartBlock(state.chart) });
    if (state.table) parts.push({ key: "breakdown", label: state.table.title, ic: "table", body: tableBlock(state.table) });
    if (state.insights?.length) parts.push({ key: "insights", label: "Insights", ic: "sparkle", body: insightsBlock(state.insights) });
    const sections = parts.map((p, i) => section(p.key, p.label, p.ic, p.body, i === 0 ? "fsk-rep-sec--first" : undefined));

    const go = (key) => {
      const target = sections.find((s) => s.dataset.sec === key);
      target?.scrollIntoView({ behavior: reduce ? "auto" : "smooth", block: "start" });
      target?.querySelector(".fsk-rep-h")?.focus({ preventScroll: true });
    };
    const sentinel = h("div", { "aria-hidden": "true", style: { height: "1px", marginBottom: "-1px" } });
    const nav = parts.length >= 3 && h("nav", { class: "fsk-rep-nav", "aria-label": "Report sections" },
      parts.map((p, i) => h("button", { class: "fsk-rep-navbtn", type: "button", "data-go": p.key, "aria-current": String(i === 0), onclick: () => go(p.key) }, p.key === "breakdown" ? "Breakdown" : p.label)));

    const wrap = h("div", { class: `fsk fsk-rep${first ? " fsk-rep-enter" : ""}` },
      h("article", { class: "fsk-rep-inner", "aria-label": state.title },
        h("header", {},
          h("div", { class: "fsk-rep-top" },
            h("span", { class: "fsk-badge fsk-badge--agent" }, icon("chart", 12), state.eyebrow ?? "Report"),
            actions?.openInApp && h("button", { class: "fsk-btn fsk-btn--ghost", type: "button", onclick: () => actions.openInApp?.(), "aria-label": "Open in app" },
              icon("external", 14), h("span", {}, "Open in app"))),
          h("h2", { class: "fsk-rep-title" }, state.title),
          (state.period || state.updated) && h("p", { class: "fsk-rep-meta" },
            state.period && h("span", {}, icon("calendar", 14), state.period),
            state.updated && h("span", {}, icon("clock", 14), `Updated ${state.updated}`)),
          state.summary && h("p", { class: "fsk-rep-summary" }, state.summary)),
        nav && sentinel,
        nav,
        sections,
        h("p", { class: "fsk-rep-foot" }, icon("message", 14), "Ask me about any number in this report.")));
    root.replaceChildren(wrap);
    if (nav) wireNav(nav, sentinel, sections);
    first = false;
  }

  render();
  return () => { off?.(); disposers.forEach((d) => d()); root.replaceChildren(); };
}

/** Mobile has no canvas: a summary card (a chat card action) with the headline numbers and the top findings. */
export function mountMobile({ root, head, data, api }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-rep", CSS);
  const kpis = (data.kpis ?? []).slice(0, 4);
  root.replaceChildren(h("section", { class: "fsk fsk-card fsk-repc", "aria-label": data.title },
    h("header", { class: "fsk-head" },
      h("span", { class: "fsk-chip" }, icon("chart", 18)),
      h("div", {}, h("h3", { class: "fsk-title" }, data.title), data.period && h("p", { class: "fsk-sub" }, data.period))),
    kpis.length > 0 && h("div", { class: "fsk-repc-kpis" }, kpis.map((m) => {
      const tone = deltaTone(m.delta);
      const sign = m.delta ? Math.sign(m.delta.value) : 0;
      return h("div", { class: "fsk-repc-kpi" },
        h("span", { class: "fsk-rep-kpi-label" }, m.label),
        h("span", { class: "fsk-rep-kpi-value fsk-num" }, formatValue(m.value, m.format)),
        m.delta && h("span", {}, h("span", { class: `fsk-rep-delta fsk-rep-delta--${tone} fsk-num` },
          sign !== 0 && icon(sign > 0 ? "up" : "down", 12),
          h("span", { class: "fsk-sr" }, sign > 0 ? "up " : sign < 0 ? "down " : "no change "),
          `${Math.abs(m.delta.value)}%`)));
    })),
    (data.insights?.length ?? 0) > 0 && h("ul", { class: "fsk-repc-ins" }, data.insights.slice(0, 3).map((x) => {
      const t = TONES[x.tone] ?? TONES.neutral;
      return h("li", { class: `fsk-rep-in--${x.tone}` },
        h("span", { class: "fsk-rep-in-ico", "aria-hidden": "true" }, icon(t.icon, 14)),
        h("span", {}, h("span", { class: "fsk-sr" }, t.sr), x.title));
    })),
    h("p", { class: "fsk-repc-foot" }, icon("expand", 12), "Open on desktop for the full report.")));
  api?.displayed?.();
  return () => root.replaceChildren();
}

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

const loadingLabel = (s) => (s.kind === "loading" ? s.label ?? "Loading the report…" : "");

/** The report as bones: section tabs, four headline numbers, a chart and the first table rows. */
function reportSkeleton() {
  const heading = (w, i) => h("div", { class: "fsk-rep-sk-h" }, bone("16px", "16px", { cls: "fsk-bone--box", i }), bone(w, "11px", { i }));
  return [
    h("div", { class: "fsk-rep-sk-nav" }, ["72px", "56px", "84px", "64px"].map((w, i) => bone(w, "26px", { cls: "fsk-bone--box", i }))),
    h("section", { class: "fsk-rep-sec fsk-rep-sec--first" }, heading("80px", 0),
      h("div", { class: "fsk-rep-kpis", "data-n": 4 }, Array.from({ length: 4 }, (_, i) =>
        h("div", { class: "fsk-rep-sk-kpi" }, bone("48%", "9px", { i }), bone("64%", "22px", { i }), bone("38%", "14px", { i }), bone("100%", "26px", { i }))))),
    h("section", { class: "fsk-rep-sec" }, heading("64px", 2),
      h("div", { class: "fsk-rep-panel fsk-rep-chartpanel fsk-rep-sk-chart" }, bone("34%", "11px", { i: 2 }),
        h("div", { class: "fsk-rep-sk-bars" }, [42, 48, 46, 55, 58, 64, 61, 70, 74, 79, 84, 96].map((v, i) => bone("auto", `${v}%`, { i: i % 6 }))))),
    h("section", { class: "fsk-rep-sec" }, heading("110px", 4),
      h("div", { class: "fsk-rep-panel" }, Array.from({ length: 4 }, (_, i) =>
        h("div", { class: "fsk-rep-sk-row" }, bone(`${[30, 26, 22, 24][i]}%`, "10px", { i }), bone("48px", "10px", { i }), bone("72px", "10px", { i }), bone("44px", "10px", { i }))))),
  ];
}

/**
 * Desktop canvas in a state: the report's header (badge, title, period) above the report as bones while it loads,
 * or a centered empty or error block. Returns the cleanup; mount the report once its data is in.
 */
export function mountState({ root, head, state, title, subtitle, canvas, canvasTitle, eyebrow }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-rep", CSS);
  canvas?.setTitle?.((canvasTitle ?? title ?? "Report").slice(0, 80));
  const loading = state.kind === "loading";
  let dispose = () => {};
  let body;
  if (state.kind === "loading") body = h("div", { "aria-hidden": "true" }, reportSkeleton());
  else if (state.kind === "empty") body = h("div", { class: "fsk-rep-st-box" }, h("div", { class: "fsk-rep-st-panel" }, emptyBlock(state)));
  else {
    const e = errorBlock(state);
    dispose = e.dispose;
    body = h("div", { class: "fsk-rep-st-box" }, h("div", { class: "fsk-rep-st-panel" }, e.el));
  }
  root.replaceChildren(h("div", {
    class: "fsk fsk-rep fsk-rep-st", "data-state": state.kind,
    role: loading ? "status" : null, "aria-busy": loading ? "true" : null, "aria-live": loading ? "polite" : null,
  },
    loading && h("span", { class: "fsk-sr" }, loadingLabel(state)),
    h("div", { class: "fsk-rep-inner" },
      h("span", { class: "fsk-badge fsk-badge--agent" }, icon("chart", 12), eyebrow ?? "Report"),
      h("h2", { class: "fsk-rep-title" }, title ?? (loading ? bone("56%", "24px") : "Report")),
      subtitle ? h("p", { class: "fsk-rep-meta" }, h("span", {}, icon("calendar", 14), subtitle)) : loading && h("p", { class: "fsk-rep-meta", "aria-hidden": "true" }, bone("160px", "10px")),
      loading && h("div", { class: "fsk-rep-summary fsk-sk-lines", "aria-hidden": "true" }, bone("94%", "11px"), bone("68%", "11px")),
      body)));
  return () => { dispose(); root.replaceChildren(); };
}

/** Mobile summary card in a state: its header above headline-number bones, or an empty or error block. Read-only: report displayed() yourself. */
export function mountMobileState({ root, head, state, title, subtitle, surface = "mobile" }) {
  ensureStyles(head, "fsk-base", BASE_CSS);
  ensureStyles(head, "fsk-rep", CSS);
  const card = stateCard({
    state: state.kind === "loading" ? { ...state, label: loadingLabel(state) } : state, cls: "fsk-repc", icon: "chart", title, subtitle, surface,
    skeleton: () => [
      h("div", { class: "fsk-repc-kpis" }, Array.from({ length: 4 }, (_, i) =>
        h("div", { class: "fsk-repc-kpi" }, bone("58%", "9px", { i }), bone("72%", "18px", { i }), bone("36%", "12px", { i })))),
      h("div", { class: "fsk-rep-sk-ins" }, Array.from({ length: 3 }, (_, i) =>
        h("div", {}, bone("24px", "24px", { cls: "fsk-bone--box", i }), bone(`${[74, 62, 68][i]}%`, "10px", { i })))),
    ],
  });
  root.replaceChildren(card.el);
  return () => { card.dispose(); root.replaceChildren(); };
}

export const fixtures = {
  default: {
    canvasTitle: "Revenue report: October 2026",
    eyebrow: "Monthly report",
    title: "Revenue, October 2026",
    summary: "MRR grew 6.2% to $482,300 and beat target for the fourth month in a row. Churn is the one number moving the wrong way.",
    period: "Oct 1 to Oct 31, 2026",
    updated: "8 min ago",
    kpis: [
      { label: "MRR", value: 482300, format: { style: "currency" }, delta: { value: 6.2, vs: "vs Sep" }, trend: [402, 411, 418, 431, 440, 452, 454, 482] },
      { label: "New customers", value: 128, delta: { value: 14, vs: "vs Sep" }, trend: [88, 97, 92, 104, 101, 110, 112, 128] },
      { label: "Net revenue retention", value: 108.4, format: { style: "percent" }, delta: { value: 1.1, vs: "vs Sep" }, trend: [104, 105, 105, 106, 107, 107, 107.2, 108.4] },
      { label: "Churned MRR", value: 9850, format: { style: "currency" }, delta: { value: 18, good: false, vs: "vs Sep" }, trend: [6.1, 6.4, 6.2, 7, 7.4, 8.1, 8.3, 9.85] },
    ],
    chart: {
      type: "line",
      title: "Monthly recurring revenue",
      labels: ["Nov", "Dec", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct"],
      series: [
        { name: "MRR", values: [361000, 368500, 377200, 381900, 392400, 402100, 411300, 418600, 431200, 440900, 454100, 482300] },
        { name: "Target", values: [360000, 370000, 380000, 390000, 400000, 410000, 420000, 430000, 438000, 446000, 452000, 460000], compare: true },
      ],
      format: { style: "currency" },
    },
    table: {
      title: "MRR by region",
      rowLabel: "Region",
      columns: [
        { label: "Customers" },
        { label: "MRR", format: { style: "currency" }, bar: true },
        { label: "Change", delta: true },
      ],
      rows: [
        { label: "North America", values: [1612, 228400, 5.8] },
        { label: "Western Europe", values: [902, 121900, 7.1] },
        { label: "UK and Ireland", values: [388, 54300, 3.9] },
        { label: "Asia Pacific", values: [344, 41700, 16.4] },
        { label: "Nordics", values: [161, 22600, 2.2] },
        { label: "Latin America", values: [128, 13400, -1.5] },
      ],
      limit: 5,
    },
    insights: [
      { tone: "positive", title: "Enterprise upgrades drove most of the growth", detail: "Nine enterprise accounts upgraded and added $18,400 MRR, 65% of this month's net new." },
      { tone: "negative", title: "Churn rose for the third month in a row", detail: "Churned MRR is up 18% vs September, mostly Starter accounts in their first 90 days." },
      { tone: "neutral", title: "Asia Pacific is now your fourth-largest region", detail: "It passed the Nordics after three new annual contracts." },
    ],
  },
  bars: {
    title: "Sign-ups, last 8 weeks",
    period: "Sep 7 to Nov 1, 2026",
    updated: "just now",
    kpis: [
      { label: "Sign-ups", value: 2140, delta: { value: 9.4, vs: "vs prior 8 weeks" } },
      { label: "Activated", value: 46.2, format: { style: "percent" }, delta: { value: -1.8, vs: "vs prior 8 weeks" } },
    ],
    chart: {
      type: "bar",
      title: "Sign-ups per week",
      labels: ["W37", "W38", "W39", "W40", "W41", "W42", "W43", "W44"],
      series: [
        { name: "This year", values: [212, 238, 251, 246, 268, 281, 302, 342] },
        { name: "Last year", values: [190, 201, 214, 222, 219, 240, 251, 262], compare: true },
      ],
    },
    insights: [
      { tone: "positive", title: "Week 44 was your best week this year" },
      { tone: "negative", title: "Fewer new users finish setup on day one" },
    ],
  },
};
```

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

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