"use client";

import { Fragment, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import type { ActiveElement, Chart, ChartEvent } from "chart.js";
import { useTranslation } from "@enode/core/translations/hooks";
import { ChevronDownIcon, ChevronRightIcon, EyeFillIcon, EyeSlashFillIcon } from "@enode/ui/icons";
import { InfoTooltip } from "../info-tooltip";
import { ChartLinkRowMenu } from "./chart-link-menu";
import { chartLinks, type ChartLinkActions, type ChartLinkTarget } from "./chart-links";
import { metricShade, withAlpha, type ShadeTone } from "./chart-setup";
import { useLegendPlacement } from "./chart-shell";
import { useFocusOpening, type ChartTileValue } from "./chart-tile-context";
import {
  SEARCH_ABOVE,
  SHORTLIST_ABOVE,
  SHORTLIST_SIZE,
  matchesQuery,
  nextFocused,
  panelDetail,
  resolveEmphasis,
  selectLegendRows,
  zeroCrossing,
  type Emphasis,
  type PanelPlacement,
} from "./legend-model";
import { LOOK } from "@enode/ui/live/look";

// Rich legend shared by every analysis chart: a sortable table of one row per
// series with its colour swatch, per-series summary stats, an eye-toggle to
// hide/show the series, and click-to-focus (dims the other series). The chart
// owns the data (it computes the rows + reacts to the hidden/focused state from
// `useSeriesInteraction`); this component is presentational + owns only its view
// state (sort, search, folded rows, short/full list, detail columns) and the
// structural labels. Big legends stay readable via the rules in legend-model.ts:
// a short list with "Show all", a search field, folded rows and detail columns
// behind "Show statistics".
//
// In the focus view's side panel (22rem; see ChartShell) the same rows render as
// a compact list instead (LegendPanel): open from the start, one value per row
// (the stat marked `primary`), the other plain stats on a detail line under the
// name, the rows the answer names first, and "Full table" for this table at full
// width under the plot.

/** One stat cell: a pre-formatted display string plus the raw value to sort on. */
export interface SeriesStat {
  key: string;
  label: string;
  display: string;
  sort: number;
  /**
   * Tints the cell green (up) / red (down). Only for values where a rise is
   * known to be good: Trend's change deliberately sets none, since for metrics
   * like velocity loss a rise is bad (insights 9a).
   */
  tone?: "up" | "down";
  /** Explains the column; shown from an info button next to its header. */
  hint?: string;
  /**
   * When set, the cell renders a sparkline of these {x,y} points instead of
   * `display`. The x is honoured (gaps preserved) so the sparkline matches a
   * chart overlay drawn from the same points.
   */
  spark?: { x: number; y: number }[];
  /** A detail column, shown only after "Show statistics". */
  secondary?: boolean;
  /** The row's value in the focus view's side panel (the one its answer is about); one stat per row. */
  primary?: boolean;
  /** Side panel: "omit" keeps the stat to the full table; by default it joins the row's detail line. */
  panel?: PanelPlacement;
}

export interface SeriesRow {
  id: string;
  label: string;
  /** Resolved series colour (solid hex/rgb) for the swatch. */
  color: string;
  stats: SeriesStat[];
  /**
   * Member series folded under this row (e.g. an athlete's lifts). The row's
   * own id is then a group id: focusing/hiding it acts on every member.
   */
  children?: SeriesRow[];
  /** Position in a ranked legend, shown before the label. */
  rank?: number;
  /** What the row refers to; a linkable target adds a "⋯" links menu to it. */
  links?: ChartLinkTarget;
  /**
   * How the row reads in the focus view's side panel where it differs from the
   * table: a shorter label, a value that isn't one of the stats, a badge, and
   * text that leads the detail line.
   */
  panel?: { label?: string; value?: string; badge?: string; detail?: string };
}

/**
 * The rows a short legend shows by default ({@link selectLegendRows}), with a
 * caption that says how they were picked.
 */
export interface LegendShortlist {
  ids: string[];
  caption: string;
  /** For a top + bottom pick: rows before the "⋯ N in between" line. */
  splitAfter?: number;
}

export type { Emphasis };

/** Hidden + focused series state, with the helpers a chart needs to react. */
export interface SeriesInteraction {
  isHidden: (id: string) => boolean;
  toggleHidden: (id: string) => void;
  /** Hide every id in `ids` except `keep` (“show only this”, or only these). */
  showOnly: (keep: string | readonly string[], ids: readonly string[]) => void;
  /** Show every hidden series again. */
  showAll: () => void;
  hiddenCount: number;
  /** The focused series the selection card is about (the last one focused), or null. */
  focusedId: string | null;
  /** Every focused series: one, or up to {@link MAX_COMPARED} while comparing. */
  focusedIds: ReadonlySet<string>;
  /** Focus `id` (or release it); `additive` (⌘ / Ctrl) adds it to the comparison. */
  toggleFocus: (id: string, additive?: boolean) => void;
  /** Drop the focus without touching hidden state — e.g. a click on empty canvas. */
  clearFocus: () => void;
  /**
   * A transient highlight while nothing is focused: a hovered legend row or
   * the legend's Find… matches. Null for none.
   */
  setPreview: (ids: readonly string[] | null, source?: PreviewSource) => void;
  /** The preview's ids and where they come from, or null (e.g. a chart scrolls to Find's matches, not to a hover). */
  preview: { ids: ReadonlySet<string>; source: PreviewSource } | null;
  /** “Compare” on touch: while on, a tap adds to the comparison like ⌘ / Ctrl-click. */
  compareMode: boolean;
  setCompareMode: (on: boolean) => void;
  /** What the emphasis treats as focused: the focus, else the preview. */
  emphasisFocus: () => ReadonlySet<string>;
  /**
   * How a series is drawn: "dimmed" for every non-focused series while one is
   * focused, else "normal". {@link withHighlight} adds the crowded-chart rules.
   */
  emphasis: (id: string) => Emphasis;
  /**
   * The board's spotlight colour while the spotlight drives this chart's focus
   * (see `withSpotlightFocus`): the spotlit series are drawn in it on every
   * chart, everything else grey. Absent otherwise.
   */
  spotlightColor?: string | null;
  /**
   * The metric shade a highlighted series is drawn in (see
   * {@link withMetricShades}); null for a series that isn't highlighted or
   * while the chart's metric is unknown. Absent: series keep their own colour.
   */
  shadeOf?: (id: string) => string | null;
  /** Where a highlighted series sits among the metric shades (the same rule as `shadeOf`), for charts drawing two hues. */
  shadeTone?: (id: string) => ShadeTone | null;
  /**
   * True while the focus is the board's spotlight rather than one the coach
   * set on this chart (see `withSpotlightFocus`). The spotlight only
   * highlights: it doesn't open the selection card.
   */
  focusFromSpotlight?: boolean;
  /** Clear all hidden/focused state — e.g. when a chart re-keys its series. */
  reset: () => void;
}

/** Where a preview comes from: a hovered legend row or plot mark, or the legend's Find…. */
export type PreviewSource = "hover" | "find";

/** The focused set the emphasis uses: the focus, else the preview. */
export function emphasisSet(focusedIds: ReadonlySet<string>, preview: ReadonlySet<string> | null): ReadonlySet<string> {
  return focusedIds.size > 0 ? focusedIds : (preview ?? EMPTY);
}
const EMPTY: ReadonlySet<string> = new Set();

/**
 * A chart's hidden + focused series. In the focus view it starts on the series
 * the tile click asked for (see `useFocusOpening`).
 */
export function useSeriesInteraction(): SeriesInteraction {
  const opening = useFocusOpening();
  const [hidden, setHidden] = useState<ReadonlySet<string>>(new Set());
  const [focused, setFocused] = useState<readonly string[]>(() => (opening?.focusId ? [opening.focusId] : []));
  const [preview, setPreviewState] = useState<{ ids: ReadonlySet<string>; source: PreviewSource } | null>(null);
  const [compareMode, setCompareMode] = useState(false);
  const focusedIds = useMemo(() => new Set(focused), [focused]);
  const setPreview = useCallback(
    (ids: readonly string[] | null, source: PreviewSource = "hover") =>
      setPreviewState(ids && ids.length ? { ids: new Set(ids), source } : null),
    [],
  );
  const effective = emphasisSet(focusedIds, preview?.ids ?? null);

  return {
    isHidden: (id) => hidden.has(id),
    toggleHidden: (id) =>
      setHidden((prev) => {
        const next = new Set(prev);
        if (next.has(id)) next.delete(id);
        else next.add(id);
        return next;
      }),
    showOnly: (keep, ids) => {
      const kept = new Set(typeof keep === "string" ? [keep] : keep);
      setHidden(new Set(ids.filter((other) => !kept.has(other))));
    },
    showAll: () => setHidden(new Set()),
    hiddenCount: hidden.size,
    focusedId: focused.length ? focused[focused.length - 1] : null,
    focusedIds,
    toggleFocus: (id, additive = false) => setFocused((prev) => nextFocused(prev, id, additive || compareMode)),
    clearFocus: () => {
      setFocused([]);
      setCompareMode(false);
    },
    setPreview,
    preview,
    compareMode,
    setCompareMode,
    emphasisFocus: () => effective,
    emphasis: (id) => resolveEmphasis(id, { focused: effective, crowded: false }),
    reset: () => {
      setHidden(new Set());
      setFocused([]);
      setPreviewState(null);
      setCompareMode(false);
    },
  };
}

/**
 * Layer the big-chart rules over a chart's series interaction:
 *
 * - `crowded` (see {@link isCrowded}): everything not focused or highlighted
 *   turns a neutral grey ("muted") instead of keeping its own colour.
 * - `highlightIds`: what keeps its colour on a crowded chart while nothing is
 *   focused (series ids and, for folded legends, their row ids).
 * - `groupOf`: series id → its folded legend row id. Focusing or hiding that
 *   row focuses or hides every member.
 *
 * Pass the returned interaction to both the plot and {@link ChartLegendTable}
 * so swatches match the plot.
 */
export function withHighlight(
  interaction: SeriesInteraction,
  rules: {
    crowded: boolean;
    highlightIds?: ReadonlySet<string>;
    groupOf?: (id: string) => string | null;
  },
): SeriesInteraction {
  const { groupOf } = rules;
  return {
    ...interaction,
    isHidden: (id) => {
      if (interaction.isHidden(id)) return true;
      const group = groupOf?.(id);
      return group != null && interaction.isHidden(group);
    },
    emphasis: (id) => {
      const emphasis = resolveEmphasis(id, { ...rules, focused: interaction.emphasisFocus() });
      // Under the spotlight everyone else is grey, not dimmed in their own colours.
      return interaction.spotlightColor && emphasis === "dimmed" ? "muted" : emphasis;
    },
  };
}

/**
 * The colour a series is drawn in: the spotlight's colour while it is the
 * board's spotlit athlete, so they look the same on every chart; else, while
 * highlighted, its metric shade (pass `id`); else its own.
 */
export function seriesColor(
  interaction: SeriesInteraction,
  color: string,
  emphasis: Emphasis,
  id?: string,
): string {
  if (emphasis === "focused" && interaction.spotlightColor) return interaction.spotlightColor;
  if (id != null && (emphasis === "normal" || emphasis === "focused")) {
    return interaction.shadeOf?.(id) ?? color;
  }
  return color;
}

/**
 * Colour only what is highlighted, in the chart's metric colour (insights
 * feedback G7): the series the coach focused, the answer names, or a crowded
 * chart picks. Everything else stays grey (the charts layer `withHighlight`
 * with `crowded: true` for that).
 *
 * - Several athletes highlighted: each athlete takes a shade (the full metric
 *   colour first, then lighter and darker steps, in legend order), the same
 *   for all their series.
 * - One athlete with several series (lifts): all in a slightly lighter tint,
 *   the hovered one (legend row or plot) in the full colour.
 * - One series: the full colour.
 *
 * `rowIds` are the legend's rows in order and `seriesIds` the plotted series;
 * `athleteOf` maps either to its athlete; `groupOf` maps a series to its
 * folded legend row (hovering the row lights its series).
 */
export function withMetricShades(
  interaction: SeriesInteraction,
  rules: {
    hue: string | null;
    dark: boolean;
    rowIds: readonly string[];
    seriesIds: readonly string[];
    athleteOf: (id: string) => string | null;
    groupOf?: (id: string) => string | null;
  },
): SeriesInteraction {
  const { hue, dark, rowIds, seriesIds, athleteOf, groupOf } = rules;
  if (!hue) return interaction;
  const isLit = (id: string) => {
    const emphasis = interaction.emphasis(id);
    return !interaction.isHidden(id) && (emphasis === "normal" || emphasis === "focused");
  };
  const athletes: string[] = [];
  for (const id of rowIds) {
    const athlete = athleteOf(id) ?? id;
    if (isLit(id) && !athletes.includes(athlete)) athletes.push(athlete);
  }
  const litSeries = seriesIds.filter(isLit).length;
  const hovered = interaction.preview?.source === "hover" ? interaction.preview.ids : null;
  const isHovered = (id: string) => {
    if (!hovered) return false;
    const group = groupOf?.(id);
    return hovered.has(id) || (group != null && hovered.has(group));
  };
  const shadeTone = (id: string): ShadeTone | null => {
    const place = athletes.indexOf(athleteOf(id) ?? id);
    if (place < 0) return null;
    if (athletes.length > 1 || litSeries <= 1) return { place, light: false };
    return { place: 0, light: !isHovered(id) };
  };
  return {
    ...interaction,
    shadeTone,
    shadeOf: (id) => {
      const tone = shadeTone(id);
      return tone ? metricShade(hue, dark, tone) : null;
    },
  };
}

/** Neutral grey for "muted" series on a crowded chart (readable in both themes). */
const MUTED_SERIES_COLOR = "#8e8e93";

/**
 * The base colour a series is painted in: neutral grey when muted, else its
 * own. For charts that paint custom shapes and apply their own alpha.
 */
export function emphasisBaseColor(color: string, emphasis: Emphasis): string {
  return isGrey(emphasis) ? MUTED_SERIES_COLOR : color;
}

function isGrey(emphasis: Emphasis): boolean {
  return emphasis === "muted" || emphasis === "neutral";
}

/** Swatch colour for a legend row, matching how its series is drawn. */
function swatchColor(color: string, emphasis: Emphasis): string {
  return isGrey(emphasis) ? withAlpha(MUTED_SERIES_COLOR, 0.6) : color;
}

/**
 * Custom field every chart tags its chart.js datasets with, so a canvas click can
 * map a hit element back to the series (and its legend row) it belongs to.
 */
export interface SeriesTaggedDataset {
  _seriesId?: string;
}

/** Near-miss radius (canvas px): a click this close to a mark still focuses its
 *  series, so clicking along a line — not only dead-centre on a point — works. */
const FOCUS_HIT_RADIUS = 26;

/**
 * The series under (or close to) a pointer event on a chart.js canvas: a direct
 * hit on a mark, else the nearest mark within {@link FOCUS_HIT_RADIUS}, else
 * null. Every dataset must carry its series id under `_seriesId` (see
 * {@link SeriesTaggedDataset}). Shared by click-to-focus and the actions
 * gestures (right-click, long-press).
 */
export function seriesIdAtEvent(chart: Chart, native: Event): string | null {
  const seriesIdAt = (datasetIndex: number) =>
    (chart.data.datasets[datasetIndex] as SeriesTaggedDataset | undefined)?._seriesId ?? null;
  const onMark = chart.getElementsAtEventForMode(native, "nearest", { intersect: true }, false);
  if (onMark.length) {
    const id = seriesIdAt(onMark[0].datasetIndex);
    if (id != null) return id;
  }
  const [hit] = chart.getElementsAtEventForMode(native, "nearest", { intersect: false }, false);
  if (!hit) return null;
  const rect = chart.canvas.getBoundingClientRect();
  const pointer = native as MouseEvent;
  const x = pointer.clientX - rect.left;
  const y = pointer.clientY - rect.top;
  const distance = Math.hypot(x - hit.element.x, y - hit.element.y);
  return distance <= FOCUS_HIT_RADIUS ? seriesIdAt(hit.datasetIndex) : null;
}

/** Whether a click adds to the comparison instead of replacing the focus (⌘ on macOS, Ctrl elsewhere). */
export function isAdditiveClick(event: Event | null | undefined): boolean {
  const mouse = event as MouseEvent | null | undefined;
  return Boolean(mouse?.metaKey || mouse?.ctrlKey);
}

/**
 * What a click on a plot does, for every chart type. On a board tile it opens
 * the focus view with the clicked series focused (or nothing, off the marks);
 * in the builder's preview (a tile without `onOpen`) it does nothing. Anywhere
 * else it focuses the series (⌘ / Ctrl adds it to a comparison) or, off the
 * marks, releases the focus. A plain click never opens a menu; actions sit in
 * the selection card and behind a right-click (see chart-card-actions.tsx).
 */
export function plotClick(
  id: string | null,
  event: Event | null | undefined,
  interaction: SeriesInteraction,
  tile: ChartTileValue | null,
): void {
  if (tile) {
    tile.onOpen?.({ focusId: id });
    return;
  }
  if (id != null) interaction.toggleFocus(id, isAdditiveClick(event));
  else interaction.clearFocus();
}

/** A chart.js `options.onClick` that applies {@link plotClick} to the series under the pointer. */
export function seriesFocusOnClick(interaction: SeriesInteraction, tile: ChartTileValue | null) {
  return (event: ChartEvent, _elements: ActiveElement[], chart: Chart) => {
    const native = event.native;
    if (!native) return;
    plotClick(seriesIdAtEvent(chart, native), native, interaction, tile);
  };
}

/**
 * Apply an emphasis to a series colour: dimmed series fade toward transparent,
 * muted series (crowded chart) turn neutral grey, focused/normal keep
 * `baseAlpha`. Charts call this when building chart.js colours so focusing a
 * legend row visibly dims the rest of the plot.
 */
export function emphasizeColor(
  color: string,
  emphasis: Emphasis,
  baseAlpha = 1,
): string {
  if (emphasis === "dimmed") return withAlpha(color, baseAlpha * 0.16);
  // Muted greys sit behind coloured series: faint, so they don't compete.
  if (emphasis === "muted") return withAlpha(MUTED_SERIES_COLOR, baseAlpha * 0.16);
  // Neutral greys are the whole picture (nothing coloured): keep them readable.
  if (emphasis === "neutral") return withAlpha(MUTED_SERIES_COLOR, baseAlpha * 0.55);
  return baseAlpha < 1 ? withAlpha(color, baseAlpha) : color;
}

/**
 * chart.js draw order for an emphasis: coloured series paint over grey ones
 * (a lower `order` draws on top).
 */
export function emphasisDrawOrder(emphasis: Emphasis): number {
  return emphasis === "normal" || emphasis === "focused" ? 0 : 1;
}

type SortDir = "asc" | "desc";

/**
 * Which "you can click a series" hint the legend shows: `trendLine` where a
 * click draws the series' trend line (Trend), `highlight` where it highlights
 * the series (Correlation). Omit for charts without a visible click effect.
 */
export type LegendFocusHint = "trendLine" | "highlight";

// Device-local "the coach has focused a series once" flag: after the first
// focus anywhere, the hint has done its job and stays hidden on every chart.
const FOCUS_HINT_SEEN_KEY = "enode.insights.legend-focus-hint-seen";

function readFocusHintSeen(): boolean {
  try {
    return window.localStorage.getItem(FOCUS_HINT_SEEN_KEY) === "1";
  } catch {
    return false;
  }
}

/**
 * Whether the click-a-series hint is retired. It retires the first time a
 * series is focused (legend row or canvas) and stays retired on this device.
 */
function useFocusHintSeen(focusedId: string | null): boolean {
  const [seen, setSeen] = useState(readFocusHintSeen);
  // Render-time adjustment: the first focus retires the hint immediately.
  if (focusedId != null && !seen) setSeen(true);
  useEffect(() => {
    if (!seen) return;
    try {
      window.localStorage.setItem(FOCUS_HINT_SEEN_KEY, "1");
    } catch {
      // Private mode / blocked storage — the hint just reappears next visit.
    }
  }, [seen]);
  return seen;
}

// Device-local "Show statistics" choice, shared by every legend: a coach who
// wants r / R² / IQR wants them on all charts, and after a reload.
const SHOW_STATS_KEY = "enode.insights.legend-show-statistics";
const showStatsListeners = new Set<() => void>();
let showStatsCache: boolean | null = null;

function readShowStats(): boolean {
  if (showStatsCache == null) {
    try {
      showStatsCache = window.localStorage.getItem(SHOW_STATS_KEY) === "1";
    } catch {
      showStatsCache = false;
    }
  }
  return showStatsCache;
}

function writeShowStats(next: boolean) {
  showStatsCache = next;
  try {
    window.localStorage.setItem(SHOW_STATS_KEY, next ? "1" : "0");
  } catch {
    // Private mode / blocked storage — the choice just lasts until reload.
  }
  showStatsListeners.forEach((listener) => listener());
}

function subscribeShowStats(listener: () => void): () => void {
  showStatsListeners.add(listener);
  return () => showStatsListeners.delete(listener);
}

/** Whether detail columns are shown, plus a setter that updates every legend. */
function useShowStatistics(): [boolean, (update: (prev: boolean) => boolean) => void] {
  const shown = useSyncExternalStore(subscribeShowStats, readShowStats, () => false);
  return [shown, (update) => writeShowStats(update(readShowStats()))];
}

/** Touch screens get "Tap", pointers "Click". */
function isTouchOnly(): boolean {
  return typeof window !== "undefined" && window.matchMedia?.("(hover: none)").matches === true;
}

type LegendProps = {
  rows: SeriesRow[];
  interaction: SeriesInteraction;
  /** Shared y-range for sparkline cells (the chart's data domain). */
  sparkYDomain?: [number, number];
  /** Small muted note under the table (e.g. selected entities with no data). */
  note?: string;
  /** Show the "click a series" hint in the header until it's first used. */
  focusHint?: LegendFocusHint;
  /** The rows a long legend starts on; without it a long legend lists everything. */
  shortlist?: LegendShortlist;
  /** Header count in plain words (e.g. "20 athletes"); default "N series". */
  countLabel?: string;
  /** In-page actions for a row's links (e.g. open a drawer); default: redirect. */
  linkActions?: (target: ChartLinkTarget) => ChartLinkActions;
  /** Side panel: the rows the chart's answer names; they lead under "In the heading". */
  leadIds?: ReadonlySet<string>;
  /** Side panel: the value's heading when rows carry `panel.value` (else the primary stat's label). */
  panelValueLabel?: string;
  /** Side panel: a line under the rows that explains the values (e.g. Correlation's marks). */
  panelKey?: string;
  /** Side panel: a divider where the value crosses zero, with this label (Ranking: the team median). */
  panelZeroLine?: string;
  /** Side panel: names and show/hide only, no values (the Trend matrix already holds them). */
  panelFilterOnly?: boolean;
  /** Side panel: the value and its heading are space-separated cells to line up (Correlation's per-lift marks). */
  panelCells?: boolean;
  /**
   * Side panel as a live readout (the Trend's crosshair): each row's value at
   * the hovered point, keyed by row id, under `label` (the date). Null or
   * absent: the rows' own values.
   */
  readout?: { label: string; values: ReadonlyMap<string, string> };
};

/**
 * A chart's legend: the table under the plot, or in the focus view's side
 * panel the compact list, with "Full table" switching to the table at full
 * width under the plot (see {@link useLegendPlacement}).
 */
export function ChartLegendTable(props: LegendProps) {
  const placement = useLegendPlacement();
  if (placement?.placement === "panel") return <LegendPanel {...props} onFullTable={placement.showFullTable} />;
  return <LegendTable {...props} onBackToPanel={placement?.showPanel} />;
}

/** The "click a series" hint until the first focus, or null. Literal t() per variant so each string stays extractable. */
function useFocusHintText(focusHint: LegendFocusHint | undefined, focusedId: string | null): string | null {
  const { t } = useTranslation();
  const hintSeen = useFocusHintSeen(focusedId);
  const [touch] = useState(isTouchOnly);
  if (!focusHint || hintSeen) return null;
  if (focusHint === "trendLine") {
    return touch ? t("Tap a series to see its trend line") : t("Click a series to see its trend line");
  }
  return touch ? t("Tap a series to highlight it") : t("Click a series to highlight it");
}

/** While Find… has a query, its matching rows light up on the plot (a preview, not a focus). */
function useFindPreview(query: string, rows: readonly SeriesRow[], interaction: SeriesInteraction) {
  const { setPreview } = interaction;
  const needle = query.trim();
  const matchKey = needle
    ? rows.filter((row) => matchesQuery(row, needle)).map((row) => row.id).join("\u0000")
    : "";
  // Re-applied when a hovered row lets go of the preview, so the matches stay lit.
  const previewCleared = interaction.preview == null;
  const applied = useRef("");
  useEffect(() => {
    if (matchKey) {
      if (previewCleared || applied.current !== matchKey) setPreview(matchKey.split("\u0000"), "find");
    } else if (applied.current) {
      setPreview(null);
    }
    applied.current = matchKey;
  }, [matchKey, previewCleared, setPreview]);
}

/** “2 hidden · Show all”, while any series is hidden. */
function HiddenCount({ interaction }: { interaction: SeriesInteraction }) {
  const { t } = useTranslation();
  if (interaction.hiddenCount === 0) return null;
  return (
    <button
      type="button"
      onClick={interaction.showAll}
      className="body-small shrink-0 font-medium text-foreground-muted hover:text-foreground-default hover:underline"
    >
      {t("{count} hidden · Show all", { count: interaction.hiddenCount })}
    </button>
  );
}

function LegendTable({
  rows,
  interaction,
  sparkYDomain,
  note,
  focusHint,
  shortlist,
  countLabel,
  linkActions,
  onBackToPanel,
}: LegendProps & {
  /** In the focus view: the table was opened from the side panel; this puts it back. */
  onBackToPanel?: () => void;
}) {
  const { t } = useTranslation();
  const hintText = useFocusHintText(focusHint, interaction.focusedId);
  // Sort by a stat key (or "label"); null = the chart's natural order.
  const [sort, setSort] = useState<{ key: string; dir: SortDir } | null>(null);
  // Collapsed by default: the card leads with the chart; the table is on demand.
  // Opened from the focus view's side panel, it starts open.
  const [collapsed, setCollapsed] = useState(onBackToPanel == null);
  const [query, setQuery] = useState("");
  const [showAll, setShowAll] = useState(false);
  const [showStats, setShowStats] = useShowStatistics();
  const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set());
  useFindPreview(query, rows, interaction);

  // Stat columns come from the rows themselves (every row carries the same
  // keys); empty when a chart provides label-only rows. Detail columns stay
  // hidden until "Show statistics".
  const allColumns = rows[0]?.stats ?? [];
  const hasDetailColumns = allColumns.some((col) => col.secondary);
  const columns = allColumns.filter((col) => showStats || !col.secondary);
  const columnKeys = new Set(columns.map((col) => col.key));

  const sortedRows = useMemo(() => {
    if (!sort) return rows;
    const factor = sort.dir === "asc" ? 1 : -1;
    return [...rows].sort((a, b) => {
      if (sort.key === "label") return factor * a.label.localeCompare(b.label);
      const av = a.stats.find((s) => s.key === sort.key)?.sort ?? 0;
      const bv = b.stats.find((s) => s.key === sort.key)?.sort ?? 0;
      return factor * (av - bv);
    });
  }, [rows, sort]);

  // A focused member series keeps its folded row on screen.
  const focusedId = interaction.focusedId;
  const focusedRowId =
    focusedId == null
      ? null
      : (rows.find(
          (r) => r.id === focusedId || r.children?.some((c) => c.id === focusedId),
        )?.id ?? null);
  const selection = selectLegendRows(sortedRows, {
    query,
    showAll,
    sorted: sort != null,
    shortlistIds: shortlist?.ids,
    splitAfter: shortlist?.splitAfter,
    focusedRowId,
  });
  const hasFoldableRows = rows.some((r) => (r.children?.length ?? 0) > 0);
  const isLinkable = (r: SeriesRow) => r.links != null && chartLinks(r.links).length > 0;
  const hasLinks = rows.some((r) => isLinkable(r) || (r.children?.some(isLinkable) ?? false));
  // Columns after the eye column: label, stats, and the links menu if any.
  const wideColSpan = columns.length + 1 + (hasLinks ? 1 : 0);
  const canShorten = rows.length > SHORTLIST_ABOVE && (shortlist != null || sort != null);
  const showSearch = rows.length > SEARCH_ABOVE;

  function toggleSort(key: string) {
    setSort((prev) =>
      prev?.key === key
        ? prev.dir === "desc"
          ? { key, dir: "asc" }
          : null
        : { key, dir: "desc" },
    );
  }

  function toggleExpanded(id: string) {
    setExpanded((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }

  function ariaSort(key: string): "ascending" | "descending" | "none" {
    if (sort?.key !== key) return "none";
    return sort.dir === "asc" ? "ascending" : "descending";
  }

  function sortGlyph(key: string): string {
    if (sort?.key !== key) return "";
    return sort.dir === "asc" ? " ↑" : " ↓";
  }

  if (rows.length === 0) return null;

  function renderRow(row: SeriesRow, member: boolean) {
    const hidden = interaction.isHidden(row.id);
    const emphasis = interaction.emphasis(row.id);
    const focused = emphasis === "focused";
    const foldable = !member && (row.children?.length ?? 0) > 0;
    const open = foldable && expanded.has(row.id);
    return (
      // The whole row toggles focus (a mouse convenience); the label button
      // below keeps this keyboard-reachable, and the eye/fold buttons stop
      // propagation so they only do their own thing.
      <tr
        key={row.id}
        onClick={(e) => interaction.toggleFocus(row.id, isAdditiveClick(e.nativeEvent))}
        onMouseEnter={() => interaction.setPreview([row.id])}
        onMouseLeave={() => interaction.setPreview(null)}
        className={`cursor-pointer border-b border-surface-stroke/60 transition-colors last:border-b-0 ${
          focused ? "bg-surface-base-muted" : "hover:bg-surface-base-muted/60"
        } ${emphasis === "dimmed" ? "opacity-45" : ""}`}
      >
        <td className="py-1.5">
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation();
              if (e.altKey && !member) interaction.showOnly(row.id, rows.map((r) => r.id));
              else interaction.toggleHidden(row.id);
            }}
            aria-pressed={!hidden}
            aria-label={hidden ? t("Show series") : t("Hide series")}
            title={t("Hide or show · ⌥ / Alt-click: show only this")}
            className="flex size-6 items-center justify-center rounded text-foreground-muted hover:text-foreground-default"
          >
            {hidden ? <EyeSlashFillIcon className="size-4" /> : <EyeFillIcon className="size-4" />}
          </button>
        </td>
        <td className={`py-1.5 pr-3 ${member ? "pl-7" : ""}`}>
          <span className="flex items-center gap-1.5">
            {foldable ? (
              <button
                type="button"
                onClick={(e) => {
                  e.stopPropagation();
                  toggleExpanded(row.id);
                }}
                aria-expanded={open}
                aria-label={open ? t("Collapse row") : t("Expand row")}
                className="flex size-5 shrink-0 items-center justify-center rounded text-foreground-muted hover:text-foreground-default"
              >
                <ChevronRightIcon className={`size-3 transition-transform ${open ? "rotate-90" : ""}`} />
              </button>
            ) : !member && hasFoldableRows ? (
              // Keeps unfoldable rows aligned with the folded ones.
              <span aria-hidden="true" className="size-5 shrink-0" />
            ) : null}
            <button
              type="button"
              onClick={(e) => {
                e.stopPropagation();
                interaction.toggleFocus(row.id, isAdditiveClick(e.nativeEvent));
              }}
              aria-pressed={focused}
              className="flex items-center gap-2 text-left"
            >
              {row.rank != null ? (
                <span className="body-small w-5 shrink-0 tabular-nums text-foreground-more-muted">
                  {row.rank}
                </span>
              ) : null}
              <span
                aria-hidden="true"
                className="size-2.5 shrink-0 rounded-full"
                style={{ backgroundColor: swatchColor(seriesColor(interaction, row.color, emphasis, row.id), emphasis) }}
              />
              <span
                className={`body-small ${
                  hidden
                    ? "text-foreground-more-muted line-through"
                    : member
                      ? "text-foreground-muted"
                      : "text-foreground-default"
                }`}
              >
                {row.label}
              </span>
            </button>
          </span>
        </td>
        {row.stats
          .filter((stat) => columnKeys.has(stat.key))
          .map((stat) => (
            <td
              key={stat.key}
              className={`py-1.5 pl-3 text-right tabular-nums body-small ${
                stat.tone === "up"
                  ? "text-feedback-success"
                  : stat.tone === "down"
                    ? "text-feedback-warning"
                    : "text-foreground-muted"
              }`}
            >
              {stat.spark ? (
                <span className="inline-flex justify-end">
                  <Sparkline
                    points={stat.spark}
                    color={swatchColor(seriesColor(interaction, row.color, emphasis, row.id), emphasis)}
                    yDomain={sparkYDomain}
                  />
                </span>
              ) : (
                stat.display
              )}
            </td>
          ))}
        {hasLinks ? (
          <td className="w-8 py-1.5 pl-2">
            {row.links ? (
              // The menu is portaled, but React events still bubble to the
              // row: stop them so using the menu doesn't toggle focus.
              <span className="flex justify-end" onClick={(e) => e.stopPropagation()}>
                <ChartLinkRowMenu
                  target={row.links}
                  actions={linkActions?.(row.links)}
                  ariaLabel={t("Links for {name}", { name: row.label })}
                />
              </span>
            ) : null}
          </td>
        ) : null}
      </tr>
    );
  }

  return (
    <div className="mt-4 rounded-xl border border-surface-stroke">
      <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-2 px-4 py-2.5">
        <span className="flex min-w-0 items-baseline gap-2">
          <span className="heading-small shrink-0 text-foreground-default">
            {countLabel ??
              t("{count, plural, one {# series} other {# series}}", {
                count: rows.length,
              })}
          </span>
          {hintText && !collapsed ? (
            <span className="body-small truncate text-foreground-more-muted">
              · {hintText}
            </span>
          ) : null}
          <HiddenCount interaction={interaction} />
        </span>
        <span className="flex items-center gap-3">
          {showSearch && !collapsed ? (
            <input
              type="search"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder={t("Find…")}
              aria-label={t("Find in legend")}
              className="body-small w-36 rounded-full border border-surface-stroke bg-surface-base px-3 py-1 text-foreground-default placeholder:text-foreground-more-muted focus:border-surface-stroke-muted focus:outline-none"
            />
          ) : null}
          {hasDetailColumns && !collapsed ? (
            <button
              type="button"
              onClick={() => setShowStats((v) => !v)}
              aria-pressed={showStats}
              className="body-small text-foreground-muted transition-colors hover:text-foreground-default"
            >
              {showStats ? t("Hide statistics") : t("Show statistics")}
            </button>
          ) : null}
          {onBackToPanel ? (
            <button
              type="button"
              onClick={onBackToPanel}
              className="body-small text-foreground-muted transition-colors hover:text-foreground-default"
            >
              {t("Back beside the chart")}
            </button>
          ) : (
            <button
              type="button"
              onClick={() => setCollapsed((v) => !v)}
              aria-expanded={!collapsed}
              className="group flex items-center gap-1 text-foreground-muted transition-colors hover:text-foreground-default"
            >
              <span className="body-small">
                {collapsed ? t("Show legend") : t("Hide legend")}
              </span>
              <ChevronDownIcon className={`size-3.5 transition-transform ${!collapsed ? "rotate-180" : ""}`} />
            </button>
          )}
        </span>
      </div>
      {collapsed ? null : (
        <>
          <div className="overflow-x-auto border-t border-surface-stroke px-4 pb-3 pt-1">
            <table className="w-full border-collapse text-left">
              <thead>
                <tr className="border-b border-surface-stroke">
                  <th className="w-8 py-1.5" />
                  <th aria-sort={ariaSort("label")} className="py-1.5 pr-3">
                    <SortHeader
                      label={t("Series")}
                      glyph={sortGlyph("label")}
                      onClick={() => toggleSort("label")}
                    />
                  </th>
                  {columns.map((col) =>
                    col.spark ? (
                      <th
                        key={col.key}
                        className="heading-small py-1.5 pl-3 text-right text-foreground-muted"
                      >
                        {col.label}
                      </th>
                    ) : (
                      <th
                        key={col.key}
                        aria-sort={ariaSort(col.key)}
                        className="py-1.5 pl-3 text-right"
                      >
                        <span className="flex items-center justify-end gap-1">
                          <SortHeader
                            label={col.label}
                            glyph={sortGlyph(col.key)}
                            align="right"
                            onClick={() => toggleSort(col.key)}
                          />
                          {col.hint ? (
                            <InfoTooltip label={t("About this column")}>{col.hint}</InfoTooltip>
                          ) : null}
                        </span>
                      </th>
                    ),
                  )}
                  {hasLinks ? <th className="w-8 py-1.5" /> : null}
                </tr>
              </thead>
              <tbody>
                {selection.rows.map((row, index) => (
                  <Fragment key={row.id}>
                    {renderRow(row, false)}
                    {expanded.has(row.id)
                      ? row.children?.map((child) => renderRow(child, true))
                      : null}
                    {selection.splitAfter === index + 1 ? (
                      <tr className="border-b border-surface-stroke/60">
                        <td />
                        <td
                          colSpan={wideColSpan}
                          className="py-1 body-small text-foreground-more-muted"
                        >
                          {t("⋯ {count} in between", { count: selection.leftOut })}
                        </td>
                      </tr>
                    ) : null}
                  </Fragment>
                ))}
                {selection.rows.length === 0 ? (
                  <tr>
                    <td />
                    <td colSpan={wideColSpan} className="py-2 body-small text-foreground-muted">
                      {t("Nothing matches “{query}”", { query: query.trim() })}
                    </td>
                  </tr>
                ) : null}
              </tbody>
            </table>
          </div>
          {canShorten && !query.trim() && (selection.leftOut > 0 || showAll) ? (
            <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-surface-stroke px-4 py-2">
              <button
                type="button"
                onClick={() => setShowAll((v) => !v)}
                className="body-small font-medium text-foreground-default hover:underline"
              >
                {showAll
                  ? t("Show fewer")
                  : t("Show all {count}", { count: rows.length })}
              </button>
              {!showAll ? (
                <span className="body-small text-foreground-more-muted">
                  {sort != null ? t("Top {count} of the sorted column", { count: SHORTLIST_SIZE }) : shortlist?.caption}
                </span>
              ) : null}
            </div>
          ) : null}
        </>
      )}
      {note ? (
        <p className="border-t border-surface-stroke px-4 py-2 body-small text-foreground-muted">
          {note}
        </p>
      ) : null}
    </div>
  );
}

/**
 * The legend in the focus view's side panel: a list that fits its 22rem.
 *   - Open from the start; the header is the count and "Full table".
 *   - Search on its own line, above {@link SEARCH_ABOVE} rows.
 *   - Per row: swatch, name (or `panel.label`) with an optional badge, a detail
 *     line of the other plain stats ({@link panelDetail}), the value (the
 *     `primary` stat, or `panel.value`), the links menu and show/hide at the end.
 *   - The rows the answer names lead ("In the heading"), the rest follow in
 *     the chart's order or its shortlist, with "Show all".
 */
function LegendPanel({
  rows,
  interaction,
  note,
  focusHint,
  shortlist,
  countLabel,
  linkActions,
  leadIds,
  panelValueLabel,
  panelKey,
  panelZeroLine,
  panelFilterOnly = false,
  panelCells = false,
  readout,
  onFullTable,
}: LegendProps & { onFullTable: () => void }) {
  const { t } = useTranslation();
  const hintText = useFocusHintText(focusHint, interaction.focusedId);
  const [query, setQuery] = useState("");
  const [showAll, setShowAll] = useState(false);
  const [expanded, setExpanded] = useState<ReadonlySet<string>>(new Set());
  useFindPreview(query, rows, interaction);

  if (rows.length === 0) return null;

  const primaryOf = (row: SeriesRow) => row.stats.find((stat) => stat.primary);
  const valueLabel = readout?.label ?? panelValueLabel ?? (rows[0] ? primaryOf(rows[0])?.label : undefined);
  const searching = query.trim() !== "";
  const leads = !searching && leadIds?.size ? rows.filter((r) => leadIds.has(r.id)) : [];
  const rest = leads.length ? rows.filter((r) => !leadIds?.has(r.id)) : rows;
  const focusedId = interaction.focusedId;
  const focusedRowId =
    focusedId == null
      ? null
      : (rest.find((r) => r.id === focusedId || r.children?.some((c) => c.id === focusedId))?.id ?? null);
  const selection = selectLegendRows(rest, {
    query,
    showAll,
    sorted: false,
    shortlistIds: shortlist?.ids,
    // With the named rows taken out, a ranked shortlist's gap no longer sits where it says.
    splitAfter: leads.length ? undefined : shortlist?.splitAfter,
    focusedRowId,
  });
  // The zero line only means something on a list without gaps.
  const zeroAt =
    panelZeroLine && selection.leftOut === 0 && selection.splitAfter == null
      ? zeroCrossing(selection.rows.map((r) => primaryOf(r)?.sort ?? 0))
      : null;
  const canShorten = rest.length > SHORTLIST_ABOVE && shortlist != null;
  const asCells = (text: string) =>
    panelCells ? (
      <span className="inline-flex">
        {text.split(" ").map((cell, index) => (
          <span key={index} className="w-8 text-center">
            {cell}
          </span>
        ))}
      </span>
    ) : (
      text
    );

  function toggleExpanded(id: string) {
    setExpanded((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }

  function renderRow(row: SeriesRow, member: boolean) {
    const hidden = interaction.isHidden(row.id);
    const emphasis = interaction.emphasis(row.id);
    const focused = emphasis === "focused";
    const foldable = !member && (row.children?.length ?? 0) > 0;
    const open = foldable && expanded.has(row.id);
    const primary = primaryOf(row);
    const value = readout ? (readout.values.get(row.id) ?? "—") : (row.panel?.value ?? primary?.display);
    const detail = panelFilterOnly ? "" : [row.panel?.detail, panelDetail(row.stats)].filter(Boolean).join(" · ");
    return (
      // The whole row toggles focus (a mouse convenience); the name button keeps
      // it keyboard-reachable, and the other buttons stop propagation.
      <div
        key={row.id}
        onClick={(e) => interaction.toggleFocus(row.id, isAdditiveClick(e.nativeEvent))}
        onMouseEnter={() => interaction.setPreview([row.id])}
        onMouseLeave={() => interaction.setPreview(null)}
        className={`group flex cursor-pointer items-center gap-2 border-b border-surface-stroke/60 py-1.5 pr-2 transition-colors ${
          member ? "pl-9" : "pl-4"
        } ${focused ? "bg-surface-base-muted" : "hover:bg-surface-base-muted/60"} ${emphasis === "dimmed" ? "opacity-45" : ""}`}
      >
        {foldable ? (
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation();
              toggleExpanded(row.id);
            }}
            aria-expanded={open}
            aria-label={open ? t("Collapse row") : t("Expand row")}
            className="-ml-1 flex size-5 shrink-0 items-center justify-center rounded text-foreground-muted hover:text-foreground-default"
          >
            <ChevronRightIcon className={`size-3 transition-transform ${open ? "rotate-90" : ""}`} />
          </button>
        ) : null}
        <button
          type="button"
          onClick={(e) => {
            e.stopPropagation();
            interaction.toggleFocus(row.id, isAdditiveClick(e.nativeEvent));
          }}
          aria-pressed={focused}
          className="flex min-w-0 flex-1 items-center gap-2 text-left"
        >
          <span
            aria-hidden="true"
            className="size-2.5 shrink-0 rounded-full"
            style={{ backgroundColor: swatchColor(seriesColor(interaction, row.color, emphasis, row.id), emphasis) }}
          />
          <span className="min-w-0 flex-1">
            <span className="flex min-w-0 items-center gap-1.5">
              <span
                className={`body-small truncate ${
                  hidden ? "text-foreground-more-muted line-through" : member ? "text-foreground-muted" : "text-foreground-default"
                }`}
              >
                {row.panel?.label ?? row.label}
              </span>
              {row.panel?.badge && !panelFilterOnly ? (
                <span className="body-small shrink-0 rounded-full bg-feedback-warning-surface px-1.5 text-feedback-warning">
                  {row.panel.badge}
                </span>
              ) : null}
            </span>
            {detail ? <span className="body-small block truncate text-foreground-muted">{detail}</span> : null}
          </span>
        </button>
        {!panelFilterOnly && value ? (
          <span
            className={`body-small shrink-0 text-right font-medium tabular-nums ${
              readout
                ? "text-foreground-default"
                : primary?.tone === "up"
                ? "text-feedback-success"
                : primary?.tone === "down"
                  ? "text-feedback-warning"
                  : "text-foreground-default"
            }`}
          >
            {asCells(value)}
          </span>
        ) : null}
        {row.links ? (
          // The menu is portaled, but React events still bubble to the row.
          <span className="flex shrink-0" onClick={(e) => e.stopPropagation()}>
            <ChartLinkRowMenu
              target={row.links}
              actions={linkActions?.(row.links)}
              ariaLabel={t("Links for {name}", { name: row.label })}
            />
          </span>
        ) : null}
        <button
          type="button"
          onClick={(e) => {
            e.stopPropagation();
            if (e.altKey && !member) interaction.showOnly(row.id, rows.map((r) => r.id));
            else interaction.toggleHidden(row.id);
          }}
          aria-pressed={!hidden}
          aria-label={hidden ? t("Show series") : t("Hide series")}
          title={t("Hide or show · ⌥ / Alt-click: show only this")}
          className={`flex size-6 shrink-0 items-center justify-center rounded text-foreground-muted transition-opacity hover:text-foreground-default focus-visible:opacity-100 ${
            hidden ? "" : "opacity-40 group-hover:opacity-100"
          }`}
        >
          {hidden ? <EyeSlashFillIcon className="size-4" /> : <EyeFillIcon className="size-4" />}
        </button>
      </div>
    );
  }

  const withMembers = (row: SeriesRow) => (
    <Fragment key={row.id}>
      {renderRow(row, false)}
      {expanded.has(row.id) ? row.children?.map((child) => renderRow(child, true)) : null}
    </Fragment>
  );
  const sectionLabel = (text: string) => (
    <p className={`${LOOK.eyebrow} px-4 pb-1 pt-2.5`}>{text}</p>
  );

  return (
    // Many lifts' cells (a Correlation over several exercises) can be wider than
    // the side panel: the list then scrolls inside its border, every row at the
    // same width so the cells stay under their codes.
    <div className="mt-4 overflow-x-auto rounded-xl border border-surface-stroke lg:mt-0">
      <div className="min-w-min">
      <div className="flex items-center gap-3 px-4 pb-1.5 pt-2.5">
        <span className="heading-small min-w-0 flex-1 truncate text-foreground-default">
          {countLabel ?? t("{count, plural, one {# series} other {# series}}", { count: rows.length })}
        </span>
        <HiddenCount interaction={interaction} />
        {panelFilterOnly ? null : (
          <button
            type="button"
            onClick={onFullTable}
            className="body-small shrink-0 font-medium text-foreground-default hover:underline"
          >
            {t("Full table")}
          </button>
        )}
      </div>
      {rows.length > SEARCH_ABOVE ? (
        <div className="px-4 pb-2">
          <input
            type="search"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder={t("Find…")}
            aria-label={t("Find in legend")}
            className="body-small w-full rounded-full border border-surface-stroke bg-surface-base px-3 py-1 text-foreground-default placeholder:text-foreground-more-muted focus:border-surface-stroke-muted focus:outline-none"
          />
        </div>
      ) : null}
      {!panelFilterOnly && valueLabel ? (
        // Right edge in line with the values, which sit before the eye (and the links menu when rows have one).
        <p
          className={`body-small border-b border-surface-stroke pb-1 pl-4 text-right text-foreground-muted ${
            rows.some((r) => r.links) ? "pr-[4.5rem]" : "pr-10"
          }`}
        >
          {asCells(valueLabel)}
        </p>
      ) : null}
      {leads.length ? (
        <>
          {sectionLabel(t("In the heading"))}
          {leads.map(withMembers)}
          {selection.rows.length ? sectionLabel(t("The rest")) : null}
        </>
      ) : null}
      {selection.rows.map((row, index) => (
        <Fragment key={row.id}>
          {zeroAt === index && panelZeroLine ? (
            <p className="body-small flex items-center gap-2 px-4 py-1 text-foreground-muted before:flex-1 before:border-t before:border-dashed before:border-surface-stroke-muted after:flex-1 after:border-t after:border-dashed after:border-surface-stroke-muted">
              {panelZeroLine}
            </p>
          ) : null}
          {withMembers(row)}
          {selection.splitAfter === index + 1 ? (
            <p className="body-small border-b border-surface-stroke/60 py-1 pl-9 text-foreground-more-muted">
              {t("⋯ {count} in between", { count: selection.leftOut })}
            </p>
          ) : null}
        </Fragment>
      ))}
      {searching && selection.rows.length === 0 ? (
        <p className="body-small px-4 py-2 text-foreground-muted">
          {t("Nothing matches “{query}”", { query: query.trim() })}
        </p>
      ) : null}
      {canShorten && !searching && (selection.leftOut > 0 || showAll) ? (
        <div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-2">
          <button
            type="button"
            onClick={() => setShowAll((v) => !v)}
            className="body-small font-medium text-foreground-default hover:underline"
          >
            {showAll ? t("Show fewer") : t("Show all {count}", { count: rows.length })}
          </button>
          {!showAll ? <span className="body-small text-foreground-more-muted">{shortlist?.caption}</span> : null}
        </div>
      ) : null}
      {hintText ? <p className="body-small px-4 py-2 text-foreground-more-muted">{hintText}</p> : null}
      {panelKey ? <p className="body-small border-t border-surface-stroke px-4 py-2 text-foreground-muted">{panelKey}</p> : null}
      {note ? <p className="body-small border-t border-surface-stroke px-4 py-2 text-foreground-muted">{note}</p> : null}
      </div>
    </div>
  );
}

/**
 * A tiny inline trend line. Plots the {x,y} points honouring their x positions
 * (so gaps show, exactly like a chart overlay drawn from the same points), with
 * straight segments between the (already-smoothed, dense) points.
 */
/** A series as a small line, e.g. in a legend cell or the Trend matrix's cell popover. */
export function Sparkline({
  points,
  color,
  yDomain,
}: {
  points: { x: number; y: number }[];
  color: string;
  /** Shared y-range (e.g. the chart's axis) so the sparkline matches its shape. */
  yDomain?: [number, number];
}) {
  const finite = points.filter((p) => Number.isFinite(p.x) && Number.isFinite(p.y));
  if (finite.length < 2) return null;
  const width = 84;
  const height = 22;
  const pad = 2;
  const xs = finite.map((p) => p.x);
  const ys = finite.map((p) => p.y);
  const xMin = Math.min(...xs);
  const xRange = Math.max(...xs) - xMin || 1;
  const yMin = yDomain ? yDomain[0] : Math.min(...ys);
  const yMax = yDomain ? yDomain[1] : Math.max(...ys);
  const yRange = yMax - yMin || 1;
  const path = finite
    .map((p) => {
      const x = pad + ((p.x - xMin) / xRange) * (width - 2 * pad);
      const y = height - pad - ((p.y - yMin) / yRange) * (height - 2 * pad);
      return `${x.toFixed(1)},${y.toFixed(1)}`;
    })
    .join(" ");
  return (
    <svg
      width={width}
      height={height}
      viewBox={`0 0 ${width} ${height}`}
      fill="none"
      aria-hidden="true"
    >
      <polyline
        points={path}
        stroke={color}
        strokeWidth={1.5}
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function SortHeader({
  label,
  glyph,
  align = "left",
  onClick,
}: {
  label: string;
  glyph: string;
  align?: "left" | "right";
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`heading-small text-foreground-muted hover:text-foreground-default ${
        align === "right" ? "ml-auto block" : ""
      }`}
    >
      {label}
      <span aria-hidden="true">{glyph}</span>
    </button>
  );
}

