# Profitability map

> Every customer as a bubble of margin against revenue, sized by support hours, with the ones below 0% listed under it and a fix for each that moves their bubble when applied.

Two stacked cards for a review of the customer book. The first maps 38 customers: margin up the side, revenue along the bottom, support hours as the bubble’s size, a dashed line at the median revenue and a red zone below 0% where each bubble wears a dotted ring. Plan or Industry recolours the bubbles and the legend; hover, focus or the arrow keys show a tooltip. The second card lists the customers that cost more than they pay, each with the fix an assistant suggests: cap support, move up a plan, add an onboarding fee or review at renewal. The footer adds up what the checked fixes are worth from a small cost model; Apply moves their bubbles to their new margin, with Undo. A row and its bubble light together. Light and dark.

A React component by Bruno Delorence: https://brunodelorence.com/components/profitability-map. MIT License, Copyright (c) 2026 Bruno Delorence.

Category: Dashboards.

## Anatomy

1. **Header**: An icon tile, the title, how many customers over which period, and the Plan / Industry switch.
2. **Colour switch**: A radio group of two: Plan or Industry recolours every bubble and the legend. The arrow keys move the choice.
3. **Map**: Margin up the side, revenue along the bottom, on axes that widen in round steps when a customer falls outside −40% to 80% or past $120k.
4. **Median line**: A dashed line at the book’s median revenue, labelled on the axis; it splits Keep lean from Grow these and slides when a fix raises revenue.
5. **Loss zone**: Below the red dashed 0% line, a faint red band labelled Costing you money; each bubble in it wears a dotted red ring.
6. **Bubble**: A button per customer, its width from the square root of its support hours, a translucent fill and a stroke in its group’s colour.
7. **Tooltip**: The customer and its group, then its margin and support hours, beside the lit bubble (to its left past the middle).
8. **Legend**: The groups of the current colouring, and a size key for support hours from the fewest to the most.
9. **Fix row**: A checkbox, the customer with its revenue and hours, its margin in red, and the fix picker. Hovering it lights its bubble.
10. **Footer**: What the checked fixes add over a year, computed from the cost model, with Draft emails and Apply.

## Properties

### Cards (`show`)

1. **Both (default)**: The map over the list of fixes, with a row and its bubble lighting together.
2. **Map**: Only the map, to read the shape of the book without acting on it.
3. **Fixes**: Only the customers below 0% with their fixes, footer and Apply.

Keep both for a review where people decide and act in one place. Show the map alone on a report nobody edits, and the fixes alone where the map already sits elsewhere on the page.

### Colour by at first (`defaultGroup`)

1. **Plan (default)**: Starter to Enterprise: shows whether the losses sit on the cheaper plans.
2. **Industry**: Retail, Healthcare, Hospitality, Services: shows whether one trade costs more to serve.

Open on the slicing the review is about. The switch stays in the header either way, and the bubbles keep their places when it changes.

## When to use

- A book of a few dozen customers where the question is which ones pay their way: margin against revenue, with the cost of serving each as the bubble’s size.
- Finding the accounts below 0% and acting on them in the same place: a fix per customer, what the fixes add up to, and a way to apply them.
- Comparing two ways of slicing the same book, such as plan and industry, without redrawing the axes.
- A weekly or monthly review where a suggested action per row saves the reader from working out the fix on their own.

## When not to use

- Hundreds of customers. The bubbles pile up and the arrow keys walk forever; use a table sorted by margin with a small histogram.
- Margin over time. The map is one period; use a line per segment or a cohort view to see a customer’s margin move.
- Fixes that need approval or negotiation. Apply changes the book at once; send those to a review queue or the account owner instead.
- Exact figures for finance. The bubbles place customers to the eye; export the numbers or use a table for reconciling.
- A single customer. Show its own page with revenue, costs and support history instead of one bubble on a map.

### Reading the map

- **Up is margin, right is revenue, size is support hours.** A bubble’s area grows with the hours, so a big bubble low down is a customer that takes a lot of help for what it pays.
- **The red zone is below 0%.** Its customers cost more than they pay, and each wears a dotted red ring as well as sitting under the line.
- **The dashed line is the median revenue**, worked out from the book. Left of it is Keep lean, right of it Grow these.
- The axes start at −40% to 80% and $0 to $120k and widen in round steps when a customer falls outside, so a whole book always fits.

### Suggested fixes

- Each fix comes from the cost model in `data.ts`: cap support at 20 hours, move up a plan, add an onboarding fee under $20k a year, or review at renewal. What each adds is computed, never typed.
- The suggestion is the fix that adds most margin. When renewal is two months away or less, it is a review instead, and that row starts unchecked.
- Apply changes the book at once and moves the bubbles, with Undo in a toast. `onApply` gets each fix with what it adds a year: save them there.
- Draft emails only calls `onDraftEmails` with the checked customers, and its toast says the drafts were requested, not written. Writing and sending the emails is yours.

### Map vs. list

**Map**
- Every customer at once, so the losing ones show against the rest.
- Good for spotting a pattern: a plan, an industry, a size of account.
- Places customers to the eye; the exact figures are in each bubble’s label.

**List of fixes**
- Only the customers below 0%, each with a fix and what it adds.
- Good for acting: check, change a fix, apply.
- Says nothing about the healthy part of the book.

## Do’s and don’ts

- **Do**: Map a book of a few dozen customers, so every bubble can be told apart and the arrow keys reach them all quickly.
- **Don’t**: Pour hundreds of customers onto the map. The bubbles pile up into one blot; use a table sorted by margin instead.
- **Do**: Name the period in a few lower-case words, like `last 12 months`, so it reads after the count.
- **Don’t**: Put the method into `period`. The subtitle wraps and pushes the switch about; explain the figures elsewhere on the page.
- **Do**: Give the assistant a short name, like `Tally`: the subtitle reads “Tally suggests one fix for each”.
- **Don’t**: Describe the assistant in `assistant`. Its whole text lands in front of “suggests one fix for each” and in the empty state.

## Content

The component writes its own titles and totals from the book; the words you pass are the period and the assistant’s name.

- **The period** follows the count under the title (“38 customers · last 12 months”), so write it in lower case with no full stop.
- **The assistant’s name** is a proper noun, one or two words. It opens the second card’s subtitle and the empty state.
- **Customer names** show in the tooltip, the rows and the bubble labels: keep them as people know the account, not an ID.
- **Margins and money** come out formatted (`−22%`, `$54k`) with a true minus sign. Pass revenue in thousands and margin in percent.

## Installation

Install it with the shadcn CLI, into components/profitability-map of any React project:

```sh
npx shadcn@latest add https://brunodelorence.com/r/profitability-map.json
```

Or add the registry to components.json once, as a namespace that coding agents and the shadcn MCP server search by name:

```json
{
  "registries": {
    "@brunodelorence": "https://brunodelorence.com/r/{name}.json"
  }
}
```

```sh
npx shadcn@latest add @brunodelorence/profitability-map
```

Or copy all the source files below into one folder of your project. Either way it needs React 19 and a bundler with CSS Modules (Next.js, Vite).

It has a dark colour scheme. Its colours are CSS light-dark() pairs, kept inside @supports so that builds which rewrite light-dark() for older browsers leave them alone: it follows your page’s color-scheme (light unless the page sets one) or its colorScheme prop, with nothing to configure. Browsers without light-dark() show it light.

## Usage

```tsx
import { ProfitabilityMap } from './profitability-map';

export function BookReview() {
  return (
    <ProfitabilityMap
      assistant="Tally"
      period="last 12 months"
      onApply={(fixes) => console.log('Apply', fixes)}
      onDraftEmails={(customers) => console.log('Draft', customers)}
      autoplay={false}
    />
  );
}
```

## States

- **Coloured by plan**: The default: 38 customers, four in the red zone, three fixes checked and one review left unchecked.
- **Bubble tooltip**: A bubble hovered or focused: it grows a little, the rest fade, and its row in the list lights too.
- **Coloured by industry**: The same positions in four other colours, and a legend of industries.
- **Row hovered**: A row hovered in the list lights its bubble on the map and shows its tooltip.
- **Fix picker**: The fixes the customer can take, each with what it adds a year; the sparkle marks the suggested one.
- **Fix changed, one unchecked**: A different fix for one row and another left out: the footer counts two fixes and their own total.
- **More menu**: The ··· menu checks every fix, unchecks them all, or goes back to the suggestions.
- **Fixes applied**: After Apply: three bubbles have climbed out of the red zone and the list keeps the one left, with Undo in a toast.
- **Nothing to fix**: A book with no margin below 0%: the second card says every customer pays its way.
- **Light**: With `colorScheme="light"` the cards turn white on a pale mint backdrop and the colours deepen to keep their contrast.
- **Phone**: Under 560 px the switch spans the card, the middle revenue ticks drop, and each fix picker moves under its name.

## Examples

### Industry grouping

The same book coloured by industry: the same positions, four other colours and a legend of industries.

```tsx
import { ProfitabilityMap } from './profitability-map';

/** The same book, coloured by industry: healthcare and services carry the heavy support. */
export function IndustryGrouping() {
  return <ProfitabilityMap autoplay={false} defaultGroup="industry" />;
}
```

### Healthy book

No customer below 0%: the red zone is empty and the second card says every customer pays its way, with the range of margins.

```tsx
import { HEALTHY } from './data';
import { ProfitabilityMap } from './profitability-map';

/** Every customer above 0%: no red zone bubbles, and the second card says so. */
export function HealthyBook() {
  return <ProfitabilityMap autoplay={false} customers={HEALTHY} assistant="Tally" />;
}
```

### Scatter only

The map on its own for twenty customers over the last quarter, with its own median and two bubbles in the red zone.

```tsx
import { CUSTOMERS } from './data';
import { ProfitabilityMap } from './profitability-map';

/** The map on its own, for the twenty newest customers over the last quarter. */
export function ScatterOnly() {
  return (
    <ProfitabilityMap
      autoplay={false}
      show="scatter"
      period="last quarter"
      customers={CUSTOMERS.slice(-20)}
    />
  );
}
```

### Fixes applied

Opens just after Apply: three bubbles have climbed out of the red zone, the list keeps the one left for its renewal, and the toast offers Undo.

```tsx
import { ProfitabilityMap } from './profitability-map';

/** Opens after Apply: three bubbles have climbed out of the red zone, one review is left. */
export function FixesApplied() {
  return <ProfitabilityMap autoplay={false} defaultState={{ applied: true }} />;
}
```

## How it works

- The bubbles are buttons placed by left and top as shares of the axes, with a diameter from the square root of the support hours, so the area grows with the hours. Moving a customer is a change of those two numbers; a CSS transition carries the bubble there. The biggest are drawn first, so the small ones stay on top.
- The axes start at −40% to 80% and $0 to $120k and widen in round steps (40 points, $30k) when a customer falls outside. The median revenue is computed from the book and labelled on the axis, hiding the tick it would collide with.
- Plan / Industry is a radio group; it only swaps a data-tone on each bubble and legend key, whose colour comes from a token per group, so the colours cross-fade while the positions stay.
- The fixes are a small cost model in data.ts: a support hour costs $450, a plan one step up pays a set amount more, and accounts under $20k can take an onboarding fee. withFix returns the customer after a fix and gainOf the margin it adds, so the suggestion (the fix that adds most, or a review when renewal is a month or two away), the menu’s figures and the footer’s total are all computed.
- Apply replaces the fixed customers with their new selves: their bubbles climb out of the red zone (and right, when revenue rose), the list drops them, and a toast offers Undo, which restores the book as it was. A review stays in the list as booked.
- One hovered customer is shared by both cards: hovering or focusing a bubble lights its row, and a row lights its bubble and shows its tooltip, with the rest of the map faded.
- The stage is a container: under 560 px the switch spans the card, the middle revenue ticks drop and each fix picker moves under its name.
- While on screen and untouched, a demo pointer hovers two bubbles, switches to Industry and back, changes a fix, unchecks one and applies the rest. Any real input hands it over; it comes back after 9 s of quiet.

## API reference

- **customers** (`Customer[]`, default `a book of 38`): The customers mapped: name, plan, industry, revenue (in thousands) and margin over the period, support hours, and months to renewal.
- **assistant** (`string`, default `'Tally'`): The assistant named as suggesting the fixes.
- **period** (`string`, default `'last 12 months'`): The period the figures cover, under the title.
- **show** (`'both' | 'scatter' | 'fixes'`, default `'both'`): Both cards, or only the map or the fixes.
- **defaultGroup** (`'plan' | 'industry'`, default `'plan'`): What colours the bubbles at first.
- **onApply** (`(fixes: AppliedFix[]) => void`): Called with each fix Apply makes: the customer, the fix and what it adds a year.
- **onDraftEmails** (`(customers: Customer[]) => void`): Called with the checked customers when Draft emails is pressed.
- **defaultState** (`ProfitabilityMapState`): Opens in a given moment, held still with no demo: the colouring, a hovered customer, changed or unchecked fixes, fixes applied, or a menu open.
- **autoplay** (`boolean`, default `true`): While on screen and untouched, a demo pointer shows the main interactions. Any real input stops it.
- **colorScheme** (`'light' | 'dark' | 'system'`): Light or dark colours, or the reader’s; without it, the page’s color-scheme.
- **className** (`string`): Classes for the stage.

## Accessibility

### The map in words

- The plot is a group whose label sums it up: how many customers, how many below 0% and the median revenue. Each bubble is a button labelled with the customer, its group, revenue, margin and support hours, so no figure lives only in the picture (WCAG 1.1.1, A).
- The tooltip is hidden from screen readers, since the focused bubble’s label already says more.

### Colour is never the only sign

Losing customers sit under the 0% line in a band labelled Costing you money, wear a dotted ring and show a minus sign in the list. Plan and industry colours are named in the legend and in every bubble’s label (WCAG 1.4.1, A).

### Contrast

In both schemes every line of text, the axis figures included, holds 4.5:1 on its surface (WCAG 1.4.3, AA), and the bubble rings, the checkboxes and the focus ring hold 3:1 (WCAG 1.4.11, AA).

### Keyboard

The bubbles take one tab stop. The arrows walk them by revenue, from the smallest account to the largest, Home and End jump to the ends and Escape hides the tooltip. Plan / Industry moves with the arrows; each fix picker and the ··· button open menus that move with the arrows, Home and End and close on Escape with focus back on their button.

### Changes announced

The footer’s total is a polite live region, a change of colouring and Undo are announced, and Apply and Draft emails report in a status toast (WCAG 4.1.3, AA). The toast that carries Undo doesn’t time out, so Undo has no time limit (WCAG 2.2.1, Timing adjustable); Undo takes presses over at least 24 × 24 px (WCAG 2.5.8).

### The demo

The demo pointer never plays under reduced motion. A hover or a wheel over the stage only pauses it; the reader’s first press, key or focus stops it for good, and it doesn’t start again on its own (WCAG 2.2.2, Pause, stop, hide).

### In this build

- The map is a group whose label says what it shows in words: how many customers, how many below 0% and the median revenue. Each bubble is a button labelled with the customer, its group, revenue, margin and support hours.
- One bubble is in the tab order; the arrow keys walk the rest from left to right, Home and End jump to the ends, Escape hides the tooltip. The tooltip is aria-hidden, since the focused bubble says the same.
- Plan / Industry is a radio group moved with the arrow keys. The checkboxes are role="checkbox" buttons; each fix picker and the ··· button open menus that move with the arrows, Home and End, and close on Escape with the focus back on their button.
- The footer’s total is a polite live region, a change of colouring is announced, and Apply reports in a status toast with Undo.
- Under reduced motion the bubbles jump instead of gliding, nothing fades in, and the demo never plays. The demo pointer is decorative.

## Source

### profitability-map/profitability-map.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import {
  useEffect,
  useEffectEvent,
  useId,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type CSSProperties,
  type KeyboardEvent as ReactKeyboardEvent,
} from 'react';
import {
  CUSTOMERS,
  INDUSTRIES,
  INDUSTRY_NAME,
  PLANS,
  PLAN_NAME,
  fixLabel,
  fixesFor,
  gainOf,
  median,
  money,
  percent,
  suggestFix,
  withFix,
  type Customer,
  type FixId,
  type Grouping,
} from './data';
import { DemoPointer, runDemo, type Point } from './demo-pointer';
import { Icon, Sparkle } from './glyphs';
import { Menu, MenuItem } from './menu';
import { useAutoplay } from './use-autoplay';
import styles from './profitability-map.module.css';

/*
 * Profitability map: two stacked cards over a soft backdrop.
 *
 * - The first maps every customer: margin up the side, revenue along the bottom, support hours as
 *   the bubble's size. A dashed line marks the median revenue; below 0% a red zone holds the
 *   customers that cost more than they pay, each ringed in red dots. Plan / Industry recolours
 *   the bubbles and the legend. Hover or focus shows a tooltip; the arrow keys walk the bubbles.
 * - The second lists those customers, each with the fix the assistant suggests (the one that adds
 *   most margin, or a review when renewal is close). The footer adds up what the checked fixes are
 *   worth; Apply moves their bubbles to their new margin, with Undo in a toast. A row and its
 *   bubble light together.
 * - While on screen and untouched, a demo pointer hovers bubbles, switches to Industry and back,
 *   changes a fix, unchecks one and applies the rest, in a loop. The reader's first press, key or
 *   focus stops it for good; a hover or a wheel over it only pauses it.
 */

export type { Customer, FixId, Grouping } from './data';

/** A moment to open in, held still: no demo. */
export type ProfitabilityMapState = {
  group?: Grouping;
  /** A customer lit, by id: its bubble, its tooltip and its row. */
  hover?: string;
  /** Fixes other than the suggested one, by customer id. */
  choice?: Record<string, FixId>;
  /** Rows left unchecked, by customer id. */
  unchecked?: string[];
  /** The checked fixes already applied. */
  applied?: boolean;
  /** A menu open: 'more', or a customer's id for its fix picker. */
  menu?: string;
};

/** A fix as Apply hands it out: who, which, and what it adds a year, in thousands. */
export type AppliedFix = { customer: Customer; fix: FixId; gain: number };

type MenuState = { id: string; anchor: HTMLElement; byReader: boolean };
type Toast = { n: number; text: string; undo?: Snapshot };
type Snapshot = {
  customers: Customer[];
  checked: Set<string>;
  reviewed: Set<string>;
};

const isLosing = (customer: Customer) => customer.margin < 0;

/** The checked rows and the chosen fixes the book opens with. */
function opening(customers: Customer[], start: ProfitabilityMapState) {
  const losing = customers.filter(isLosing);
  const choice: Record<string, FixId> = {};
  for (const customer of losing) {
    const wanted = start.choice?.[customer.id];
    choice[customer.id] =
      wanted && fixesFor(customer).includes(wanted) ? wanted : suggestFix(customer);
  }
  const checked = new Set(
    losing
      .filter((customer) => suggestFix(customer) !== 'review')
      .filter((customer) => !start.unchecked?.includes(customer.id))
      .map((customer) => customer.id),
  );
  const reviewed = new Set<string>();
  if (!start.applied) return { customers, choice, checked, reviewed, toast: null };
  let gain = 0;
  const after = customers.map((customer) => {
    if (!checked.has(customer.id)) return customer;
    gain += gainOf(customer, choice[customer.id]);
    if (choice[customer.id] === 'review') {
      reviewed.add(customer.id);
      return customer;
    }
    return withFix(customer, choice[customer.id]);
  });
  const toast: Toast = {
    n: 1,
    text: appliedText(checked.size, gain),
    undo: { customers, checked, reviewed: new Set() },
  };
  return { customers: after, choice, checked: new Set<string>(), reviewed, toast };
}

/** What the toast says after Apply. */
const appliedText = (count: number, gain: number) =>
  gain > 0.5
    ? `Applied ${count} ${plural(count, 'fix', 'fixes')}: +${money(gain)} margin a year`
    : `${count} ${plural(count, 'review', 'reviews')} booked for renewal`;

/** The axis: a round step that holds every value, from at least `floor` to `ceiling`. */
function axis(values: number[], step: number, floor: number, ceiling: number) {
  const low = Math.min(floor, Math.floor(Math.min(...values, floor) / step) * step);
  const high = Math.max(ceiling, Math.ceil(Math.max(...values, ceiling) / step) * step);
  const ticks: number[] = [];
  for (let at = low; at <= high + 1e-9; at += step) ticks.push(Math.round(at));
  return { low, high, ticks };
}

/** A bubble's diameter, in px, from its support hours. */
const diameter = (hours: number) => 6 + Math.sqrt(Math.max(hours, 0)) * 3.4;

const plural = (n: number, one: string, many: string) => (n === 1 ? one : many);

export function ProfitabilityMap({
  customers: initialCustomers = CUSTOMERS,
  assistant = 'Tally',
  period = 'last 12 months',
  show = 'both',
  defaultGroup = 'plan',
  onApply,
  onDraftEmails,
  autoplay = true,
  defaultState,
  colorScheme,
  className = '',
}: {
  /** The customers mapped: plan, industry, revenue and margin over the period, support hours. */
  customers?: Customer[];
  /** The assistant that suggests the fixes, named in the second card. */
  assistant?: string;
  /** The period the figures cover, under the title. */
  period?: string;
  /** Both cards, or one of them. */
  show?: 'both' | 'scatter' | 'fixes';
  /** What colours the bubbles at first. */
  defaultGroup?: Grouping;
  /** Called with the fixes Apply makes. */
  onApply?: (fixes: AppliedFix[]) => void;
  /** Called with the customers whose emails are drafted. */
  onDraftEmails?: (customers: Customer[]) => void;
  /** While on screen and untouched, a demo pointer shows the main interactions. */
  autoplay?: boolean;
  /** Opens in a given moment, held still (no demo). */
  defaultState?: ProfitabilityMapState;
  /** Light or dark colours, or the reader's ('system'); without it, the page's color-scheme. */
  colorScheme?: 'light' | 'dark' | 'system';
  className?: string;
}) {
  const uid = useId();
  const { ref: root, playing, take, hold } = useAutoplay<HTMLDivElement>(9000);
  const pointer = useRef<HTMLSpanElement>(null);
  const held = defaultState !== undefined;
  const start = defaultState ?? {};
  const first = useMemo(
    () => opening(initialCustomers, start),
    // The opening is read once.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [],
  );

  const [customers, setCustomers] = useState(first.customers);
  const [group, setGroup] = useState<Grouping>(start.group ?? defaultGroup);
  const [choice, setChoice] = useState(first.choice);
  const [checked, setChecked] = useState(first.checked);
  const [reviewed, setReviewed] = useState(first.reviewed);
  const [hot, setHot] = useState<{ id: string; from: 'chart' | 'row' } | null>(
    start.hover ? { id: start.hover, from: 'chart' } : null,
  );
  const [walk, setWalk] = useState<string | null>(null);
  const [menu, setMenu] = useState<MenuState | null>(null);
  const [toast, setToast] = useState<Toast | null>(first.toast);
  const [moved, setMoved] = useState<Set<string>>(new Set());
  const [news, setNews] = useState('');

  // ---- The map's scales --------------------------------------------------------------------------

  const x = useMemo(
    () =>
      axis(
        customers.map((c) => c.revenue),
        30,
        0,
        120,
      ),
    [customers],
  );
  const y = useMemo(
    () =>
      axis(
        customers.map((c) => c.margin),
        40,
        -40,
        80,
      ),
    [customers],
  );
  const mid = useMemo(() => median(customers.map((c) => c.revenue)), [customers]);
  const left = (revenue: number) => ((revenue - x.low) / (x.high - x.low)) * 100;
  const top = (margin: number) => ((y.high - margin) / (y.high - y.low)) * 100;

  const groups = group === 'plan' ? PLANS : INDUSTRIES;
  const toneOf = (c: Customer) => (group === 'plan' ? c.plan : c.industry);
  const groupName = (c: Customer) =>
    group === 'plan' ? PLAN_NAME[c.plan] : INDUSTRY_NAME[c.industry];
  const nameOf = (tone: string) =>
    group === 'plan'
      ? PLAN_NAME[tone as keyof typeof PLAN_NAME]
      : INDUSTRY_NAME[tone as keyof typeof INDUSTRY_NAME];

  /** Left to right, the order the arrow keys walk. */
  const walkOrder = useMemo(
    () => [...customers].sort((a, b) => a.revenue - b.revenue || b.margin - a.margin),
    [customers],
  );
  /** Bigger bubbles first, so the small ones stay on top. */
  const drawOrder = useMemo(() => [...customers].sort((a, b) => b.hours - a.hours), [customers]);
  const losingNow = customers.filter(isLosing);
  const hours = customers.map((c) => c.hours);
  const fewest = Math.min(...hours);
  const most = Math.max(...hours);

  // ---- The fixes ---------------------------------------------------------------------------------

  /** The rows: customers below 0%, in the book's order. */
  const rows = losingNow;
  const open = rows.filter((c) => !reviewed.has(c.id));
  const picked = open.filter((c) => checked.has(c.id));
  const gain = picked.reduce((sum, c) => sum + gainOf(c, choice[c.id] ?? suggestFix(c)), 0);
  const fixCount = picked.length;

  const say = (text: string, undo?: Snapshot) =>
    setToast((now) => ({ n: (now?.n ?? 0) + 1, text, undo }));

  // A toast that only reports goes after a while; one that carries Undo stays until it is used or
  // the next toast replaces it, so Undo has no time limit (WCAG 2.2.1).
  useEffect(() => {
    if (!toast || held || toast.undo) return;
    const timer = window.setTimeout(() => setToast(null), 5600);
    return () => window.clearTimeout(timer);
  }, [toast, held]);

  useEffect(() => {
    if (!moved.size) return;
    const timer = window.setTimeout(() => setMoved(new Set()), 1600);
    return () => window.clearTimeout(timer);
  }, [moved]);

  const toggle = (id: string) =>
    setChecked((now) => {
      const next = new Set(now);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });

  const apply = () => {
    if (!fixCount) return;
    const snapshot: Snapshot = { customers, checked, reviewed };
    const made: AppliedFix[] = picked.map((c) => {
      const fix = choice[c.id] ?? suggestFix(c);
      return { customer: c, fix, gain: gainOf(c, fix) };
    });
    const ids = new Set(made.map((m) => m.customer.id));
    setCustomers((now) =>
      now.map((c) => {
        const fix = made.find((m) => m.customer.id === c.id)?.fix;
        return fix && fix !== 'review' ? withFix(c, fix) : c;
      }),
    );
    setReviewed((now) => {
      const next = new Set(now);
      made.filter((m) => m.fix === 'review').forEach((m) => next.add(m.customer.id));
      return next;
    });
    setChecked((now) => new Set([...now].filter((id) => !ids.has(id))));
    setMoved(ids);
    setHot(null);
    const total = made.reduce((sum, m) => sum + m.gain, 0);
    say(appliedText(made.length, total), snapshot);
    onApply?.(made);
  };

  const undo = (snapshot: Snapshot) => {
    setCustomers(snapshot.customers);
    setChecked(snapshot.checked);
    setReviewed(snapshot.reviewed);
    setMoved(new Set(snapshot.customers.filter(isLosing).map((c) => c.id)));
    setToast(null);
    setNews('Fixes undone');
  };

  const draft = () => {
    if (!fixCount) return;
    // The component writes no email: it hands the customers to onDraftEmails, and says so.
    say(
      `Email drafts requested for ${fixCount} ${plural(fixCount, 'account owner', 'account owners')}`,
    );
    onDraftEmails?.(picked);
  };

  const switchGroup = (next: Grouping) => {
    if (next === group) return;
    setGroup(next);
    setNews(`Coloured by ${next}`);
  };

  // ---- Menus -------------------------------------------------------------------------------------

  const openMenu = (id: string, anchor: HTMLElement, byReader = true) =>
    setMenu((now) => (now?.id === id ? null : { id, anchor, byReader }));
  const closeMenu = (back: boolean) => {
    if (back) menu?.anchor.focus();
    setMenu(null);
  };

  // A menu held open by defaultState.
  useLayoutEffect(() => {
    if (!start.menu) return;
    const anchor = root.current?.querySelector<HTMLElement>(
      start.menu === 'more' ? '[data-demo="more"]' : `[data-demo="fix-${start.menu}"]`,
    );
    if (anchor) setMenu({ id: start.menu, anchor, byReader: false });
    // Only on mount.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // ---- The demo ----------------------------------------------------------------------------------

  const demo = autoplay && !held && playing;
  const reset = useEffectEvent(() => {
    const fresh = opening(initialCustomers, {});
    setCustomers(fresh.customers);
    setChoice(fresh.choice);
    setChecked(fresh.checked);
    setReviewed(fresh.reviewed);
    setGroup(defaultGroup);
    setMenu(null);
    setToast(null);
    setHot(null);
  });
  const dirty = useEffectEvent(() => {
    const fresh = opening(initialCustomers, {});
    const same = (a: Set<string>, b: Set<string>) =>
      a.size === b.size && [...a].every((id) => b.has(id));
    return (
      customers !== fresh.customers ||
      group !== defaultGroup ||
      reviewed.size > 0 ||
      !same(checked, fresh.checked) ||
      Object.keys(fresh.choice).some((id) => fresh.choice[id] !== choice[id])
    );
  });
  const demoHover = useEffectEvent((id: string | null, from: 'chart' | 'row' = 'chart') =>
    setHot(id ? { id, from } : null),
  );
  const demoClear = useEffectEvent(() => {
    setMenu(null);
    setHot(null);
  });

  useEffect(() => {
    const stage = root.current;
    const arrow = pointer.current;
    if (!demo || !stage || !arrow) return;
    const find = (name: string) => stage.querySelector<HTMLElement>(`[data-demo="${name}"]`);
    const on = (element: Element | null, fx = 0.5, fy = 0.5): Point => {
      const frame = stage.getBoundingClientRect();
      const scale = frame.width / stage.offsetWidth || 1;
      const rect = element?.getBoundingClientRect() ?? frame;
      return {
        x: (rect.left + rect.width * fx - frame.left) / scale,
        y: (rect.top + rect.height * fy - frame.top) / scale,
      };
    };
    let over: HTMLElement | null = null;
    const stop = runDemo(stage, arrow, async ({ wait, glide, glyph }) => {
      const press = async (name: string, ms: number, after: number, fx = 0.5, fy = 0.5) => {
        const element = find(name);
        if (!element) return;
        glyph('arrow');
        await glide(on(element, fx, fy), ms);
        glyph('hand');
        over = element;
        element.dataset.over = '';
        await wait(240);
        const live = find(name) ?? element;
        delete element.dataset.over;
        over = null;
        live.click();
        await wait(after);
      };
      const hover = async (name: string, id: string, ms: number, after: number, fx = 0.5) => {
        const element = find(name);
        if (!element) return;
        glyph('arrow');
        await glide(on(element, fx, 0.5), ms);
        demoHover(id, name.startsWith('row') ? 'row' : 'chart');
        await wait(after);
      };
      for (;;) {
        if (dirty()) {
          reset();
          await wait(1400);
        }
        await wait(900);
        // The one that costs most in hours, then one worth growing.
        await hover('bubble-brightwater', 'brightwater', 900, 1700);
        await hover('bubble-lumen-pediatrics', 'lumen-pediatrics', 750, 1400);
        demoHover(null);
        // The same map by industry, and back.
        await press('group-industry', 750, 1900);
        await press('group-plan', 450, 900);
        // A different fix for one, and one left for later.
        await press('fix-larkspur', 800, 650, 0.8);
        await press('fix-larkspur-cap', 450, 1100, 0.3);
        await press('check-fig-fern', 650, 1100);
        await hover('row-brightwater', 'brightwater', 600, 1300, 0.3);
        demoHover(null);
        // The rest, applied: their bubbles climb.
        await press('apply', 750, 3200);
        glyph('arrow');
        await glide(on(stage, 0.86, 0.94), 800);
        await wait(1600);
      }
    });
    return () => {
      stop();
      if (over) delete over.dataset.over;
      demoClear();
    };
  }, [demo, root]);

  // ---- Keyboard over the map ---------------------------------------------------------------------

  const plotRef = useRef<HTMLDivElement>(null);
  const tipRef = useRef<HTMLSpanElement>(null);
  /** The plot's size and the tooltip's, in the stage's own px: where the tooltip has room. */
  const [box, setBox] = useState({ w: 520, h: 224, tw: 190, th: 48 });
  useLayoutEffect(() => {
    const plot = plotRef.current;
    if (!plot) return;
    const read = () =>
      setBox((now) => {
        const tip = tipRef.current;
        const next = {
          w: plot.offsetWidth,
          h: plot.offsetHeight,
          tw: tip?.offsetWidth ?? now.tw,
          th: tip?.offsetHeight ?? now.th,
        };
        return Object.entries(next).every(([k, v]) => now[k as keyof typeof now] === v)
          ? now
          : next;
      });
    read();
    const observer = new ResizeObserver(read);
    observer.observe(plot);
    if (tipRef.current) observer.observe(tipRef.current);
    return () => observer.disconnect();
  }, [hot?.id, group]);
  const current = walk ?? walkOrder[0]?.id ?? null;
  const onPlotKey = (event: ReactKeyboardEvent) => {
    const index = walkOrder.findIndex((c) => c.id === current);
    let to = -1;
    if (event.key === 'ArrowRight' || event.key === 'ArrowDown') to = index + 1;
    else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') to = index - 1;
    else if (event.key === 'Home') to = 0;
    else if (event.key === 'End') to = walkOrder.length - 1;
    else if (event.key === 'Escape') {
      setHot(null);
      return;
    } else return;
    event.preventDefault();
    const next = walkOrder[(to + walkOrder.length) % walkOrder.length];
    setWalk(next.id);
    setHot({ id: next.id, from: 'chart' });
    plotRef.current?.querySelector<HTMLElement>(`[data-demo="bubble-${next.id}"]`)?.focus();
  };

  // ---- Drawing -----------------------------------------------------------------------------------

  const tipCustomer = hot ? customers.find((c) => c.id === hot.id) : undefined;
  /**
   * Beside the bubble, on the side with room; over it (or under it, near the top) when neither
   * side has room, as on a phone.
   */
  const tipAt = (c: Customer): CSSProperties => {
    const cx = (left(c.revenue) / 100) * box.w;
    const cy = (top(c.margin) / 100) * box.h;
    const r = diameter(c.hours) / 2 + 9;
    const clampY = (v: number) => Math.max(-8, Math.min(v, box.h - box.th + 8));
    if (cx + r + box.tw <= box.w + 8) return { left: cx + r, top: clampY(cy - box.th / 2) };
    if (cx - r - box.tw >= -8) return { left: cx - r - box.tw, top: clampY(cy - box.th / 2) };
    const tx = Math.max(-4, Math.min(cx - box.tw / 2, box.w - box.tw + 4));
    const above = cy - r - box.th;
    return { left: tx, top: above >= -8 ? above : cy + r };
  };
  const tickLabel = (value: number) => {
    const near = (Math.abs(left(value) - left(mid)) / 100) * box.w < 64;
    return near ? null : value === 0 ? '$0' : `$${value}k`;
  };
  const sizes = [fewest, most].map((h) => diameter(h));

  const scatter = (
    <section className={styles.card} data-part="scatter-card" aria-labelledby={`${uid}-map-title`}>
      <header className={styles.head} data-part="header">
        <span className={styles.tile} data-tone="map">
          <Icon name="scatter" />
        </span>
        <div className={styles.titles}>
          <h3 id={`${uid}-map-title`} className={styles.title}>
            Customer profitability
          </h3>
          <p className={styles.sub}>
            {customers.length} {plural(customers.length, 'customer', 'customers')} · {period}
          </p>
        </div>
        <div
          className={styles.segmented}
          role="radiogroup"
          aria-label="Colour by"
          data-part="group-toggle"
          onKeyDown={(event) => {
            if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(event.key)) return;
            event.preventDefault();
            const next = group === 'plan' ? 'industry' : 'plan';
            switchGroup(next);
            event.currentTarget.querySelector<HTMLElement>(`[data-demo="group-${next}"]`)?.focus();
          }}
        >
          {(['plan', 'industry'] as Grouping[]).map((g) => (
            <button
              key={g}
              type="button"
              role="radio"
              aria-checked={group === g}
              tabIndex={group === g ? 0 : -1}
              className={styles.segment}
              data-demo={`group-${g}`}
              onClick={() => switchGroup(g)}
            >
              {g === 'plan' ? 'Plan' : 'Industry'}
            </button>
          ))}
        </div>
      </header>

      <div className={styles.chartBox} data-part="chart">
        <div className={styles.chartGrid}>
          <div className={styles.yAxis} aria-hidden="true">
            {y.ticks.map((t) => (
              <span
                key={t}
                className={styles.yTick}
                data-zero={t === 0 || undefined}
                style={{ top: `${top(t)}%` }}
              >
                {percent(t)}
              </span>
            ))}
          </div>

          <div
            ref={plotRef}
            className={styles.plot}
            role="group"
            aria-label={`Margin against revenue for ${customers.length} customers, bubble size by support hours. ${losingNow.length} below 0% margin; median revenue ${money(mid)}.`}
            data-part="plot"
            data-hot={hot ? '' : undefined}
            onKeyDown={onPlotKey}
            onBlur={(event) => {
              if (!event.currentTarget.contains(event.relatedTarget as Node)) setHot(null);
            }}
          >
            {y.ticks.map((t) =>
              t === 0 ? null : (
                <span key={t} className={styles.gridLine} style={{ top: `${top(t)}%` }} />
              ),
            )}
            <span className={styles.lossZone} data-part="loss-zone" style={{ top: `${top(0)}%` }}>
              <span className={styles.lossLabel}>Costing you money</span>
            </span>
            <span className={styles.zeroLine} style={{ top: `${top(0)}%` }} />
            <span
              className={styles.medianLine}
              data-part="median"
              style={{ left: `${left(mid)}%` }}
            />
            <span className={styles.quadrant} data-side="start">
              Keep lean
            </span>
            <span className={styles.quadrant} data-side="end">
              Grow these
            </span>

            {drawOrder.map((c) => {
              const d = diameter(c.hours);
              const lit = hot?.id === c.id;
              return (
                <button
                  key={c.id}
                  type="button"
                  className={styles.bubble}
                  data-part="bubble"
                  data-demo={`bubble-${c.id}`}
                  data-tone={toneOf(c)}
                  data-losing={isLosing(c) || undefined}
                  data-hot={lit || undefined}
                  data-moved={moved.has(c.id) || undefined}
                  tabIndex={c.id === current ? 0 : -1}
                  aria-label={`${c.name}, ${groupName(c)}: ${money(c.revenue)} revenue, ${percent(c.margin)} margin, ${c.hours} support hours`}
                  style={
                    {
                      left: `${left(c.revenue)}%`,
                      top: `${top(c.margin)}%`,
                      width: d,
                      height: d,
                    } as CSSProperties
                  }
                  onPointerEnter={() => setHot({ id: c.id, from: 'chart' })}
                  onPointerLeave={() =>
                    setHot((now) => (now?.id === c.id && now.from === 'chart' ? null : now))
                  }
                  onFocus={() => {
                    setWalk(c.id);
                    setHot({ id: c.id, from: 'chart' });
                  }}
                />
              );
            })}

            {tipCustomer && (
              <span
                ref={tipRef}
                className={styles.tip}
                data-part="tooltip"
                style={tipAt(tipCustomer)}
                aria-hidden="true"
              >
                <span className={styles.tipName}>
                  {tipCustomer.name} · {groupName(tipCustomer)}
                </span>
                <span className={styles.tipFacts}>
                  {percent(tipCustomer.margin)} margin · {tipCustomer.hours} support h
                </span>
              </span>
            )}
          </div>

          <div className={styles.xAxis} aria-hidden="true">
            {x.ticks.map((t, i) => {
              const label = tickLabel(t);
              return label ? (
                <span
                  key={t}
                  className={styles.xTick}
                  data-edge={i === 0 ? 'start' : i === x.ticks.length - 1 ? 'end' : undefined}
                  style={{ left: `${left(t)}%` }}
                >
                  {label}
                </span>
              ) : null;
            })}
            <span className={styles.xTick} data-median style={{ left: `${left(mid)}%` }}>
              {money(mid)} median
            </span>
          </div>
        </div>

        <div className={styles.legend} data-part="legend">
          <ul className={styles.keys} aria-label={`Colours: by ${group}`}>
            {groups.map((g) => (
              <li key={g} className={styles.key} data-tone={g}>
                <span className={styles.keyDot} />
                {nameOf(g)}
              </li>
            ))}
          </ul>
          <span className={styles.sizeKey}>
            <span className={styles.sizeDots} aria-hidden="true">
              <span style={{ width: sizes[0] * 0.55, height: sizes[0] * 0.55 }} />
              <span style={{ width: sizes[1] * 0.55, height: sizes[1] * 0.55 }} />
            </span>
            Support hours
            <span className={styles.srOnly}>
              , from {fewest} to {most} as the bubble grows
            </span>
          </span>
        </div>
      </div>
    </section>
  );

  const reviewedRows = rows.filter((c) => reviewed.has(c.id));
  const listTitle =
    rows.length === 0
      ? 'Every customer pays its way'
      : `${rows.length} ${plural(rows.length, 'customer costs more than it pays', 'customers cost more than they pay')}`;
  const listSub =
    rows.length === 0
      ? `No margin below 0% over the ${period}`
      : open.length === 0
        ? `${reviewedRows.length === 1 ? 'Its' : 'Their'} review is booked for renewal`
        : `${assistant} suggests one fix for each`;

  const fixes = (
    <section className={styles.card} data-part="fixes-card" aria-labelledby={`${uid}-fix-title`}>
      <header className={styles.head}>
        <span className={styles.tile} data-tone={rows.length ? 'leak' : 'done'}>
          <Icon name={rows.length ? 'leak' : 'done'} />
        </span>
        <div className={styles.titles}>
          <h3 id={`${uid}-fix-title`} className={styles.title}>
            {listTitle}
          </h3>
          <p className={styles.sub}>{listSub}</p>
        </div>
        {rows.length > 0 && (
          <button
            type="button"
            className={styles.more}
            aria-label="More actions"
            aria-haspopup="menu"
            aria-expanded={menu?.id === 'more'}
            data-demo="more"
            onClick={(event) => openMenu('more', event.currentTarget, event.detail === 0)}
          >
            <Icon name="more" />
          </button>
        )}
      </header>

      {rows.length > 0 ? (
        <ul className={styles.rows} aria-label="Customers below 0% margin">
          {rows.map((c) => {
            const fix = choice[c.id] ?? suggestFix(c);
            const suggested = suggestFix(c);
            const isReviewed = reviewed.has(c.id);
            const on = checked.has(c.id) && !isReviewed;
            return (
              <li
                key={c.id}
                className={styles.row}
                data-part="fix-row"
                data-demo={`row-${c.id}`}
                data-hot={hot?.id === c.id || undefined}
                data-off={!on || undefined}
                onPointerEnter={() => setHot({ id: c.id, from: 'row' })}
                onPointerLeave={() =>
                  setHot((now) => (now?.id === c.id && now.from === 'row' ? null : now))
                }
                onFocus={() => setHot({ id: c.id, from: 'row' })}
                onBlur={(event) => {
                  if (!event.currentTarget.contains(event.relatedTarget as Node))
                    setHot((now) => (now?.id === c.id ? null : now));
                }}
              >
                {isReviewed ? (
                  <span className={styles.checkSpacer} aria-hidden="true" />
                ) : (
                  <button
                    type="button"
                    role="checkbox"
                    aria-checked={on}
                    aria-label={`Apply a fix to ${c.name}`}
                    className={styles.check}
                    data-demo={`check-${c.id}`}
                    onClick={() => toggle(c.id)}
                  >
                    {on && <Icon name="check" width={2.6} />}
                  </button>
                )}
                <span className={styles.who}>
                  <span className={styles.name}>{c.name}</span>
                  <span className={styles.meta}>
                    {money(c.revenue)} · {c.hours} support h
                  </span>
                </span>
                <span className={styles.loss}>{percent(c.margin)}</span>
                {isReviewed ? (
                  <span className={styles.booked}>Review booked for renewal</span>
                ) : (
                  <button
                    type="button"
                    className={styles.select}
                    aria-haspopup="menu"
                    aria-expanded={menu?.id === c.id}
                    aria-label={`Fix for ${c.name}: ${fixLabel(fix, c)}${fix === suggested && fix !== 'review' ? ', suggested' : ''}`}
                    data-part="fix-select"
                    data-demo={`fix-${c.id}`}
                    data-plain={fix === 'review' || undefined}
                    onClick={(event) => openMenu(c.id, event.currentTarget, event.detail === 0)}
                  >
                    {fix === suggested && fix !== 'review' && (
                      <Sparkle className={styles.sparkle} />
                    )}
                    <span className={styles.selectText}>{fixLabel(fix, c)}</span>
                    <Icon name="chevronDown" className={styles.chevron} />
                  </button>
                )}
              </li>
            );
          })}
        </ul>
      ) : (
        <div className={styles.empty}>
          Margins run from {percent(Math.min(...customers.map((c) => c.margin)))} to{' '}
          {percent(Math.max(...customers.map((c) => c.margin)))}. {assistant} will flag a customer
          here when one slips below 0%.
        </div>
      )}

      {open.length > 0 && (
        <footer className={styles.foot} data-part="footer">
          <p className={styles.sum} aria-live="polite">
            {fixCount === 0 ? (
              'Pick the fixes to apply'
            ) : gain > 0.5 ? (
              <>
                {fixCount} {plural(fixCount, 'fix adds', 'fixes add')}{' '}
                <strong className={styles.gain}>{money(gain)} margin</strong> a year
              </>
            ) : (
              `${fixCount} ${plural(fixCount, 'review', 'reviews')} for renewal`
            )}
          </p>
          <div className={styles.actions}>
            <button
              type="button"
              className={styles.button}
              disabled={!fixCount}
              data-demo="draft"
              onClick={draft}
            >
              Draft emails
            </button>
            <button
              type="button"
              className={styles.button}
              data-primary
              disabled={!fixCount}
              data-demo="apply"
              onClick={apply}
            >
              Apply {fixCount || ''} {plural(fixCount, 'fix', 'fixes')}
            </button>
          </div>
        </footer>
      )}
    </section>
  );

  const menuCustomer = menu && menu.id !== 'more' ? rows.find((c) => c.id === menu.id) : null;

  return (
    <div
      ref={root}
      className={`${styles.root} ${className}`}
      data-part="stage"
      data-color-scheme={colorScheme}
      onPointerDownCapture={take}
      onKeyDownCapture={take}
      onFocusCapture={take}
      onWheel={hold}
      onPointerMove={(event) => {
        if (event.pointerType !== 'touch') hold();
      }}
    >
      <div className={styles.stack}>
        {show !== 'fixes' && scatter}
        {show !== 'scatter' && fixes}
      </div>

      {menu && menu.id === 'more' && (
        <Menu
          anchor={menu.anchor}
          label="More actions"
          align="end"
          takeFocus={menu.byReader}
          onClose={closeMenu}
        >
          <MenuItem
            lead={<Icon name="select" />}
            onSelect={() => {
              setChecked(new Set(open.map((c) => c.id)));
              closeMenu(true);
            }}
          >
            Check every fix
          </MenuItem>
          <MenuItem
            lead={<Icon name="clear" />}
            onSelect={() => {
              setChecked(new Set());
              closeMenu(true);
            }}
          >
            Uncheck all
          </MenuItem>
          <MenuItem
            lead={<Icon name="reset" />}
            onSelect={() => {
              setChoice(Object.fromEntries(rows.map((c) => [c.id, suggestFix(c)])));
              setNews(`Back to ${assistant}’s suggestions`);
              closeMenu(true);
            }}
          >
            Use the suggested fixes
          </MenuItem>
        </Menu>
      )}

      {menuCustomer && menu && (
        <Menu
          anchor={menu.anchor}
          label={`Fix for ${menuCustomer.name}`}
          match
          takeFocus={menu.byReader}
          onClose={closeMenu}
        >
          {fixesFor(menuCustomer).map((fix) => {
            const add = gainOf(menuCustomer, fix);
            return (
              <MenuItem
                key={fix}
                radio
                checked={choice[menuCustomer.id] === fix}
                demo={`fix-${menuCustomer.id}-${fix}`}
                lead={
                  fix === suggestFix(menuCustomer) && fix !== 'review' ? (
                    <Sparkle className={styles.sparkle} />
                  ) : undefined
                }
                trail={add > 0.5 ? `+${money(add)}` : '—'}
                onSelect={() => {
                  setChoice((now) => ({ ...now, [menuCustomer.id]: fix }));
                  setChecked((now) => new Set(now).add(menuCustomer.id));
                  closeMenu(true);
                }}
              >
                {fixLabel(fix, menuCustomer)}
              </MenuItem>
            );
          })}
        </Menu>
      )}

      {toast && (
        <div key={toast.n} className={styles.toast} role="status" data-part="toast">
          <span>{toast.text}</span>
          {toast.undo && (
            <button type="button" className={styles.toastUndo} onClick={() => undo(toast.undo!)}>
              Undo
            </button>
          )}
        </div>
      )}

      <p className={styles.srOnly} aria-live="polite">
        {news}
      </p>

      <div className={styles.pointerLayer}>
        <DemoPointer
          ref={pointer}
          className={styles.pointer}
          arrowClass={styles.arrow}
          handClass={styles.hand}
        />
      </div>
    </div>
  );
}
```

### profitability-map/profitability-map.module.css

```css
/* Profitability map (profitability-map.tsx): two stacked cards over a soft green backdrop,
   near-black by night and white on mint by day. The first card maps the customers as bubbles;
   the second lists the ones below 0% with a fix each and a footer that adds them up.

   The backdrop is gradients only: a few blurred greens over a deep base, and a fine grain of
   repeating gradients. Colours are the tokens below, light-dark(light, dark): the component takes
   the color-scheme it inherits from the page, or the one its colorScheme prop sets
   (data-color-scheme). Under 520 px of stage the fix rows fold the picker under the name. */

.root {
  --base: light-dark(#e3efe6, #050806);
  --glow-1: light-dark(#bfe6cb, #0f5a2c);
  --glow-2: light-dark(#d6f0dc, #157a3a);
  --glow-3: light-dark(#a9d9b8, #0a3a1d);
  --card: light-dark(#ffffff, #141414);
  --card-edge: light-dark(rgb(16 40 24 / 0.08), rgb(255 255 255 / 0.07));
  --well: light-dark(#f6f8f6, #191919);
  --well-edge: light-dark(#e8ece9, #232323);
  --line: light-dark(#e6eae7, #262626);
  --grid: light-dark(#eceeed, #232323);
  --ink: light-dark(#141815, #f0f0f0);
  --ink-2: light-dark(#5d655f, #a2a2a2);
  --ink-3: light-dark(#6c736d, #818181);
  --chip: light-dark(#eef1ef, #222222);
  --chip-on: light-dark(#ffffff, #333333);
  --chip-edge: light-dark(#e1e5e2, #2c2c2c);
  --hover: light-dark(#f1f4f2, #202020);
  --menu: light-dark(#ffffff, #1d1d1d);
  --tip: light-dark(#ffffff, #1c1c1c);
  --tip-edge: light-dark(#dfe4e0, #333333);
  --red: light-dark(#c82f27, #f06c62);
  --red-zone: light-dark(rgb(217 68 60 / 0.07), rgb(240 108 98 / 0.07));
  --green: light-dark(#117f40, #3ee08a);
  --tile-map: light-dark(#e3f1f4, #15292d);
  --tile-map-ink: light-dark(#167c90, #5fd3e6);
  --tile-leak: light-dark(#e2f4e8, #16301f);
  --tile-leak-ink: light-dark(#14924a, #3ee08a);
  --primary: light-dark(#141815, #f4f4f4);
  --primary-ink: light-dark(#ffffff, #111111);
  --shadow: light-dark(rgb(20 50 30 / 0.12), rgb(0 0 0 / 0.55));
  /* The groups: by plan, by industry. */
  --starter: light-dark(#1a95ac, #4cc6dc);
  --growth: light-dark(#7a5fe0, #a08cf4);
  --scale: light-dark(#b37f11, #e5b54a);
  --enterprise: light-dark(#4462e0, #7088f4);
  --retail: light-dark(#d4557f, #ee8aae);
  --health: light-dark(#169a72, #4fd4a6);
  --hospitality: light-dark(#cd6f1e, #f2a058);
  --services: light-dark(#3a72d8, #7fa6ff);
  /* The same on both schemes. */
  --focus: light-dark(#0c8dff, #5fb4ff);
  --pointer: #1c1c1e;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.3);
  --sans: var(--body, Inter, ui-sans-serif, system-ui, sans-serif);
}
.root[data-color-scheme='light'] {
  color-scheme: light;
}
.root[data-color-scheme='dark'] {
  color-scheme: dark;
}
.root[data-color-scheme='system'] {
  color-scheme: light dark;
}

.root {
  position: relative;
  container-type: inline-size;
  width: 100%;
  padding: 72px 28px;
  overflow: hidden;
  overflow: clip;
  border-radius: 18px;
  background:
    radial-gradient(60% 40% at 22% 10%, var(--glow-2), transparent 72%),
    radial-gradient(45% 55% at 92% 30%, var(--glow-1), transparent 72%),
    radial-gradient(50% 40% at 4% 55%, var(--glow-1), transparent 70%),
    radial-gradient(60% 40% at 78% 70%, var(--glow-3), transparent 72%),
    radial-gradient(70% 40% at 30% 96%, var(--glow-2), transparent 70%), var(--base);
  color: var(--ink);
  font-family: var(--sans);
  font-size: 13px;
  line-height: 1.35;
  -webkit-tap-highlight-color: transparent;
}
/* A fine grain over the glow, so the backdrop reads as a surface and not a flat gradient. */
.root::before {
  content: '';
  position: absolute;
  inset: 0;
  pointer-events: none;
  background:
    repeating-radial-gradient(
      circle at 30% 40%,
      rgb(255 255 255 / 0.025) 0 1px,
      transparent 1px 3px
    ),
    repeating-radial-gradient(circle at 70% 60%, rgb(0 0 0 / 0.05) 0 1px, transparent 1px 4px);
  mix-blend-mode: overlay;
}
:where(.root) :where(button) {
  font: inherit;
  color: inherit;
}
:where(.root) button {
  cursor: pointer;
}
.root :focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}
.root svg {
  flex: none;
  display: block;
}
.srOnly {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

.stack {
  position: relative;
  display: grid;
  gap: 14px;
  max-width: 640px;
  margin: 0 auto;
}

/* ---- Cards ------------------------------------------------------------------------------------ */

.card {
  padding: 18px 8px 8px;
  border: 1px solid var(--card-edge);
  border-radius: 24px;
  background: var(--card);
  box-shadow:
    0 1px 0 rgb(255 255 255 / 0.04) inset,
    0 28px 60px -24px var(--shadow);
}
.head {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 0 10px 16px 8px;
}
.tile {
  display: grid;
  place-items: center;
  flex: none;
  width: 32px;
  height: 32px;
  border-radius: 9px;
  background: var(--tile-map);
  color: var(--tile-map-ink);
}
.tile[data-tone='leak'],
.tile[data-tone='done'] {
  background: var(--tile-leak);
  color: var(--tile-leak-ink);
}
.tile svg {
  width: 17px;
  height: 17px;
}
.titles {
  flex: 1;
  min-width: 0;
}
.title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: -0.01em;
  line-height: 1.25;
}
.sub {
  margin: 2px 0 0;
  color: var(--ink-2);
  font-size: 12.5px;
}

.segmented {
  display: flex;
  flex: none;
  padding: 3px;
  border-radius: 12px;
  background: var(--chip);
}
.segment {
  min-width: 46px;
  height: 28px;
  padding: 0 11px;
  border: 0;
  border-radius: 9px;
  background: none;
  color: var(--ink-2) !important;
  font-size: 12.5px;
  font-weight: 500;
  transition:
    background 0.2s ease,
    color 0.2s ease;
}
.segment:hover,
.segment[data-over] {
  color: var(--ink) !important;
}
.segment[aria-checked='true'] {
  background: var(--chip-on);
  color: var(--ink) !important;
  box-shadow: 0 1px 3px rgb(0 0 0 / 0.12);
}
.more {
  display: grid;
  place-items: center;
  flex: none;
  width: 30px;
  height: 30px;
  border: 0;
  border-radius: 9px;
  background: none;
  color: var(--ink-2) !important;
}
.more:hover,
.more[aria-expanded='true'] {
  background: var(--hover);
  color: var(--ink) !important;
}
.more svg {
  width: 18px;
  height: 18px;
}

/* ---- The map ---------------------------------------------------------------------------------- */

.chartBox {
  padding: 18px 16px 14px 10px;
  border: 1px solid var(--well-edge);
  border-radius: 17px;
  background: var(--well);
}
.chartGrid {
  display: grid;
  grid-template-columns: 38px minmax(0, 1fr);
  grid-template-rows: 224px 26px;
}
.yAxis {
  position: relative;
}
.yTick {
  position: absolute;
  left: 0;
  color: var(--ink-3);
  font-size: 11.5px;
  font-variant-numeric: tabular-nums;
  translate: 0 -50%;
}
.yTick[data-zero] {
  color: var(--red);
}
.plot {
  position: relative;
  outline: none;
}
.gridLine {
  position: absolute;
  right: 0;
  left: 0;
  border-top: 1px solid var(--grid);
}
.zeroLine {
  position: absolute;
  right: 0;
  left: 0;
  border-top: 1.2px dashed var(--red);
  opacity: 0.75;
}
.lossZone {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  background: linear-gradient(
    to right,
    var(--red-zone),
    color-mix(in oklab, var(--red-zone), transparent 40%)
  );
}
.lossLabel {
  position: absolute;
  right: 8px;
  bottom: 7px;
  color: var(--ink-2);
  font-size: 12px;
}
.medianLine {
  position: absolute;
  top: 0;
  bottom: 0;
  border-left: 1px dashed var(--ink-3);
  opacity: 0.6;
  transition: left 0.9s cubic-bezier(0.3, 0.7, 0.2, 1);
}
.quadrant {
  position: absolute;
  top: 4px;
  color: var(--ink-2);
  font-size: 12px;
  pointer-events: none;
}
.quadrant[data-side='start'] {
  left: 10px;
}
.quadrant[data-side='end'] {
  right: 8px;
}

.bubble {
  --c: var(--starter);
  position: absolute;
  padding: 0;
  border: 1.5px solid var(--c);
  border-radius: 50%;
  background: light-dark(
    color-mix(in oklab, var(--c) 48%, transparent),
    color-mix(in oklab, var(--c) 38%, transparent)
  );
  translate: -50% -50%;
  transition:
    left 0.9s cubic-bezier(0.3, 0.7, 0.2, 1),
    top 0.9s cubic-bezier(0.3, 0.7, 0.2, 1),
    width 0.9s ease,
    height 0.9s ease,
    border-color 0.4s ease,
    background 0.4s ease,
    opacity 0.2s ease,
    scale 0.2s ease;
}
.bubble[data-tone='growth'] {
  --c: var(--growth);
}
.bubble[data-tone='scale'] {
  --c: var(--scale);
}
.bubble[data-tone='enterprise'] {
  --c: var(--enterprise);
}
.bubble[data-tone='retail'] {
  --c: var(--retail);
}
.bubble[data-tone='health'] {
  --c: var(--health);
}
.bubble[data-tone='hospitality'] {
  --c: var(--hospitality);
}
.bubble[data-tone='services'] {
  --c: var(--services);
}
/* Below 0%: a dotted red ring around the bubble. */
.bubble[data-losing]::after {
  content: '';
  position: absolute;
  inset: -6px;
  border: 1.5px dotted var(--red);
  border-radius: 50%;
}
.bubble:focus-visible {
  outline-offset: 3px;
}
.plot[data-hot] .bubble:not([data-hot]) {
  opacity: 0.4;
}
.bubble[data-hot] {
  z-index: 2;
  scale: 1.12;
  background: color-mix(in oklab, var(--c) 62%, transparent);
}
.bubble[data-moved] {
  z-index: 2;
  animation: landed 1.6s ease;
}
@keyframes landed {
  0%,
  55% {
    box-shadow: 0 0 0 0 color-mix(in oklab, var(--c) 60%, transparent);
  }
  100% {
    box-shadow: 0 0 0 12px transparent;
  }
}

.tip {
  position: absolute;
  z-index: 3;
  display: grid;
  gap: 2px;
  padding: 7px 11px;
  border: 1px solid var(--tip-edge);
  border-radius: 10px;
  background: var(--tip);
  box-shadow: 0 10px 26px -8px var(--shadow);
  white-space: nowrap;
  pointer-events: none;
  animation: pop 0.14s ease;
}
.tipName {
  color: var(--ink-2);
  font-size: 12px;
}
.tipFacts {
  font-size: 12.5px;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
}

.xAxis {
  position: relative;
  grid-column: 2;
}
.xTick {
  position: absolute;
  bottom: 0;
  color: var(--ink-3);
  font-size: 11.5px;
  white-space: nowrap;
  translate: -50% 0;
}
.xTick[data-edge='start'] {
  translate: 0 0;
}
.xTick[data-edge='end'] {
  translate: -100% 0;
}
.xTick[data-median] {
  transition: left 0.9s cubic-bezier(0.3, 0.7, 0.2, 1);
}

.legend {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 8px 16px;
  margin-top: 14px;
  padding-left: 6px;
}
.keys {
  display: flex;
  flex-wrap: wrap;
  gap: 6px 16px;
  margin: 0;
  padding: 0;
  list-style: none;
}
.key {
  --c: var(--starter);
  display: flex;
  align-items: center;
  gap: 6px;
  color: var(--ink-2);
  font-size: 12.5px;
}
.key[data-tone='growth'] {
  --c: var(--growth);
}
.key[data-tone='scale'] {
  --c: var(--scale);
}
.key[data-tone='enterprise'] {
  --c: var(--enterprise);
}
.key[data-tone='retail'] {
  --c: var(--retail);
}
.key[data-tone='health'] {
  --c: var(--health);
}
.key[data-tone='hospitality'] {
  --c: var(--hospitality);
}
.key[data-tone='services'] {
  --c: var(--services);
}
.keyDot {
  width: 9px;
  height: 9px;
  border: 1.5px solid var(--c);
  border-radius: 50%;
  background: color-mix(in oklab, var(--c) 40%, transparent);
}
.sizeKey {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--ink-2);
  font-size: 12.5px;
}
.sizeDots {
  display: flex;
  align-items: center;
  gap: 3px;
}
.sizeDots > span {
  border: 1.3px solid var(--ink-2);
  border-radius: 50%;
}

/* ---- The fixes -------------------------------------------------------------------------------- */

.rows {
  margin: 0;
  padding: 4px 14px;
  border: 1px solid var(--well-edge);
  border-radius: 17px;
  background: var(--well);
  list-style: none;
}
.row {
  display: grid;
  grid-template-columns: 22px minmax(0, 1fr) auto minmax(0, 206px);
  align-items: center;
  gap: 14px;
  padding: 11px 0;
  border-bottom: 1px solid var(--line);
  transition: background 0.2s ease;
}
.row:last-child {
  border-bottom: 0;
}
.row[data-hot] .name {
  text-decoration: underline;
  text-decoration-color: var(--ink-3);
  text-underline-offset: 3px;
}
.check {
  position: relative;
  display: grid;
  place-items: center;
  width: 20px;
  height: 20px;
  padding: 0;
  border: 1.5px solid var(--ink-3);
  border-radius: 6px;
  background: none;
  transition:
    background 0.15s ease,
    border-color 0.15s ease;
}
/* A 24 × 24 px hit area round the 20 px box (WCAG 2.5.8), with no change to its look. */
.check::after {
  content: '';
  position: absolute;
  inset: -3.5px;
}
.check[aria-checked='true'] {
  border-color: var(--ink);
  background: var(--ink);
  color: var(--card) !important;
}
.check[data-over] {
  border-color: var(--ink);
}
.check svg {
  width: 13px;
  height: 13px;
}
.checkSpacer {
  width: 20px;
}
.who {
  display: grid;
  gap: 1px;
  min-width: 0;
}
.name {
  overflow: hidden;
  font-size: 14px;
  font-weight: 560;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.meta {
  color: var(--ink-2);
  font-size: 12.5px;
  font-variant-numeric: tabular-nums;
}
.loss {
  color: var(--red);
  font-size: 15px;
  font-weight: 500;
  font-variant-numeric: tabular-nums;
  text-align: right;
}
.row[data-off] .loss {
  opacity: 0.85;
}
.select {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
  height: 34px;
  padding: 0 10px 0 12px;
  border: 1px solid var(--chip-edge);
  border-radius: 10px;
  background: var(--card);
  font-size: 13px;
  font-weight: 500;
  text-align: left;
  transition: border-color 0.15s ease;
}
.select:hover,
.select[data-over],
.select[aria-expanded='true'] {
  border-color: var(--ink-3);
}
.select[data-plain] {
  color: var(--ink-2) !important;
  font-weight: 400;
}
.sparkle {
  width: 11px;
  height: 11px;
  color: var(--green);
}
.selectText {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.chevron {
  width: 14px;
  height: 14px;
  color: var(--ink-2);
}
.booked {
  color: var(--ink-2);
  font-size: 12.5px;
}
.empty {
  padding: 16px;
  border: 1px solid var(--well-edge);
  border-radius: 17px;
  background: var(--well);
  color: var(--ink-2);
  font-size: 13px;
  line-height: 1.5;
}

.foot {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 10px 16px;
  padding: 14px 2px 4px 10px;
}
.sum {
  margin: 0;
  color: var(--ink-2);
  font-size: 13px;
}
.gain {
  color: var(--green);
  font-weight: 500;
}
.actions {
  display: flex;
  gap: 8px;
}
.button {
  height: 38px;
  padding: 0 16px;
  border: 0;
  border-radius: 12px;
  background: var(--chip);
  font-size: 14px;
  font-weight: 560;
  white-space: nowrap;
  transition:
    background 0.15s ease,
    opacity 0.15s ease;
}
.button:hover,
.button[data-over] {
  background: color-mix(in oklab, var(--chip), var(--ink) 8%);
}
.button[data-primary] {
  background: var(--primary);
  color: var(--primary-ink) !important;
}
.button[data-primary]:hover,
.button[data-primary][data-over] {
  background: color-mix(in oklab, var(--primary), var(--card) 12%);
}
.button:disabled {
  cursor: default;
  opacity: 0.45;
}

/* ---- Layers ----------------------------------------------------------------------------------- */

.menu {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 6;
  display: grid;
  min-width: 200px;
  padding: 5px;
  border: 1px solid var(--tip-edge);
  border-radius: 12px;
  outline: none;
  background: var(--menu);
  box-shadow: 0 18px 40px -12px var(--shadow);
  animation: pop 0.16s ease;
}
.menuItem {
  display: flex;
  align-items: center;
  gap: 8px;
  min-height: 34px;
  padding: 0 9px;
  border: 0;
  border-radius: 8px;
  outline: none;
  background: none;
  font-size: 13px;
  text-align: left;
}
.menuItem:hover,
.menuItem:focus-visible,
.menuItem[data-over] {
  background: var(--hover);
}
.menuLead {
  display: grid;
  place-items: center;
  width: 14px;
  color: var(--ink-2);
}
.menuLead svg {
  width: 14px;
  height: 14px;
}
.menuText {
  flex: 1;
  white-space: nowrap;
}
.menuTrail {
  color: var(--green);
  font-size: 12px;
  font-variant-numeric: tabular-nums;
}
.menuCheck {
  width: 14px;
}
.menuCheck svg {
  width: 14px;
  height: 14px;
}
@keyframes pop {
  from {
    opacity: 0;
    scale: 0.97;
  }
}

.toast {
  position: absolute;
  bottom: 22px;
  left: 50%;
  z-index: 7;
  display: flex;
  align-items: center;
  gap: 14px;
  max-width: calc(100% - 24px);
  padding: 10px 14px;
  border: 1px solid var(--tip-edge);
  border-radius: 12px;
  background: var(--menu);
  box-shadow: 0 14px 34px -10px var(--shadow);
  translate: -50% 0;
  animation: rise 0.22s ease;
}
.toast > span {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.toastUndo {
  position: relative;
  flex: none;
  padding: 0;
  border: 0;
  background: none;
  color: var(--green) !important;
  font-weight: 600;
}
/* A hit area of at least 24 × 24 px around the word (WCAG 2.5.8), with no change to its look. */
.toastUndo::after {
  content: '';
  position: absolute;
  inset: -4px -6px;
}
@keyframes rise {
  from {
    opacity: 0;
    transform: translateY(8px);
  }
}

/* ---- Narrow stages ---------------------------------------------------------------------------- */

@container (max-width: 560px) {
  .root {
    padding: 36px 12px 56px;
  }
  .card {
    padding: 14px 6px 6px;
    border-radius: 20px;
  }
  .head {
    flex-wrap: wrap;
    padding: 0 6px 12px;
  }
  .segmented {
    order: 3;
    width: 100%;
  }
  .segment {
    flex: 1;
  }
  .chartBox {
    padding: 14px 10px 12px 6px;
  }
  .chartGrid {
    grid-template-columns: 34px minmax(0, 1fr);
    grid-template-rows: 200px 24px;
  }
  .xTick:not([data-edge]):not([data-median]) {
    display: none;
  }
  .rows {
    padding: 2px 12px;
  }
  .row {
    grid-template-columns: 22px minmax(0, 1fr) auto;
    gap: 8px 12px;
  }
  .select,
  .booked {
    grid-column: 2 / -1;
  }
  .foot {
    padding: 12px 4px 4px;
  }
  .actions {
    width: 100%;
  }
  .button {
    flex: 1;
  }
}

/* ---- The demo's pointer ----------------------------------------------------------------------- */

.pointerLayer {
  position: absolute;
  inset: 0;
  z-index: 8;
  pointer-events: none;
}
.pointer {
  width: 20px;
  height: 20px;
}
.hand {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .arrow {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .hand {
  visibility: visible;
}

@media (prefers-reduced-motion: reduce) {
  .bubble,
  .medianLine,
  .xTick,
  .segment,
  .check,
  .select,
  .button {
    transition: none;
  }
  .menu,
  .toast,
  .tip,
  .bubble[data-moved] {
    animation: none;
  }
}
```

### profitability-map/data.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/*
 * The book the map draws: 38 customers of a small software company over the last twelve months,
 * each with its plan, its industry, what it paid, its margin and the support hours it took. Four
 * cost more than they pay. The numbers are seeded, so every load draws the same map.
 *
 * The fixes are a small cost model, so what a fix adds is computed, never typed: a support hour
 * costs HOUR_COST, a plan one step up pays PLAN_STEP more a year, and an onboarding fee is FEE.
 */

export type Plan = 'starter' | 'growth' | 'scale' | 'enterprise';
export type Industry = 'retail' | 'health' | 'hospitality' | 'services';
export type Grouping = 'plan' | 'industry';
export type FixId = 'cap' | 'upgrade' | 'fee' | 'review';

export type Customer = {
  id: string;
  name: string;
  plan: Plan;
  industry: Industry;
  /** What it paid over the period, in thousands of dollars. */
  revenue: number;
  /** Its margin over the period, in percent: below 0, it costs more than it pays. */
  margin: number;
  /** Support hours it took over the period. */
  hours: number;
  /** Months until it renews: a fix this close is better made at the renewal. */
  renewsIn?: number;
};

export const PLANS: Plan[] = ['starter', 'growth', 'scale', 'enterprise'];
export const INDUSTRIES: Industry[] = ['retail', 'health', 'hospitality', 'services'];

export const PLAN_NAME: Record<Plan, string> = {
  starter: 'Starter',
  growth: 'Growth',
  scale: 'Scale',
  enterprise: 'Enterprise',
};
export const INDUSTRY_NAME: Record<Industry, string> = {
  retail: 'Retail',
  health: 'Healthcare',
  hospitality: 'Hospitality',
  services: 'Services',
};

/** What a support hour costs, in thousands. */
export const HOUR_COST = 0.45;
/** The support hours a capped customer keeps. */
export const CAP_HOURS = 20;
/** What a plan one step up pays more a year, in thousands, by the plan it leaves. */
export const PLAN_STEP: Record<Plan, number> = { starter: 4, growth: 12, scale: 15, enterprise: 0 };
/** An onboarding fee, in thousands, for accounts under FEE_UNDER a year. */
export const FEE = 5;
export const FEE_UNDER = 20;

const nextPlan = (plan: Plan) => PLANS[Math.min(PLANS.indexOf(plan) + 1, PLANS.length - 1)];

/** The fixes a customer can take, in the order the menu lists them. */
export function fixesFor(customer: Customer): FixId[] {
  const fixes: FixId[] = [];
  if (customer.hours > CAP_HOURS) fixes.push('cap');
  if (customer.plan !== 'enterprise') fixes.push('upgrade');
  if (customer.revenue < FEE_UNDER) fixes.push('fee');
  fixes.push('review');
  return fixes;
}

export function fixLabel(fix: FixId, customer: Customer) {
  if (fix === 'cap') return `Cap support at ${CAP_HOURS} h`;
  if (fix === 'upgrade') return `Move to ${PLAN_NAME[nextPlan(customer.plan)]} plan`;
  if (fix === 'fee') return 'Add onboarding fee';
  return 'Review at renewal';
}

/** The customer as it would be after a fix: a review changes nothing yet. */
export function withFix(customer: Customer, fix: FixId): Customer {
  const cost = customer.revenue * (1 - customer.margin / 100);
  let { revenue, hours, plan } = customer;
  let spend = cost;
  if (fix === 'cap' && hours > CAP_HOURS) {
    spend -= (hours - CAP_HOURS) * HOUR_COST;
    hours = CAP_HOURS;
  } else if (fix === 'upgrade' && plan !== 'enterprise') {
    revenue += PLAN_STEP[plan];
    plan = nextPlan(plan);
  } else if (fix === 'fee') revenue += FEE;
  else return customer;
  const margin = Math.round(((revenue - spend) / revenue) * 100);
  return { ...customer, revenue: Math.round(revenue * 10) / 10, hours, plan, margin };
}

/** What a fix adds to the margin over a year, in thousands. */
export function gainOf(customer: Customer, fix: FixId) {
  const profit = (c: Customer) => c.revenue * (c.margin / 100);
  const after = withFix(customer, fix);
  return after === customer ? 0 : profit(after) - profit(customer);
}

/** The fix the assistant suggests: the one that adds most, or a review when renewal is close. */
export function suggestFix(customer: Customer): FixId {
  if ((customer.renewsIn ?? 12) <= 2) return 'review';
  let best: FixId = 'review';
  let most = 0;
  for (const fix of fixesFor(customer)) {
    const gain = gainOf(customer, fix);
    if (gain > most) {
      most = gain;
      best = fix;
    }
  }
  return best;
}

/** $54k; under a thousand, $800. */
export function money(thousands: number) {
  const value = Math.abs(thousands);
  const text = value >= 1 ? `$${Math.round(value)}k` : `$${Math.round(value * 1000)}`;
  return thousands < 0 ? `−${text}` : text;
}

/** −6%, 42%. */
export const percent = (value: number) => `${value < 0 ? '−' : ''}${Math.abs(Math.round(value))}%`;

export function median(values: number[]) {
  if (!values.length) return 0;
  const sorted = [...values].sort((a, b) => a - b);
  const mid = Math.floor(sorted.length / 2);
  return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}

// ---- The book ------------------------------------------------------------------------------------

/** A small seeded generator (mulberry32), so the book is the same on every load. */
function seeded(seed: number) {
  let a = seed;
  return () => {
    a = (a + 0x6d2b79f5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

/** Where each plan sits: revenue, margin and hours as [low, high]. */
const RANGES: Record<
  Plan,
  { revenue: [number, number]; margin: [number, number]; hours: [number, number] }
> = {
  starter: { revenue: [3, 14], margin: [22, 48], hours: [4, 14] },
  growth: { revenue: [10, 38], margin: [26, 60], hours: [6, 22] },
  scale: { revenue: [30, 82], margin: [30, 62], hours: [10, 34] },
  enterprise: { revenue: [84, 110], margin: [48, 64], hours: [16, 40] },
};

const BOOK: [string, Plan, Industry][] = [
  ['Alder & Rye', 'starter', 'hospitality'],
  ['Bluefin Supply', 'growth', 'retail'],
  ['Cobalt Yoga', 'starter', 'health'],
  ['Driftline Surf', 'starter', 'retail'],
  ['Emberwood Bakery', 'starter', 'hospitality'],
  ['Foxglove Florals', 'starter', 'retail'],
  ['Granite Peak Dental', 'growth', 'health'],
  ['Harbor Lane Books', 'starter', 'retail'],
  ['Ironleaf Tea', 'growth', 'hospitality'],
  ['Juniper Clinic', 'scale', 'health'],
  ['Lumen Pediatrics', 'enterprise', 'health'],
  ['Maple Row Inns', 'scale', 'hospitality'],
  ['Nimbus Print', 'growth', 'services'],
  ['Orchard Street Vet', 'growth', 'health'],
  ['Pinecrest Hotels', 'enterprise', 'hospitality'],
  ['Quarry Fitness', 'starter', 'health'],
  ['Redwood Legal', 'scale', 'services'],
  ['Saltmarsh Kitchen', 'growth', 'hospitality'],
  ['Thistle & Co', 'starter', 'services'],
  ['Umber Studio', 'growth', 'services'],
  ['Verdant Health', 'enterprise', 'health'],
  ['Willowbank Spa', 'scale', 'hospitality'],
  ['Yarrow Physio', 'growth', 'health'],
  ['Zephyr Travel', 'scale', 'services'],
  ['Amberline Logistics', 'enterprise', 'services'],
  ['Brookside Clinics', 'scale', 'health'],
  ['Cedar & Stone', 'scale', 'retail'],
  ['Dunmore Hotels', 'enterprise', 'hospitality'],
  ['Elmhurst Partners', 'scale', 'services'],
  ['Fairhaven Market', 'growth', 'retail'],
  ['Glasswing Media', 'growth', 'services'],
  ['Hollow Oak Cafe', 'starter', 'hospitality'],
  ['Lantern Bay Resorts', 'enterprise', 'hospitality'],
  ['Meridian Tax', 'scale', 'services'],
];

/** The four that cost more than they pay. */
const LOSING: Customer[] = [
  {
    id: 'brightwater',
    name: 'Brightwater Studio',
    plan: 'scale',
    industry: 'services',
    revenue: 54,
    margin: -6,
    hours: 58,
  },
  {
    id: 'larkspur',
    name: 'Larkspur Dental',
    plan: 'growth',
    industry: 'health',
    revenue: 28,
    margin: -22,
    hours: 41,
  },
  {
    id: 'fig-fern',
    name: 'Fig & Fern',
    plan: 'starter',
    industry: 'retail',
    revenue: 9,
    margin: -31,
    hours: 22,
  },
  {
    id: 'tidewell',
    name: 'Tidewell Coffee',
    plan: 'starter',
    industry: 'hospitality',
    revenue: 6,
    margin: -12,
    hours: 14,
    renewsIn: 1,
  },
];

const slug = (name: string) =>
  name
    .toLowerCase()
    .replace(/&/g, 'and')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-|-$/g, '');

function book(): Customer[] {
  const random = seeded(38);
  const between = ([low, high]: [number, number]) => low + random() * (high - low);
  const paying = BOOK.map(([name, plan, industry]) => {
    const range = RANGES[plan];
    return {
      id: slug(name),
      name,
      plan,
      industry,
      revenue: Math.round(between(range.revenue)),
      margin: Math.round(between(range.margin)),
      hours: Math.round(between(range.hours)),
    };
  });
  // The losing four sit among the rest, in the book's order.
  return [
    ...paying.slice(0, 5),
    LOSING[0],
    ...paying.slice(5, 14),
    LOSING[1],
    ...paying.slice(14, 24),
    LOSING[2],
    ...paying.slice(24),
    LOSING[3],
  ];
}

export const CUSTOMERS: Customer[] = book();

/** A healthy book: the same customers with the four losing ones already fixed. */
export const HEALTHY: Customer[] = CUSTOMERS.map((customer) =>
  customer.margin < 0
    ? withFix(customer, suggestFix(customer) === 'review' ? 'fee' : suggestFix(customer))
    : customer,
);
```

### profitability-map/menu.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
  type ReactNode,
} from 'react';
import { Icon } from './glyphs';
import styles from './profitability-map.module.css';

/*
 * The menus: the fix picker and the card's ··· menu. Placed on the stage under their trigger (over
 * it when there is no room below), in the stage's own px, since a gallery card may scale the
 * whole stage. The arrows, Home and End move between items; Escape closes and gives the focus
 * back; a press elsewhere closes.
 */

const ITEMS = '[role="menuitem"], [role="menuitemradio"]';

export function Menu({
  anchor,
  label,
  align = 'start',
  match,
  takeFocus,
  onClose,
  children,
}: {
  anchor: HTMLElement;
  label: string;
  align?: 'start' | 'end';
  /** As wide as its trigger. */
  match?: boolean;
  /** Moves the focus to the checked or first item: when the reader opened it, not the demo. */
  takeFocus: boolean;
  /** `back`: give the focus back to the trigger. */
  onClose: (back: boolean) => void;
  children: ReactNode;
}) {
  const box = useRef<HTMLDivElement>(null);
  const [at, setAt] = useState<{ x: number; y: number; w?: number } | null>(null);

  useLayoutEffect(() => {
    const menu = box.current;
    const frame = menu?.offsetParent as HTMLElement | null;
    if (!frame || !menu) return;
    const place = () => {
      const s = frame.getBoundingClientRect();
      const scale = s.width / frame.offsetWidth || 1;
      const a = anchor.getBoundingClientRect();
      const left = (a.left - s.left) / scale;
      const right = (a.right - s.left) / scale;
      const top = (a.top - s.top) / scale;
      const bottom = (a.bottom - s.top) / scale;
      const w = match ? Math.max(right - left, menu.offsetWidth) : menu.offsetWidth;
      const h = menu.offsetHeight;
      let x = align === 'end' ? right - w : left;
      x = Math.max(8, Math.min(x, frame.clientWidth - w - 8));
      let y = bottom + 6;
      if (y + h > frame.clientHeight - 8 && top - h - 6 > 8) y = top - h - 6;
      setAt({ x, y, w: match ? right - left : undefined });
    };
    place();
    const observer = new ResizeObserver(place);
    observer.observe(menu);
    return () => observer.disconnect();
  }, [anchor, align, match]);

  useEffect(() => {
    if (!takeFocus || !at) return;
    box.current
      ?.querySelector<HTMLElement>('[aria-checked="true"], [role^="menuitem"]')
      ?.focus({ preventScroll: true });
    // Only when it first shows.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [takeFocus, at === null]);

  useEffect(() => {
    const away = (event: PointerEvent) => {
      const target = event.target as Node;
      if (box.current?.contains(target) || anchor.contains(target)) return;
      onClose(false);
    };
    document.addEventListener('pointerdown', away);
    return () => document.removeEventListener('pointerdown', away);
  }, [anchor, onClose]);

  const onKeyDown = (event: ReactKeyboardEvent) => {
    const items = [...(box.current?.querySelectorAll<HTMLElement>(ITEMS) ?? [])];
    const index = items.indexOf(document.activeElement as HTMLElement);
    const move = (to: number) => {
      event.preventDefault();
      items[(to + items.length) % items.length]?.focus();
    };
    if (event.key === 'ArrowDown') move(index + 1);
    else if (event.key === 'ArrowUp') move(index - 1);
    else if (event.key === 'Home') move(0);
    else if (event.key === 'End') move(items.length - 1);
    else if (event.key === 'Escape') {
      event.preventDefault();
      event.stopPropagation();
      onClose(true);
    } else if (event.key === 'Tab') onClose(false);
  };

  return (
    <div
      ref={box}
      role="menu"
      tabIndex={-1}
      aria-label={label}
      className={styles.menu}
      data-part="menu"
      style={{
        transform: at ? `translate(${at.x}px, ${at.y}px)` : undefined,
        minWidth: at?.w,
        visibility: at ? undefined : 'hidden',
      }}
      onKeyDown={onKeyDown}
    >
      {children}
    </div>
  );
}

export function MenuItem({
  onSelect,
  checked,
  radio,
  demo,
  lead,
  trail,
  children,
}: {
  onSelect: () => void;
  checked?: boolean;
  /** One of a set: it shows a check when chosen. */
  radio?: boolean;
  demo?: string;
  /** Before the text: an icon, a sparkle. */
  lead?: ReactNode;
  /** At the right end, before the check: a figure. */
  trail?: ReactNode;
  children: ReactNode;
}) {
  return (
    <button
      type="button"
      role={radio ? 'menuitemradio' : 'menuitem'}
      aria-checked={radio ? !!checked : undefined}
      tabIndex={-1}
      className={styles.menuItem}
      data-demo={demo}
      onClick={onSelect}
    >
      <span className={styles.menuLead}>{lead}</span>
      <span className={styles.menuText}>{children}</span>
      {trail !== undefined && <span className={styles.menuTrail}>{trail}</span>}
      {radio && (
        <span className={styles.menuCheck}>{checked && <Icon name="check" width={2.2} />}</span>
      )}
    </button>
  );
}
```

### profitability-map/glyphs.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/*
 * The line icons: a 24-unit box drawn with currentColor. The sparkle that marks a suggested fix
 * is filled.
 */

const PATHS = {
  /** Dots over a baseline: the map's own tile. */
  scatter: 'M4 19h16M7.5 14.5h.01M11 10.5h.01M15 13h.01M17.5 7.5h.01M9 16.5h.01',
  /** An arrow down into a tray: money leaving. */
  leak: 'M12 4v10M8 10.5l4 4 4-4M4.5 15.5v3.5h15v-3.5',
  chevronDown: 'M7 10l5 5 5-5',
  more: 'M6 12h.01M12 12h.01M18 12h.01',
  check: 'M5 12.5l4.5 4.5L19 7.5',
  mail: 'M3.5 6.5h17v11h-17zM4 7l8 6 8-6',
  done: 'M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM8 12.3l2.8 2.8L16.2 9.6',
  reset: 'M4.5 12a7.5 7.5 0 1 0 2.2-5.3M4.5 4.5v3.8h3.8',
  select: 'M5 12.5l4.5 4.5L19 7.5M5 5h14',
  clear: 'M6 6l12 12M18 6 6 18',
  download: 'M12 4v11M7.5 10.5 12 15l4.5-4.5M5 19.5h14',
};

export type IconName = keyof typeof PATHS;

export function Icon({
  name,
  className,
  width = 1.8,
}: {
  name: IconName;
  className?: string;
  width?: number;
}) {
  return (
    <svg viewBox="0 0 24 24" className={className} aria-hidden="true">
      <path
        d={PATHS[name]}
        fill="none"
        stroke="currentColor"
        strokeWidth={name === 'scatter' || name === 'more' ? width * 1.7 : width}
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

/** Four points, as a suggestion is marked. */
export function Sparkle({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 16 16" className={className} aria-hidden="true">
      <path
        d="M8 1.5c.4 3.3 1.3 4.6 5.5 5.5-4.2.9-5.1 2.2-5.5 6.5-.4-4.3-1.3-5.6-5.5-6.5C6.7 6.1 7.6 4.8 8 1.5z"
        fill="currentColor"
      />
    </svg>
  );
}
```

### profitability-map/demo-pointer.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import type { CSSProperties, Ref } from 'react';

/*
 * The demo's pointer, and the steps that move it. A demo is a script of awaited steps: wait, or
 * glide the pointer somewhere. Stopping the demo (the reader takes over, or it scrolls away) ends
 * the step in progress at once: its promise rejects, which ends the script right there, and the
 * pointer fades out.
 *
 * Each glide is a curved flight played by the Web Animations API, so nothing runs frame by frame.
 * The points of the flight are handed to whoever wants to move along with it. The arrow and the
 * hand are HTML boxes
 * that swap by their visibility: a change of style inside an SVG would lay the SVG out again.
 */

export type Point = { x: number; y: number };

/** A glide's path and timing, for an animation that plays along with it. */
export type Flight = { points: Point[]; timing: KeyframeAnimationOptions };

export type Demo = {
  /** Resolves after `ms`. */
  wait: (ms: number) => Promise<void>;
  /** Glides the pointer to `to`, in the stage's own px, in `ms`; `along` gets the flight. */
  glide: (to: Point, ms: number, along?: (flight: Flight) => void) => Promise<void>;
  /** Shows the arrow, or the hand a link shows. */
  glyph: (name: 'arrow' | 'hand') => void;
};

/** What a stopped demo's pending step rejects with. */
class Stopped extends Error {}

/** Where the arrow's tip is, as shares of its box: the point the pointer stands on. */
const TIP: Point = { x: 0.15, y: 0.1 };

/** How many points a flight is drawn through. */
const SAMPLES = 24;

/** Plays `script` with the pointer over `stage`; returns the function that stops it. */
export function runDemo(
  stage: HTMLElement,
  pointer: HTMLElement,
  script: (demo: Demo) => Promise<void>,
): () => void {
  let alive = true;
  let flight: Animation | null = null;
  // The stylesheet sizes the pointer from the stage's width; its tip is where it stands.
  const tip = { x: pointer.offsetWidth * TIP.x, y: pointer.offsetHeight * TIP.y };
  const place = ({ x, y }: Point) => `translate(${x - tip.x}px, ${y - tip.y}px)`;
  const timers = new Set<number>();
  const pending = new Set<() => void>();
  // The pointer comes in from the lower right.
  let at: Point = { x: stage.offsetWidth * 0.8, y: stage.offsetHeight * 0.9 };

  /** Settles like `promise`, or rejects as soon as the demo stops. */
  const step = (promise: Promise<unknown>) =>
    new Promise<void>((resolve, reject) => {
      if (!alive) return reject(new Stopped());
      const cancel = () => reject(new Stopped());
      pending.add(cancel);
      promise.then(
        () => {
          pending.delete(cancel);
          if (alive) resolve();
        },
        () => {
          pending.delete(cancel);
          reject(new Stopped());
        },
      );
    });

  const wait = (ms: number) =>
    step(
      new Promise<void>((resolve) => {
        const timer = window.setTimeout(() => {
          timers.delete(timer);
          resolve();
        }, ms);
        timers.add(timer);
      }),
    );

  const glide: Demo['glide'] = (to, ms, along) => {
    const from = at;
    at = to;
    const dx = to.x - from.x;
    const dy = to.y - from.y;
    // A gentle curve, as a hand moves: the control point sits off the straight line.
    const bend = { x: (from.x + to.x) / 2 - dy * 0.18, y: (from.y + to.y) / 2 + dx * 0.18 };
    const points: Point[] = [];
    for (let i = 0; i <= SAMPLES; i += 1) {
      const t = i / SAMPLES;
      const u = 1 - t;
      points.push({
        x: u * u * from.x + 2 * u * t * bend.x + t * t * to.x,
        y: u * u * from.y + 2 * u * t * bend.y + t * t * to.y,
      });
    }
    const timing: KeyframeAnimationOptions = {
      duration: ms,
      easing: 'cubic-bezier(0.45, 0, 0.25, 1)',
    };
    flight?.cancel();
    // Where it rests once the flight is over.
    pointer.style.transform = place(to);
    flight = pointer.animate(
      points.map((point) => ({ transform: place(point) })),
      timing,
    );
    along?.({ points, timing });
    return step(flight.finished);
  };

  const glyph: Demo['glyph'] = (name) => {
    pointer.dataset.glyph = name;
  };

  pointer.dataset.glyph = 'arrow';
  pointer.style.transform = place(at);
  pointer.style.opacity = '1';
  script({ wait, glide, glyph }).catch((error: unknown) => {
    if (!(error instanceof Stopped)) throw error;
  });

  return () => {
    if (!alive) return;
    alive = false;
    timers.forEach((timer) => window.clearTimeout(timer));
    flight?.cancel();
    pending.forEach((cancel) => cancel());
    pointer.style.opacity = '0';
  };
}

/**
 * The pointer's box: it moves, on a layer of its own. Its size comes from its class, its colours
 * from the stage's tokens (profitability-map.module.css).
 */
const POINTER: CSSProperties = {
  position: 'absolute',
  top: 0,
  left: 0,
  zIndex: 2,
  display: 'block',
  pointerEvents: 'none',
  opacity: 0,
  transition: 'opacity 0.3s ease',
  filter: 'drop-shadow(0 1px 1.5px var(--pointer-shadow))',
  willChange: 'transform',
};

/** One glyph over the other, each filling the box. */
const GLYPH: CSSProperties = { position: 'absolute', inset: 0, display: 'block' };
const DRAWING: CSSProperties = {
  display: 'block',
  width: '100%',
  height: '100%',
  overflow: 'visible',
};
/** The arrow is dark on a white edge, the hand white on a dark one, as the system draws them. */
const ARROW: CSSProperties = { fill: 'var(--pointer)', stroke: 'var(--pointer-edge)' };
const HAND: CSSProperties = { fill: 'var(--pointer-edge)', stroke: 'var(--pointer)' };

/**
 * The pointer the demo moves around: an arrow, or a pointing hand over what it can press. It is
 * decorative: what it does shows on the table itself. The stylesheet shows one glyph at a time,
 * from the box's data-glyph.
 */
export function DemoPointer({
  ref,
  className,
  arrowClass,
  handClass,
}: {
  ref: Ref<HTMLSpanElement>;
  className?: string;
  arrowClass?: string;
  handClass?: string;
}) {
  return (
    <span ref={ref} className={className} style={POINTER} aria-hidden="true">
      <span className={arrowClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          <path
            d="M3 2v14.5l3.6-3.3 2.6 5.6 2.4-1.1-2.6-5.5h5.2z"
            style={ARROW}
            strokeWidth="1.3"
            strokeLinejoin="round"
          />
        </svg>
      </span>
      <span className={handClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          {/* The tip of the finger sits where the arrow's tip is. */}
          <path
            d="M6.4 3.3c0-.8.6-1.4 1.3-1.4S9 2.5 9 3.3v5.5c.2-.5.6-.8 1.2-.8.7 0 1.2.5 1.2 1.2v.5c.2-.5.6-.8 1.2-.8.7 0 1.2.5 1.2 1.2v.7c.2-.4.6-.7 1.1-.7.7 0 1.2.5 1.2 1.2v3.5c0 2.8-1.9 4.9-4.6 4.9h-1.2c-1.8 0-3.1-.8-4.1-2.3l-2.6-3.9c-.4-.6-.2-1.3.4-1.7.6-.3 1.3-.2 1.7.4l.6.9z"
            style={HAND}
            strokeWidth="1.1"
            strokeLinejoin="round"
            transform="translate(-4.7 0.1)"
          />
        </svg>
      </span>
    </span>
  );
}
```

### profitability-map/use-autoplay.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { useCallback, useEffect, useRef, useState } from 'react';

/*
 * When a demo may play on its own: while part of it is on screen and the tab is visible, never
 * under reduced motion, and never again once the reader has used it. `take()` hands it to the
 * reader for good (until the component remounts), so it never starts again on its own (WCAG
 * 2.2.2). `hold()` only pauses it, for input that isn't a use (a hover, a wheel over it), and lets
 * it go on `idle` ms after the last one.
 */
export function useAutoplay<T extends HTMLElement>(idle = 6000) {
  const ref = useRef<T>(null);
  const [visible, setVisible] = useState(false);
  const [reduced, setReduced] = useState(true);
  const [taken, setTaken] = useState(false);
  const [held, setHeld] = useState(false);
  const timer = useRef(0);

  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    let onScreen = false;
    const update = () => setVisible(onScreen && !document.hidden);
    const observer = new IntersectionObserver(
      ([entry]) => {
        onScreen = entry.isIntersecting;
        update();
      },
      { threshold: 0.3 },
    );
    observer.observe(element);
    document.addEventListener('visibilitychange', update);
    const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
    const readMotion = () => setReduced(motion.matches);
    readMotion();
    motion.addEventListener('change', readMotion);
    return () => {
      observer.disconnect();
      document.removeEventListener('visibilitychange', update);
      motion.removeEventListener('change', readMotion);
    };
  }, []);

  const take = useCallback(() => {
    setTaken(true);
    window.clearTimeout(timer.current);
  }, []);
  const hold = useCallback(() => {
    setHeld(true);
    window.clearTimeout(timer.current);
    timer.current = window.setTimeout(() => setHeld(false), idle);
  }, [idle]);
  useEffect(() => () => window.clearTimeout(timer.current), []);

  return { ref, take, hold, visible, reduced, playing: visible && !reduced && !taken && !held };
}
```