"use client";

import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { useAnnouncementAnchor } from "@enode/core/announcements/hooks";
import type { ExerciseMappedReturnDto } from "@enode/core/api/dtos/exercises";
import type {
  PageMetadata,
  SessionReturnDto,
} from "@enode/core/api/dtos/sessions";
import { searchSessions } from "@enode/core/api/sessions";
import { usePrivilegeAccess } from "@enode/core/auth/use-privilege";
import { loadExerciseVariations } from "@enode/core/exercise-variations/store";
import {
  useExerciseDisplayName,
  useExerciseSubtitle,
} from "@enode/core/exercises/hooks";
import { useMetricByKey } from "@enode/core/metrics/hooks";
import { loadMetrics } from "@enode/core/metrics/store";
import {
  countWorkingSets,
  sessionVolumeLoad,
  type OverviewMetricIds,
} from "@enode/core/training/exercise-overview";
import { useTextContentsVersion } from "@enode/core/text-content/useTextContentsVersion";
import { useTranslation } from "@enode/core/translations/hooks";
import { useUnits, type Units } from "@enode/core/use-units";
import { useUsers } from "@enode/core/users/hooks";
import { isEffectivelyTrainable } from "@enode/core/users/trainable";
import { Skeleton } from "@enode/ui/feedback/skeleton";
import { HEADER_ICON_BUTTON } from "@enode/ui/header-button";
import { AthleteAvatar } from "@enode/ui/athlete-avatar";
import {
  CalendarIcon,
  ChevronDownIcon,
  CheckmarkRectangleStackFillIcon as SessionsIcon,
  Person2FillIcon as AthletesIcon,
  ScaleMassFillIcon as VolumeIcon,
  SquareStack3DUpFillIcon as SetsIcon,
} from "@enode/ui/icons";
import { LottieCircle } from "@enode/ui/LottieCircle";
import { ActionMenu } from "@enode/ui/action-menu";
import {
  FirstRunLine,
  useFirstRunLineState,
} from "@enode/ui/first-run/first-run-line";
import { TourAutoStart } from "@enode/ui/tour/tour-provider";
import { PageShell } from "../../components/page-shell";
import { TOUR_TARGET } from "../../tours/tour-targets";
import { useWelcomeTour } from "../../tours/use-welcome-tour";
import { SummaryCard } from "../../components/summary-card";
import {
  DashboardNotificationsCard,
  DashboardNotificationsHeaderButton,
} from "../../components/notifications/dashboard-notifications-card";
import {
  ConnectionCard,
  useShowConnectionCard,
} from "../../components/notices/connection-card";
import { DashboardMigrationHint } from "./dashboard-migration-hint";
import { DashboardQuestionnairesHint } from "./dashboard-questionnaires-hint";
import { SessionsEmptyState } from "./sessions-empty-state";
import { SessionsTable } from "./sessions-table";
import { sessionIsInertia } from "./use-session-metrics";
import { loadInBackground } from "../../components/background-load";
import {
  dashboardViewParams,
  readDashboardView,
  type RankMetric,
  type TimeRange,
} from "./dashboard-view";
import { useInitialSearchParams, useSyncSearchParams } from "./url-state";
import { LOOK } from "@enode/ui/live/look";

const DAY_MS = 24 * 60 * 60 * 1000;

const RANGE_DAYS: Record<TimeRange, number> = { "3d": 3, week: 7, month: 30 };

// Load enough of the window in one page that the summaries cover (essentially)
// every session in the range, not just the first default page.
const RANGE_PER = 500;

type DashboardStats = {
  activeAthletes: number;
  completed: number;
  volume: number;
  sets: number;
};

// The per-row totals every ranking accumulates, whatever it groups by.
type RankTotals = { [M in RankMetric]: number };

// The metric ids `sessionVolumeLoad` needs for a mass-based volume load; the
// other slots stay null because the dashboard never computes 1RM / force /
// inertia / exertion.
function volumeMetricIds(
  loadMetricId: string | null,
  repCountMetricId: string | null,
): OverviewMetricIds {
  return {
    rm1: null,
    forcePeak: null,
    loadingMass: loadMetricId,
    loadingInertia: null,
    repCount: repCountMetricId,
    exertion: null,
  };
}

// Aggregates one period's sessions into the four summary stats. `completedTotal`
// is the server's true count for the window (sessions may be one large page).
function computeStats(
  sessions: SessionReturnDto[],
  completedTotal: number,
  athleteIDs: ReadonlySet<string>,
  loadMetricId: string | null,
  repCountMetricId: string | null,
): DashboardStats {
  const active = new Set<string>();
  let volume = 0;
  let sets = 0;
  // Volume load via the shared `sessionVolumeLoad` (working sets only), so the
  // dashboard total matches the sessions table + drawer exactly. Inertia isn't
  // needed — inertia (flywheel) sessions are skipped below (mass-only concept).
  const volumeIds = volumeMetricIds(loadMetricId, repCountMetricId);
  for (const s of sessions) {
    const id = s.user?.id;
    if (id && athleteIDs.has(id)) active.add(id);
    if (!sessionIsInertia(s)) {
      volume += sessionVolumeLoad(s.sets, volumeIds) ?? 0;
    }
    sets += countWorkingSets(s.sets);
  }
  return {
    activeAthletes: active.size,
    completed: completedTotal,
    volume,
    sets,
  };
}

// Signed percent change vs. the prior period, or null when there's no baseline.
function trendPct(current: number, prior: number): number | null {
  if (prior <= 0) return null;
  return Math.round(((current - prior) / prior) * 100);
}

// Total volume over a window can reach tens of thousands of kg, whose digits
// overflow the summary card on narrow screens. At 10,000 kg and above switch to
// tonnes (e.g. "12.5 t") so the figure stays short. The threshold is metric;
// imperial keeps its native pound formatting.
function formatVolumeText(
  units: Units,
  storedKg: number,
  dimension: string | null,
): string {
  if (units.system === "metric") {
    const kg = units.toDisplay(storedKg, dimension);
    if (kg >= 10_000) {
      const tonnes = kg / 1000;
      return `${tonnes.toLocaleString(undefined, {
        maximumFractionDigits: 1,
      })} t`;
    }
  }
  const vol = units.format(storedKg, dimension);
  return vol.text ? (vol.unit ? `${vol.text} ${vol.unit}` : vol.text) : "—";
}

// Adds one session's contribution to a ranking row's totals. Volume mirrors the
// summary card exactly — shared `sessionVolumeLoad` (working sets only), with
// inertia (flywheel) sessions skipped since volume load is a mass-only concept.
function addSessionTotals(
  totals: RankTotals,
  session: SessionReturnDto,
  volumeIds: OverviewMetricIds,
): void {
  totals.sessions += 1;
  totals.sets += countWorkingSets(session.sets);
  if (!sessionIsInertia(session)) {
    totals.volume += sessionVolumeLoad(session.sets, volumeIds) ?? 0;
  }
}

// Top 5 rows for the selected metric, biggest first.
function topByMetric<T extends RankTotals>(
  rows: readonly T[],
  metric: RankMetric,
): T[] {
  return [...rows].sort((a, b) => b[metric] - a[metric]).slice(0, 5);
}

// A ranking row's trailing figure: counts render bare, volume goes through the
// unit formatter (kg / t / lb) like the summary card.
function formatRankValue(
  metric: RankMetric,
  value: number,
  units: Units,
  dimension: string | null,
): string {
  if (metric !== "volume") return String(value);
  return formatVolumeText(units, value, dimension);
}

// Compact day label, e.g. "Jun 3".
function formatDay(ms: number): string {
  return new Date(ms).toLocaleDateString(undefined, {
    month: "short",
    day: "numeric",
  });
}

// The dashboard landing: summarises the selected time range (athletes active,
// sessions, volume, sets), then lists those sessions.
export default function DashboardPage() {
  const { t } = useTranslation();
  useAnnouncementAnchor("dashboard");
  const units = useUnits();
  // The welcome tour: auto-starts on the user's first visit (see
  // <TourAutoStart> below); tours are re-armed from the settings drawer.
  const welcomeTour = useWelcomeTour();
  // The tour waits while the welcome line is (or may still become) visible.
  const welcomeLine = useFirstRunLineState();
  const router = useRouter();
  // The Athletes summary card + the Athlete-activity ranking both surface athlete
  // data, so both are gated on writeUserAthlete (same privilege as the planner's
  // athlete surfaces).
  const athleteAccess = usePrivilegeAccess("writeUserAthlete");
  const canSeeAthletes = athleteAccess === "granted";
  // The range and the ranking metrics live in the address (dashboard-view.ts).
  const params = useInitialSearchParams();
  const [initialView] = useState(() => readDashboardView(params));
  useEffect(() => {
    loadInBackground(loadMetrics);
    // The top-exercises subtitle resolves variation names against this catalogue.
    loadInBackground(loadExerciseVariations);
  }, []);

  // Completed sessions for the selected range via the from/to `search` (NOT
  // empty_search) with no entity filter — an empty `searchItems` returns every
  // session in range.
  const [range, setRange] = useState<TimeRange>(initialView.range);
  const [sessions, setSessions] = useState<SessionReturnDto[]>([]);
  const [metaData, setMetaData] = useState<PageMetadata | null>(null);
  // The equal-length window immediately before the selected one — drives the
  // summary-card trends. Best-effort: a failed prior fetch just hides trends.
  const [priorSessions, setPriorSessions] = useState<SessionReturnDto[]>([]);
  const [priorMeta, setPriorMeta] = useState<PageMetadata | null>(null);
  const [period, setPeriod] = useState<{
    from: number;
    to: number;
    priorFrom: number;
    priorTo: number;
  } | null>(null);
  const [status, setStatus] = useState<"loading" | "loaded" | "error">(
    "loading",
  );
  // The failed load's error, kept so the error surface can name the cause
  // (offline / server unreachable / maintenance) instead of a generic message.
  const [loadError, setLoadError] = useState<unknown>(null);
  // Bumped by "Try again" to re-run the fetch effect without a full reload.
  const [reloadNonce, setReloadNonce] = useState(0);
  // Switching range is a user event (not an effect), so set the loading state
  // here rather than synchronously inside the fetch effect.
  function selectRange(next: TimeRange) {
    setRange(next);
    setStatus("loading");
  }
  function retry() {
    setStatus("loading");
    setReloadNonce((n) => n + 1);
  }
  useEffect(() => {
    let cancelled = false;
    const to = Date.now();
    const rangeMs = RANGE_DAYS[range] * DAY_MS;
    const from = to - rangeMs;
    const priorTo = from;
    const priorFrom = from - rangeMs;
    Promise.all([
      searchSessions({ searchItems: [] }, { from, to, per: RANGE_PER }),
      // Prior period is best-effort — its failure must not error the page.
      searchSessions(
        { searchItems: [] },
        { from: priorFrom, to: priorTo, per: RANGE_PER },
      ).catch(() => null),
    ])
      .then(([cur, prior]) => {
        if (cancelled) return;
        setSessions(cur.pagedEntities ?? []);
        setMetaData(cur.metaData ?? null);
        setPriorSessions(prior?.pagedEntities ?? []);
        setPriorMeta(prior?.metaData ?? null);
        setPeriod({ from, to, priorFrom, priorTo });
        setLoadError(null);
        setStatus("loaded");
      })
      .catch((err) => {
        if (cancelled) return;
        console.error("Failed to load sessions:", err);
        setLoadError(err);
        setStatus("error");
      });
    return () => {
      cancelled = true;
    };
  }, [range, reloadNonce]);

  // ── Summary stats (current vs prior period) ─────────────────────────────────
  // Deliberately the FULL catalogue: `athleteIDs` below is intersected with the
  // period's sessions to compute volume/sets, so dropping archived athletes here
  // would silently move those numbers. The dashboard's stats stay as they are —
  // the archived rule stops at the History page. (Known gap: the athlete count
  // therefore still includes archived athletes.)
  const { users } = useUsers({ includeArchived: true });
  const athleteIDs = useMemo(
    () =>
      new Set(
        (users ?? []).filter(isEffectivelyTrainable).map((u) => u.id),
      ),
    [users],
  );
  const totalAthletes = athleteIDs.size;
  const loadMetric = useMetricByKey("loadingMass");
  const loadMetricId = loadMetric?.id ?? null;
  const repCountMetricId = useMetricByKey("repCount")?.id ?? null;

  const cur = useMemo(
    () =>
      computeStats(
        sessions,
        metaData?.total ?? sessions.length,
        athleteIDs,
        loadMetricId,
        repCountMetricId,
      ),
    [sessions, metaData, athleteIDs, loadMetricId, repCountMetricId],
  );
  const prior = useMemo(
    () =>
      computeStats(
        priorSessions,
        priorMeta?.total ?? priorSessions.length,
        athleteIDs,
        loadMetricId,
        repCountMetricId,
      ),
    [priorSessions, priorMeta, athleteIDs, loadMetricId, repCountMetricId],
  );

  const volumeText = formatVolumeText(
    units,
    cur.volume,
    loadMetric?.dimension ?? null,
  );

  // Detail line shown on every card: the prior window it's compared against.
  const comparison = period
    ? t("vs {start} – {end}", {
        start: formatDay(period.priorFrom),
        end: formatDay(period.priorTo),
      })
    : "";

  // ── Rankings (top 5, read straight from the sessions — no extra fetch) ───────
  // Exercises (grouped across athletes by the shared definition id) and athletes
  // each accumulate all three metrics in one pass, so picking another metric
  // only re-sorts — it never re-walks the sessions. Bars are relative to the
  // leader of whichever metric is selected.
  useTextContentsVersion(); // re-resolve exercise names as text content loads
  const [exerciseMetric, setExerciseMetric] = useState<RankMetric>(initialView.exerciseMetric);
  const [athleteMetric, setAthleteMetric] = useState<RankMetric>(initialView.athleteMetric);
  const volumeIds = useMemo(
    () => volumeMetricIds(loadMetricId, repCountMetricId),
    [loadMetricId, repCountMetricId],
  );

  const exerciseTotals = useMemo(() => {
    const byExercise = new Map<
      string,
      RankTotals & { exercise: ExerciseMappedReturnDto }
    >();
    for (const s of sessions) {
      const ex = s.exercise;
      if (!ex) continue;
      const key = ex.exerciseDefinitionID ?? ex.id;
      let entry = byExercise.get(key);
      if (!entry) {
        entry = { exercise: ex, sessions: 0, volume: 0, sets: 0 };
        byExercise.set(key, entry);
      }
      addSessionTotals(entry, s, volumeIds);
    }
    return [...byExercise.values()];
  }, [sessions, volumeIds]);
  const exerciseRanking = useMemo(
    () => topByMetric(exerciseTotals, exerciseMetric),
    [exerciseTotals, exerciseMetric],
  );
  const maxExerciseValue = exerciseRanking[0]?.[exerciseMetric] ?? 0;

  const athleteTotals = useMemo(() => {
    const byUser = new Map<
      string,
      RankTotals & { id: string; name: string | null }
    >();
    for (const s of sessions) {
      const id = s.user?.id;
      if (!id) continue;
      let entry = byUser.get(id);
      if (!entry) {
        entry = {
          id,
          name: s.user?.name ?? null,
          sessions: 0,
          volume: 0,
          sets: 0,
        };
        byUser.set(id, entry);
      }
      addSessionTotals(entry, s, volumeIds);
    }
    return [...byUser.values()];
  }, [sessions, volumeIds]);
  const athleteRanking = useMemo(
    () => topByMetric(athleteTotals, athleteMetric),
    [athleteTotals, athleteMetric],
  );
  const maxAthleteValue = athleteRanking[0]?.[athleteMetric] ?? 0;

  useSyncSearchParams(dashboardViewParams({ range, exerciseMetric, athleteMetric }));

  // Volume figures render in the load metric's unit; counts ignore it.
  const loadDimension = loadMetric?.dimension ?? null;

  // Skeleton everything (cards, rankings, table) together while a range loads —
  // and while it's errored too, so a failed load reads as a calm "still trying"
  // (the connection card above explains why) instead of flashing misleading
  // zeros.
  const loading = status !== "loaded";
  // While the profile is still on its way the privilege is unknown: the
  // skeleton assumes the athlete surfaces will show (the common owner / coach
  // case) so the placeholders already have the final grid. Once the data is
  // in, only a granted privilege renders them.
  const athleteSlots =
    canSeeAthletes ||
    (loading && (athleteAccess === "loading" || athleteAccess === "unknown"));
  // Surface the connection card as soon as the load fails — or EARLY, while
  // still loading, once the reachability signal (SSE heartbeat + request
  // outcomes) says we're down, so a dead backend doesn't mean 15s of skeletons.
  const showConnection = useShowConnectionCard(status === "loading", status === "error");

  // The selected range holds no completed sessions (loaded + empty) — show the
  // range-scoped empty state (schedule a workout / widen the range) in place of
  // the table. While still loading, the table's own skeletons cover it.
  const noSessionsInRange = status === "loaded" && sessions.length === 0;

  // Range options for the calendar menu. Literal `t(...)` args keep the labels
  // extractable.
  const rangeOptions = [
    { value: "3d", label: t("Last 3 days") },
    { value: "week", label: t("Last week") },
    { value: "month", label: t("Last month") },
  ];
  // Subtitle: the selected range's name + its actual dates, e.g.
  // "Last week • Jun 23 – Jun 30" (dates resolve once the window loads).
  const rangeLabel = rangeOptions.find((o) => o.value === range)?.label ?? "";
  const rangeSubtitle = period
    ? `${rangeLabel}  •  ${formatDay(period.from)} – ${formatDay(period.to)}`
    : rangeLabel;

  return (
    <PageShell
      title={t("Dashboard")}
      subtitle={rangeSubtitle}
      inlineActions
      actions={
        // Header control cluster: the minimized-notifications bell (present only
        // when the dashboard notifications card is collapsed) sits left of the
        // calendar-icon menu that picks the time range. Both share the size-10
        // circular chrome so they align as a pair (PageShell's inline-actions
        // wrapper spaces them with gap-2).
        <>
          <DashboardNotificationsHeaderButton />
          <ActionMenu
            ariaLabel={t("Time range")}
            triggerIcon={<CalendarIcon className="size-5" />}
            items={rangeOptions.map((o) => ({
              label: o.label,
              onClick: () => selectRange(o.value as TimeRange),
              selected: range === o.value,
            }))}
            triggerClassName={HEADER_ICON_BUTTON}
          />
        </>
      }
    >
      {!welcomeLine.visible && !welcomeLine.pending && (
        <TourAutoStart tour={welcomeTour} />
      )}
      <div className="space-y-6">
        {/* A failed (or unreachable-while-loading) load keeps the skeletons
            (calm "still trying") and names the cause in a prominent card — no
            misleading zeros. It's a fatal state, so it can't be dismissed or
            minimized. */}
        {showConnection && (
          <ConnectionCard error={loadError} onRetry={retry} />
        )}
        <FirstRunLine
          onAddAthletes={() => router.push("/dashboard/users")}
          onConnectTablet={() => router.push("/dashboard/devices")}
        />
        {/* Onboarding hero for a brand-new owner (no other users, no sessions
            yet) — nudges them into the migration flow. Self-hides otherwise. */}
        <DashboardMigrationHint />
        {/* Launch hero for the wellness / session-RPE questionnaires — shown to
            whoever can still switch one on, and self-retiring once they have. */}
        <DashboardQuestionnairesHint />
        <DashboardNotificationsCard />
        <div data-tour={TOUR_TARGET.dashboardStats} className="flex flex-wrap gap-4">
          {athleteSlots && (
            <SummaryCard
              loading={loading}
              icon={<AthletesIcon className="size-4" />}
              value={`${cur.activeAthletes}/${totalAthletes}`}
              trend={trendPct(cur.activeAthletes, prior.activeAthletes)}
              title={t("Athletes")}
              detail={comparison}
            />
          )}
          <SummaryCard
            loading={loading}
            icon={<SessionsIcon className="size-4" />}
            count={cur.completed}
            trend={trendPct(cur.completed, prior.completed)}
            title={t("Completed sessions")}
            detail={comparison}
          />
          <SummaryCard
            loading={loading}
            icon={<VolumeIcon className="size-4" />}
            value={volumeText}
            trend={trendPct(cur.volume, prior.volume)}
            title={t("Total volume")}
            detail={comparison}
          />
          <SummaryCard
            loading={loading}
            icon={<SetsIcon className="size-4" />}
            tone="muted"
            count={cur.sets}
            trend={trendPct(cur.sets, prior.sets)}
            title={t("Sets")}
            detail={comparison}
          />
        </div>

        {/* Two columns only while the athlete-activity card is there to fill the
            second one — without the privilege it's dropped, so Top exercises goes
            full-width instead of sitting stranded at half width. */}
        <div
          className={`grid grid-cols-1 gap-4 ${
            athleteSlots ? "lg:grid-cols-2" : ""
          }`}
        >
          {/* Top exercises — ranked by sets, volume or sessions (the card's own
              menu). */}
          <div className={`${LOOK.panel} p-4`}>
            <div className="mb-4 flex items-center justify-between gap-2">
              <h3 className="heading-section">{t("Top exercises")}</h3>
              <RankMetricMenu
                ariaLabel={t("Rank exercises by")}
                value={exerciseMetric}
                onChange={setExerciseMetric}
              />
            </div>
            {loading ? (
              <RankingSkeleton />
            ) : exerciseRanking.length === 0 ? (
              <p className="body-small text-foreground-muted">
                {t("No data yet.")}
              </p>
            ) : (
              <ul className="space-y-3">
                {exerciseRanking.map((item) => {
                  const value = item[exerciseMetric];
                  return (
                    <TopExerciseRow
                      key={item.exercise.id}
                      exercise={item.exercise}
                      value={formatRankValue(
                        exerciseMetric,
                        value,
                        units,
                        loadDimension,
                      )}
                      pct={
                        maxExerciseValue > 0
                          ? Math.max((value / maxExerciseValue) * 100, 6)
                          : 0
                      }
                    />
                  );
                })}
              </ul>
            )}
          </div>

          {/* Athlete activity — ranked by sessions, volume or sets (the card's
              own menu). Gated on writeUserAthlete, like the Athletes summary
              card above. */}
          {athleteSlots && (
          <div className={`${LOOK.panel} p-4`}>
            <div className="mb-4 flex items-center justify-between gap-2">
              <h3 className="heading-section">{t("Athlete activity")}</h3>
              <RankMetricMenu
                ariaLabel={t("Rank athletes by")}
                value={athleteMetric}
                onChange={setAthleteMetric}
              />
            </div>
            {loading ? (
              <RankingSkeleton />
            ) : athleteRanking.length === 0 ? (
              <p className="body-small text-foreground-muted">
                {t("No data yet.")}
              </p>
            ) : (
              <ul className="space-y-3">
                {athleteRanking.map((item) => {
                  const value = item[athleteMetric];
                  const pct =
                    maxAthleteValue > 0
                      ? Math.max((value / maxAthleteValue) * 100, 6)
                      : 0;
                  return (
                    <li key={item.id} className="flex items-center gap-3">
                      <AthleteAvatar
                        userID={item.id}
                        name={item.name}
                        size={32}
                        className="body-small font-medium"
                      />
                      <div className="min-w-0 flex-1">
                        <div className="flex items-baseline justify-between gap-2">
                          <span className="body-prominent truncate text-foreground-default">
                            {item.name ?? "—"}
                          </span>
                          <span className="stat-small shrink-0 text-foreground-muted">
                            {formatRankValue(
                              athleteMetric,
                              value,
                              units,
                              loadDimension,
                            )}
                          </span>
                        </div>
                        <div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-surface-base-muted">
                          <div
                            className="h-full rounded-full bg-foreground-platinum-green-bright"
                            style={{ width: `${pct}%` }}
                          />
                        </div>
                      </div>
                    </li>
                  );
                })}
              </ul>
            )}
          </div>
          )}
        </div>

        <div data-tour={TOUR_TARGET.dashboardSessions}>
          {noSessionsInRange ? (
            <SessionsEmptyState />
          ) : (
            <SessionsTable sessions={sessions} loading={loading} flat />
          )}
        </div>
      </div>
    </PageShell>
  );
}

// The metric picker in a ranking card's header: the current choice as quiet
// caption text (where a static "By sets" label used to sit) opening the standard
// action menu. Shared by both cards so they read and behave identically.
function RankMetricMenu({
  ariaLabel,
  value,
  onChange,
}: {
  ariaLabel: string;
  value: RankMetric;
  onChange: (metric: RankMetric) => void;
}) {
  const { t } = useTranslation();
  // Literal `t(...)` args keep the labels extractable.
  const options: { value: RankMetric; label: string }[] = [
    { value: "sessions", label: t("By sessions") },
    { value: "volume", label: t("By volume") },
    { value: "sets", label: t("By sets") },
  ];
  const label = options.find((o) => o.value === value)?.label ?? "";
  return (
    <ActionMenu
      ariaLabel={ariaLabel}
      minWidth={160}
      triggerClassName="-mr-2 flex items-center gap-1 rounded-lg px-2 py-1 stat-small text-foreground-muted transition-colors hover:bg-surface-base-muted hover:text-foreground-default"
      triggerIcon={
        <>
          {label}
          <ChevronDownIcon className="size-3" />
        </>
      }
      items={options.map((o) => ({
        label: o.label,
        onClick: () => onChange(o.value),
        selected: value === o.value,
      }))}
    />
  );
}

// A top-exercises ranking row: icon + name (with the equipment · variation
// detail, since a name alone isn't unique) + the selected metric's figure and a
// bar relative to the leader.
function TopExerciseRow({
  exercise,
  value,
  pct,
}: {
  exercise: ExerciseMappedReturnDto;
  value: string;
  pct: number;
}) {
  const { t } = useTranslation();
  const name = useExerciseDisplayName(exercise, t("Exercise"));
  const subtitle = useExerciseSubtitle(exercise);
  return (
    <li className="flex items-center gap-3">
      <LottieCircle media={exercise.media} size={32} />
      <div className="min-w-0 flex-1">
        <div className="flex items-baseline justify-between gap-2">
          <span className="min-w-0 flex-1 truncate">
            <span className="body-prominent text-foreground-default">
              {name}
            </span>
            {subtitle && (
              <span className="body-small text-foreground-muted">
                {" · "}
                {subtitle}
              </span>
            )}
          </span>
          <span className="stat-small shrink-0 text-foreground-muted">
            {value}
          </span>
        </div>
        <div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-surface-base-muted">
          <div
            className="h-full rounded-full bg-foreground-platinum-green-bright"
            style={{ width: `${pct}%` }}
          />
        </div>
      </div>
    </li>
  );
}

// Pulsing skeleton for a ranking card's rows (avatar/icon + name + bar) while the
// sessions load — mirrors the row layout above.
function RankingSkeleton({ rows = 5 }: { rows?: number }) {
  return (
    <ul className="space-y-3" aria-busy="true">
      {Array.from({ length: rows }).map((_, i) => (
        <li key={i} className="flex items-center gap-3">
          <Skeleton rounded="full" className="size-8 shrink-0" />
          <div className="min-w-0 flex-1">
            <div className="flex items-baseline justify-between gap-2">
              <span className="relative min-w-0 flex-1 body-prominent">
                <span aria-hidden className="invisible">
                  &nbsp;
                </span>
                <Skeleton className="absolute inset-y-0.5 left-0 w-28" />
              </span>
              <Skeleton className="h-3 w-6" />
            </div>
            <Skeleton rounded="full" className="mt-1.5 h-1.5 w-full" />
          </div>
        </li>
      ))}
    </ul>
  );
}
