"use client";

import { useCallback, useEffect, useId, useRef, useState } from "react";
import { createPortal } from "react-dom";
import type { SessionReturnDto } from "@enode/core/api/dtos/sessions";
import type { HistoryStatsReturnDtoV2 } from "@enode/core/api/dtos/history-stats";
import { getSessionHistoryStats, getSet, updateSession } from "@enode/core/api/sessions";
import { formatAbsoluteDateTime } from "@enode/core/format/date-time";
import {
  useExerciseDisplayName,
  useExerciseSubtitle,
} from "@enode/core/exercises/hooks";
import { useHasPrivilege } from "@enode/core/auth/use-privilege";
import { useTranslation } from "@enode/core/translations/hooks";
import {
  setOnlyFocusMetrics,
  setShowEccentricReps,
  setShowHeatmap,
  setShowReps,
  useOnlyFocusMetrics,
  useShowEccentricReps,
  useShowHeatmap,
  useShowReps,
} from "@enode/core/training/flags";
import type { EntityTagReturnDto } from "@enode/core/api/dtos/tags";
import { ActionMenu } from "@enode/ui/action-menu";
import { applyTagDiff } from "../../components/tag-diff";
import {
  DiscardChangesDialog,
  useDiscardGuard,
} from "../../components/discard-guard";
import { presentError } from "@enode/ui/feedback/use-error-presenter";
import { toast } from "@enode/ui/feedback/toast-store";
import { SurfaceZIndexProvider } from "@enode/ui/surface-z-index";
import { useModalFocus } from "@enode/ui/use-modal-focus";
import { SHELL_MAIN_ID } from "../../components/shell-cover";
import {
  HEADER_BLUR,
  HEADER_MIN_HEIGHT,
  headerEdgeClass,
} from "@enode/ui/header-height";
import { ScrollEdgeFade } from "@enode/ui/scroll-edge-fade";
import {
  AdjustmentsIcon,
  EllipsisIcon,
  SpinnerIcon,
  XIcon,
} from "@enode/ui/icons";
import {
  SegmentedPicker,
  type SegmentedPickerOption,
} from "@enode/ui/segmented-picker";
import { reportError } from "@enode/core/errors/report";
import { useMetricByKey } from "@enode/core/metrics/hooks";
import { recalculateProfile } from "./data/performance/profile-recalculation";
import { refreshSessionRm1 } from "./session-rm1-refresh";
import { saveSessionTopLoad, withSessionTopLoad } from "./session-top-load";
import { markPairStale } from "./data/performance/use-profile-reps";
import { refreshExercisePbAfterEdit } from "./exercise-pb-refresh";
import { SessionPerformanceTab } from "./session-performance-tab";
import { setCountLabel } from "./set-count-label";
import { refreshCachedUser } from "./users/user-caches";
import { SessionRepsTab } from "./session-reps-tab";
import { SessionDetailsTab, type SessionDetailsActions } from "./session-details-tab";
import { SessionSummaryTab } from "./session-summary-tab";
import { SessionTabBoundary } from "./session-tab-boundary";
import { SessionTechniqueTab } from "./session-technique-tab";
import { useSessionEditor } from "./use-session-editor";
import { useSessionIsBarbell } from "./use-session-is-barbell";
import { useSessionMetrics } from "./use-session-metrics";
import { Button } from "@enode/ui/button";

// Full-screen session drawer: slides in from the right (same transition as the
// other portal drawers) and covers the ENTIRE viewport — `fixed inset-0` over
// the sidebar too (the desktop sidebar is an in-flow flex column with no raised
// z-index, so this z-40 fixed layer sits above it). Header (title + secondary meta +
// actions) and a tab switch; tab CONTENTS are placeholders.

// Matches the drawer slide duration (transition-transform duration-300).
const SLIDE_MS = 300;

// The sheet always opens at its reading width; a drag only lasts while it is
// open. (It used to reopen at the last dragged width — with no control left
// that snaps it back, one wide drag made every later session open huge.) The
// key the width was stored under is cleared once, so that stale width goes.
const LEGACY_WIDTH_KEY = "session-drawer:width";
// Resize bounds. The sheet opens at COLLAPSED_WIDTH (≈76rem, the reading width);
// the left-edge handle drags it to anything up to full screen, clamped to
// [COLLAPSED_WIDTH, viewport] — the sheet never shrinks below its default
// opened width. At/above EXPAND_THRESHOLD the sheet counts as "expanded" —
// drives the technique tab's vertical metrics panel.
const COLLAPSED_WIDTH = 1216;
const EXPAND_THRESHOLD = 1280;

// Shared chrome for the header's circular icon buttons (close / actions) — the
// standard bordered header button (cf. DrawerViewHeader). Each call site
// prepends its own display class (`flex`).
const HEADER_BTN =
  "size-10 shrink-0 items-center justify-center rounded-full bg-surface-base shadow ring-1 ring-surface-stroke text-foreground-default transition-colors hover:bg-surface-base-muted";

// Stack of mounted SessionDrawers — a summary-tab "Open session details" opens
// one over another. Only the topmost responds to Escape.
const drawerStack: string[] = [];

export type SessionDrawerTab = "summary" | "reps" | "performance" | "technique" | "details";
type Tab = SessionDrawerTab;

export function SessionDrawer({
  session,
  onClose,
  depth = 0,
  actions = {},
  tags,
  onSetsSaved,
  initialTab = "performance",
  repFilterTags,
  onMeasurementsSaved,
}: {
  session: SessionReturnDto;
  onClose: () => void;
  // The tab it opens on, and a "Show only" preset for the Reps tab — a tag's
  // page opens a session straight on the reps that tag marked.
  initialTab?: Tab;
  repFilterTags?: EntityTagReturnDto[];
  // Stacking level. A summary-tab "Open session details" opens a nested drawer
  // at depth+1, sat above this one (higher z-index). Callers leave it at 0.
  depth?: number;
  // Session-level actions from the host (the History table's — Inspect
  // profile, Change exercise/athlete, and refreshing after a delete), offered
  // in the Details tab. The drawers they open stack above this one.
  actions?: SessionDetailsActions;
  // The host's tag write for the Details tab: `canEdit` gates the picker, and
  // `onCommit` writes and reflects the change in the host's own rows. Without
  // it the tab writes tags itself (writeData), with no host row to update.
  tags?: {
    canEdit: boolean;
    onCommit: (
      next: EntityTagReturnDto[],
      previous: ReadonlyArray<EntityTagReturnDto>,
    ) => Promise<void>;
  };
  // The session's sets as just saved from the Reps tab, so the host can show
  // them in its own row (set count, volume) without a re-search.
  onSetsSaved?: (sets: NonNullable<SessionReturnDto["sets"]>) => void;
  /** The session's measurements changed after a set edit (its 1RM, recalculated). */
  onMeasurementsSaved?: (
    measurements: NonNullable<SessionReturnDto["measurements"]>,
  ) => void;
}) {
  const { t, locale } = useTranslation();
  const drawerId = useId();
  // Same names and order as the tracking app's InsightsSheet: Performance
  // first (the tab it opens on), then History and Details last. The "summary" id
  // stays — it keys the tab's content and its "…" menu.
  const tabs: SegmentedPickerOption<Tab>[] = [
    { value: "performance", label: t("Performance") },
    { value: "reps", label: t("Reps") },
    { value: "technique", label: t("Technique") },
    { value: "summary", label: t("History") },
    { value: "details", label: t("Details") },
  ];
  // A session opened from the summary tab's history cards, shown as a nested
  // drawer stacked over this one; closing it returns here.
  const [detailSession, setDetailSession] = useState<SessionReturnDto | null>(
    null,
  );
  // Each stack level sits above the previous (backdrop + panel z-index bumped).
  const backdropZ = 30 + depth * 100;
  const panelZ = 40 + depth * 100;
  const [tab, setTab] = useState<Tab>(initialTab);
  // Measure the frosted overlay header (title + meta + tabs — it wraps, so its
  // height varies with width) so the tab-content region pads by its exact
  // height and content scrolls under the glass. Same approach as PageShell.
  // Unmeasured for the first paint only — the panel is still off-screen then
  // (it slides in), so there's no visible jump.
  const headerRef = useRef<HTMLDivElement>(null);
  const [headerHeight, setHeaderHeight] = useState<number | null>(null);
  // The panel element (via callback ref → state so descendants re-render once
  // it's live): the full-screen set review portals into it, so it fills this
  // drawer instead of the whole viewport.
  const [panelEl, setPanelEl] = useState<HTMLDivElement | null>(null);
  const panelRef = useRef<HTMLDivElement | null>(null);
  const attachPanel = useCallback((el: HTMLDivElement | null) => {
    panelRef.current = el;
    setPanelEl(el);
  }, []);
  // The panel takes the focus while open, Tab stays inside it, and on close
  // the focus returns to what opened it (the History row). Escape is not
  // handled here — it goes through the discard guard below.
  useModalFocus(panelRef, true);
  // Where the content column starts (AppShell's <main>): the sheet never
  // reaches further left, so it clears the persistent sidebar instead of
  // cutting through it. 0 when the sidebar overlays (phones) or is collapsed,
  // and outside the dashboard shell.
  const [clearLeft, setClearLeft] = useState(0);
  useEffect(() => {
    const main = document.getElementById(SHELL_MAIN_ID);
    if (!main) return;
    const measure = () => setClearLeft(Math.max(0, main.getBoundingClientRect().left));
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(main);
    window.addEventListener("resize", measure);
    return () => {
      observer.disconnect();
      window.removeEventListener("resize", measure);
    };
  }, []);
  useEffect(() => {
    const el = headerRef.current;
    if (!el) return;
    // Reads the header's laid-out height (DOM measurement) after mount / on
    // resize — a real measurement, not a render-derived value.
    const measure = () => setHeaderHeight(el.offsetHeight);
    measure();
    const observer = new ResizeObserver(measure);
    observer.observe(el);
    return () => observer.disconnect();
  }, []);
  // Whether the Technique charts show the sensor orientation flipped 180° about
  // the vertical axis — the correction for a barbell sensor mounted the wrong
  // way round (see `flipStrengthOrientation`). Toggled from the header "…" menu.
  const [flipOrientation, setFlipOrientation] = useState(false);
  // Shared global view toggles (same flags the tracking app uses, so
  // the choice is consistent app-wide): whether the Performance charts break
  // down per rep, and whether eccentric rep bars are drawn. Surfaced as an "…"
  // menu on the Reps + Performance tabs below.
  const showReps = useShowReps();
  const showEccentricReps = useShowEccentricReps();
  // Reps-tab-only view toggles (heatmap tint + focus-metric-only columns),
  // shared globals surfaced in the same header "…" menu.
  const showHeatmap = useShowHeatmap();
  const onlyFocusMetrics = useOnlyFocusMetrics();
  // A "jump to rep technique" request from the Reps tab: switches to the
  // Technique tab and preselects that set/rep there.
  const [techniqueTarget, setTechniqueTarget] = useState<{
    setId: string;
    repId: string;
  } | null>(null);
  function jumpToTechnique(setId: string, repId: string) {
    setTechniqueTarget({ setId, repId });
    setTab("technique");
  }
  // The sheet's width (px) is the single source of truth: the left-edge handle
  // drags it to any width between the reading width and full screen. Opens at
  // the reading width (narrower only when the window is).
  const [width, setWidth] = useState<number>(() =>
    typeof window === "undefined"
      ? COLLAPSED_WIDTH
      : Math.min(COLLAPSED_WIDTH, window.innerWidth),
  );
  // True while dragging the resize handle — suppresses the width transition so
  // the edge tracks the cursor 1:1.
  const [dragging, setDragging] = useState(false);
  // Derived: "expanded" once the sheet is at/over the threshold width.
  const expanded = width >= EXPAND_THRESHOLD;

  useEffect(() => {
    window.localStorage.removeItem(LEGACY_WIDTH_KEY);
  }, []);
  // Keep the width within the viewport when the window shrinks.
  useEffect(() => {
    const onResize = () => setWidth((w) => Math.min(w, window.innerWidth));
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);
  // While dragging, lock body text-selection + force the resize cursor globally.
  useEffect(() => {
    if (!dragging) return;
    const prevUserSelect = document.body.style.userSelect;
    const prevCursor = document.body.style.cursor;
    document.body.style.userSelect = "none";
    document.body.style.cursor = "col-resize";
    return () => {
      document.body.style.userSelect = prevUserSelect;
      document.body.style.cursor = prevCursor;
    };
  }, [dragging]);

  // The right-anchored sheet grows leftward, so its width is the distance from
  // the cursor to the right viewport edge.
  function resizeTo(clientX: number) {
    const next = window.innerWidth - clientX;
    setWidth(
      Math.min(Math.max(next, COLLAPSED_WIDTH), window.innerWidth - clearLeft),
    );
  }
  // Drives the slide transition: mount off-screen (translate-x-full), then flip
  // to translate-x-0 on the next frame so the transition plays; on close, slide
  // back out before unmounting.
  const [shown, setShown] = useState(false);
  const exerciseName = useExerciseDisplayName(
    session.exercise ?? undefined,
    t("Exercise"),
  );

  // The list/session reads have no reps — fetch each set (full, with reps) on open
  // and assemble the complete session. `model` is the base session until loaded.
  const [fullSession, setFullSession] = useState<SessionReturnDto | null>(null);
  const [status, setStatus] = useState<"loading" | "loaded" | "error">(
    "loading",
  );
  const model = fullSession ?? session;

  // Bar-mounted exercises only get the bar-path + inclination/rotation technique
  // charts (same gate as the tracking app's Technique tab). Resolved from the
  // root user's catalogue exercise for this session's definition — see the hook.
  const isBarbell = useSessionIsBarbell(model);
  // A weightlifting lift has a PB, not a 1RM (G-21, 17.11.26): its focus
  // metric is the top load, so the recalculation toasts say "PB" for it. The
  // strength wording stays as it was.
  const { resolve: resolveSessionMetrics } = useSessionMetrics();
  const isWeightliftingSession = resolveSessionMetrics(model).focusKey === "loadingMass";

  // A save that changed loads, validity or deletions leaves the athlete's
  // velocity profiles and 1RMs on the old values: the set/rep routes store the
  // edit and refit nothing. So ask for the recalculation here — the same queued
  // job as the user drawer's "Recalculate training data" and the profile reps
  // drawer, sharing their job store, so a running one is never duplicated — and
  // have this pair's Performance data refetch when it ends.
  //
  // The session's own 1RM isn't part of that job. It is estimated from the
  // corrected sets here, like the apps do: right away, so a closed tab can't
  // lose it, and again when the job ends, because the estimate also reads the
  // exercise's profile and 1RM, which an entered typo may still be skewing now.
  const rm1MetricID = useMetricByKey("rm1")?.id ?? null;
  function updateSessionRm1(exerciseDefinitionID: string) {
    if (!rm1MetricID) return;
    refreshSessionRm1(session.id, exerciseDefinitionID, rm1MetricID)
      .then((measurements) => {
        if (!measurements) return;
        setFullSession((prev) => (prev ? { ...prev, measurements } : prev));
        onMeasurementsSaved?.(measurements);
      })
      .catch((err: unknown) => {
        reportError(err, { context: "session-drawer.session-rm1" });
      });
  }
  function recalculateAfterSave() {
    const userID = session.user?.id;
    const exDefID = session.exercise?.exerciseDefinitionID;
    // Profiles and 1RMs are per exercise definition: without one there is
    // nothing of this session's to refit.
    if (!userID || !exDefID) return;
    // Said on the save, not on the answer — like the user drawer's button: the
    // answer isn't the result (the completion notification is).
    toast.info(
      isWeightliftingSession
        ? t(
            "Saved. Profiles and the PB are being recalculated — you’ll get a notification when they’re up to date.",
          )
        : t(
            "Saved. Profiles and 1RMs are being recalculated — you’ll get a notification when they’re up to date.",
          ),
    );
    updateSessionRm1(exDefID);
    // Waits under the session's id: another session of this exercise saved during
    // the job has its own 1RM to update.
    void recalculateProfile(userID, session.id, () => {
      markPairStale(userID, exDefID);
      updateSessionRm1(exDefID);
    }).then((accepted) => {
      if (accepted) return;
      toast.warning(
        isWeightliftingSession
          ? t(
              "Saved, but profiles and the PB couldn’t be recalculated, so Performance still shows the old values.",
            )
          : t(
              "Saved, but profiles and 1RMs couldn’t be recalculated, so Performance still shows the old values.",
            ),
        {
          durationMs: 0,
          actionLabel: t("Try again"),
          onAction: recalculateAfterSave,
        },
      );
    });
    // Right away too, so Performance shows the edited sets while the job runs.
    markPairStale(userID, exDefID);
    // 18.11.26 (audit A): the bumps above run BEFORE the server's PB job, so
    // the lift card and the History row read the old PB basis. Poll the
    // exercise's PB at 2, 5, 10, 20 s until it changed (or stop), then fetch
    // the stats, the session 1RM and the pair's analyses once more.
    void refreshExercisePbAfterEdit(userID, exDefID, {
      onSettled: () => {
        setStatsVersion((v) => v + 1);
        updateSessionRm1(exDefID);
        markPairStale(userID, exDefID);
      },
    });
  }

  // Editing layer for the Reps tab. Seeded once the full set/rep tree loads; on
  // save the committed tree flows back into `fullSession` so the other tabs and
  // the header stay consistent.
  // Editing session data needs writeData. Without it the drawer still opens
  // and shows everything — the editor just comes back read-only (no-op mutators,
  // never dirty), so the reps tab drops its menus/value editors and the
  // save/discard footer can't appear.
  const canWriteData = useHasPrivilege("writeData");
  const loadingMassMetricID = useMetricByKey("loadingMass")?.id ?? null;
  // Bumped after a saved set edit, so the history stats below are fetched
  // again (r5-17).
  const [statsVersion, setStatsVersion] = useState(0);
  // A weightlifting session's focus value is its highest load, stored on the
  // session (G-21); the set routes leave it as tracked. Patched here right away
  // (the History row's focus column and the summary follow the edit without a
  // reload, r5-17, 17.11.26), then stored like the apps' `updateFocusMetric`.
  // A session without a stored highest load is no weightlifting session.
  function updateSessionTopLoad(sets: NonNullable<SessionReturnDto["sets"]>) {
    if (!loadingMassMetricID || !isWeightliftingSession) return;
    const measurements = withSessionTopLoad(model.measurements, sets, loadingMassMetricID);
    if (!measurements) return;
    setFullSession((prev) => (prev ? { ...prev, measurements } : prev));
    onMeasurementsSaved?.(measurements);
    saveSessionTopLoad(session.id, sets, loadingMassMetricID)
      // Once stored, the stats are fetched again, in case the server's
      // figures read the stored value.
      .then((saved) => {
        if (saved) setStatsVersion((v) => v + 1);
      })
      .catch((err: unknown) => {
        reportError(err, { context: "session-drawer.session-top-load" });
      });
  }
  const editor = useSessionEditor(
    fullSession?.sets ?? null,
    (sets, trainingDataChanged) => {
      setFullSession((prev) => (prev ? { ...prev, sets } : prev));
      onSetsSaved?.(sets);
      updateSessionTopLoad(sets);
      // The summary's server figures (lifts per band, muscle map) are from the
      // sets as they were: fetch them again, keeping the old ones on screen
      // until the new ones are in (r5-17).
      setStatsVersion((v) => v + 1);
      // The Users page caches the athlete's sessions (week, activity) for the
      // whole visit; drop them now rather than when the recalculation ends.
      if (session.user?.id) refreshCachedUser(session.user.id);
      if (trainingDataChanged) recalculateAfterSave();
    },
    canWriteData,
  );

  useEffect(() => {
    let cancelled = false;
    Promise.all((session.sets ?? []).map((s) => getSet(s.id)))
      .then((sets) => {
        if (cancelled) return;
        setFullSession({ ...session, sets });
        setStatus("loaded");
      })
      .catch((err) => {
        if (cancelled) return;
        console.error("Failed to load session sets:", err);
        setStatus("error");
      });
    return () => {
      cancelled = true;
    };
  }, [session]);

  // Aggregate history stats (V2) for this session — fetched on open so the debug
  // button below can log the raw payload while we wire up the real UI.
  const [historyStats, setHistoryStats] =
    useState<HistoryStatsReturnDtoV2 | null>(null);
  // Separate loading flag for the stats fetch (the summary's two top cards show
  // skeletons until it settles). Settles on BOTH success and error so the
  // skeletons never hang.
  const [historyStatsLoading, setHistoryStatsLoading] = useState(true);
  // Reset to the skeleton state when a different session is shown — render-phase
  // adjustment (not in an effect) per the project's prop-change reset idiom.
  const [statsSessionID, setStatsSessionID] = useState(session.id);
  if (session.id !== statsSessionID) {
    setStatsSessionID(session.id);
    setHistoryStats(null);
    setHistoryStatsLoading(true);
    setFlipOrientation(false);
  }
  useEffect(() => {
    let cancelled = false;
    getSessionHistoryStats(session.id)
      .then((stats) => {
        if (!cancelled) setHistoryStats(stats);
      })
      .catch((err) => {
        if (!cancelled) console.error("Failed to load history stats:", err);
      })
      .finally(() => {
        if (!cancelled) setHistoryStatsLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [session.id, statsVersion]);

  useEffect(() => {
    // Double rAF: let the browser paint the closed (off-screen) state once, then
    // flip to open — so the slide-in transition plays even when the drawer mounts
    // mid-update (e.g. a nested drawer opened from a history card).
    let inner = 0;
    const outer = requestAnimationFrame(() => {
      inner = requestAnimationFrame(() => setShown(true));
    });
    return () => {
      cancelAnimationFrame(outer);
      cancelAnimationFrame(inner);
    };
  }, []);

  const closingRef = useRef(false);
  const slideOut = useCallback(() => {
    // A second close request (double click, Escape + click) must not run onClose twice.
    if (closingRef.current) return;
    closingRef.current = true;
    setShown(false);
    window.setTimeout(onClose, SLIDE_MS);
  }, [onClose]);
  const discardGuard = useDiscardGuard(slideOut);
  const { handleDirtyChange } = discardGuard;
  useEffect(() => {
    handleDirtyChange(editor.isDirty);
  }, [editor.isDirty, handleDirtyChange]);
  const requestClose = discardGuard.requestClose;
  const requestCloseRef = useRef(requestClose);
  useEffect(() => {
    requestCloseRef.current = requestClose;
  });

  // Register in the drawer stack while mounted so only the topmost handles Esc.
  useEffect(() => {
    drawerStack.push(drawerId);
    return () => {
      const idx = drawerStack.lastIndexOf(drawerId);
      if (idx !== -1) drawerStack.splice(idx, 1);
    };
  }, [drawerId]);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (
        e.key === "Escape" &&
        drawerStack[drawerStack.length - 1] === drawerId
      ) {
        requestCloseRef.current();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [drawerId]);

  // The session's tags and note as the Details tab last wrote them. Keyed to
  // the `session` object they were written over: a fresh one from the host
  // (its row patched, a new session opened) is authoritative again.
  const [metaEdit, setMetaEdit] = useState<{
    source: SessionReturnDto;
    tags: EntityTagReturnDto[];
    note: string | null;
  } | null>(null);
  const edited = metaEdit?.source === session ? metaEdit : null;
  const sessionTags = edited?.tags ?? session.assignedTags ?? [];
  const sessionNote = edited ? edited.note : (session.note ?? null);
  // The tag editor's optimistic state resets when this changes.
  const tagsSource = edited ?? session;

  async function commitTags(
    next: EntityTagReturnDto[],
    previous: ReadonlyArray<EntityTagReturnDto>,
  ) {
    if (tags) await tags.onCommit(next, previous);
    else await applyTagDiff(previous, next, { workoutSessionIDs: [session.id] });
    setMetaEdit({ source: session, tags: next, note: sessionNote });
  }

  // PUT replaces both the note and the tag list, so the current tags are sent
  // along (see `updateSession`).
  async function saveNote(next: string) {
    try {
      await updateSession(session.id, {
        id: session.id,
        note: next === "" ? null : next,
        assignedTagIDs: sessionTags
          .map((tag) => tag.id)
          .filter((id): id is string => !!id),
      });
    } catch (err) {
      presentError(err, t, { onRetry: () => {
          // saveNote presents its own failure; the retry must not reject unhandled.
          saveNote(next).catch(() => {});
        },
      });
      throw err;
    }
    setMetaEdit({ source: session, tags: sessionTags, note: next === "" ? null : next });
  }

  // Header mirrors the profile drawer: "Athlete × Exercise" as the title, with a
  // meta subtitle carrying the session's when + the full exercise (name + its
  // equipment/variation detail) + set count. No athlete name in the subtitle —
  // it already leads the title.
  const exerciseSubtitle = useExerciseSubtitle(session.exercise ?? undefined);
  // Whole prescribed sets: warm-ups excluded, a unilateral L/R pair counted
  // once — the same count the sessions table shows, warm-ups named when there
  // is nothing else.
  const setCount = setCountLabel(session.sets, t);
  const title = `${session.user?.name ?? "—"} × ${exerciseName}`;
  const secondary = [
    formatAbsoluteDateTime(session.created, locale),
    exerciseName,
    exerciseSubtitle ?? undefined,
    setCount,
  ]
    .filter((s): s is string => !!s)
    .join("  ·  ");

  // Top padding for the tab-content area while the header overlays it: the
  // measured header height + 8px. The header box already ends 16px below the
  // tab row (its pb-4 breathing room for the frost feather), so content still
  // starts 24px under the tabs — the p-6 gap it always had.
  const overlayPad =
    HEADER_BLUR && headerHeight != null
      ? { paddingTop: headerHeight + 8 }
      : undefined;

  // Portal to <body> so the full-screen overlay is never re-scoped by an
  // ancestor's containing block (a transform / overflow / contain in the page's
  // table subtree shrank `fixed inset-0` on the History page). A body child is
  // always positioned against the viewport.
  if (typeof document === "undefined") return null;

  return createPortal(
    <>
      {/* Backdrop — dims the app behind the slide-over; tap to close. Only the
          TOPMOST drawer dims (hidden while it has a nested child open), so the
          dark doesn't compound as drawers stack. The topmost's backdrop sits
          above all lower panels, so it still dims them. */}
      <div
        aria-hidden
        onClick={requestClose}
        style={{ zIndex: backdropZ }}
        className={`fixed inset-0 bg-black/40 transition-opacity duration-300 ${
          shown && !detailSession ? "opacity-100" : "opacity-0"
        }`}
      />
      {/* A nested drawer stacks above the floating-popover layer (panelZ climbs
          with depth). Tell body-portaled popovers (ActionMenu, …) opened inside
          this panel to lift above it, so their menus don't render behind it. */}
      <SurfaceZIndexProvider value={panelZ}>
      <div
        ref={attachPanel}
        role="dialog"
        tabIndex={-1}
        aria-modal="true"
        aria-label={title}
        // Right-anchored slide-over. Width is driven by `width` (px) — but only
        // from md up (via the CSS var): on mobile the sheet is always the full
        // screen, so a width persisted on desktop never narrows it there. From
        // md up it is also capped at the content column (`--drawer-clear`, the
        // sidebar's width), so its left edge never cuts through the sidebar.
        // Surface, backdrop, slide and shadow-only-while-open match DrawerStack.
        style={
          {
            "--drawer-w": `${width}px`,
            "--drawer-clear": `${clearLeft}px`,
            zIndex: panelZ,
          } as React.CSSProperties
        }
        className={`fixed inset-y-0 right-0 flex w-full flex-col bg-surface-drawer outline-none md:max-w-[min(var(--drawer-w),calc(100vw_-_var(--drawer-clear)))] ${
          shown ? "translate-x-0 shadow-2xl" : "translate-x-full"
        } ${
          dragging
            ? ""
            : // Tailwind v4 animates `translate-x-*` via the `translate`
              // property (not `transform`), so the slide must transition
              // `translate` here; `max-width` covers the chevron/drag resize.
              "transition-[translate,max-width] duration-300 ease-out motion-reduce:transition-none"
        }`}
      >
        {/* Drag-to-resize handle — a thin strip on the left edge; drag to set any
            width. Hidden on mobile, where the sheet is full-width. */}
        <div
          role="separator"
          aria-orientation="vertical"
          aria-label={t("Resize panel")}
          onPointerDown={(e) => {
            e.preventDefault();
            e.currentTarget.setPointerCapture(e.pointerId);
            setDragging(true);
          }}
          onPointerMove={(e) => {
            if (dragging) resizeTo(e.clientX);
          }}
          onPointerUp={(e) => {
            e.currentTarget.releasePointerCapture?.(e.pointerId);
            setDragging(false);
          }}
          className="group absolute inset-y-0 left-0 z-40 hidden w-3 cursor-col-resize md:block"
        >
          {/* A small grip pill, vertically centred in the full-height hit area
              (the split-view handle of macOS / iPadOS), instead of a tinted
              full-height rail: hidden at rest, a muted pill on hover, darker and
              a little taller while dragging. */}
          <div
            aria-hidden
            className={`absolute left-1/2 top-1/2 w-1 -translate-x-1/2 -translate-y-1/2 rounded-full transition-[height,opacity,background-color] duration-150 ${
              dragging
                ? "h-14 bg-foreground-muted opacity-100"
                : "h-10 bg-foreground-more-muted opacity-0 group-hover:opacity-100"
            }`}
          />
        </div>
      {/* Header — under HEADER_BLUR it overlays the tab-content region as one
          frosted bar (title + meta + tabs share the glass; the edge class
          paints a masked blur layer behind all three rows). Falls back to the
          original in-flow block when the app-wide switch is off. */}
      <div
        ref={headerRef}
        className={
          HEADER_BLUR
            ? // pb-4 extends the glass 16px below the tab row so the mask's
              // 15px bottom feather fades out in that padding, not across the
              // tabs' edge.
              `absolute inset-x-0 top-0 z-20 pb-4 ${headerEdgeClass(true)}`
            : "shrink-0"
        }
      >
        {/* Top bar in the standard drawer-header shape (cf. DrawerViewHeader):
            leading close, title + meta subtitle, spacer, trailing actions. The
            edge/glass chrome is NOT repeated here — the frosted wrapper above
            owns it, extending through the tab row. The old second row (back
            arrow + meta) folded in: the arrow duplicated `requestClose`, and
            the meta line is now the subtitle. */}
        <div
          className={`${HEADER_MIN_HEIGHT} flex shrink-0 items-center gap-3 px-4 pt-3 pb-3`}
        >
          <button
            type="button"
            onClick={requestClose}
            aria-label={t("Close session")}
            className={`flex ${HEADER_BTN}`}
          >
            <XIcon className="size-5" />
          </button>
          <div className="min-w-0 flex-1">
            <h2 className="heading-large truncate">{title}</h2>
            {secondary && (
              <p className="body-small truncate text-foreground-muted">
                {secondary}
              </p>
            )}
          </div>
          <div className="flex shrink-0 items-center gap-2">
            {/* Header "…" menu — its actions are tab-specific. Technique: flip
                the selected rep's trajectory. Reps / Performance: the shared
                global view toggles (single-rep breakdown + eccentric bars). The
                menu is meaningless on History and Details, so it's hidden there.
                Expanded → a sliders glyph (there's room, and it reads as
                "adjust"); collapsed → the familiar "…" overflow. Both wear the
                bordered header button. The session's own actions (tags, change
                athlete / exercise, delete) live in the Details tab. */}
            {tab === "technique" && (
              <ActionMenu
                ariaLabel={t("Session actions")}
                triggerClassName={`flex ${HEADER_BTN}`}
                triggerIcon={
                  expanded ? (
                    <AdjustmentsIcon className="size-5" />
                  ) : (
                    <EllipsisIcon className="size-5" />
                  )
                }
                items={[
                  {
                    label: t("Flip trajectory data"),
                    onClick: () => setFlipOrientation((v) => !v),
                    selected: flipOrientation,
                  },
                ]}
              />
            )}
            {(tab === "reps" || tab === "performance") && (
              <ActionMenu
                ariaLabel={t("View options")}
                minWidth={260}
                triggerClassName={`flex ${HEADER_BTN}`}
                triggerIcon={
                  expanded ? (
                    <AdjustmentsIcon className="size-5" />
                  ) : (
                    <EllipsisIcon className="size-5" />
                  )
                }
                items={[
                  {
                    label: t("Single rep review"),
                    onClick: () => setShowReps(!showReps),
                    selected: showReps,
                  },
                  {
                    label: t("Show eccentric reps"),
                    onClick: () => setShowEccentricReps(!showEccentricReps),
                    selected: showEccentricReps,
                  },
                  // Heatmap + focus-only columns are Reps-table concepts, so
                  // they only appear in the Reps tab's menu.
                  ...(tab === "reps"
                    ? [
                        { divider: true as const },
                        {
                          label: t("Show heatmap"),
                          onClick: () => setShowHeatmap(!showHeatmap),
                          selected: showHeatmap,
                        },
                        {
                          label: t("Show only focus metrics"),
                          onClick: () => setOnlyFocusMetrics(!onlyFocusMetrics),
                          selected: onlyFocusMetrics,
                        },
                      ]
                    : []),
                ]}
              />
            )}
          </div>
        </div>

        {/* Tabs — the same header pills as the Notifications / Insights pages,
            with the loading spinner riding beside the track. */}
        <div className="flex items-center gap-3 px-6">
          <SegmentedPicker
            scrollable
            ariaLabel={t("Session views")}
            value={tab}
            onChange={setTab}
            options={tabs}
          />
          {status === "loading" && (
            <span
              className="flex items-center"
              role="status"
              aria-label={t("Loading session data")}
            >
              <SpinnerIcon className="size-4 animate-spin text-foreground-muted" />
            </span>
          )}
        </div>
      </div>

      {/* Tab content. With the frosted overlay header this region is the
          panel's first in-flow child, so it extends up behind the glass;
          whichever element scrolls pads down by the measured header height
          (+24px, the old p-6 gap) so content starts below the bar and scrolls
          under it. The region is the positioned anchor for the bottom
          ScrollEdgeFade — a SIBLING of the scrollers, so it stays pinned. */}
      <div className="relative flex min-h-0 flex-1 flex-col overflow-hidden">
        {/* Reps fills the area and scrolls internally (sticky header); the other
            tabs scroll as a whole inside their own flex-fill region.

            The boundary keeps a failing tab from taking the whole dashboard
            route down with it; passing `tab` lets it clear the failure when the
            coach switches away. */}
        <SessionTabBoundary tab={tab} style={overlayPad}>
          {tab === "reps" ? (
            // Internal scroller → nothing scrolls under the bar here; the wrapper
            // itself pads below the overlay header instead.
            <div
              className="flex min-h-0 flex-1 flex-col overflow-hidden p-6"
              style={overlayPad}
            >
              <SessionRepsTab
                session={model}
                editor={editor}
                loading={status !== "loaded"}
                onJumpToTechnique={jumpToTechnique}
                initialFilterTags={repFilterTags}
              />
            </div>
          ) : (
            <div className="scrollbar-none min-h-0 flex-1 overflow-auto p-6" style={overlayPad}>
              {tab === "technique" ? (
                <SessionTechniqueTab
                  session={model}
                  loading={status !== "loaded"}
                  target={techniqueTarget}
                  flipOrientation={flipOrientation}
                  expanded={expanded}
                  reviewContainer={panelEl}
                  isBarbell={isBarbell}
                />
              ) : tab === "performance" ? (
                <SessionPerformanceTab
                  session={model}
                  loading={status !== "loaded"}
                />
              ) : tab === "details" ? (
                <SessionDetailsTab
                  session={model}
                  exerciseName={exerciseName}
                  exerciseDetail={exerciseSubtitle ?? null}
                  historyStats={historyStats}
                  historyStatsLoading={historyStatsLoading}
                  tags={{
                    tags: sessionTags,
                    source: tagsSource,
                    canEdit: tags ? tags.canEdit : canWriteData,
                    onCommit: commitTags,
                  }}
                  note={{
                    note: sessionNote,
                    onSave: canWriteData ? saveNote : undefined,
                  }}
                  actions={{ ...actions, canDelete: canWriteData }}
                />
              ) : (
                <SessionSummaryTab
                  session={model}
                  loading={status !== "loaded"}
                  onOpenSession={setDetailSession}
                />
              )}
            </div>
          )}
        </SessionTabBoundary>
        {/* Soft fade at the foot of the scroll area — scroll affordance
            matching the app's other scrollable views. Tints to --frost-bg
            (the default page background, which is this panel's surface). */}
        <ScrollEdgeFade />
      </div>

      {/* Unsaved-changes footer: appears whenever the reps editor has staged
          edits, regardless of the active tab. */}
      {editor.isDirty && (
        <div className="shrink-0 border-t border-surface-stroke bg-surface-base px-6 py-3">
          <div className="flex flex-wrap items-center justify-end gap-3">
            {editor.error && (
              <span className="body-small mr-auto text-red-600">
                {editor.error}
              </span>
            )}
            <span className="body-small mr-auto text-foreground-muted">
              {t("You have unsaved changes.")}
            </span>
            <button
              type="button"
              onClick={editor.discard}
              disabled={editor.saving}
              className="clickable-small body-prominent rounded-full border border-surface-stroke px-4 py-2 text-foreground-default hover:bg-surface-base-muted disabled:opacity-50"
            >
              {t("Discard")}
            </button>
            <Button
              variant="primary"
              size="rounded"
              onClick={editor.save}
              busy={editor.saving}
              leadingIcon={editor.saving ? <SpinnerIcon className="size-4 animate-spin" /> : undefined}
            >
              {t("Save changes")}
            </Button>
          </div>
        </div>
      )}
      </div>
      </SurfaceZIndexProvider>

      {/* A history card's "Open session details" opens a nested drawer stacked
          over this one (higher z via depth+1); closing it returns here. */}
      {detailSession && (
        <SessionDrawer
          session={detailSession}
          onClose={() => setDetailSession(null)}
          depth={depth + 1}
        />
      )}
      <DiscardChangesDialog
        open={discardGuard.confirmOpen}
        onConfirm={discardGuard.discard}
        onCancel={discardGuard.keepEditing}
        message={t(
          "Your edits to this session haven’t been saved. Close without saving?",
        )}
      />
    </>,
    document.body,
  );
}

