"use client";

import { useRef, useState, type ReactNode } from "react";
import { Scatter } from "react-chartjs-2";
import type { Chart, ChartData, ChartDataset, ChartOptions, Plugin } from "chart.js";
import type { ChartConfig, ChartReturn } from "@enode/core/api/dtos/charts";
import { useTranslation } from "@enode/core/translations/hooks";
import { useUnits } from "@enode/core/use-units";
import { ChartShell } from "./chart-shell";
import { ChartExportMenu } from "./chart-export-menu";
import { useReportFrame } from "./report-frame";
import { loadRangeText, type ChartReport, type ReportTable } from "./report-model";
import {
  ChartHeader,
  LoadsMixedChip,
  UsualLoadChip,
  useChartControls,
  useChartSubject,
  useStandardFacets,
} from "./chart-header";
import { distinctLoads, loadCoverage, loadPointRadius, matchesLoad, mostUsedLoad } from "./chart-controls";
import {
  ChartLegendTable,
  emphasisDrawOrder,
  emphasizeColor,
  plotClick,
  seriesColor,
  seriesIdAtEvent,
  type SeriesRow,
  type SeriesStat,
  useSeriesInteraction,
  withHighlight,
  withMetricShades,
} from "./chart-legend";
import { useChartLinkDrawers } from "./chart-link-drawers";
import {
  spotlightMatches,
  useChartActions,
  useChartAnswerHeading,
  useChartSpotlight,
  useNameLinks,
  selectionOf,
  withNamedEmphasis,
  withSpotlightFocus,
  type ActionTarget,
} from "./chart-card-actions";
import { ChartTileHeader, ChartTileKeys, useChartFocus, useChartTile } from "./chart-tile-context";
import { asThumbnailOptions, THUMB_PLOT_CLASS, TILE_CORRELATION_PANELS, TILE_PLOT_CLASS } from "./chart-tile-model";
import { linkStrength, MIN_LINK_POINTS } from "./chart-stats";
import {
  betweenAthletesLink,
  linkMark,
  strongestLinkedAthletes,
  withinAthleteSummary,
} from "./correlation-model";
import { distanceToSegment } from "./distribution-model";
import { groupInOrder, isCrowded, liftCodes, pickLargest } from "./legend-model";
import {
  chartFont,
  ensureChartsRegistered,
  formatValue,
  linearRegression,
  metricSeriesColor,
  metricShade,
  useChartTheme,
  withAlpha,
} from "./chart-setup";
import { configDisplayBaseIDs, useMetricHue } from "./metric-hue";

ensureChartsRegistered();

// `_key` is unique per dataset (an athlete's dots and fit line share a label),
// so react-chartjs-2 updates each in place instead of drawing it in again.
type ScatterDataset = ChartDataset<"scatter"> & {
  _fit?: boolean;
  _seriesId?: string;
  _key?: string;
  /** Dots drawn half and half: [upper-left, lower-right] colours (see `splitDots`). */
  _split?: [string, string];
};

// A highlighted athlete's dots in both metrics' colours (insights feedback G7),
// split on the diagonal from north-east to south-west: the upper-left half the
// vertical metric's, the lower-right half the horizontal one's, in the order
// the heading names them ("Peak power vs Peak force"). Chart.js
// draws those datasets' points transparent (so hover and hit-testing still
// work); this paints the two halves over them at the same radius.
const splitDots: Plugin<"scatter"> = {
  id: "correlationSplitDots",
  afterDatasetDraw(chart, args) {
    const split = (chart.data.datasets[args.index] as ScatterDataset)._split;
    if (!split || !chart.isDatasetVisible(args.index)) return;
    const ctx = chart.ctx;
    ctx.save();
    for (const point of args.meta.data) {
      if ((point as { skip?: boolean }).skip) continue;
      const radius = (point.options as { radius?: number }).radius ?? 4;
      const { x, y } = point.getProps(["x", "y"], true) as { x: number; y: number };
      // Canvas angles run clockwise from east: south-west is 3π/4, north-east 7π/4.
      ctx.beginPath();
      ctx.arc(x, y, radius, (3 * Math.PI) / 4, (7 * Math.PI) / 4);
      ctx.closePath();
      ctx.fillStyle = split[0];
      ctx.fill();
      ctx.beginPath();
      ctx.arc(x, y, radius, -Math.PI / 4, (3 * Math.PI) / 4);
      ctx.closePath();
      ctx.fillStyle = split[1];
      ctx.fill();
    }
    ctx.restore();
  },
};
type CorrelationPoint = { x: number; y: number; load: number | null };

// XY scatter of two metrics, one series per (athlete × exercise) with a
// least-squares fit line through each. Each exercise gets its own panel (side
// by side when there are several), so a lift is never mixed with another and
// every panel shows at rest. Athlete drives colour, consistently across panels.
// Above each panel one sentence answers the question in plain words — for how
// many athletes the two metrics moved together, and, with enough athletes,
// whether athletes who score higher on one also score higher on the other.
// A link gets a verdict only from 10 sessions; fewer is said in the legend and
// drawn as a faint dashed line. The load picker opens on each series' usual
// load (a load-driven link is otherwise easy to mistake for a real one);
// "All loads" sizes dots by load and flags the mix. The legend has one row per
// athlete — with several exercises, one verdict column per exercise — and
// drives hide / focus across all panels. With many athletes (insights 8.2) the
// points and lines turn grey and only a focused athlete keeps their colour.
// A legend row's "⋯" menu links out to the athlete, their velocity profile and
// their sessions (insights 10); a point click only focuses.
/** The fit line within 8 px of the pointer: its series and the nearest point on it (canvas px), or null. */
function fitLineAt(chart: Chart, native: MouseEvent): { seriesId: string; x: number; y: number } | null {
  const rect = chart.canvas.getBoundingClientRect();
  const px = native.clientX - rect.left;
  const py = native.clientY - rect.top;
  let best: { seriesId: string; x: number; y: number; distance: number } | null = null;
  chart.data.datasets.forEach((dataset, index) => {
    const tagged = dataset as ScatterDataset;
    if (!tagged._fit || !tagged._seriesId || !chart.isDatasetVisible(index)) return;
    const [a, b] = chart.getDatasetMeta(index).data;
    if (!a || !b) return;
    const distance = distanceToSegment(px, py, a, b);
    if (distance > 8 || (best && distance >= best.distance)) return;
    best = { seriesId: tagged._seriesId, x: px, y: py, distance };
  });
  return best;
}

export function CorrelationChart({
  item,
  emptyTitle,
  emptyDetail,
  emptyAction,
  actions,
}: {
  item: ChartReturn<"correlation">;
  emptyTitle: string;
  emptyDetail: string;
  /** A control under the empty state, e.g. Try again on a chart that couldn't be built. */
  emptyAction?: ReactNode;
  actions?: ReactNode;
}) {
  const { t } = useTranslation();
  const theme = useChartTheme();
  const loadUnit = useUnits().symbol("mass");
  const baseInteraction = useSeriesInteraction();
  const controls = useChartControls();
  // "Usual load" is the default; picking "All loads" or a load turns it off.
  const [usualLoad, setUsualLoad] = useState(true);
  // One chart per lift panel, by lift (not by position): react-chartjs-2 hands
  // a panel's chart to the ref it had when it mounted, so a panel that moves
  // (one lift shown alone) must stay findable under the same key.
  const panelCharts = useRef(new Map<string, Chart<"scatter">>());
  // The legend's "Open athlete" / "Velocity profile" open their drawers here.
  const linkDrawers = useChartLinkDrawers();
  const spot = useChartSpotlight();
  // An athlete's actions: the chip while focused, right-click, long-press.
  const chartActions = useChartActions(linkDrawers.actionsFor);

  const athletes = item.data?.athletes ?? [];
  const exercises = item.data?.exercises ?? [];
  const series = item.data?.series ?? [];
  const xMeta = item.data?.xMetric;
  const yMeta = item.data?.yMetric;
  const config: ChartConfig = item.chartConfigDto ?? {};
  // Athletes are shades of the vertical metric's colour (insights feedback G7,
  // option 1): the y axis is the outcome the chart asks about.
  const metricHue = useMetricHue(configDisplayBaseIDs(config)[1], yMeta?.id);
  // The horizontal metric's colour, for its name in the kicker.
  const xMetricHue = useMetricHue(configDisplayBaseIDs(config)[0], xMeta?.id);
  // The chart's heading: the user's title if set, else the server-generated name.
  const chartTitle = config.title || item.data?.chartName;
  const chartNote = config.note?.trim() || undefined;

  const loadOptions = distinctLoads(
    series.flatMap((s) => (s.points ?? []).map((p) => p.load)),
  );
  // Per load, how many of the chart's athletes have a session at it.
  const loadCoverageCounts = loadCoverage(
    series.flatMap((s) => (s.points ?? []).map((p) => ({ athleteID: s.athleteID, load: p.load }))),
  );
  const offerUsualLoad = loadOptions.length > 0;
  const onUsualLoad = offerUsualLoad && usualLoad;
  // The answer at the shown load (the focus view's heading), and the athletes
  // it names ("Name", or "Name (Lift)" with several lifts).
  const answer = useChartAnswerHeading(item, { type: "correlation", usualLoad: onUsualLoad, load: controls.load });
  const named = answer.named;
  const withLoadUnit = (load: number) =>
    `${formatValue(load, 2)}${loadUnit ? ` ${loadUnit}` : ""}`;

  // One series per (athlete × exercise) with points under the active load:
  // its usual load, one picked load, or all of them.
  const athleteIndex = new Map(athletes.map((a, index) => [a.id, index]));
  const built = series.flatMap((s) => {
    const athlete = athletes.find((a) => a.id === s.athleteID);
    const exercise = exercises.find((e) => e.id === s.exerciseID);
    const raw = s.points ?? [];
    const usual = onUsualLoad ? mostUsedLoad(raw.map((p) => p.load)) : null;
    const points: CorrelationPoint[] = raw
      .filter((p) =>
        onUsualLoad ? usual == null || p.load === usual : matchesLoad(p.load, controls.load),
      )
      .map((p) => ({ x: p.x, y: p.y, load: p.load }))
      .filter((p) => Number.isFinite(p.x) && Number.isFinite(p.y));
    if (points.length === 0) return [];
    const fit = linearRegression(points);
    return [
      {
        id: `${s.athleteID}:${s.exerciseID}`,
        athleteID: s.athleteID,
        // Series without an exercise (athlete-level metrics) share one panel.
        panelKey: s.exerciseID ?? "",
        athleteLabel: athlete?.label ?? "",
        exerciseLabel: exercise?.label ?? "",
        label:
          athlete && exercise
            ? `${athlete.label} · ${exercise.label}`
            : (athlete?.label ?? exercise?.label ?? ""),
        // Colour follows the athlete, so they read the same in every panel.
        color: metricSeriesColor(metricHue, athlete, theme.dark, athleteIndex.get(s.athleteID) ?? 0),
        points,
        fit,
        r: fit ? (fit.slope < 0 ? -1 : 1) * Math.sqrt(fit.r2) : 0,
        usualLoad: usual,
        enough: points.length >= MIN_LINK_POINTS,
      },
    ];
  });
  type Built = (typeof built)[number];

  // Panels: one per exercise, the one with the most sessions first.
  const sessionsByPanel = new Map<string, number>();
  for (const b of built) {
    sessionsByPanel.set(b.panelKey, (sessionsByPanel.get(b.panelKey) ?? 0) + b.points.length);
  }
  const panelKeys = [...sessionsByPanel.entries()]
    .sort((a, b) => b[1] - a[1])
    .map(([key]) => key);
  // A board tile (layout L) shows the lifts with the most sessions side by side
  // and counts the rest; the panel sentences move into its answer.
  const tile = useChartTile();
  // A thumbnail (the focus view's strip): the tile's picture alone.
  const thumb = tile?.thumbnail === true;
  // The focus view: a single panel fills the screen's height.
  const focus = useChartFocus();
  // One lift alone, at full size (the focus view; a lift's name picks it).
  const [soloPanel, setSoloPanel] = useState<string | null>(null);
  const solo = !tile && soloPanel != null && panelKeys.includes(soloPanel) ? soloPanel : null;
  const shownPanels = tile ? panelKeys.slice(0, TILE_CORRELATION_PANELS) : solo != null ? [solo] : panelKeys;
  const foldedPanels = panelKeys.length - shownPanels.length;
  // Several lifts in the chart (the legend keeps a mark per lift even while one is shown alone).
  const multiLift = (tile ? shownPanels.length : panelKeys.length) > 1;
  // Several panels on screen (the layout).
  const multiPanel = shownPanels.length > 1;
  // A fit line under the pointer: its athlete's link in words, by the line.
  const [fitTip, setFitTip] = useState<{ panel: string; x: number; y: number; text: string } | null>(null);
  // The athlete the pointer last previewed, so a move over the same one doesn't re-render.
  const previewedRef = useRef<string | null>(null);
  const panelName = (key: string) =>
    exercises.find((e) => e.id === key)?.label ?? "";

  // The link in words (insights 7a): r and R² stay behind "Show statistics".
  // Literal t() per variant so each string stays extractable.
  function linkWords(b: Built): string {
    if (!b.enough) {
      return t("Too few sessions ({count} of {needed})", {
        count: b.points.length,
        needed: MIN_LINK_POINTS,
      });
    }
    const link = linkStrength(b.r, b.points.length);
    if (!link) return "—";
    if (link.strength === "weak") return t("Weak");
    if (link.strength === "moderate") {
      return link.opposite ? t("Moderate, opposite direction") : t("Moderate");
    }
    return link.opposite ? t("Strong, opposite direction") : t("Strong");
  }
  // Too few sessions sort below every real verdict.
  const linkSort = (b: Built) => (b.enough ? Math.abs(b.r) : -1);

  // One legend row per athlete; their series are its members, so hiding or
  // focusing the row acts on that athlete in every panel.
  const athleteGroups = groupInOrder(built, (b) => b.athleteID);
  const athleteOfSeries = new Map(built.map((b) => [b.id, b.athleteID]));
  const linkColumns = (members: Built[]): SeriesStat[] => {
    if (multiLift) {
      return panelKeys.map((key) => {
        const member = members.find((m) => m.panelKey === key);
        return {
          key: `link:${key}`,
          label: panelName(key),
          display: member ? linkWords(member) : "—",
          sort: member ? linkSort(member) : -2,
          // The side panel shows every lift as one mark instead (see `panelMarks`).
          panel: "omit" as const,
        };
      });
    }
    const only = members[0];
    return [
      { key: "link", label: t("How closely linked"), display: linkWords(only), sort: linkSort(only), primary: true },
      ...(onUsualLoad
        ? [
            {
              key: "load",
              label: t("Load"),
              display: only.usualLoad != null ? withLoadUnit(only.usualLoad) : "—",
              sort: only.usualLoad ?? 0,
            },
          ]
        : []),
      { key: "r", label: t("r"), display: only.enough ? formatValue(only.r, 2) : "—", sort: only.r, secondary: true },
      {
        key: "r2",
        label: t("R²"),
        display: only.enough ? formatValue(only.fit?.r2 ?? 0, 2) : "—",
        sort: only.fit?.r2 ?? 0,
        secondary: true,
      },
    ];
  };
  // Side panel, several lifts: one mark per lift, in panel order (too narrow for a word each).
  const panelCodes = liftCodes(panelKeys.map(panelName));
  const panelMarks = (members: Built[]) =>
    panelKeys
      .map((key) => {
        const member = members.find((m) => m.panelKey === key);
        return member ? linkMark(member.r, member.points.length) : "–";
      })
      .join(" ");
  const legendRows: SeriesRow[] = athleteGroups
    .map(({ key: athleteID, members }) => {
      const sessions = members.reduce((sum, m) => sum + m.points.length, 0);
      return {
        id: athleteID,
        label: members[0].athleteLabel,
        color: members[0].color,
        links: {
          athleteID,
          athleteName: members[0].athleteLabel,
          exerciseID: multiLift ? undefined : (members[0].panelKey || undefined),
          exerciseName: multiLift ? undefined : members[0].exerciseLabel,
        },
        stats: [
          { key: "n", label: t("Sessions"), display: formatValue(sessions, 0), sort: sessions },
          ...linkColumns(members),
        ],
        panel: multiLift ? { value: panelMarks(members) } : undefined,
      };
    })
    // Most data first: a link drawn through a handful of points means little.
    .sort((a, b) => b.stats[0].sort - a.stats[0].sort);
  const shortlist = {
    ids: pickLargest(legendRows.map((row) => ({ id: row.id, value: row.stats[0].sort }))),
    caption: t("Most sessions first"),
  };

  // Crowded: grey everyone except the athletes whose two metrics move together
  // most clearly (their legend row and every one of their series keep colour),
  // so the plot opens on the answer instead of a grey cloud.
  const crowded = isCrowded(athleteGroups.length);
  const highlightIds = new Set<string>();
  if (crowded) {
    const linked = strongestLinkedAthletes(
      athleteGroups.map(({ key, members }) => ({
        id: key,
        series: members.map((m) => ({ r: m.r, sessions: m.points.length })),
      })),
    );
    for (const athleteID of linked) {
      highlightIds.add(athleteID);
      for (const b of built) if (b.athleteID === athleteID) highlightIds.add(b.id);
    }
  }
  // The board's spotlit athlete counts as focused (in every panel) while
  // nothing else is.
  const spotlitAthlete =
    athleteGroups.find(({ key, members }) =>
      spotlightMatches(spot?.spotlight ?? null, { athleteID: key, athleteName: members[0].athleteLabel }),
    )?.key ?? null;
  const namedIds = new Set<string>();
  if (named) {
    for (const b of built) {
      if (!named.has(b.athleteLabel) && !named.has(`${b.athleteLabel} (${b.exerciseLabel})`)) continue;
      namedIds.add(b.id);
      namedIds.add(b.athleteID);
    }
  }
  // Grey by default; colour (metric shades) only for what's highlighted.
  const athleteOf = (id: string) => athleteOfSeries.get(id) ?? null;
  const interaction = withMetricShades(
    withNamedEmphasis(
      withHighlight(withSpotlightFocus(baseInteraction, spotlitAthlete, theme.accent), {
        crowded: true,
        highlightIds,
        groupOf: athleteOf,
      }),
      namedIds,
    ),
    {
      hue: metricHue,
      dark: theme.dark,
      rowIds: athleteGroups.map(({ key }) => key),
      seriesIds: built.map((b) => b.id),
      athleteOf: (id) => athleteOf(id) ?? id,
      groupOf: athleteOf,
    },
  );
  // Names in the answer, linked to their athlete in every lift.
  useNameLinks(interaction, athleteGroups.map(({ key, members }) => ({ id: key, names: [members[0].athleteLabel] })));
  // A click on a point focuses its athlete (in every panel), not one series;
  // a click on the focused athlete releases them (on a tile: opens the focus
  // view on them). The selection card then holds the actions.
  const athleteFocusOnClick: NonNullable<ChartOptions<"scatter">["onClick"]> = (event, _elements, chart) => {
    const native = event.native;
    if (!native) return;
    const id = seriesIdAtEvent(chart, native);
    plotClick(id == null ? null : (athleteOfSeries.get(id) ?? id), native, interaction, tile);
  };
  const comparison = selectionOf(
    interaction,
    (id) => built.find((b) => b.athleteID === id)?.athleteLabel ?? id,
    athleteGroups.map(({ key }) => key),
  );
  // “Reset view”: the load the chart opens on (each athlete's usual load), every lift.
  const viewChanged = controls.load !== "all" || (offerUsualLoad && !usualLoad) || solo != null;
  const resetView = () => {
    controls.setLoad("all");
    setUsualLoad(true);
    setSoloPanel(null);
  };

  // Hovering a point lights that athlete in every lift and in the legend (a
  // preview, not a focus). In the focus view, hovering an athlete's fit line
  // says their link in words by the line.
  function onPanelHover(key: string, native: MouseEvent | null) {
    const chart = panelCharts.current.get(key);
    let athlete: string | null = null;
    let tip: typeof fitTip = null;
    if (chart && native) {
      const hits = chart.getElementsAtEventForMode(native, "nearest", { intersect: true }, false);
      const seriesId = hits.length ? (chart.data.datasets[hits[0].datasetIndex] as ScatterDataset | undefined)?._seriesId : undefined;
      athlete = seriesId ? (athleteOfSeries.get(seriesId) ?? null) : null;
      if (!athlete && !tile) {
        const fit = fitLineAt(chart, native);
        const b = fit ? built.find((candidate) => candidate.id === fit.seriesId) : undefined;
        if (fit && b) {
          athlete = b.athleteID;
          tip = {
            panel: key,
            x: fit.x,
            y: fit.y,
            text: `${b.athleteLabel} · ${linkWords(b)} · ${t("{count, plural, one {# session} other {# sessions}}", { count: b.points.length })}`,
          };
        }
      }
    }
    if (athlete !== previewedRef.current) {
      previewedRef.current = athlete;
      interaction.setPreview(athlete ? [athlete] : null);
    }
    if (tip?.text !== fitTip?.text || tip?.panel !== fitTip?.panel) setFitTip(tip);
  }
  const athleteTarget = (b: Built): ActionTarget => ({
    title: b.athleteLabel,
    target: { athleteID: b.athleteID, athleteName: b.athleteLabel, exerciseID: b.panelKey || null },
  });
  const focusedSeries = built.find((b) => b.athleteID === interaction.focusedId);
  const focusedTarget = focusedSeries ? athleteTarget(focusedSeries) : null;
  // The athlete under a right-click / long-press in one panel.
  const panelTargetAt = (key: string) => (event: MouseEvent): ActionTarget | null => {
    const chart = panelCharts.current.get(key);
    const id = chart ? seriesIdAtEvent(chart, event) : null;
    const b = id ? built.find((s) => s.id === id) : undefined;
    return b ? athleteTarget(b) : null;
  };

  // "All loads" with more than one load on the plot: dots are sized by load and
  // the header flags the mix.
  const plottedLoads = distinctLoads(built.flatMap((b) => b.points.map((p) => p.load)));
  const loadsMixed = !onUsualLoad && controls.load === "all" && plottedLoads.length > 1;

  // Both halves of a highlighted athlete's dots, in the same shade step for
  // both metrics (`withMetricShades`' rule), or null to draw them in one colour
  // (grey, the spotlight's, or while a metric colour is unknown).
  const splitOf = (b: Built): [string, string] | null => {
    const emphasis = interaction.emphasis(b.id);
    if (emphasis !== "normal" && emphasis !== "focused") return null;
    const tone = interaction.shadeTone?.(b.id);
    if (!tone || !metricHue || !xMetricHue) return null;
    if (interaction.spotlightColor && emphasis === "focused") return null;
    return [metricShade(metricHue, theme.dark, tone), metricShade(xMetricHue, theme.dark, tone)];
  };

  function panelDatasets(members: Built[]): ScatterDataset[] {
    const datasets: ScatterDataset[] = [];
    for (const b of members) {
      const emphasis = interaction.emphasis(b.id);
      const hidden = interaction.isHidden(b.id);
      const split = splitOf(b);
      datasets.push({
        label: b.label,
        _seriesId: b.id,
        _key: `${b.id}:points`,
        _split: split ?? undefined,
        hidden,
        data: b.points,
        backgroundColor: split ? "transparent" : emphasizeColor(seriesColor(interaction, b.color, emphasis, b.id), emphasis),
        borderColor: split ? "transparent" : emphasizeColor(seriesColor(interaction, b.color, emphasis, b.id), emphasis),
        pointRadius: loadsMixed
          ? b.points.map((p) => loadPointRadius(p.load, plottedLoads) ?? 4)
          : 4,
        pointHoverRadius: 6,
        showLine: false,
        order: emphasisDrawOrder(emphasis),
      });
      if (!b.fit || b.points.length < 2) continue;
      // Each athlete keeps their own line (a line through everyone would show
      // how athletes differ, not how one athlete responds). Too few sessions:
      // faint and dashed. Crowded: thin grey unless focused.
      const thin = crowded && emphasis !== "focused";
      const alpha = b.enough ? 0.9 : 0.45;
      const xs = b.points.map((p) => p.x);
      const min = Math.min(...xs);
      const max = Math.max(...xs);
      datasets.push({
        label: b.label,
        _seriesId: b.id,
        _key: `${b.id}:fit`,
        _fit: true,
        hidden,
        data: [
          { x: min, y: b.fit.intercept + b.fit.slope * min },
          { x: max, y: b.fit.intercept + b.fit.slope * max },
        ],
        // Two-coloured dots get a neutral line: it belongs to neither metric.
        borderColor: split ? withAlpha(theme.muted, alpha) : emphasizeColor(seriesColor(interaction, b.color, emphasis, b.id), emphasis, alpha),
        backgroundColor: split ? withAlpha(theme.muted, alpha) : emphasizeColor(seriesColor(interaction, b.color, emphasis, b.id), emphasis, alpha),
        borderWidth: thin ? 1 : 1.8,
        borderDash: b.enough ? undefined : [4, 3],
        pointRadius: 0,
        pointHoverRadius: 0,
        showLine: true,
        fill: false,
        order: emphasis === "focused" ? 0 : 1,
      });
    }
    return datasets;
  }

  const xLabel = xMeta?.label ?? "x";
  const yLabel = yMeta?.label ?? "y";

  // The panel's answer in words, from the athletes visible in it.
  function panelSentences(members: Built[]): { within: string; between: string | null } {
    const visible = members.filter((b) => !interaction.isHidden(b.id));
    const summary = withinAthleteSummary(
      visible.map((b) => ({ r: b.r, sessions: b.points.length })),
    );
    let within: string;
    if (summary.eligible === 0) {
      within = t(
        "Not enough sessions yet to say whether {x} and {y} move together (an athlete needs {needed}).",
        { x: xLabel, y: yLabel, needed: MIN_LINK_POINTS },
      );
    } else if (summary.same === 0 && summary.opposite === 0) {
      within = t(
        "For none of the {total, plural, one {# athlete} other {# athletes}} with enough sessions did {x} and {y} clearly move together.",
        { total: summary.eligible, x: xLabel, y: yLabel },
      );
    } else if (summary.same >= summary.opposite) {
      within = t(
        "For {count} of {total, plural, one {# athlete} other {# athletes}} with enough sessions, higher {x} went with higher {y}.",
        { count: summary.same, total: summary.eligible, x: xLabel, y: yLabel },
      );
    } else {
      within = t(
        "For {count} of {total, plural, one {# athlete} other {# athletes}} with enough sessions, higher {x} went with lower {y}.",
        { count: summary.opposite, total: summary.eligible, x: xLabel, y: yLabel },
      );
    }
    const means = groupInOrder(visible, (b) => b.athleteID).map(({ members: own }) => {
      const pts = own.flatMap((m) => m.points);
      return {
        x: pts.reduce((s, p) => s + p.x, 0) / pts.length,
        y: pts.reduce((s, p) => s + p.y, 0) / pts.length,
      };
    });
    const across = betweenAthletesLink(means);
    const between =
      across === "same"
        ? t("Across athletes, those with higher {x} also had higher {y}.", { x: xLabel, y: yLabel })
        : across === "opposite"
          ? t("Across athletes, those with higher {x} had lower {y}.", { x: xLabel, y: yLabel })
          : null;
    return { within, between };
  }

  const isEmpty = item.isEmpty || legendRows.length === 0;

  const xTitle = xMeta?.unit ? `${xMeta.label} (${xMeta.unit})` : (xMeta?.label ?? "");
  const yTitle = yMeta?.unit ? `${yMeta.label} (${yMeta.unit})` : (yMeta?.label ?? "");

  const metricLabel = xMeta && yMeta ? `${yMeta.label} / ${xMeta.label}` : undefined;
  const facets = useStandardFacets(config, metricLabel, exercises.map((e) => e.label));
  // What the chart is about, around its answer: both metrics in the kicker.
  const subject = useChartSubject(config, {
    topic: xMeta && yMeta ? t("{y} vs {x}", { y: yMeta.label, x: xMeta.label }) : t("Correlation"),
    topicTints: [
      ...(yMeta && metricHue ? [{ text: yMeta.label, color: metricHue }] : []),
      ...(xMeta && xMetricHue ? [{ text: xMeta.label, color: xMetricHue }] : []),
    ],
    exerciseNames: exercises.map((e) => e.label),
    reading: { basis: "session", aggregation: null, load: offerUsualLoad ? (onUsualLoad ? "usual" : controls.load) : null },
  });

  // The export: the file is named after the coach's title or the metrics; the
  // CSV is the legend (with r and R²); the report is built on click.
  const exportTitle = chartTitle || metricLabel || t("Correlation");
  const reportFrame = useReportFrame();

  // The report: every lift side by side on one page (drawn for print, so a
  // lift shown alone on screen doesn't hide the others), then one athlete
  // table: the link in words and the load behind each athlete's sessions.
  function buildReport(): ChartReport | null {
    const visible = athleteGroups.filter(({ key }) => !interaction.isHidden(key));
    if (visible.length === 0) return null;
    const visibleIds = new Set(visible.map(({ key }) => key));
    const picked = visible.filter(({ key }) => interaction.focusedIds.has(key));
    const leadIds = new Set(
      (picked.length ? picked : visible.filter(({ members }) => named?.has(members[0].athleteLabel))).map(({ key }) => key),
    );
    // Reports are light only, whatever the app's theme.
    const colorOf = (athleteID: string) =>
      metricSeriesColor(metricHue, athletes.find((a) => a.id === athleteID), false, athleteIndex.get(athleteID) ?? 0);
    const loadOf = (b: Built): string | null =>
      onUsualLoad
        ? b.usualLoad != null
          ? withLoadUnit(b.usualLoad)
          : null
        : controls.load !== "all"
          ? withLoadUnit(Number(controls.load))
          : loadRangeText(b.points.map((p) => p.load), withLoadUnit, (load) => formatValue(load, 2));
    const hasLoads = loadOptions.length > 0;
    const multi = panelKeys.length > 1;
    const sessions = (members: Built[]) => members.reduce((sum, m) => sum + m.points.length, 0);
    const table: ReportTable = multi
      ? {
          columns: [
            { label: t("Athlete"), weight: 1.6 },
            { label: t("Sessions"), weight: 0.9, align: "end" },
            ...panelKeys.map((key) => ({ label: panelName(key) || t("No lift"), weight: 1.8, align: "end" as const })),
          ],
          rows: visible.map(({ key, members }) => ({
            color: colorOf(key),
            named: leadIds.has(key),
            cells: [
              members[0].athleteLabel,
              formatValue(sessions(members), 0),
              ...panelKeys.map((panel) => {
                const member = members.find((m) => m.panelKey === panel);
                if (!member) return t("no data");
                const load = hasLoads ? loadOf(member) : null;
                return load ? `${linkWords(member)} · ${load}` : linkWords(member);
              }),
            ],
          })),
        }
      : {
          columns: [
            { label: t("Athlete"), weight: 1.4 },
            ...(hasLoads ? [{ label: onUsualLoad ? t("Usual load") : t("Load"), weight: 1.1, align: "end" as const }] : []),
            { label: t("Sessions"), weight: 0.9, align: "end" },
            { label: t("How closely linked"), weight: 1.6, align: "end", key: true },
          ],
          rows: visible.map(({ key, members }) => ({
            color: colorOf(key),
            named: leadIds.has(key),
            cells: [
              members[0].athleteLabel,
              ...(hasLoads ? [loadOf(members[0]) ?? "—"] : []),
              formatValue(sessions(members), 0),
              linkWords(members[0]),
            ],
          })),
        };
    const frame = reportFrame({
      subject,
      config,
      heading: answer.heading,
      named,
      highlighted: picked.map(({ members }) => members[0].athleteLabel),
    });
    const loadNote = !hasLoads
      ? null
      : onUsualLoad
        ? t("Usual load: each athlete's sessions at the load they trained at most, so the link isn't just heavier days moving both values.")
        : controls.load !== "all"
          ? t("Every session shown is at {load}.", { load: withLoadUnit(Number(controls.load)) })
          : t("Sessions at all loads (the range per athlete): heavier days can move both values and look like a link.");
    const hiddenNames = athleteGroups.filter(({ key }) => interaction.isHidden(key)).map(({ members }) => members[0].athleteLabel);
    return {
      chartType: "correlation",
      fileTitle: exportTitle,
      kicker: frame.kicker,
      verdict: frame.verdict,
      standfirst: frame.standfirst,
      figure: {
        kind: "scatter",
        panels: panelKeys.map((key) => ({
          title: panelName(key),
          series: built
            .filter((b) => b.panelKey === key && visibleIds.has(b.athleteID))
            .map((b) => {
              const xs = b.points.map((p) => p.x);
              const x0 = Math.min(...xs);
              const x1 = Math.max(...xs);
              return {
                name: b.athleteLabel,
                color: colorOf(b.athleteID),
                points: b.points,
                fit: b.enough && b.fit ? { x0, y0: b.fit.intercept + b.fit.slope * x0, x1, y1: b.fit.intercept + b.fit.slope * x1 } : null,
              };
            }),
        })),
        xLabel: xTitle,
        yLabel: yTitle,
        formatX: (v) => formatValue(v, xMeta?.precision),
        formatY: (v) => formatValue(v, yMeta?.precision),
      },
      table,
      tableBeside: multi ? undefined : 0.6,
      appendix: [],
      notes: [
        t("Each dot is one session. A line is drawn for each athlete with enough sessions to show a link; the table says how closely the two values move together."),
        ...(loadNote ? [loadNote] : []),
        t("The statistical values (r, R²) are in the CSV."),
        ...(hiddenNames.length ? [t("Not shown: {names} (hidden on screen).", { names: hiddenNames.join(", ") })] : []),
        ...frame.notes,
      ],
      slideKeys: visible
        .filter(({ key }) => leadIds.has(key))
        .slice(0, 4)
        .map(({ members }) => `${members[0].athleteLabel}: ${linkWords(members[0])}`)
        .join("   ·   "),
    };
  }

  const exportLegend = legendRows.map((r) => ({
    ...r,
    hidden: interaction.isHidden(r.id),
  }));

  const fullOptions: ChartOptions<"scatter"> = {
    responsive: true,
    maintainAspectRatio: false,
    interaction: { mode: "nearest", intersect: true },
    onClick: athleteFocusOnClick,
    plugins: {
      legend: { display: false },
      tooltip: {
        titleFont: chartFont(theme, 12, 500),
        bodyFont: chartFont(theme, 12),
        backgroundColor: theme.tooltipBg,
        titleColor: theme.text,
        bodyColor: theme.text,
        borderColor: theme.border,
        borderWidth: 1,
        usePointStyle: true,
        filter: (ctx) => !(ctx.dataset as ScatterDataset)._fit,
        callbacks: {
          title: (items) => (tile || !items.length ? "" : (items[0].dataset.label ?? "")),
          // Two-coloured dots are transparent to chart.js: key the row by the vertical metric's half.
          labelColor: (ctx) => {
            const split = (ctx.dataset as ScatterDataset)._split;
            const color = split ? split[0] : String(ctx.dataset.backgroundColor ?? theme.muted);
            return { borderColor: color, backgroundColor: color };
          },
          label: (ctx) => {
            // A tile reads in one line: who · x / y.
            if (tile) {
              const athlete = built.find((b) => b.id === (ctx.dataset as ScatterDataset)._seriesId)?.athleteLabel ?? ctx.dataset.label ?? "";
              return `${athlete} · ${formatValue(Number(ctx.parsed.x), xMeta?.precision)} / ${formatValue(Number(ctx.parsed.y), yMeta?.precision)}`;
            }
            const xText = `${xLabel}: ${formatValue(Number(ctx.parsed.x), xMeta?.precision)}${xMeta?.unit ? ` ${xMeta.unit}` : ""}`;
            const yText = `${yLabel}: ${formatValue(Number(ctx.parsed.y), yMeta?.precision)}${yMeta?.unit ? ` ${yMeta.unit}` : ""}`;
            const load = (ctx.raw as Partial<CorrelationPoint> | undefined)?.load;
            return load != null ? [xText, yText, `${t("Load")}: ${withLoadUnit(load)}`] : [xText, yText];
          },
        },
      },
    },
    scales: {
      x: {
        type: "linear",
        grid: { color: theme.grid },
        border: { display: false },
        title: { display: Boolean(xTitle), text: xTitle, color: theme.muted, font: chartFont(theme, 12) },
        ticks: {
          color: theme.muted,
          font: chartFont(theme, 11),
          callback: (value) => formatValue(Number(value), xMeta?.precision),
        },
      },
      y: {
        type: "linear",
        grid: { color: theme.grid },
        border: { display: false },
        title: { display: Boolean(yTitle), text: yTitle, color: theme.muted, font: chartFont(theme, 12) },
        ticks: {
          color: theme.muted,
          font: chartFont(theme, 11),
          callback: (value) => formatValue(Number(value), yMeta?.precision),
        },
      },
    },
  };

  const options = thumb ? (asThumbnailOptions(fullOptions) as typeof fullOptions) : fullOptions;

  return (
    <ChartShell
      imageSource={{ chartType: "correlation", title: exportTitle, getReport: buildReport }}
      isEmpty={isEmpty}
      emptyTitle={emptyTitle}
      emptyDetail={emptyDetail}
      emptyAction={emptyAction}
      emptyHeightClass={tile ? (thumb ? THUMB_PLOT_CLASS : TILE_PLOT_CLASS) : undefined}
      // Panels size themselves (one tall plot, or a grid of shorter ones).
      heightClass="h-auto"
      header={
        thumb ? null : tile ? (
          <ChartTileHeader subject={subject} actions={actions} />
        ) : (
        <ChartHeader
          title={chartTitle}
          subject={subject}
          note={chartNote}
          answer={answer}
          facets={facets}
          showAggregation={false}
          aggregation={controls.aggregation}
          onAggregationChange={controls.setAggregation}
          loadOptions={loadOptions}
          loadCoverage={{ counts: loadCoverageCounts, total: athletes.length }}
          load={controls.load}
          onLoadChange={(value) => {
            setUsualLoad(false);
            controls.setLoad(value);
          }}
          usualLoad={
            offerUsualLoad ? { selected: usualLoad, onSelect: () => setUsualLoad(true) } : undefined
          }
          controls={
            loadsMixed ? <LoadsMixedChip /> : onUsualLoad && loadOptions.length > 0 ? <UsualLoadChip chart="correlation" /> : null
          }
          view={{ changed: viewChanged, reset: resetView }}
          actions={
            <div className="flex items-center gap-1">
              <ChartExportMenu chartType="correlation" title={exportTitle} legend={exportLegend} getReport={buildReport} />
              {actions}
            </div>
          }
        />
        )
      }
      legend={
        thumb ? null : tile ? (
          <ChartTileKeys
            folded={foldedPanels ? t("{count, plural, one {+# lift} other {+# lifts}} in the full chart", { count: foldedPanels }) : null}
          />
        ) : (
        <ChartLegendTable
          rows={legendRows}
          interaction={interaction}
          focusHint="highlight"
          shortlist={shortlist}
          linkActions={linkDrawers.actionsFor}
          countLabel={t("{count, plural, one {# athlete} other {# athletes}}", {
            count: legendRows.length,
          })}
          leadIds={namedIds}
          panelValueLabel={multiLift ? panelCodes.join(" ") : undefined}
          panelCells={multiLift}
          panelKey={
            multiLift
              ? `${t("● strong · ◐ moderate · ○ weak · · too few sessions · ↘ opposite direction")} — ${panelKeys
                  .map((key, index) => `${panelCodes[index]} ${panelName(key)}`)
                  .join(" · ")}`
              : undefined
          }
        />
        )
      }
    >
      <div
        className={
          tile
            ? shownPanels.length === 3
              ? "grid grid-cols-3 gap-3"
              : shownPanels.length === 2
                ? "grid grid-cols-2 gap-3"
                : undefined
            : multiPanel
              ? "grid grid-cols-1 gap-5 sm:grid-cols-2"
              : undefined
        }
      >
        {shownPanels.map((key) => {
          const members = built.filter((b) => b.panelKey === key);
          const sentences = panelSentences(members);
          const data: ChartData<"scatter"> = { datasets: panelDatasets(members) };
          return (
            <section key={key || "panel"} className="flex min-w-0 flex-col gap-1">
              {multiLift && !thumb ? (
                tile ? (
                  <h4 className="body-small truncate font-medium text-foreground-default">{panelName(key)}</h4>
                ) : (
                  <h4 className="body-small flex items-center gap-2 font-medium text-foreground-default">
                    {solo ? (
                      <button
                        type="button"
                        onClick={() => setSoloPanel(null)}
                        className="clickable-small rounded-full border border-surface-stroke px-2.5 py-0.5 font-normal text-foreground-muted hover:text-foreground-default"
                      >
                        {t("← All lifts")}
                      </button>
                    ) : null}
                    {solo ? (
                      <span className="truncate">{panelName(key)}</span>
                    ) : (
                      <button
                        type="button"
                        onClick={() => setSoloPanel(key)}
                        title={t("Show this lift alone")}
                        className="clickable-small truncate text-left underline decoration-dotted decoration-foreground-more-muted underline-offset-[3px] hover:decoration-foreground-default"
                      >
                        {panelName(key)}
                      </button>
                    )}
                  </h4>
                )
              ) : null}
              {tile ? null : (
                <>
                  <p className="body-small text-foreground-default">{sentences.within}</p>
                  {sentences.between ? (
                    <p className="body-small text-foreground-muted">{sentences.between}</p>
                  ) : null}
                </>
              )}
              <div
                className={`relative mt-1 w-full select-none [-webkit-touch-callout:none] ${
                  thumb ? THUMB_PLOT_CLASS : tile ? (multiPanel ? "h-[212px]" : "h-[240px]") : multiPanel ? "h-[300px]" : focus ? "h-full min-h-[300px]" : "h-[380px]"
                }`}
                onContextMenu={tile ? undefined : (event) => chartActions.onContextMenu(event, panelTargetAt(key))}
                onPointerDown={(event) => chartActions.onPointerDown(event)}
                onMouseMove={(event) => onPanelHover(key, event.nativeEvent)}
                onMouseLeave={() => onPanelHover(key, null)}
              >
                <Scatter
                  ref={(chart) => {
                    if (chart) panelCharts.current.set(key, chart);
                    else panelCharts.current.delete(key);
                  }}
                  data={data}
                  options={options}
                  plugins={[splitDots]}
                  datasetIdKey="_key"
                  // A hover (athlete, fit line) redraws in place, without replaying the animation.
                  updateMode={interaction.preview != null || fitTip != null ? "none" : undefined}
                />
                {fitTip && fitTip.panel === key ? (
                  <span
                    role="tooltip"
                    className="body-small pointer-events-none absolute z-10 -translate-x-1/2 -translate-y-full whitespace-nowrap rounded-lg border border-surface-stroke bg-surface-base px-2.5 py-1 text-foreground-default shadow-sm"
                    style={{ left: fitTip.x, top: fitTip.y - 8 }}
                  >
                    {fitTip.text}
                  </span>
                ) : null}
              </div>
            </section>
          );
        })}
      </div>
      {tile ? null : chartActions.card(focusedTarget, comparison)}
      {linkDrawers.drawers}
      {chartActions.menu}
    </ChartShell>
  );
}
