"use client";

import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useHasPrivilege } from "@enode/core/auth/use-privilege";
import type {
  PageMetadata,
  SessionMeasurementReturnDto,
  SessionReturnDto,
  SetReturnDto,
} from "@enode/core/api/dtos/sessions";
import type { MetricReturnDto } from "@enode/core/api/dtos/metrics";
import { getMetric, loadMetrics } from "@enode/core/metrics/store";
import { compareSetsByCreated } from "@enode/core/training/rep-order";
import { formatRanged, isBoundedMetric } from "@enode/core/metrics/range";
import { loadExerciseVariations } from "@enode/core/exercise-variations/store";
import {
  useExerciseDisplayName,
  useExerciseSubtitle,
  useExercisesByDefinition,
} from "@enode/core/exercises/hooks";
import { exerciseDisplayName } from "@enode/core/exercises/display-name";
import {
  countWarmupSets,
  countWorkingSets,
  markSecondSides,
  summarizeSession,
} from "@enode/core/training/exercise-overview";
import { sideLabel } from "@enode/ui/set-side";
import { setCountLabel } from "./set-count-label";
import { useTranslation } from "@enode/core/translations/hooks";
import { formatAbsoluteDateTime } from "@enode/core/format/date-time";
import { useUnits, type Units } from "@enode/core/use-units";
import { AthleteAvatar } from "@enode/ui/athlete-avatar";
import { LottieCircle } from "@enode/ui/LottieCircle";
import {
  DumbbellFillIcon,
  SquareAndArrowDownIcon,
  SquareStack3DUpFillIcon,
  TagIcon,
  TrashIcon,
  TrophyFillIcon,
  VideoFillIcon,
} from "@enode/ui/icons";
import {
  SessionHistoryCard,
  SessionHistoryCardSkeleton,
} from "@enode/ui/session-history-card";
import { TagPill } from "@enode/ui/tag-pill";
import { useTagPicker } from "@enode/ui/tags-card";
import type { EntityTagReturnDto } from "@enode/core/api/dtos/tags";
import type { ActionMenuItem } from "@enode/ui/action-menu";
import {
  DataTable,
  type DataTableColumn,
} from "../../components/data-table-view";
import {
  NAME_CELL_MAX_W,
  type SelectionActionItem,
} from "../../components/data-table";
import {
  MobileSelectPill,
  MobileSelectionHeader,
  MobileSelectionPill,
  SelectMark,
  toggleAllVisible,
} from "../../components/mobile-list";
import { pageCount } from "../../components/page-window";
import { TablePagination } from "../../components/table-pagination";
import {
  SummaryGrid,
  SummaryHeaderCell,
  summaryCellClass,
} from "../../components/summary-grid";
import { ActionMenu } from "@enode/ui/action-menu";
import { ConfirmDialog } from "@enode/ui/confirm-dialog";
import { useActionDrawer } from "../../components/action-drawer";
import { InlineTagsEditor } from "../../components/inline-tags-editor";
import { applyTagDiff } from "../../components/tag-diff";
import { useBulkAddSessionTags } from "./bulk-add-session-tags";
import { useBulkDeleteSessions } from "./bulk-delete-sessions";
import type { SessionDetailsActions } from "./session-details-tab";
import { ProfileDrawer } from "./users/profile-drawer-view";
import {
  ChangeExerciseDrawer,
  type ChangeExerciseTarget,
} from "./change-exercise-drawer";
import {
  ChangeAthleteDrawer,
  type ChangeAthleteTarget,
} from "./change-athlete-drawer";
import { SessionDrawer } from "./session-drawer";
import { selectionRange } from "./data/export/export-range";
import type { ExportSeed } from "./data/export/export-flow";
import {
  useSessionMetrics,
  type SessionMetricInfo,
} from "./use-session-metrics";
import { loadInBackground } from "../../components/background-load";

// The completed-sessions table — a composition over the generic DataTable with
// the session column config baked in, plus the row→drawer behaviour. Reused
// across pages (History, …); each page owns its own data source (search,
// pagination) and just feeds the rows.
export function SessionsTable({
  sessions,
  loading = false,
  emptyMessage,
  selectable = false,
  hideAthlete = false,
  hideExercise = false,
  flat = false,
  onOpenSession,
  onMutated,
  onRowPatched,
}: {
  sessions: SessionReturnDto[];
  // A failed load stays in `loading` (skeletons) — the owning page names the
  // cause with a ConnectionCard above the table, so there's no error prop here.
  loading?: boolean;
  emptyMessage?: string;
  // Opt into the multi-select toolbar with an "Export data" action. Off by
  // default so read-only embeds (e.g. the dashboard) stay plain.
  selectable?: boolean;
  // Drop the Athlete column — for a single-athlete context (e.g. the user
  // drawer) where it's redundant.
  hideAthlete?: boolean;
  // Drop the Exercise column — for a single-exercise context (e.g. the session
  // drawer's History tab, whose rows are all one athlete's same exercise).
  hideExercise?: boolean;
  // Drop the card shadow for a plainer, un-elevated table surface.
  flat?: boolean;
  // Hand a clicked row to the owner instead of opening this table's own session
  // drawer — for a table that already lives inside a session drawer, which
  // stacks the next one itself (at the right depth). The row "…" menu goes too:
  // its drawers (profile, change exercise / athlete) open at page level and
  // would sit beneath the hosting drawer.
  onOpenSession?: (session: SessionReturnDto) => void;
  // Called after a bulk mutation (delete OR tag-assign) so the owner (which
  // sources the rows via search) can re-run its query and reflect the change.
  onMutated?: () => void;
  // Called with every in-place row edit (tags, sets, Change exercise / athlete)
  // so an owner that keeps the rows can patch its own copy. Without it the edit
  // lives only in this table's overrides, which a fresh `sessions` array — a
  // re-filter in the owner included — drops again.
  onRowPatched?: (
    id: string,
    patch: (row: SessionReturnDto) => SessionReturnDto,
  ) => void;
}) {
  // Load metrics drive the value columns; the session measurements reference
  // metrics by id only, so resolve the ids from the catalogue. `useUnits` makes
  // values metric/imperial-aware.
  useEffect(() => {
    loadInBackground(loadMetrics);
    // The exercise subtitle resolves variation names against this catalogue.
    loadInBackground(loadExerciseVariations);
  }, []);
  const { t, locale } = useTranslation();
  const emptyText = emptyMessage ?? t("No completed sessions.");
  const { openExportDrawer } = useActionDrawer();
  // Gate data export behind its privilege (adjustable via the debug page).
  const canExportData = useHasPrivilege("featureDataExport");
  // Athlete data (the Athlete column + the mobile card's athlete header) is gated
  // on writeUserAthlete — the same privilege as the dashboard's athlete cards and
  // the planner's athlete surfaces.
  const canSeeAthletes = useHasPrivilege("writeUserAthlete");
  // Editing/deleting session data is gated on writeData. History stays
  // VISIBLE without it — only the mutations go away (see the drawer, which
  // renders read-only).
  const canWriteData = useHasPrivilege("writeData");  const units = useUnits();
  // Per-session metric selection: the focus metric (1RM / peak force / top load
  // / jump height, by exercise group) drives the "1RM" cell + card headline, and
  // mass-vs-inertia (from the session's measurements) gates volume.
  const { resolve } = useSessionMetrics();

  const [selected, setSelected] = useState<SessionReturnDto | null>(null);
  // The athlete × exercise pairing whose profile drawer is open (from a row's
  // "Inspect Profile" action), or null when none.
  const [profile, setProfile] = useState<ProfileTarget | null>(null);
  const [changeExercise, setChangeExercise] =
    useState<ChangeExerciseTarget | null>(null);
  const [changeAthlete, setChangeAthlete] =
    useState<ChangeAthleteTarget | null>(null);

  // Optimistic single-row overrides: a "Change exercise" edit merges its updated
  // row here (keyed by id) so the change shows in place — no full re-search. A
  // fresh `sessions` prop (new search / page / refresh) is authoritative, so
  // overrides are dropped when it arrives (reset-on-prop-change, during render).
  const [rowOverrides, setRowOverrides] = useState<
    ReadonlyMap<string, SessionReturnDto>
  >(() => new Map());
  // A fresh result set (new search / page / refresh) is authoritative, so drop
  // the optimistic overrides when it arrives.
  /* eslint-disable react-hooks/set-state-in-effect */
  useEffect(() => {
    setRowOverrides(new Map());
  }, [sessions]);
  /* eslint-enable react-hooks/set-state-in-effect */
  const effectiveSessions = useMemo(
    () =>
      rowOverrides.size === 0
        ? sessions
        : sessions.map((s) => rowOverrides.get(s.id) ?? s),
    [sessions, rowOverrides],
  );

  // Multi-select keeps the selected session OBJECTS (not just ids) so the export
  // can derive each session's athlete + exercise even after pagination swaps the
  // `sessions` page out. Newly-checked ids are always on the current page, so we
  // resolve them there; deselected ids drop out.
  const [selectedSessions, setSelectedSessions] = useState<
    ReadonlyMap<string, SessionReturnDto>
  >(() => new Map());
  const selectedKeys = useMemo(
    () => new Set(selectedSessions.keys()),
    [selectedSessions],
  );

  function changeSelection(next: ReadonlySet<string>) {
    setSelectedSessions((prev) => {
      const map = new Map<string, SessionReturnDto>();
      for (const id of next) {
        const session =
          prev.get(id) ?? effectiveSessions.find((s) => s.id === id);
        if (session) map.set(id, session);
      }
      return map;
    });
  }

  // What "Export data" starts from: the selected sessions' distinct athletes and
  // exercise definitions, and the days from the earliest to the latest one.
  // History's own filters (e.g. a tag) are deliberately not carried over: the
  // export covers every session of those athletes and exercises in those days.
  const exportSeed = useMemo(() => {
    const athletes = new Set<string>();
    const exercises = new Set<string>();
    const created: Array<number | null | undefined> = [];
    for (const s of selectedSessions.values()) {
      if (s.user?.id) athletes.add(s.user.id);
      if (s.exercise?.exerciseDefinitionID)
        exercises.add(s.exercise.exerciseDefinitionID);
      created.push(s.created);
    }
    const range = selectionRange(created);
    return {
      athletes: Array.from(athletes),
      exercises: Array.from(exercises),
      ...(range ? { range } : {}),
    } satisfies ExportSeed;
  }, [selectedSessions]);
  const canExport =
    exportSeed.athletes.length > 0 || exportSeed.exercises.length > 0;

  // Mobile select mode: cards become toggles and the bulk bar shows. Desktop
  // selects through the table's checkboxes and never needs it.
  const [selectMode, setSelectMode] = useState(false);
  function endSelection() {
    setSelectedSessions(new Map());
    setSelectMode(false);
  }

  // Bulk "Add tags" over the selected sessions (entityKind "session").
  const bulkTags = useBulkAddSessionTags({
    selectedIDs: selectedKeys,
    onApplied: () => {
      endSelection();
      // No store backs the table — the Tags column only updates via re-search.
      onMutated?.();
    },
  });

  // Bulk delete over the selected sessions. Clears the selection and asks the
  // owner to refresh (no store backs the table).
  const bulkDelete = useBulkDeleteSessions({
    selectedIDs: selectedKeys,
    onApplied: () => {
      endSelection();
      onMutated?.();
    },
  });
  // "Add tags" opens the shared tag picker anchored to its selection-bar button.
  // The mobile bar has its own trigger, so it gets its own picker instance.
  const tagTriggerRef = useRef<HTMLButtonElement>(null);
  const tagPicker = useTagPicker({
    entityKind: "session",
    tags: bulkTags.staged,
    onChange: bulkTags.setStaged,
    triggerRef: tagTriggerRef,
  });
  const mobileTagTriggerRef = useRef<HTMLButtonElement>(null);
  const mobileTagPicker = useTagPicker({
    entityKind: "session",
    tags: bulkTags.staged,
    onChange: bulkTags.setStaged,
    triggerRef: mobileTagTriggerRef,
  });

  // Bulk actions that MUTATE sessions (→ writeData), shared by the desktop
  // selection pill and the mobile bar; each bar attaches its own picker
  // trigger to "Add tags". Export (a read, desktop-only) is added to the
  // desktop list below.
  const deleteAction: SelectionActionItem = {
    key: "delete",
    icon: <TrashIcon className="size-5" />,
    label: t("Delete sessions"),
    description: t(
      "{count, plural, one {# session} other {# sessions}} will be removed",
      { count: bulkDelete.count },
    ),
    tone: "destructive",
    onClick: bulkDelete.openConfirm,
  };
  const tagsAction: SelectionActionItem = {
    key: "tags",
    icon: <TagIcon className="size-5" />,
    label: t("Add tags"),
    description: t("Assign tags to selected"),
    badge: bulkTags.staged.length,
    staged: true,
  };
  const bulkApply = {
    onClick: bulkTags.apply,
    disabled: !bulkTags.canApply,
    busy: bulkTags.applying,
  };

  // A session's own actions, shared by the row "…" menu (as menu items) and the
  // session drawer's Details tab (as the athlete / exercise "Change" buttons
  // and its actions card). The drawers they open stack above the session
  // drawer. Empty when the session has no athlete × exercise pairing.
  function sessionDetailsActions(s: SessionReturnDto): SessionDetailsActions {
    // Performance pairs an athlete with an exercise DEFINITION — fall back to
    // the instance id when the session carries no definition id.
    const athlete = s.user?.id ?? null;
    const ex = s.exercise;
    const exDefID = ex?.exerciseDefinitionID ?? ex?.id ?? null;
    if (!athlete || !ex || !exDefID) return {};
    return {
      // Open the profile drawer (same flow as the user page's Activity tab)
      // rather than navigating straight to Performance.
      onInspectProfile: () =>
        setProfile({
          userID: athlete,
          name: s.user?.name ?? null,
          exercise: ex,
          exDefID,
        }),
      // "Change exercise" mutates the session — writeData only. It swaps the
      // session's exercise for a compatible one from the athlete's own
      // instances (see ChangeExerciseDrawer).
      onChangeExercise: canWriteData
        ? () => setChangeExercise({ session: s })
        : undefined,
      // "Change athlete" mutates the session (writeData) AND lists athletes
      // (writeUserAthlete). It needs the definition id to resolve the new
      // athlete's instance of the same exercise.
      onChangeAthlete:
        canWriteData && canSeeAthletes && ex.exerciseDefinitionID
          ? () => setChangeAthlete({ session: s })
          : undefined,
    };
  }

  function sessionActions(s: SessionReturnDto): ActionMenuItem[] {
    const actions = sessionDetailsActions(s);
    const items: ActionMenuItem[] = [];
    if (actions.onInspectProfile) {
      items.push({ label: t("Inspect Profile"), onClick: actions.onInspectProfile });
    }
    if (actions.onChangeExercise) {
      items.push({ label: t("Change exercise"), onClick: actions.onChangeExercise });
    }
    if (actions.onChangeAthlete) {
      items.push({ label: t("Change athlete"), onClick: actions.onChangeAthlete });
    }
    return items;
  }

  // Shows an edit of one row in place — as an override here and in the owner's
  // rows through `onRowPatched` — instead of re-running the search.
  function patchRow(
    id: string,
    patch: (row: SessionReturnDto) => SessionReturnDto,
  ) {
    setRowOverrides((prev) => {
      const row = prev.get(id) ?? sessions.find((s) => s.id === id);
      return row ? new Map(prev).set(id, patch(row)) : prev;
    });
    onRowPatched?.(id, patch);
  }

  // Writes a session's tag change and shows it in place as a row override (like
  // "Change exercise") instead of re-running the search. Used by the Tags cell
  // and the session drawer's tag row.
  async function commitSessionTags(
    s: SessionReturnDto,
    next: EntityTagReturnDto[],
    previous: ReadonlyArray<EntityTagReturnDto>,
  ) {
    await applyTagDiff(previous, next, { workoutSessionIDs: [s.id] });
    patchRow(s.id, (row) => ({ ...row, assignedTags: next }));
  }

  // Sorting names the whole list at once, so it can't use the per-row hook the
  // cell uses; it shares the same rule via the pure `exerciseDisplayName` over
  // this index, which keeps sort order and rendered names in agreement.
  const exercisesByDefinition = useExercisesByDefinition();

  // Columns close over the resolved units + metric ids; per-row name resolution
  // (which needs a hook) lives in a cell component.
  const allColumns: DataTableColumn<SessionReturnDto>[] = [
    {
      key: "date",
      header: t("Date"),
      cellClassName: "whitespace-nowrap text-foreground-muted",
      sortAccessor: (s) => s.created ?? 0,
      cell: (s) => formatAbsoluteDateTime(s.created, locale),
    },
    {
      key: "athlete",
      header: t("Athlete"),
      sortAccessor: (s) => s.user?.name ?? "",
      cell: (s) => (
        <div className={`flex items-center gap-3 ${NAME_CELL_MAX_W}`}>
          <AthleteAvatar
            userID={s.user?.id}
            name={s.user?.name}
            size={32}
            className="body-small font-medium"
          />
          <span className="body-prominent truncate text-foreground-default">
            {s.user?.name ?? ""}
          </span>
        </div>
      ),
    },
    {
      key: "exercise",
      header: t("Exercise"),
      sortAccessor: (s) =>
        exerciseDisplayName(s.exercise, exercisesByDefinition),
      cell: (s) => <ExerciseCell session={s} />,
    },
    {
      key: "volume",
      header: t("Volume"),
      headerClassName: "text-right",
      cellClassName: "whitespace-nowrap text-right",
      cell: (s) => {
        const info = resolve(s);
        // Volume (Σ working-set load × reps) via the shared summarizeSession —
        // the exact figure the drawer's Volume-load card/chart shows, so table
        // and drawer always agree. Mass-only concept: blank for inertia
        // (flywheel) sessions, whose load can't be summed this way (the drawer
        // likewise omits the volume card for them).
        const volume = info.isInertia ? null : volumeDisplay(s, info, units);
        // Whole prescribed sets — warm-ups excluded, and a unilateral L/R pair
        // counted once — so the subtitle agrees with the volume above it. A
        // session of warm-ups only names them instead of reading "0 sets".
        const setCount = setCountLabel(s.sets, t);
        return (
          <>
            <div className="body-prominent text-foreground-default">
              {volume ? (
                <>
                  {volume.text}
                  {volume.unit && (
                    <span className="stat-small ml-1 text-foreground-muted">
                      {volume.unit}
                    </span>
                  )}
                </>
              ) : (
                ""
              )}
            </div>
            <div className="stat-small text-foreground-muted">
              {setCount}
            </div>
          </>
        );
      },
    },
    {
      key: "rm1",
      // The session focus metric varies by exercise type, so the header is the
      // generic "Focus" and each cell names its own metric under the value.
      header: t("Focus"),
      headerClassName: "text-right",
      cellClassName: "whitespace-nowrap text-right",
      // Value over the focus metric's name (1RM / peak force / top load / jump
      // height) — a right-aligned stack in the same fonts as the Volume cell.
      cell: (s) => {
        const info = resolve(s);
        const focus = focusDisplay(s, info, units);
        if (!focus) return "";
        return (
          <>
            <div className="body-prominent text-foreground-default">
              {focus.text}
              {focus.unit && (
                <span className="stat-small ml-1 text-foreground-muted">
                  {focus.unit}
                </span>
              )}
            </div>
            <div className="stat-small text-foreground-muted">
              {focusMetricLabel(info.focusKey, t)}
            </div>
          </>
        );
      },
    },
    {
      key: "tags",
      header: t("Tags"),
      // Editable in place on the selectable (History) table with writeData —
      // read-only embeds stay plain. A change lands as a row override, like
      // "Change exercise", instead of re-running the search.
      cell: (s) => (
        <InlineTagsEditor
          entityKind="session"
          tags={s.assignedTags ?? []}
          source={s}
          canEdit={selectable && canWriteData}
          onCommit={(next, previous) => commitSessionTags(s, next, previous)}
        />
      ),
    },
    {
      key: "actions",
      header: "",
      headerClassName: "w-12",
      // Row overflow menu. Wrapper stops the click from bubbling to the row
      // (which would open the session drawer).
      cell: (s) => {
        const items = sessionActions(s);
        // No resolvable pairing → no actions to offer.
        if (items.length === 0) return null;
        return (
          <div
            role="presentation"
            onClick={(e) => e.stopPropagation()}
            className="flex justify-end"
          >
            <ActionMenu ariaLabel={t("Session actions")} items={items} />
          </div>
        );
      },
    },
  ];
  // The Athlete column is dropped either because the host is already single-
  // athlete (`hideAthlete` — e.g. the user drawer, where it's redundant) or
  // because the user lacks writeUserAthlete, the privilege that gates every
  // athlete surface. Folding both into one flag also drops it from the mobile
  // cards below (they key off `showAthlete`).
  const showAthlete = !hideAthlete && canSeeAthletes;
  const columns = allColumns.filter(
    (c) =>
      !(c.key === "athlete" && !showAthlete) &&
      !(c.key === "exercise" && hideExercise) &&
      !(c.key === "actions" && onOpenSession),
  );
  // Row click / card tap: the owner's drawer when it stacks its own, else ours.
  const openSession = onOpenSession ?? setSelected;
  // Mobile bulk actions are the writeData ones only (export stays desktop), so
  // without writeData there is nothing to select for.
  const mobileSelectable = selectable && canWriteData;
  const mobileSelectAll = toggleAllVisible(
    selectedKeys,
    effectiveSessions.map((s) => s.id),
  );

  return (
    <>
      {/* Desktop (≥md): the full table. */}
      <div className="hidden md:block">
      <DataTable
        columns={columns}
        rows={effectiveSessions}
        rowKey={(s) => s.id}
        onRowClick={openSession}
        flat={flat}
        // The chevron sits in a trailing column (right of the actions menu) and
        // expands a read-only per-set summary in place; row-click still opens
        // the full drawer. The summary aligns flush under the first column.
        renderExpandedRow={(s) => (
          <SessionSetSummary session={s} units={units} info={resolve(s)} />
        )}
        loading={loading}
        emptyMessage={emptyText}
        selection={
          selectable
            ? {
                selectedKeys,
                onChange: changeSelection,
                noun: t("sessions"),
                items: [
                  // Delete + Add-tags MUTATE sessions → writeData. Export is a
                  // read, so it keeps its own featureDataExport gate.
                  ...(canWriteData
                    ? [
                        deleteAction,
                        {
                          ...tagsAction,
                          buttonRef: tagTriggerRef,
                          onClick: tagPicker.toggleOpen,
                        },
                      ]
                    : []),
                  ...(canExportData
                    ? [
                        {
                          key: "export",
                          icon: <SquareAndArrowDownIcon className="size-5" />,
                          label: t("Export data"),
                          description: t("Export selected sessions"),
                          disabled: !canExport,
                          onClick: () => openExportDrawer(exportSeed),
                        },
                      ]
                    : []),
                ],
                apply: bulkApply,
                overlay: tagPicker.overlay,
              }
            : undefined
        }
      />
      </div>

      {/* Mobile (<md): a single-column list of session history cards. Tapping a
          card opens the session drawer (same as a table row), whose header menu
          carries the row actions. On the selectable (History) list, the
          floating "Select" pill enters select mode (as in the workout
          builder): taps then toggle cards, and the pill becomes the compact
          selection pill (Delete + Add tags; its count circle exits). The owner leaves room for
          the pill below its pager (MOBILE_PILL_SPACER). No sort here: the list
          is one server page, and sorting it would look like sorting the whole
          history. */}
      <div className="space-y-3 md:hidden">
        {mobileSelectable && selectMode && (
          <MobileSelectionHeader
            allSelected={mobileSelectAll.allSelected}
            onToggleAll={() => changeSelection(mobileSelectAll.next())}
          />
        )}
        {loading ? (
          Array.from({ length: 4 }).map((_, i) => (
            <SessionHistoryCardSkeleton key={i} />
          ))
        ) : effectiveSessions.length === 0 ? (
          <p className="body-normal py-8 text-center text-foreground-muted">
            {emptyText}
          </p>
        ) : (
          effectiveSessions.map((s) => (
            <SessionMobileCard
              key={s.id}
              session={s}
              info={resolve(s)}
              units={units}
              showAthlete={showAthlete}
              selected={selectMode ? selectedKeys.has(s.id) : undefined}
              onClick={() => {
                if (!selectMode) {
                  openSession(s);
                  return;
                }
                const next = new Set(selectedKeys);
                if (next.has(s.id)) next.delete(s.id);
                else next.add(s.id);
                changeSelection(next);
              }}
            />
          ))
        )}
        {mobileSelectable &&
          (selectMode ? (
            <MobileSelectionPill
              count={selectedKeys.size}
              noun={t("sessions")}
              items={[
                deleteAction,
                {
                  ...tagsAction,
                  buttonRef: mobileTagTriggerRef,
                  onClick: mobileTagPicker.toggleOpen,
                },
              ]}
              apply={bulkApply}
              overlay={mobileTagPicker.overlay}
              onClear={endSelection}
            />
          ) : (
            !loading &&
            effectiveSessions.length > 0 && (
              <MobileSelectPill onSelect={() => setSelectMode(true)} />
            )
          ))}
      </div>

      <ConfirmDialog
        open={bulkDelete.confirmOpen}
        destructive
        title={t(
          "{count, plural, one {Delete # session?} other {Delete # sessions?}}",
          { count: bulkDelete.count },
        )}
        message={t(
          "This permanently deletes the selected sessions and all their sets, reps and videos. This can’t be undone.",
        )}
        confirmLabel={t("Delete")}
        busy={bulkDelete.deleting}
        onConfirm={bulkDelete.confirmDelete}
        onCancel={bulkDelete.cancelConfirm}
      />

      {selected && (
        <SessionDrawer
          session={selected}
          onClose={() => setSelected(null)}
          actions={{
            ...sessionDetailsActions(selected),
            // The deleted row leaves with the next search, like a bulk delete.
            onDeleted: () => {
              setSelected(null);
              onMutated?.();
            },
          }}
          tags={{
            canEdit: selectable && canWriteData,
            onCommit: (next, previous) =>
              commitSessionTags(selected, next, previous),
          }}
          // Reflect set edits (warm-up ↔ working, deletions, values) in the
          // row's volume and set count, like the other row edits.
          onSetsSaved={(sets) =>
            patchRow(selected.id, (row) => ({ ...row, sets }))
          }
          onMeasurementsSaved={(measurements) =>
            patchRow(selected.id, (row) => ({ ...row, measurements }))
          }
        />
      )}

      <ProfileDrawer target={profile} onClose={() => setProfile(null)} />

      {/* Change a session's exercise (athlete's compatible instances). Refresh
          the search on success — no store backs the table. */}
      <ChangeExerciseDrawer
        target={changeExercise}
        onClose={() => setChangeExercise(null)}
        // Upsert the updated row in place rather than forcing a re-search.
        onChanged={(updated) => patchRow(updated.id, () => updated)}
      />

      {/* Hand a session to another athlete (their instance of the same
          exercise). Upserts the row in place, like Change exercise. */}
      <ChangeAthleteDrawer
        target={changeAthlete}
        onClose={() => setChangeAthlete(null)}
        onChanged={(updated) => patchRow(updated.id, () => updated)}
      />
    </>
  );
}

// The athlete × exercise pairing behind an open profile drawer.
type ProfileTarget = {
  userID: string;
  name: string | null;
  exercise: NonNullable<SessionReturnDto["exercise"]>;
  exDefID: string;
};

// Mobile (<md) row: the shared SessionHistoryCard, made tappable (opens the
// session drawer) and — in multi-athlete contexts — topped with a compact
// athlete header the card itself doesn't carry. The card names its focus
// metric, marks each set's source + notes and lists the session's tags — the
// detail the desktop row shows in its columns and expanded summary. `selected`
// (mobile select mode) draws the checkbox and makes the card a toggle.
function SessionMobileCard({
  session,
  info,
  units,
  showAthlete,
  selected,
  onClick,
}: {
  session: SessionReturnDto;
  info: SessionMetricInfo;
  units: Units;
  showAthlete: boolean;
  selected?: boolean;
  onClick: () => void;
}) {
  const { t } = useTranslation();
  const summary = summarizeSession(session, info.ids);
  const selecting = selected !== undefined;
  return (
    <button
      type="button"
      onClick={onClick}
      aria-pressed={selected}
      className="block w-full text-left transition-opacity active:opacity-80"
    >
      {(showAthlete || selecting) && (
        <div className="mb-1.5 flex items-center gap-2 px-1">
          {selecting && <SelectMark checked={selected} />}
          {showAthlete && (
            <>
              <AthleteAvatar
                userID={session.user?.id}
                name={session.user?.name}
                size={22}
                className="stat-small font-medium"
              />
              <span className="body-small truncate text-foreground-muted">
                {session.user?.name ?? ""}
              </span>
            </>
          )}
        </div>
      )}
      <SessionHistoryCard
        session={session}
        summary={summary}
        units={units}
        loadDimension={info.loadingDimension}
        oneRmDimension={info.focusDimension}
        showVolumeSum={!info.isInertia}
        focusLabel={focusMetricLabel(info.focusKey, t)}
        showSetMarkers
        showTags
      />
    </button>
  );
}

// ─── expanded-row per-set summary ────────────────────────────────────────────
// The read-only summary shown when a session row is expanded: a chip strip of
// real aggregates (set count / total reps / best load) over a headerless,
// content-width grid of per-set lines. Each line is: the set's tracking-source
// icon (media, no circular frame) · set label · Intensity (the session's loading
// metric — mass OR inertia) · reps · exertion/RIR · tags · note. Reads straight
// from the session's sets — the History payload already carries them, so no
// extra fetch. Empty cells render blank (no dash); the chip strip deliberately
// stays numeric (no tag/PR badges).
function SessionSetSummary({
  session,
  units,
  info,
}: {
  session: SessionReturnDto;
  units: Units;
  info: SessionMetricInfo;
}) {
  const { t } = useTranslation();
  // Order sets by when they were recorded — the same rule the reps table uses —
  // so the S1…Sn labels match the drawer.
  const sets = (session.sets ?? []).slice().sort(compareSetsByCreated);
  if (sets.length === 0) {
    return (
      <p className="body-small text-foreground-muted">{t("No sets recorded.")}</p>
    );
  }

  // The loading dimension (mass or inertia) formats every Intensity value + the
  // best-load chip; reps come from the repCount metric.
  const loadDimension = info.loadingDimension;
  const repCountMetricId = info.ids.repCount;
  // A weightlifting session (focus: top load) has no RIR — its Exertion cells
  // stay empty even where an older set still carries a value.
  const weightlifting = info.focusKey === "loadingMass";
  const totalReps = sets.reduce(
    (sum, s) => sum + (setValueByMetricId(s, repCountMetricId) ?? 0),
    0,
  );
  const bestLoadRaw = sets.reduce<number | null>((max, s) => {
    const load = setLoadingValue(s);
    return load != null && (max == null || load > max) ? load : max;
  }, null);
  const bestLoad =
    bestLoadRaw != null ? units.format(bestLoadRaw, loadDimension) : null;

  // Tracking-source media by (lower-cased) id, from the exercise's equipment —
  // the set's `trackingSourceID` selects which glyph to show per line. UUIDs are
  // case-insensitive and arrive mixed-case, so key/lookup both lower-case.
  const trackingSourceMedia = new Map<string, string>();
  for (const ts of session.exercise?.equipment?.trackingSources ?? []) {
    if (ts.id && ts.media) trackingSourceMedia.set(ts.id.toLowerCase(), ts.media);
  }
  const mediaFor = (set: SetReturnDto): string | null =>
    set.trackingSourceID
      ? (trackingSourceMedia.get(set.trackingSourceID.toLowerCase()) ?? null)
      : null;
  // Only render the leading icon column when at least one set actually has a
  // tracking-source glyph — otherwise it would be an empty column padding the
  // whole table in from the left (breaking the symmetric left/right inset).
  const showIcon = sets.some((s) => mediaFor(s) != null);
  const gridCols = showIcon
    ? "grid-cols-[repeat(6,max-content)_minmax(0,1fr)]"
    : "grid-cols-[repeat(5,max-content)_minmax(0,1fr)]";

  // Set labels follow the app-wide convention: work sets and warm-ups each carry
  // their own running number — "Set 1, Set 2, …" for work sets, "Warmup 1, …"
  // for warm-ups (`set.work === false`). A unilateral set is recorded as two
  // sets sharing one number, distinguished by their side: "Set 2 L", "Set 2 R".
  const secondSides = markSecondSides(sets);
  const workingCount = countWorkingSets(sets);
  const warmupCount = workingCount === 0 ? countWarmupSets(sets) : 0;
  const setLabels: string[] = [];
  {
    let workNo = 0;
    let warmupNo = 0;
    for (const [i, s] of sets.entries()) {
      if (!secondSides[i]) {
        if (s.work) workNo += 1;
        else warmupNo += 1;
      }
      const side = sideLabel(s.side, t);
      setLabels.push(
        !s.work
          ? t("Warmup {n}", { n: warmupNo })
          : side != null
            ? t("Set {num} {side}", { num: workNo, side })
            : t("Set {n}", { n: workNo }),
      );
    }
  }

  return (
    <div className="space-y-3">
      <div className="flex flex-wrap items-center gap-2">
        <SummaryChip
          icon={<SquareStack3DUpFillIcon className="size-3.5" />}
          label={
            warmupCount > 0
              ? t(
                  "{count, plural, one {# Warm-up set} other {# Warm-up sets}}",
                  { count: warmupCount },
                )
              : t("{count, plural, one {# Set} other {# Sets}}", {
                  count: workingCount,
                })
          }
        />
        <SummaryChip
          icon={<DumbbellFillIcon className="size-3.5" />}
          label={t("{count, plural, one {# Rep} other {# Reps}}", {
            count: totalReps,
          })}
        />
        {bestLoad?.text && (
          <SummaryChip
            icon={<TrophyFillIcon className="size-3.5" />}
            label={
              <span>
                {t("Best {value}", { value: bestLoad.text })}
                {bestLoad.unit && (
                  <span className="stat-small ml-1 text-foreground-muted">
                    {bestLoad.unit}
                  </span>
                )}
              </span>
            }
          />
        )}
      </div>

      {/* The shared inner-table layout. Columns size to their content
          (max-content) + the note taking the remaining width. */}
      <SummaryGrid gridCols={gridCols}>
        {/* Header row. The tracking-source icon column (when shown) has no
            label. */}
        {showIcon && <SummaryHeaderCell />}
        <SummaryHeaderCell>{t("Set")}</SummaryHeaderCell>
        <SummaryHeaderCell>{t("Intensity")}</SummaryHeaderCell>
        <SummaryHeaderCell>{t("Reps")}</SummaryHeaderCell>
        <SummaryHeaderCell>{t("Exertion")}</SummaryHeaderCell>
        <SummaryHeaderCell>{t("Tags")}</SummaryHeaderCell>
        <SummaryHeaderCell>{t("Note")}</SummaryHeaderCell>

        {sets.map((set, i) => (
          <SetSummaryLine
            key={set.id}
            set={set}
            label={setLabels[i]}
            isLast={i === sets.length - 1}
            units={units}
            repCountMetricId={repCountMetricId}
            loadDimension={loadDimension}
            showExertion={!weightlifting}
            showIcon={showIcon}
            media={mediaFor(set)}
          />
        ))}
      </SummaryGrid>
    </div>
  );
}

// One set as a run of seven grid cells (a fragment, so they flow into the parent
// grid and stay column-aligned). Each cell carries the row's bottom border (a
// continuous line since there's no grid gap) — dropped on the last row — plus
// generous horizontal padding for breathing room. Empty measurements render an
// empty (but still bordered) cell.
function SetSummaryLine({
  set,
  label,
  isLast,
  units,
  repCountMetricId,
  loadDimension,
  showExertion,
  showIcon,
  media,
}: {
  set: SetReturnDto;
  label: string;
  isLast: boolean;
  units: Units;
  repCountMetricId: string | null;
  loadDimension: string | null;
  // False for a weightlifting session: the Exertion cell stays empty.
  showExertion: boolean;
  // Whether the leading icon column exists (some set in the session has media).
  showIcon: boolean;
  media: string | null;
}) {
  const loadRaw = setLoadingValue(set);
  const load = loadRaw != null ? units.format(loadRaw, loadDimension) : null;
  const reps = setValueByMetricId(set, repCountMetricId);
  const exertion = showExertion ? setExertion(set, units) : null;
  const tags = set.assignedTags ?? [];
  const note = set.note?.trim();

  // Shared per-cell chrome (border + padding); append cell-specific classes.
  const cell = summaryCellClass(isLast);

  return (
    <>
      {showIcon && (
        <div className={cell}>
          {media && (
            <LottieCircle
              media={media}
              variant="equipmentIcon"
              size={18}
              surfaceClassName="bg-transparent"
            />
          )}
        </div>
      )}
      <div className={`${cell} body-small whitespace-nowrap text-foreground-muted`}>
        {label}
      </div>
      <div className={`${cell} whitespace-nowrap`}>
        {load?.text && (
          <span className="body-prominent tabular-nums text-foreground-default">
            {load.text}
            {load.unit && (
              <span className="stat-small ml-1 text-foreground-muted">
                {load.unit}
              </span>
            )}
          </span>
        )}
      </div>
      <div className={`${cell} whitespace-nowrap`}>
        {reps != null && (
          <span className="body-prominent tabular-nums text-foreground-default">
            {reps}
          </span>
        )}
      </div>
      <div className={`${cell} whitespace-nowrap`}>
        {exertion && (
          <span className="body-prominent tabular-nums text-foreground-default">
            {exertion.text}
            {exertion.unit && (
              <span className="stat-small ml-1 text-foreground-muted">
                {exertion.unit}
              </span>
            )}
          </span>
        )}
      </div>
      <div className={cell}>
        {tags.length > 0 && (
          <div className="flex flex-wrap gap-1.5">
            {tags.map((tag) => (
              <TagPill key={tag.id} tag={tag} />
            ))}
          </div>
        )}
      </div>
      <div className={`${cell} body-small min-w-0 text-foreground-muted`}>
        {note && <span className="min-w-0 truncate">{note}</span>}
      </div>
    </>
  );
}

function SummaryChip({ icon, label }: { icon: ReactNode; label: ReactNode }) {
  return (
    <span className="stat-normal inline-flex items-center gap-1.5 rounded-full bg-surface-base-muted px-3 py-1 text-foreground-muted">
      {icon}
      {label}
    </span>
  );
}

// A set-level measurement's value for a metric id (user override when set, else
// the auto value) — or null when the set carries no such measurement.
function setValueByMetricId(
  set: SetReturnDto,
  metricId: string | null,
): number | null {
  if (!metricId) return null;
  const m = (set.measurements ?? []).find((x) => x.metricID === metricId);
  if (!m) return null;
  return measurementValue(m);
}

// The set's loading value (its Intensity) — from whichever measurement carries
// the `loading`-flagged metric, so it works for mass (loadingMass) AND inertia
// (flywheel) sessions alike. Null when the set carries no load.
function setLoadingValue(set: SetReturnDto): number | null {
  for (const m of set.measurements ?? []) {
    const metric = m.metric ?? getMetric(m.metricID) ?? null;
    if (metric?.loading) return measurementValue(m);
  }
  return null;
}

// The set's exertion (RIR) measurement, resolved + formatted for display. RIR is
// a bounded metric, so its value passes through `formatRanged` for the "6+"
// overflow; the unit ("RIR") is the exertion dimension's symbol.
function setExertion(
  set: SetReturnDto,
  units: Units,
): { text: string; unit: string | null } | null {
  for (const m of set.measurements ?? []) {
    const metric: MetricReturnDto | null =
      m.metric ?? getMetric(m.metricID) ?? null;
    if (metric?.dimension !== "exertion") continue;
    const value = measurementValue(m);
    const text = isBoundedMetric(metric)
      ? formatRanged(value, metric)
      : String(value);
    return { text, unit: units.symbol(metric.dimension) };
  }
  return null;
}

function measurementValue(m: SessionMeasurementReturnDto): number {
  return m.valueUser != null && m.valueUser > 0 ? m.valueUser : m.value;
}

// Exercise name (localized, per-row hook) + a camera marker when the session has
// a video on any of its sets.
function ExerciseCell({ session }: { session: SessionReturnDto }) {
  const { t } = useTranslation();
  const exerciseName = useExerciseDisplayName(
    session.exercise ?? undefined,
    t("Exercise"),
  );
  // An exercise name isn't unique on its own; pair it with the equipment ·
  // variation detail (same treatment as the Exercises table).
  const subtitle = useExerciseSubtitle(session.exercise ?? undefined);
  const hasVideo = (session.sets ?? []).some((set) => set.video != null);
  return (
    // Cap the cell so a very long exercise name TRUNCATES (…) instead of widening
    // the auto-layout column and pushing the whole table past the container —
    // now the shared cap, so every table's name column truncates at one point.
    <div className={`min-w-0 ${NAME_CELL_MAX_W}`}>
      <div className="flex items-center gap-2">
        <span className="min-w-0 truncate">{exerciseName}</span>
        {hasVideo && (
          <span title={t("Has video")} aria-label={t("Has video")}>
            <VideoFillIcon className="size-4 shrink-0 text-foreground-muted" />
          </span>
        )}
      </div>
      {subtitle && (
        <div className="body-small truncate text-foreground-muted">
          {subtitle}
        </div>
      )}
    </div>
  );
}

// Pager for the sessions list — exported alongside the table since the browse
// experience reuses both. A thin wrapper over the shared TablePagination: this
// list pages on the SERVER (`page`/`per` on the search endpoints), so the page
// state lives in the metadata rather than in the table.
export function SessionsPagination({
  metaData,
  onPage,
}: {
  metaData: PageMetadata;
  onPage: (page: number) => void;
}) {
  const { t } = useTranslation();
  return (
    <TablePagination
      page={metaData.page}
      totalPages={pageCount(metaData.total, metaData.per)}
      onPage={onPage}
      summary={t("{count, plural, one {# session} other {# sessions}}", {
        count: metaData.total,
      })}
    />
  );
}

// The focus-metric value the "1RM" column shows: 1RM for barbell strength, but
// peak force (flywheel), top load (weightlifting) or jump height (jumps) per the
// exercise group — `summarizeSession`'s `oneRm` reads the resolved focus metric
// (falling back to 1RM / peak force), and `info.focusDimension` units it for the
// active metric/imperial system.
function focusDisplay(
  session: SessionReturnDto,
  info: SessionMetricInfo,
  units: Units,
): { text: string; unit: string | null } | null {
  const value = summarizeSession(session, info.ids).oneRm;
  if (value == null) return null;
  const f = units.format(value, info.focusDimension);
  if (f.text == null) return null;
  return { text: f.text, unit: f.unit };
}

// The focus metric's short name, shown under its value in the Focus column so
// each row says which figure it is (it varies by exercise type).
function focusMetricLabel(
  focusKey: SessionMetricInfo["focusKey"],
  t: (key: string) => string,
): string {
  switch (focusKey) {
    case "forcePeak":
      return t("Peak force");
    case "loadingMass":
      return t("Highest load");
    case "jumpHeight":
      return t("Jump height");
    default:
      return t("1RM");
  }
}

// The per-session Volume cell: Σ working-set load × reps via the shared
// `summarizeSession` (so the table matches the drawer's Volume-load card/chart
// exactly), formatted + united by the load metric's dimension. Number + unit
// separate so the cell can style the unit smaller.
function volumeDisplay(
  session: SessionReturnDto,
  info: SessionMetricInfo,
  units: Units,
): { text: string; unit: string | null } | null {
  const value = summarizeSession(session, info.ids).volumeLoad;
  if (value == null) return null;
  const dimension = getMetric(info.ids.loadingMass)?.dimension ?? null;
  const f = units.format(value, dimension);
  if (f.text == null) return null;
  return { text: f.text, unit: f.unit };
}


