"use client";

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type ReactNode,
} from "react";
import { createPortal } from "react-dom";
import { useBodyScrollLock } from "@enode/core/scroll-lock";
import { useTranslation } from "@enode/core/translations/hooks";
import { popBackGuard, pushBackGuard } from "@enode/core/back-button-guard";
import {
  HEADER_MIN_HEIGHT,
  HEADER_BLUR,
  headerEdgeClass,
} from "./header-height";
import {
  containmentPositionClass,
  overlayPortalHost,
  useContainment,
} from "./containment";
import { CloseXIcon } from "./icons/close-x";
import { HEADER_ICON_BUTTON } from "./header-button";
import {
  backgroundOf,
  computedZIndex,
  holdInert,
  liftInert,
} from "./inert-background";
import { ScrollEdgeFade } from "./scroll-edge-fade";

// A right-side drawer that hosts a stack of pushable views. The chrome (aside,
// backdrop, slide animation) lives here once; each "view" inside is just
// content. Pushing a view slides it in over the current one (iOS-style); pop
// slides it back out. The outer chrome animates when `open` toggles.

// Swallow re-entrant push() calls until the previous push has actually
// SETTLED — rendered, slid in, and covering the trigger. Two conditions,
// both needed:
//
//   • A 400ms floor for taps that land while nothing is entering yet
//     (sub-frame double-taps on the first push).
//   • "An entry is still entering": from push() until that entry's enter
//     transform transitionend. A fixed window alone is NOT enough — on a
//     slow Android WebView the pushed view's mount can block the main
//     thread for far longer than any window; the user's extra taps queue
//     during the block and get processed after it, each arriving "late"
//     enough to pass a time check but before the view covers the trigger.
//     Each would append the same view again (plus a back-guard history
//     sentinel each, so Back must be pressed once per copy).
//
// The backstop timer reopens the gate if the enter transitionend never
// arrives (lost event), so pushes can't lock up forever. It's long on
// purpose: it must outlast commit + rAF promotion + the 300ms slide even
// when a heavy render delays the transition start.
const PUSH_GUARD = true;
const PUSH_GUARD_MS = 400;
const PUSH_SETTLE_BACKSTOP_MS = 1500;

// Removal backstop for leaving entries. A leaving entry is normally removed on
// its transform transitionend — but an interrupted transition (entry popped
// while its enter slide is still playing, or the target flipped within the
// same frame) ends in `transitioncancel` INSTEAD of `transitionend`, which
// would strand the entry forever: mounted but invisible at translate-x-full,
// still holding its back-guard history sentinel (a dead Back press for the
// user). Verified reproducible under 20x CPU throttle. The timer force-removes
// the entry if the event never arrives; removal is idempotent.
const LEAVE_REMOVE_BACKSTOP_MS = 700;

// Open viewport-mode stacks, in opening order — the LAST entry is the topmost
// drawer and the ONLY one whose document-level Escape listener may act
// (mirroring the back-button guard's LIFO stack in back-button-guard.ts).
// Without this arbitration, nested DrawerStacks (e.g. a chart builder opened
// over an info drawer) each hold an Escape listener and one press closes ALL.
const openViewportStacks: symbol[] = [];

type EntryStatus = "entering" | "active" | "leaving";

type StackEntry = {
  id: number;
  body: ReactNode;
  status: EntryStatus;
};

type StackApi = {
  push: (body: ReactNode) => void;
  pop: () => void;
  close: () => void;
};

const StackContext = createContext<StackApi | null>(null);
const DepthContext = createContext<number>(0);
// Per-entry pop callback so a view's auto back button (and back-button guard)
// can pop *its own* entry rather than "the top one", which keeps the LIFO
// semantics correct even mid-transition.
const EntryPopContext = createContext<(() => void) | null>(null);
// The user-initiated dismiss-all (header X at depth 0, "Done", backdrop).
// Routes through `onDismissAttempt` when the host set one; otherwise it is
// `onClose` (see drawerDismissAllAction). Kept
// apart from `StackApi.close`, which stays the programmatic close (e.g. after
// a Save) and must never ask "Discard changes?".
const RequestDismissContext = createContext<(() => void) | null>(null);
// Per-entry registration of a pushed view's pop guard (see usePopGuard).
// Returns the unregister function. Absent outside a pushed entry.
const PopGuardContext = createContext<
  ((guard: PopGuard) => () => void) | null
>(null);

/**
 * A pushed view's veto over a user-initiated pop. Return `false` to keep the
 * view (it then typically shows its own confirmation and pops itself with
 * `useDrawerStack().pop()`); any other return lets the pop go ahead.
 */
export type PopGuard = () => boolean | void;

/**
 * Whether an entry's pop guard should run at all: only for an active entry.
 * A leaving or removed entry ignores the pop, so its guard (which may call
 * `stack.pop()` after vetoing) must not fire.
 *
 * @param status - the entry's status, `undefined` when it no longer exists
 */
export function popGuardApplies(status: StackEntry["status"] | undefined): boolean {
  return status === "active";
}

/**
 * Whether a user-initiated pop may proceed past the entry's guard (if any).
 *
 * @param guard - the guard registered by the pushed view, if any
 * @returns `false` only when the guard returned `false`
 */
export function popGuardAllows(guard: PopGuard | undefined): boolean {
  return guard?.() !== false;
}

/**
 * What a user-initiated dismiss (X / Escape / hardware Back / backdrop) does:
 * pop the top pushed view, hand the decision to the host's
 * `onDismissAttempt`, or close the drawer.
 *
 * @param hasActivePushed - a pushed view is on top (Escape / Back pop it first)
 * @param guarded - the host passed `onDismissAttempt`
 */
export function drawerDismissAction(
  hasActivePushed: boolean,
  guarded: boolean,
): "pop" | "attempt" | "close" {
  if (hasActivePushed) return "pop";
  return guarded ? "attempt" : "close";
}

/**
 * What a user-initiated "dismiss the whole drawer" (form sheet / page "Done",
 * backdrop click, root X) does. Unlike {@link drawerDismissAction} it never
 * pops: it closes everything — through the host's `onDismissAttempt` when
 * given, otherwise at once.
 *
 * @param guarded - the host passed `onDismissAttempt`
 */
export function drawerDismissAllAction(guarded: boolean): "attempt" | "close" {
  return guarded ? "attempt" : "close";
}

/**
 * Id of the pushed entry the user is on — the newest one that is not sliding
 * out — or `undefined` when the root view is on top. Every other view (the
 * root and deeper entries underneath, leaving entries) is inert + aria-hidden,
 * so Tab and screen readers only reach the visible view.
 *
 * @param entries - the pushed entries, oldest first
 */
export function topEntryId(
  entries: ReadonlyArray<{ id: number; status: EntryStatus }>,
): number | undefined {
  return entries.findLast((e) => e.status !== "leaving")?.id;
}

/**
 * Where the focus goes back to when a drawer closes or a pushed view pops: the
 * first usable candidate (the opener first, then a fallback), or `null` — do
 * nothing — when there is none or the focus has since been put somewhere else
 * on purpose (outside the closing view, not on the bare page).
 *
 * @param candidates - best first; empty slots are skipped
 * @param usable - still on the page, not inert, shown
 * @param focusMovedElsewhere - the focus is on a control outside the closing view
 */
export function focusReturnTarget<T>(
  candidates: ReadonlyArray<T | null | undefined>,
  usable: (candidate: T) => boolean,
  focusMovedElsewhere: boolean,
): T | null {
  if (focusMovedElsewhere) return null;
  for (const candidate of candidates) {
    if (candidate != null && usable(candidate)) return candidate;
  }
  return null;
}

/**
 * How a {@link DrawerStack} presents itself:
 * - `"drawer"` (default) — the right-side drawer.
 * - `"formSheet"` — an iPad-style centred card (max 580px wide, 40px from the
 *   top/bottom edges plus the safe-area insets) that rises in over a dimmed
 *   backdrop; the root header shows a trailing "Done" instead of the X.
 * - `"page"` — a phone-style full-screen page that slides in from the right.
 * - `"screen"` — an app screen that fills its container (the positioned
 *   content area under `ContainmentProvider "container"`, else the viewport):
 *   `bg-background`, no backdrop element, no shadow, no rounded corners; it
 *   enters with a short fade/rise (none under prefers-reduced-motion). Escape
 *   goes back / closes in both containment modes; header and back button look
 *   like the drawer's.
 */
export type DrawerPresentation = "drawer" | "formSheet" | "page" | "screen";

/**
 * Class strings for the backdrop and the sliding panel of a
 * {@link DrawerStack}. For `"drawer"` they are exactly the drawer's classes;
 * `widthClassName` only applies there.
 *
 * @param presentation - see {@link DrawerPresentation}
 * @param positionClass - `fixed` (viewport) or `absolute` (container mode)
 * @param widthClassName - the drawer's width classes
 * @param open - the panel is shown (after the mount reflow)
 * @param dismissable - a backdrop tap closes
 * @returns `backdrop` is `null` for `"screen"` (no backdrop element at all)
 */
export function drawerPresentationClasses(
  presentation: DrawerPresentation,
  positionClass: string,
  widthClassName: string,
  open: boolean,
  dismissable: boolean,
): { backdrop: string | null; aside: string } {
  if (presentation === "screen") {
    // A screen, not an overlay: nothing dims what is underneath during the
    // entry, and there is no shadow or rounding. Short fade + small rise.
    return {
      backdrop: null,
      aside: `${positionClass} inset-0 z-50 flex w-full flex-col overflow-hidden bg-background transition-[transform,opacity] duration-200 ease-out motion-reduce:transition-none ${
        open ? "translate-y-0 opacity-100" : "pointer-events-none translate-y-2 opacity-0"
      }`,
    };
  }
  const backdrop = `${positionClass} inset-0 z-50 bg-black/40 transition-opacity duration-300 ${
    open ? "opacity-100" : "pointer-events-none opacity-0"
  } ${dismissable ? "" : "cursor-default"}`;
  if (presentation === "formSheet") {
    // The hairline is repeated on an `after:` overlay because the entries
    // (absolute, own background) paint over the aside's inset ring. In dark
    // the grouped page inside lifts from black to `surface-drawer` so the
    // card stands off the dimmed backdrop instead of merging with it.
    return {
      backdrop,
      aside: `${positionClass} inset-x-0 bottom-[calc(40px+env(safe-area-inset-bottom))] top-[calc(40px+env(safe-area-inset-top))] z-50 mx-auto flex w-[min(580px,calc(100vw-32px))] flex-col overflow-hidden rounded-[20px] bg-surface-drawer ring-1 ring-inset ring-surface-stroke-muted after:pointer-events-none after:absolute after:inset-0 after:z-10 after:rounded-[inherit] after:ring-1 after:ring-inset after:ring-surface-stroke-muted dark:[--settings-page-bg:var(--surface-drawer)] transition-[transform,opacity] duration-[320ms] ease-out motion-reduce:transition-none ${
        open
          ? "translate-y-0 opacity-100 shadow-2xl"
          : "pointer-events-none translate-y-20 opacity-0"
      }`,
    };
  }
  if (presentation === "page") {
    return {
      backdrop,
      aside: `${positionClass} inset-0 z-50 flex h-dvh w-full flex-col overflow-hidden bg-surface-drawer transition-transform duration-300 ease-out motion-reduce:transition-none ${
        open ? "translate-x-0" : "translate-x-full"
      }`,
    };
  }
  return {
    backdrop,
    aside: `${positionClass} inset-y-0 right-0 z-50 flex w-full ${widthClassName} flex-col overflow-hidden bg-surface-drawer transition-transform duration-300 ease-out ${
      // Shadow ONLY while open. DrawerStack stays mounted when closed
      // (it just slides to translate-x-full), and not every consumer
      // unmounts it (e.g. RetrospectiveSourceDrawer renders it directly) —
      // a shadow on an off-screen drawer bleeds a strip onto the viewport
      // edge. No element paints the shadow when off-screen, so no bleed.
      open ? "translate-x-0 shadow-2xl" : "translate-x-full"
    }`,
  };
}

/**
 * The header buttons of a drawer view: the leading button (close X, back
 * chevron, or none) and whether a trailing "Done" closes the whole stack.
 * A form sheet's root has only "Done"; its pushed views keep the back chevron
 * and add "Done".
 *
 * @param presentation - see {@link DrawerPresentation}
 * @param depth - 0 for the root view, > 0 for pushed views
 */
export function drawerHeaderAffordances(
  presentation: DrawerPresentation,
  depth: number,
): { leading: "close" | "back" | null; done: boolean } {
  if (presentation === "formSheet") {
    return { leading: depth > 0 ? "back" : null, done: true };
  }
  return { leading: depth > 0 ? "back" : "close", done: false };
}

/**
 * How a pushed view's back button looks: iOS-style text ("‹ Account") on a
 * phone page or iPad form sheet, the round chevron button in side drawers.
 *
 * @param presentation - see {@link DrawerPresentation}
 */
export function drawerBackButtonStyle(
  presentation: DrawerPresentation,
): "text" | "round" {
  return presentation === "drawer" || presentation === "screen"
    ? "round"
    : "text";
}

/**
 * Where a {@link DrawerStack} listens for Escape: `"document"` for viewport
 * stacks (only the topmost open one acts), `"aside"` for a container-mode
 * `"screen"` (keys pressed inside it), `null` for other container-mode
 * presentations (closed through their own affordances).
 *
 * @param presentation - see {@link DrawerPresentation}
 * @param isContainer - the stack renders in container mode
 */
export function drawerEscapeScope(
  presentation: DrawerPresentation,
  isContainer: boolean,
): "document" | "aside" | null {
  if (!isContainer) return "document";
  return presentation === "screen" ? "aside" : null;
}

/**
 * The title of the view underneath a pushed view — the label of its text back
 * button. `null` at the root or when that view has no title (the button then
 * reads "Back").
 *
 * @param titles - header titles registered per depth (see DrawerViewHeader)
 * @param depth - depth of the view whose back button is rendered
 */
export function previousViewTitle(
  titles: ReadonlyMap<number, string>,
  depth: number,
): string | null {
  if (depth <= 0) return null;
  const title = titles.get(depth - 1)?.trim();
  return title ? title : null;
}

// Stack-level registry of header titles per depth, so a pushed view's text
// back button can read the title of the view underneath. Only filled for
// presentations with a text back button (see drawerBackButtonStyle).
type ViewTitlesApi = {
  titles: ReadonlyMap<number, string>;
  // Returns the unregister cleanup.
  register: (depth: number, title: string) => () => void;
};
const ViewTitlesContext = createContext<ViewTitlesApi | null>(null);

/**
 * Focus trap for form sheets and pages: the index Tab (or Shift+Tab) must wrap
 * to, or `null` to let the browser move the focus normally.
 *
 * @param count - focusable controls in the visible view
 * @param activeIndex - index of the focused one, -1 when the focus is elsewhere
 * @param backwards - Shift+Tab
 */
export function focusWrapIndex(
  count: number,
  activeIndex: number,
  backwards: boolean,
): number | null {
  if (count === 0) return null;
  if (activeIndex === -1) return backwards ? count - 1 : 0;
  if (backwards && activeIndex === 0) return count - 1;
  if (!backwards && activeIndex === count - 1) return 0;
  return null;
}

// ── Focus return ─────────────────────────────────────────────────────────────
// The control that opened a drawer (or pushed a view) gets the focus back when
// it closes (pops). Safari does not focus a clicked button, so besides
// document.activeElement the last pressed control is kept (as in
// use-modal-focus.ts) — it is read in the same click that opens or pushes.

const PRESSABLE_SELECTOR =
  'a[href], button, input, select, textarea, [tabindex], [role="button"], [role="menuitem"], [role="option"]';
const FOCUSABLE_SELECTOR =
  'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
const PRESS_OPENS_WITHIN_MS = 1500;
let lastPress: { element: HTMLElement; at: number } | null = null;
let listeningForPresses = false;

function rememberDrawerPresses(): void {
  if (listeningForPresses || typeof document === "undefined") return;
  document.addEventListener(
    "click",
    (event) => {
      const target = event.target as Element | null;
      const element = target?.closest?.<HTMLElement>(PRESSABLE_SELECTOR);
      if (element) lastPress = { element, at: Date.now() };
    },
    true,
  );
  listeningForPresses = true;
}

function nothingFocused(at: Element | null): boolean {
  return at == null || at === document.body || at === document.documentElement;
}

/** What opened `container`'s next view, best first — never inside it. */
function openerCandidates(container: HTMLElement | null): HTMLElement[] {
  const found: HTMLElement[] = [];
  const at = document.activeElement;
  const outside = (el: Element) => !container || !container.contains(el);
  if (at instanceof HTMLElement && !nothingFocused(at) && outside(at)) {
    found.push(at);
  }
  const press = lastPress;
  if (
    press &&
    Date.now() - press.at <= PRESS_OPENS_WITHIN_MS &&
    outside(press.element) &&
    !found.includes(press.element)
  ) {
    found.push(press.element);
  }
  return found;
}

/** Like {@link openerCandidates}, but for a push: the opener is inside `view`. */
function pusherCandidates(view: HTMLElement | null): HTMLElement[] {
  if (!view) return [];
  const found: HTMLElement[] = [];
  const at = document.activeElement;
  if (at instanceof HTMLElement && view.contains(at)) found.push(at);
  const press = lastPress;
  if (
    press &&
    Date.now() - press.at <= PRESS_OPENS_WITHIN_MS &&
    view.contains(press.element) &&
    !found.includes(press.element)
  ) {
    found.push(press.element);
  }
  return found;
}

function canTakeFocus(el: HTMLElement): boolean {
  return (
    el.isConnected &&
    el.closest("[inert]") == null &&
    !(el as HTMLButtonElement).disabled &&
    el.getClientRects().length > 0
  );
}

/** Focus `target` without scrolling (a view may still be sliding). */
function focusQuietly(target: HTMLElement | null): void {
  target?.focus({ preventScroll: true });
}

const PROGRAMMATIC_FOCUS_CLASSES = [
  "outline-none",
  "focus-visible:outline-2",
  "focus-visible:outline-offset-2",
  "focus-visible:outline-foreground-red-orange",
];

/** A pushed view's first heading, else its first control, else the view. */
function pushedViewFocusTarget(view: HTMLElement): HTMLElement {
  const heading = view.querySelector<HTMLElement>("h1, h2, h3");
  if (heading) {
    if (!heading.hasAttribute("tabindex")) {
      heading.tabIndex = -1;
      // Programmatic focus (a11y) without a ring for mouse/touch users; the
      // ring only shows for keyboard focus.
      heading.classList.add(...PROGRAMMATIC_FOCUS_CLASSES);
    }
    return heading;
  }
  const control = Array.from(
    view.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
  ).find((el) => el.getClientRects().length > 0);
  if (control) return control;
  if (!view.hasAttribute("tabindex")) view.tabIndex = -1;
  return view;
}

export function useDrawerStack(): StackApi {
  const ctx = useContext(StackContext);
  if (!ctx) throw new Error("useDrawerStack: no <DrawerStack> ancestor");
  return ctx;
}

export function useDrawerDepth(): number {
  return useContext(DepthContext);
}

const PresentationContext = createContext<DrawerPresentation>("drawer");

/**
 * The {@link DrawerPresentation} of the nearest {@link DrawerStack} — e.g. to
 * pick "Done" vs the close X. `"drawer"` outside any stack.
 */
export function useDrawerPresentation(): DrawerPresentation {
  return useContext(PresentationContext);
}

/**
 * A control the host puts at the very start of the head of every full-screen
 * view below it (a `DrawerStack` with `presentation="screen"`, on every page
 * pushed in it) — e.g. the tracking iPad's "Show sidebar" while its rail is
 * collapsed. Drawers, sheets and form sheets don't show it. Default: nothing.
 */
export const ScreenHeaderStartContext = createContext<ReactNode>(null);

/**
 * The {@link ScreenHeaderStartContext} control for a head, or null outside a
 * full-screen view.
 */
export function useScreenHeaderStart(): ReactNode {
  const start = useContext(ScreenHeaderStartContext);
  return useDrawerPresentation() === "screen" ? start : null;
}

function useEntryPop(): (() => void) | null {
  return useContext(EntryPopContext);
}

/**
 * Lets a pushed view intercept its own user-initiated pop — the header back
 * button, Escape and the hardware/OS Back (incl. the iOS edge swipe). The
 * guard runs before the pop; returning `false` cancels it. Programmatic
 * `useDrawerStack().pop()` / `close()` are never guarded, so the view pops
 * itself that way once the user confirms.
 *
 * @param guard - read fresh on every pop attempt (no memoization needed)
 *
 * @remarks No-op in the root view: a root's dismissal is guarded by the
 * host's `onDismissAttempt` / `onClose` instead. A refused hardware Back
 * re-arms the entry's back guard, so the next Back asks again.
 */
export function usePopGuard(guard: PopGuard): void {
  const register = useContext(PopGuardContext);
  const guardRef = useRef(guard);
  useEffect(() => {
    guardRef.current = guard;
  });
  useEffect(() => register?.(() => guardRef.current()), [register]);
}

/**
 * Named widths of a `"drawer"`-presentation {@link DrawerStack}, so drawers
 * share a small set of sizes instead of ad-hoc `max-w-[…]` classes:
 * - `"default"` — 538px, forms and pickers.
 * - `"wide"` — 720px, side-by-side content or wider tables.
 * - `"extraWide"` — 960px, multi-column editors.
 * - `"full"` — no cap; the drawer spans the viewport (or its container).
 *
 * On narrow viewports every width is still capped by the drawer's `w-full`.
 */
export type DrawerWidth = "default" | "wide" | "extraWide" | "full";

// Literal class strings so Tailwind's scanner sees each one.
const DRAWER_WIDTH_CLASS: Record<DrawerWidth, string> = {
  default: "max-w-[538px]",
  wide: "max-w-[720px]",
  extraWide: "max-w-[960px]",
  full: "max-w-none",
};

/**
 * The `max-w-*` class for a {@link DrawerWidth}.
 *
 * @param width - the named drawer width
 * @returns a single Tailwind max-width class
 */
export function drawerWidthClass(width: DrawerWidth): string {
  return DRAWER_WIDTH_CLASS[width];
}

type Props = {
  open: boolean;
  onClose: () => void;
  ariaLabel: string;
  // The first view in the stack. May be null when the drawer is sliding out;
  // the host snapshots the last non-null root so the slide-out renders with
  // real content instead of going visually empty.
  root: ReactNode | null;
  // When false, the backdrop click no-ops — the drawer can only be closed
  // through an explicit affordance (X / Save / Escape / Back). Defaults to
  // true. Use for editors where an accidental backdrop tap would discard
  // pending changes.
  dismissable?: boolean;
  // Unsaved-edits guard. When set, the user-initiated exits — header X,
  // Escape, hardware/OS Back and (if `dismissable`) the backdrop — do NOT
  // close the drawer; they call this instead and the host decides (typically
  // a "Discard changes?" confirm that then calls its own close). Programmatic
  // `useDrawerStack().close()` is unaffected. Unlike Sheet's hook there is no
  // return value: the host closes itself.
  onDismissAttempt?: () => void;
  // Named width of the aside — see DrawerWidth. Defaults to "default"
  // (538px). Only for the "drawer" presentation; ignored by the others.
  width?: DrawerWidth;
  // Raw width classes for the aside (alongside its `w-full`). When set it
  // replaces `width` entirely — for responsive one-offs, e.g. a narrower
  // width on short screens so a full-bleed hero doesn't dominate. Prefer
  // `width`. Only for the "drawer" presentation.
  widthClassName?: string;
  // Drawer (default), iPad form sheet or phone page — see DrawerPresentation.
  // Dismiss paths, focus handling and push navigation are the same for all.
  presentation?: DrawerPresentation;
};

export function DrawerStack({
  open,
  onClose,
  ariaLabel,
  root,
  dismissable = true,
  onDismissAttempt,
  width = "default",
  widthClassName,
  presentation = "drawer",
}: Props) {
  // In container mode (multi-station column), the stack mounts inside
  // its column's positioned ancestor — backdrop + aside use absolute
  // instead of fixed, and the global body-scroll-lock / back-button
  // wiring stays off so other columns/page chrome remain interactive.
  const containment = useContainment();
  const positionClass = containmentPositionClass(containment);
  const isContainer = containment === "container";
  // Snapshot of the last non-null root so the slide-out animation has
  // something to render. Updated during render via the prev-value pattern.
  const [renderedRoot, setRenderedRoot] = useState<ReactNode>(root);
  if (root != null && root !== renderedRoot) {
    setRenderedRoot(root);
  }

  // Slide-in animation: the aside paints off-screen, then transitions in.
  const [mounted, setMounted] = useState(false);
  // The sliding panel — read for a forced reflow before flipping `mounted`.
  const asideRef = useRef<HTMLElement>(null);
  const backdropRef = useRef<HTMLDivElement>(null);

  // Gate the viewport-mode body portal on a post-mount flag so it never runs
  // during SSR/first hydration (createPortal needs a live `document`). Until the
  // flag flips we render NOTHING (see the return below) rather than an inline
  // copy of the tree: an inline-then-portal switch RE-PARENTS the whole subtree,
  // which unmounts and remounts every child — re-running their mount effects and
  // double-firing any on-open fetch a drawer view does (fetch-before-edit, a
  // search, a colour load). Rendering null first means the subtree mounts once,
  // directly in the portal. The pre-flag frame is invisible anyway (the aside is
  // off-screen and the mount/slide-in effect below already waits for `canPortal`
  // before it plays), and SSR + first client render agree on null, so hydration
  // stays clean.
  const [canPortal, setCanPortal] = useState(false);
  // eslint-disable-next-line react-hooks/set-state-in-effect
  useEffect(() => setCanPortal(true), []);

  // Deterministic slide-in: once the aside is committed off-screen — and, in
  // viewport mode, has settled into its <body> portal — force a reflow so the
  // off-screen transform is registered as the transition's start, THEN flip
  // `mounted`. Replaces the single rAF, which snapped the drawer in whenever
  // the open coincided with heavy synchronous work or the portal re-parent.
  useEffect(() => {
    if (mounted) return;
    if (!isContainer && !canPortal) return; // wait for the body portal to settle
    const el = asideRef.current;
    if (el) void el.offsetHeight; // force reflow → registers the "from"
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setMounted(true);
  }, [mounted, isContainer, canPortal]);
  const asideOpen = mounted && open;

  const [pushed, setPushed] = useState<StackEntry[]>([]);
  const nextIdRef = useRef(1);
  const lastPushAtRef = useRef(0);
  // Ids of entries whose enter transition hasn't completed yet — while any
  // are present, push() swallows new calls (see the PUSH_GUARD note above).
  const enteringIdsRef = useRef<Set<number>>(new Set());

  // Drop pushed entries when the drawer closes — by the time it reopens
  // (typically with a fresh root), the previous push stack is stale.
  const [prevOpen, setPrevOpen] = useState(open);
  if (open !== prevOpen) {
    setPrevOpen(open);
    if (!open && pushed.length > 0) setPushed([]);
  }

  // Drop stale enter-guard ids on close (an effect, not the render-phase
  // block above — ref writes during render are off-limits). The backstop
  // timers would expire them anyway; this just makes a quick reopen clean.
  useEffect(() => {
    if (!open) enteringIdsRef.current.clear();
  }, [open]);

  // Promote freshly-pushed entries from "entering" → "active" one frame after
  // mount, so the transform transition actually plays (the entry first paints
  // at translate-x-full, then slides to translate-x-0).
  useEffect(() => {
    if (!pushed.some((e) => e.status === "entering")) return;
    const raf = requestAnimationFrame(() => {
      setPushed((prev) =>
        prev.map((e) =>
          e.status === "entering" ? { ...e, status: "active" } : e,
        ),
      );
    });
    return () => cancelAnimationFrame(raf);
  }, [pushed]);

  // Per pushed entry: the control (in the view underneath) that pushed it.
  const pushersRef = useRef<Map<number, HTMLElement[]>>(new Map());
  const getPushers = useCallback(
    (id: number) => pushersRef.current.get(id) ?? [],
    [],
  );
  const forgetPushers = useCallback((id: number) => {
    pushersRef.current.delete(id);
  }, []);

  const push = useCallback((body: ReactNode) => {
    if (PUSH_GUARD) {
      const now = performance.now();
      if (now - lastPushAtRef.current < PUSH_GUARD_MS) return;
      if (enteringIdsRef.current.size > 0) return;
      lastPushAtRef.current = now;
    }
    const id = nextIdRef.current++;
    // The view on top right now (the root or the newest live entry) holds
    // the row that pushed; remembered for the pop.
    const aside = asideRef.current;
    const liveViews = aside
      ? Array.from(aside.children).filter(
          (el): el is HTMLElement =>
            el instanceof HTMLElement && !el.inert && el.dataset.leaving == null,
        )
      : [];
    pushersRef.current.set(id, pusherCandidates(liveViews.at(-1) ?? null));
    if (PUSH_GUARD) {
      enteringIdsRef.current.add(id);
      window.setTimeout(() => {
        enteringIdsRef.current.delete(id);
      }, PUSH_SETTLE_BACKSTOP_MS);
    }
    setPushed((prev) => [...prev, { id, body, status: "entering" }]);
  }, []);

  const popEntry = useCallback((id: number) => {
    setPushed((prev) =>
      prev.map((e) =>
        e.id === id && e.status === "active" ? { ...e, status: "leaving" } : e,
      ),
    );
  }, []);

  const pushedRef = useRef(pushed);
  useEffect(() => {
    pushedRef.current = pushed;
  }, [pushed]);

  // Pop guards registered by pushed views (usePopGuard), by entry id.
  const popGuardsRef = useRef<Map<number, PopGuard>>(new Map());
  const registerPopGuard = useCallback((id: number, guard: PopGuard) => {
    popGuardsRef.current.set(id, guard);
    return () => {
      if (popGuardsRef.current.get(id) === guard) popGuardsRef.current.delete(id);
    };
  }, []);
  // A user-initiated pop of one entry: asks its guard first. Returns whether
  // the pop went ahead.
  const requestPopEntry = useCallback(
    (id: number) => {
      // An entry that is already leaving (or gone) ignores the pop and must not
      // run its guard: a vetoing guard may call `stack.pop()`, which would
      // pop the next active entry instead.
      const entry = pushedRef.current.find((e) => e.id === id);
      if (!popGuardApplies(entry?.status)) return true;
      if (!popGuardAllows(popGuardsRef.current.get(id))) return false;
      popEntry(id);
      return true;
    },
    [popEntry],
  );

  const pop = useCallback(() => {
    setPushed((prev) => {
      for (let i = prev.length - 1; i >= 0; i--) {
        if (prev[i].status === "active") {
          const id = prev[i].id;
          return prev.map((e) =>
            e.id === id ? { ...e, status: "leaving" } : e,
          );
        }
      }
      return prev;
    });
  }, []);

  // Latest callbacks for the back guard, which must not re-register (and so
  // reshuffle the guard LIFO order) on every render.
  const onCloseRef = useRef(onClose);
  const onDismissAttemptRef = useRef(onDismissAttempt);
  useEffect(() => {
    onCloseRef.current = onClose;
    onDismissAttemptRef.current = onDismissAttempt;
  });

  const api = useMemo<StackApi>(
    () => ({ push, pop, close: onClose }),
    [push, pop, onClose],
  );

  const [viewTitles, setViewTitles] = useState<ReadonlyMap<number, string>>(
    () => new Map(),
  );
  const registerViewTitle = useCallback((depth: number, title: string) => {
    setViewTitles((prev) => {
      if (prev.get(depth) === title) return prev;
      const next = new Map(prev);
      next.set(depth, title);
      return next;
    });
    // Only clear the slot if it still holds this title — a view pushed to the
    // same depth after a pop may already have registered its own.
    return () =>
      setViewTitles((prev) => {
        if (prev.get(depth) !== title) return prev;
        const next = new Map(prev);
        next.delete(depth);
        return next;
      });
  }, []);
  const viewTitlesApi = useMemo<ViewTitlesApi>(
    () => ({ titles: viewTitles, register: registerViewTitle }),
    [viewTitles, registerViewTitle],
  );

  function handleEntryTransitionEnd(id: number, status: EntryStatus) {
    // Any transform settle ends this entry's enter window: status "active"
    // means the slide-in finished; "leaving" means it was popped mid-enter
    // and the leave transition ended instead.
    enteringIdsRef.current.delete(id);
    if (status !== "leaving") return;
    setPushed((prev) => prev.filter((e) => e.id !== id));
  }

  // Viewport-mode only: in container mode the column doesn't own the
  // whole window, so body scroll lock / hardware Back / Escape stay off
  // — the drawer closes through its own X / explicit affordances.
  useBodyScrollLock(open && !isContainer);
  // Root-level back guard: when no pushed entry is on top, the OS Back gesture
  // (and the iOS left-edge swipe-back) closes the whole drawer. Registered in
  // container mode too — on phones a station column is "container", so without
  // this the first drawer level would have no swipe-dismissible guard and the
  // edge-swipe couldn't close it. Pushed entries register their own guards (in
  // PushedEntry below), and LIFO ordering means those fire first.
  //
  // Inlined (not useDrawerBackButton) so a Back refused via onDismissAttempt
  // can re-arm: the popstate already consumed this guard's sentinel, and the
  // drawer stays open, so a fresh one is pushed (`backRearm`) — same as Sheet.
  const [backRearm, setBackRearm] = useState(0);
  useEffect(() => {
    if (!open) return;
    const id = pushBackGuard(() => {
      const attempt = onDismissAttemptRef.current;
      if (attempt) {
        setBackRearm((n) => n + 1);
        attempt();
      } else onCloseRef.current();
    });
    return () => popBackGuard(id);
  }, [open, backRearm]);

  // Register this stack as an open viewport drawer. Kept separate from the
  // key listener below (which re-registers whenever `pushed` changes) so a
  // re-render can never reshuffle the LIFO opening order.
  const escapeIdRef = useRef<symbol | null>(null);
  useEffect(() => {
    if (!open || isContainer) return;
    const id = Symbol("drawer-stack-escape");
    escapeIdRef.current = id;
    openViewportStacks.push(id);
    return () => {
      escapeIdRef.current = null;
      const idx = openViewportStacks.indexOf(id);
      if (idx !== -1) openViewportStacks.splice(idx, 1);
    };
  }, [open, isContainer]);

  // The control that opened the drawer, remembered on open — before the
  // background is made inert below (inert can take its focus away).
  useEffect(rememberDrawerPresses, []);
  const openersRef = useRef<HTMLElement[]>([]);
  useLayoutEffect(() => {
    if (!open) return;
    openersRef.current = openerCandidates(asideRef.current);
  }, [open]);

  // While closed (viewport AND container mode), the drawer's own nodes are
  // inert + aria-hidden: a closed drawer stays mounted off-screen (e.g.
  // RetrospectiveSourceDrawer), and its buttons must not be Tab stops. Held
  // through inert-background (not React props) so it composes with the holds
  // of other drawers. A layout effect: the release on open lands before any
  // child effect moves focus into the drawer. The slide-out is unaffected.
  useLayoutEffect(() => {
    if (open || (!isContainer && !canPortal)) return;
    const own = [asideRef.current, backdropRef.current].filter(
      (el): el is HTMLElement => el != null,
    );
    return holdInert(own);
  }, [open, isContainer, canPortal]);

  // Viewport mode: while open, the page behind the drawer (and any drawer opened
  // before this one) is inert + aria-hidden — Tab, screen readers and
  // name-based lookups can't reach it. Overlays painted above the drawer
  // (toasts, tours) stay live; see inert-background.ts. Container mode leaves
  // the other columns interactive on purpose. A layout effect, so the lift lands
  // before child effects move focus into the drawer.
  useLayoutEffect(() => {
    if (!open || isContainer || !canPortal) return;
    const aside = asideRef.current;
    const host = aside?.parentElement;
    if (!aside || !host) return;
    const own = [aside, backdropRef.current].filter(
      (el): el is HTMLElement => el != null,
    );
    // Lift first: this drawer may have been held by one opened before it
    // (mounted closed at that time). Then hold everything behind it.
    const releaseOwn = liftInert(own);
    const releaseBackground = holdInert(
      backgroundOf(host.children, own, computedZIndex),
    );
    return () => {
      releaseBackground();
      releaseOwn();
    };
  }, [open, isContainer, canPortal]);

  // On close (or unmount): focus back to the opener. Declared after the inert
  // effects so their cleanups — which make the opener reachable again — run
  // first. Not when the focus was put somewhere else meanwhile (a Sheet opened
  // on Save); a gone opener means nothing is focused.
  useLayoutEffect(() => {
    if (!open) return;
    const aside = asideRef.current;
    return () => {
      const at = document.activeElement;
      const elsewhere =
        !nothingFocused(at) && !(aside != null && aside.contains(at));
      const target = focusReturnTarget(
        openersRef.current,
        canTakeFocus,
        elsewhere,
      );
      openersRef.current = [];
      focusQuietly(target);
    };
  }, [open]);

  // What Escape does: pop a pushed entry if any, otherwise close (or ask
  // the host).
  function escapeBack() {
    const topActive = pushed.findLast((p) => p.status === "active");
    const action = drawerDismissAction(
      topActive !== undefined,
      !!onDismissAttempt,
    );
    if (action === "pop" && topActive) requestPopEntry(topActive.id);
    else if (action === "attempt") onDismissAttempt?.();
    else onClose();
  }
  const escapeBackRef = useRef(escapeBack);
  useLayoutEffect(() => {
    escapeBackRef.current = escapeBack;
  });

  // Escape mirrors the back behaviour. Constraint: only the TOPMOST open stack
  // (the last-registered instance in openViewportStacks) may act — every open
  // viewport drawer listens on the same document.
  const escapeScope = drawerEscapeScope(presentation, isContainer);
  useEffect(() => {
    if (!open || escapeScope !== "document") return;
    function onKey(e: KeyboardEvent) {
      if (e.key !== "Escape") return;
      const top = openViewportStacks[openViewportStacks.length - 1];
      if (top === undefined || top !== escapeIdRef.current) return;
      escapeBackRef.current();
    }
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, escapeScope]);

  // Container-mode screen: Escape pressed inside this screen (not inside a
  // dialog nested in it) goes back / closes. Scoped to the aside so other
  // columns and drawers keep their own keys.
  function onScreenEscape(e: React.KeyboardEvent<HTMLElement>) {
    if (e.key !== "Escape" || e.defaultPrevented) return;
    const target = e.target instanceof Element ? e.target : null;
    if (target?.closest('[role="dialog"]') !== asideRef.current) return;
    e.preventDefault();
    escapeBackRef.current();
  }

  // One guarded "dismiss all" path for the root X, "Done" and the backdrop.
  function requestDismiss() {
    const action = drawerDismissAllAction(!!onDismissAttempt);
    if (action === "attempt") onDismissAttempt?.();
    else onClose();
  }

  const topId = topEntryId(pushed);
  const classes = drawerPresentationClasses(
    presentation,
    positionClass,
    widthClassName ?? drawerWidthClass(width),
    asideOpen,
    dismissable,
  );

  // Form sheet / page: Tab wraps within the visible view. The drawer keeps
  // relying on the inert background alone (unchanged behaviour).
  function onTrapTab(e: React.KeyboardEvent<HTMLElement>) {
    if (e.key !== "Tab" || e.altKey || e.ctrlKey || e.metaKey) return;
    const aside = asideRef.current;
    if (!aside) return;
    const view = Array.from(aside.children)
      .filter(
        (el): el is HTMLElement =>
          el instanceof HTMLElement && !el.inert && el.dataset.leaving == null,
      )
      .at(-1);
    if (!view) return;
    const focusables = Array.from(
      view.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
    ).filter(canTakeFocus);
    const at = document.activeElement;
    const index = focusWrapIndex(
      focusables.length,
      focusables.findIndex((el) => el === at),
      e.shiftKey,
    );
    if (index === null) return;
    e.preventDefault();
    focusQuietly(focusables[index]);
  }

  const tree = (
    <StackContext.Provider value={api}>
      <RequestDismissContext.Provider value={requestDismiss}>
      <PresentationContext.Provider value={presentation}>
      <ViewTitlesContext.Provider value={viewTitlesApi}>
        {classes.backdrop !== null && (
          <div
            ref={backdropRef}
            aria-hidden="true"
            onClick={dismissable ? requestDismiss : undefined}
            // Backdrop sits at the same z-index as the aside so it can still
            // dim a sibling Sheet at z-50 (e.g. the active-training modal
            // when Settings is opened from inside it). DOM order keeps the
            // aside painted on top of the backdrop within the tie.
            className={classes.backdrop}
          />
        )}
        <aside
          ref={asideRef}
          role="dialog"
          aria-modal="true"
          aria-label={ariaLabel}
          onKeyDown={
            presentation === "drawer"
              ? undefined
              : (e) => {
                  if (escapeScope === "aside") onScreenEscape(e);
                  onTrapTab(e);
                }
          }
          // The clamp boundary for anchored popovers rendered inside the drawer
          // (normative base picker, tag selector) — see popover-position.ts. Keeps
          // a fixed-positioned menu within the drawer instead of spilling onto the
          // backdrop or off-screen.
          data-popover-boundary=""
          // Tell any frosted header inside the drawer that its host surface is
          // `surface-drawer`, not the page background — so the frosted bar tints
          // to the drawer colour. Inherited by DrawerHeader (root + pushed).
          style={
            {
              "--frost-bg":
                presentation === "screen"
                  ? "var(--background)"
                  : "var(--surface-drawer)",
            } as React.CSSProperties
          }
          // Edge-to-edge so the drawer's surface covers the safe-area
          // zones (no grey bars showing the backdrop). The inner chrome
          // (DrawerView) handles its own safe-area padding so the X /
          // trailing slot / scroll content all sit inside the visible
          // region on a Capacitor build.
          className={classes.aside}
        >
          {renderedRoot && (
            <DepthContext.Provider value={0}>
              {/* z-0 makes each entry its own stacking context so any
                inner z-index (e.g. SlotCard's chain pill at z-10)
                stays contained — otherwise it leaks up and overlays
                whatever sibling entry sits on top during a push. */}
              <div
                className={`absolute inset-0 z-0 flex flex-col ${presentation === "screen" ? "bg-background" : "bg-surface-drawer"}`}
                inert={topId !== undefined}
                aria-hidden={topId !== undefined || undefined}
              >
                {renderedRoot}
              </div>
            </DepthContext.Provider>
          )}
          {pushed.map((entry, idx) => (
            <PushedEntry
              key={entry.id}
              entry={entry}
              depth={idx + 1}
              covered={entry.id !== topId}
              onPopMe={() => requestPopEntry(entry.id)}
              registerPopGuard={registerPopGuard}
              getPushers={getPushers}
              forgetPushers={forgetPushers}
              onTransitionEnd={() =>
                handleEntryTransitionEnd(entry.id, entry.status)
              }
            />
          ))}
        </aside>
      </ViewTitlesContext.Provider>
      </PresentationContext.Provider>
      </RequestDismissContext.Provider>
    </StackContext.Provider>
  );

  // Container mode: render inline so the `absolute inset-0` backdrop + aside
  // anchor to the column's positioned ancestor (and `absolute` is immune to the
  // transformed-ancestor problem). The subtree mounts once and never re-parents.
  if (isContainer) return tree;
  // Viewport mode: wait for the post-mount flag, then portal to <body> so the
  // `fixed inset-0` backdrop + aside resolve against the real viewport, not a
  // transformed ancestor — without this the scrim stops short of the iOS
  // status-bar strip. Render null (not the inline tree) until then so the
  // subtree mounts a single time inside the portal — see the `canPortal` note.
  if (!canPortal) return null;
  // Portal into the fullscreen element when one is active (present mode /
  // replay player) so the aside + backdrop paint; `document.body` otherwise.
  return createPortal(tree, overlayPortalHost());
}

function PushedEntry({
  entry,
  depth,
  covered,
  onPopMe,
  registerPopGuard,
  getPushers,
  forgetPushers,
  onTransitionEnd,
}: {
  entry: StackEntry;
  depth: number;
  // Not the view on top (see topEntryId): inert + aria-hidden.
  covered: boolean;
  // User-initiated pop of this entry, through its pop guard; false = refused.
  onPopMe: () => boolean;
  registerPopGuard: (id: number, guard: PopGuard) => () => void;
  // The control that pushed this entry, best first (see DrawerStack.push).
  getPushers: (id: number) => HTMLElement[];
  forgetPushers: (id: number) => void;
  onTransitionEnd: () => void;
}) {
  const entryId = entry.id;
  const viewRef = useRef<HTMLDivElement>(null);

  // Pushed: the focus moves into this view (it is on top from its first
  // commit — see topEntryId — while the view underneath turns inert).
  useLayoutEffect(() => {
    const view = viewRef.current;
    if (view) focusQuietly(pushedViewFocusTarget(view));
  }, []);

  // Popped: the view underneath is live again in this same commit; the focus
  // goes back to the row that pushed this one — unless it was moved out of
  // this view on purpose.
  const leaving = entry.status === "leaving";
  useLayoutEffect(() => {
    if (!leaving) return;
    const view = viewRef.current;
    const at = document.activeElement;
    const elsewhere =
      !nothingFocused(at) && !(view != null && view.contains(at));
    focusQuietly(focusReturnTarget(getPushers(entryId), canTakeFocus, elsewhere));
  }, [leaving, getPushers, entryId]);
  useEffect(() => () => forgetPushers(entryId), [forgetPushers, entryId]);
  // Per-entry back guard. While this entry exists (any status), Back pops it.
  // Even mid-leave the guard is harmless (popMe is a no-op for non-active
  // entries), and unmount cleans it up. A Back refused by the view's pop
  // guard re-arms (the popstate consumed the sentinel) — same as the root.
  const onPopMeRef = useRef(onPopMe);
  useEffect(() => {
    onPopMeRef.current = onPopMe;
  });
  const [backRearm, setBackRearm] = useState(0);
  useEffect(() => {
    const id = pushBackGuard(() => {
      if (!onPopMeRef.current()) setBackRearm((n) => n + 1);
    });
    return () => popBackGuard(id);
  }, [backRearm]);
  const popMe = useCallback(() => {
    onPopMeRef.current();
  }, []);
  const registerOwnPopGuard = useCallback(
    (guard: PopGuard) => registerPopGuard(entryId, guard),
    [registerPopGuard, entryId],
  );

  // Leave-removal backstop — see LEAVE_REMOVE_BACKSTOP_MS. onTransitionEnd is
  // re-created per render, so the timer resets on renders while leaving; it
  // still fires once renders settle, and the removal is idempotent.
  useEffect(() => {
    if (entry.status !== "leaving") return;
    const t = window.setTimeout(onTransitionEnd, LEAVE_REMOVE_BACKSTOP_MS);
    return () => window.clearTimeout(t);
  }, [entry.status, onTransitionEnd]);

  const transform =
    entry.status === "active" ? "translate-x-0" : "translate-x-full";
  const entryBg =
    useDrawerPresentation() === "screen" ? "bg-background" : "bg-surface-drawer";
  return (
    <DepthContext.Provider value={depth}>
      <EntryPopContext.Provider value={popMe}>
      <PopGuardContext.Provider value={registerOwnPopGuard}>
        <div
          ref={viewRef}
          data-leaving={leaving ? "" : undefined}
          // z-0 contains inner z-index values (e.g. SlotCard's chain
          // pill at z-10) within this entry's stacking context. Without
          // it, those values leak up to the aside level and overlay
          // entries pushed on top.
          className={`absolute inset-0 z-0 flex flex-col ${entryBg} transition-transform duration-300 ease-out ${transform}`}
          inert={covered}
          aria-hidden={covered || undefined}
          onTransitionEnd={(e) => {
            if (e.propertyName !== "transform") return;
            if (e.target !== e.currentTarget) return;
            onTransitionEnd();
          }}
        >
          {entry.body}
        </div>
      </PopGuardContext.Provider>
      </EntryPopContext.Provider>
    </DepthContext.Provider>
  );
}

// ─── DrawerView ────────────────────────────────────────────────────────────
//
// Layout primitive used by every view. Renders a top header row with a
// leading button (auto: back chevron when depth > 0, close X at depth 0) and
// an optional trailing slot, plus a scrollable body.
//
// Views that need to break the standard chrome (own scroll container, sticky
// bottom bar, custom header) can pass `bare` to opt out and render their own
// structure — only the scroll lock + push API remain shared.

type DrawerViewProps = {
  // Left-aligned title shown in the header bar next to the back/close
  // button. Pairs with the rest of the app's unified header pattern —
  // fixed bar, thin border-b, body scrolls underneath.
  title?: string;
  // Optional second line under the title — same alignment, muted
  // typography. Use sparingly (e.g. workout date / "Workout details").
  subtitle?: string;
  trailing?: ReactNode;
  // When true, skips the auto header + scroll wrapper. The view renders its
  // own structure (e.g. pickers with a sticky Confirm bar) — those views
  // should call `<DrawerViewHeader title=… />` themselves so the bar
  // still matches the standard layout.
  bare?: boolean;
  /**
   * Opt-in edge-to-edge body for a grouped settings page: drops the
   * horizontal padding (keeps the bottom safe-area padding) and paints the
   * whole view in the grouped page colour (`settings-grouped-page`), full
   * height. Ignored when `bare` is set. Default: padded.
   */
  flush?: boolean;
  children: ReactNode;
};

const FLUSH_FROST_STYLE = {
  "--frost-bg": "var(--settings-page-bg)",
} as React.CSSProperties;

export function DrawerView({
  title,
  subtitle,
  trailing,
  bare,
  flush,
  children,
}: DrawerViewProps) {
  // The top safe-area inset lives on the header (DrawerViewHeader) so the
  // frosted bar extends up under the iOS status bar — NOT on this root. Viewport
  // drawers are fixed under the status bar; station columns are lifted under it
  // (the today rail cancels the body's top padding). Bottom inset is
  // deliberately NOT applied here — floating affordances (Confirm bars, action
  // buttons) opt into a bottom safe-area offset themselves so they clear the
  // home indicator.
  // A form sheet is a card inset from the screen edges: no safe-area padding.
  const inCard = useDrawerPresentation() === "formSheet";
  if (bare) {
    return (
      <div className="relative flex h-full min-h-0 flex-col">{children}</div>
    );
  }
  const header = (
    <DrawerViewHeader title={title} subtitle={subtitle} trailing={trailing} />
  );
  return (
    <div
      // A flush body hosts a grouped settings page: the whole view (behind the
      // header, below short content, the bottom padding) paints the grouped
      // colour, and the frosted header + foot fade tint to it — otherwise the
      // drawer surface shows as a strip under the content.
      className={`relative flex h-full min-h-0 flex-col ${flush ? "settings-grouped-page" : ""}`}
      style={flush ? FLUSH_FROST_STYLE : undefined}
    >
      {HEADER_BLUR ? (
        <div className="absolute inset-x-0 top-0 z-20">{header}</div>
      ) : (
        header
      )}
      <div
        className={`scrollbar-none flex-1 overflow-y-auto overscroll-contain ${flush ? "" : "px-6"} ${
          // +inset over HEADER_OVERLAY_PT: the frosted header is now taller by
          // the safe-area inset (it extends under the status bar).
          HEADER_BLUR
            ? inCard
              ? "pt-[85px]"
              : "pt-[calc(85px+env(safe-area-inset-top))]"
            : ""
        } ${
          flush
            ? "pb-[calc(3rem+env(safe-area-inset-bottom))]"
            : "pb-12 ios:px-4"
        }`}
      >
        {children}
      </div>
      {/* Soft fade at the foot of the scroll area — scroll affordance matching
          the app's other scrollable views. Sibling of the scroller, anchored to
          this positioned root so it never repaints on scroll. */}
      <ScrollEdgeFade />
    </div>
  );
}

// Standard drawer top bar — back/close on the left, title + optional
// subtitle in the middle (left-aligned), trailing actions on the
// right, 1-px border-b underneath. Single source of the app's "page
// header" pattern; full-screen Sheets duplicate the same shape inline.
export function DrawerViewHeader({
  title,
  subtitle,
  trailing,
}: {
  title?: string;
  subtitle?: string;
  trailing?: ReactNode;
}) {
  const depth = useDrawerDepth();
  const popMe = useEntryPop();
  const { close } = useDrawerStack();
  const requestDismiss = useContext(RequestDismissContext) ?? close;
  const { t } = useTranslation();

  const presentation = useDrawerPresentation();
  const { leading, done } = drawerHeaderAffordances(presentation, depth);
  const start = useScreenHeaderStart();

  const onLeading = depth > 0 ? (popMe ?? requestDismiss) : requestDismiss;
  const isBack = leading === "back";

  // Text back buttons read the title of the view underneath, so every header
  // of such a stack registers its own title at its depth.
  const textBack = drawerBackButtonStyle(presentation) === "text";
  const viewTitles = useContext(ViewTitlesContext);
  const register = viewTitles?.register;
  useLayoutEffect(() => {
    if (!textBack || !register || !title) return;
    return register(depth, title);
  }, [textBack, register, depth, title]);
  const backTitle = viewTitles ? previousViewTitle(viewTitles.titles, depth) : null;

  return (
    <div
      // pt carries the top safe-area inset so the frosted bar extends up under
      // the iOS status bar (the drawer host no longer pads its root — viewport
      // drawers are fixed under the status bar, and station columns are lifted
      // under it). env() is 0 off iOS, so this is a no-op there. A form sheet
      // card already sits inside the safe area, so it skips the inset.
      className={`${HEADER_MIN_HEIGHT} ${headerEdgeClass(HEADER_BLUR)} flex shrink-0 items-center gap-3 px-4 pb-3 ${
        presentation === "formSheet"
          ? "pt-3"
          : "pt-[calc(0.75rem+env(safe-area-inset-top))]"
      }`}
    >
      {start}
      {isBack && textBack ? (
        // "‹ Account": text like "Done" (app text colour, as the app's other
        // header actions), no round chrome; 44 px tall, long titles truncate
        // at ~45% of the bar.
        <button
          type="button"
          onClick={onLeading}
          aria-label={
            backTitle
              ? t("Back to {title}", { title: backTitle })
              : t("Back")
          }
          className="clickable-small -ml-2 flex h-11 min-w-11 max-w-[45%] shrink-0 items-center gap-0.5 pr-1 text-foreground-default hover:opacity-80"
        >
          <BackChevron className="size-6 shrink-0" />
          <span className="min-w-0 truncate">{backTitle ?? t("Back")}</span>
        </button>
      ) : leading && (
        <button
          type="button"
          onClick={onLeading}
          aria-label={isBack ? t("Back") : t("Close")}
          className={HEADER_ICON_BUTTON}
        >
          {isBack ? <BackChevron className="size-5" /> : <CloseX className="size-5" />}
        </button>
      )}
      {title && (
        <div className="min-w-0 flex-1">
          <h2 className="heading-large truncate">{title}</h2>
          {subtitle && (
            <p className="body-small truncate text-foreground-muted">
              {subtitle}
            </p>
          )}
        </div>
      )}
      {/* Spacer so the trailing slot always anchors to the right edge,
          even when there's no title — matches the layout before the
          title slot existed. */}
      {!title && <div className="flex-1" />}
      {trailing}
      {done && (
        // Closes the whole sheet through the dismiss-all path, so the
        // host's onDismissAttempt still applies.
        <button
          type="button"
          onClick={requestDismiss}
          className="clickable-small flex h-11 shrink-0 items-center rounded-full px-3 text-foreground-default hover:bg-surface-base-muted"
        >
          {t("Done")}
        </button>
      )}
    </div>
  );
}

// ─── Icons ─────────────────────────────────────────────────────────────────

type IconProps = { className?: string };

function CloseX({ className }: IconProps) {
  return <CloseXIcon className={className} />;
}

function BackChevron({ className }: IconProps) {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={2}
      className={className}
      aria-hidden="true"
    >
      <path
        strokeLinecap="round"
        strokeLinejoin="round"
        d="M15.75 19.5 8.25 12l7.5-7.5"
      />
    </svg>
  );
}
