"use client";

import {
  Fragment,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type CSSProperties,
  type MouseEvent,
  type ReactNode,
  type Ref,
} from "react";
import { useTranslation } from "@enode/core/translations/hooks";
import { CheckIcon, Person2FillIcon, SpinnerIcon, XIcon } from "@enode/ui/icons";
import { LOOK } from "@enode/ui/live/look";

// Portal-local shared table primitives, extracted from the Users table so the
// Sessions/History table (and future dashboard tables) reuse the same chrome.
// Generic table CHROME only — page-specific row content stays in the page.

/**
 * Width cap for a name / identity cell — apply to the cell's ROOT element (keep
 * `min-w-0` + `truncate` on the text inside it).
 *
 * @remarks
 * The tables use auto layout, where a `<td>` sizes to its content's *min-content*
 * width. A long name — especially an unbroken one — therefore widens the whole
 * column, pushes the other columns out, and `truncate` never engages because the
 * cell always grows to fit it. A `max-width` on a block inside the cell clamps
 * that intrinsic contribution, so the column stops growing and the ellipsis does
 * its job.
 *
 * The cap grows on wider screens; below the table's `minWidth` the row scrolls
 * sideways (see {@link TableScroll}) rather than squashing further. One shared
 * value so every table truncates at the same point.
 */
export const NAME_CELL_MAX_W =
  "max-w-[160px] lg:max-w-[240px] xl:max-w-[320px]";

// Rounded, bordered surface that wraps a table (+ optional empty message).
// `flat` drops the shadow for a plainer, un-elevated card.
export function TableCard({
  children,
  flat = false,
  bounded = false,
  pageSticky = false,
}: {
  children: ReactNode;
  flat?: boolean;
  // The header row sticks to the page's scroll container (see TableScroll).
  // The card then clips with `overflow-clip`: `overflow-hidden` would make the
  // card a scroll container and the header would stick to it, not the page.
  pageSticky?: boolean;
  // Shrinks to the height its flex parent leaves, its table scrolling inside
  // (for a sticky header); as tall as its rows when they fit.
  bounded?: boolean;
}) {
  return (
    <div
      className={`${pageSticky ? "overflow-clip" : "overflow-hidden"} ${LOOK.panel} ${
        flat ? "" : "shadow-prominent"
      } ${bounded ? "flex min-h-0 flex-col" : ""}`}
    >
      {children}
    </div>
  );
}

/**
 * Spacer width for the horizontal scrollbar proxy of a wide table, so the proxy
 * scrolls over exactly the body's range and both can share one `scrollLeft`.
 *
 * @param scrollWidth - The body scroller's `scrollWidth` (the table's width).
 * @param clientWidth - The body scroller's `clientWidth` (the card's inner width).
 * @param proxyClientWidth - The proxy's `clientWidth` (inset from the card edges).
 * @returns The spacer width; the proxy's own width when nothing overflows.
 */
export function scrollProxySpacerWidth(
  scrollWidth: number,
  clientWidth: number,
  proxyClientWidth: number,
): number {
  return proxyClientWidth + Math.max(0, scrollWidth - clientWidth);
}

// The measured geometry the split header strip and the scrollbar proxy copy
// from the body table (see TableScroll `head`).
type SplitLayout = {
  tableWidth: number;
  // The body's scroll width: content can overhang the table itself.
  scrollWidth: number;
  columns: number[];
  spacer: number;
};

// The width a header cell's content needs: its label (plus sort arrow or
// control) measured as laid out, overflow included, plus the cell's padding.
function headerContentWidth(cell: HTMLTableCellElement): number {
  const range = document.createRange();
  range.selectNodeContents(cell);
  const style = getComputedStyle(cell);
  return (
    range.getBoundingClientRect().width +
    parseFloat(style.paddingLeft) +
    parseFloat(style.paddingRight)
  );
}

function sameLayout(a: SplitLayout | null, b: SplitLayout): boolean {
  if (!a || a.columns.length !== b.columns.length) return false;
  const close = (x: number, y: number) => Math.abs(x - y) < 0.5;
  return (
    close(a.tableWidth, b.tableWidth) &&
    close(a.scrollWidth, b.scrollWidth) &&
    close(a.spacer, b.spacer) &&
    a.columns.every((w, i) => close(w, b.columns[i]))
  );
}

// The scrollbar proxy's own bar: styled with `::-webkit-scrollbar` where
// supported, because a styled bar always shows — a macOS overlay scrollbar
// would only appear while scrolling, and the proxy exists to be found. Browsers
// without it (Firefox) get the thin standard bar.
const PROXY_SCROLLBAR =
  "[&::-webkit-scrollbar]:h-2 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-surface-stroke supports-[not_selector(::-webkit-scrollbar)]:[scrollbar-color:var(--surface-stroke)_transparent] supports-[not_selector(::-webkit-scrollbar)]:[scrollbar-width:thin]";

// Horizontal-scroll wrapper + the <table>. `minWidth` keeps columns readable on
// narrow screens (the row scrolls sideways instead of squashing).
export function TableScroll({
  minWidth = "min-w-[720px]",
  fixed = false,
  separate = false,
  stickyHeader = false,
  pageSticky = false,
  head,
  children,
}: {
  // The header row sticks to the PAGE's scroll container (PageShell), right
  // under its frosted header. While the table fits its width that is plain CSS
  // `position: sticky` on the header cells. A table wider than its card needs a
  // horizontal scroll box, which would capture the sticky header — so, given
  // `head`, the table splits (see `head`); without it, it falls back to plain
  // sideways scrolling.
  pageSticky?: boolean;
  // The header ROW (`<tr>`); TableScroll renders the `<thead>` around it. With
  // `pageSticky`, a table wider than its card renders the row twice: in a
  // sticky header strip above the body (its own table, sized from the body's
  // measured columns, its `scrollLeft` mirrored from the body), and collapsed
  // (`visibility: collapse`, inert) inside the body table so the header content
  // still sizes the columns. The body hides its scrollbar; a thin scrollbar
  // proxy sticks to the bottom of the page instead, so it is reachable without
  // scrolling to the end of the table.
  head?: ReactNode;
  // The table scrolls on both axes inside its card, so the header row (and the
  // pinned columns) can stay in view with plain CSS `position: sticky`. The
  // host bounds the card's height (a flex column, e.g. PageShell `fill`).
  stickyHeader?: boolean;
  // Separated borders: rows draw no border, each cell its own (`border-b`).
  // For tables with pinned columns — a pinned cell keeps its own border where
  // a collapsed row border would not line up with it.
  separate?: boolean;
  minWidth?: string;
  // Use `table-layout: fixed` so columns take their configured widths and long
  // cell content truncates instead of widening the table (→ no horizontal
  // scroll). Pair with `minWidth="min-w-0"` and per-column widths.
  fixed?: boolean;
  children: ReactNode;
}) {
  // Where the row content sits under the pinned columns: only then do they
  // show an edge (see `stickyClass` in data-table-view). A table that fits, or
  // one scrolled back to its start, looks like any other table.
  const [edges, setEdges] = useState({ overflow: false, left: false, right: false });
  const measure = (el: HTMLDivElement | null) => {
    if (!el) return;
    const overflow = el.scrollWidth > el.clientWidth + 1;
    const left = overflow && el.scrollLeft > 0;
    const right = overflow && el.scrollLeft + el.clientWidth < el.scrollWidth - 1;
    setEdges((e) =>
      e.overflow === overflow && e.left === left && e.right === right
        ? e
        : { overflow, left, right },
    );
  };
  const ref = useRef<HTMLDivElement | null>(null);
  const bodyHeadRef = useRef<HTMLTableSectionElement | null>(null);
  const stripRef = useRef<HTMLDivElement | null>(null);
  const proxyRef = useRef<HTMLDivElement | null>(null);
  // Where the header row sticks: the bottom of the page's overlay header
  // (PageShell's absolutely positioned <header>, a sibling of the scroll body).
  const [pageTop, setPageTop] = useState(0);
  // Where the scrollbar proxy sticks: the page scroller's bottom edge. Sticky
  // offsets count from inside the scroller's padding, so step back over it.
  const [pageBottom, setPageBottom] = useState(0);
  useEffect(() => {
    if (!pageSticky) return;
    let scroller = ref.current?.parentElement ?? null;
    while (scroller && !/(auto|scroll)/.test(getComputedStyle(scroller).overflowY)) {
      scroller = scroller.parentElement;
    }
    if (scroller) setPageBottom(-parseFloat(getComputedStyle(scroller).paddingBottom));
    const header = scroller?.previousElementSibling;
    if (!(header instanceof HTMLElement) || getComputedStyle(header).position !== "absolute") {
      return;
    }
    // `top` is measured from the scroller's padding edge (its padding already
    // clears the header, plus a little air), so subtract that padding.
    const scrollBody = scroller;
    const update = () =>
      setPageTop(
        header.offsetHeight -
          parseFloat(getComputedStyle(scrollBody as HTMLElement).paddingTop),
      );
    update();
    const observer = new ResizeObserver(update);
    observer.observe(header);
    return () => observer.disconnect();
  }, [pageSticky]);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    measure(el);
    const observer = new ResizeObserver(() => measure(el));
    observer.observe(el);
    if (el.firstElementChild) observer.observe(el.firstElementChild);
    return () => observer.disconnect();
  }, []);

  // A wide page-sticky table: header strip + body + scrollbar proxy.
  const split = pageSticky && head != null && edges.overflow;
  const [layout, setLayout] = useState<SplitLayout | null>(null);
  // A split table never truncates a header label: a fixed-layout table (columns
  // in percent) whose labels overflow their columns grows to the width at which
  // they fit. A few steps at most — a column that does not grow with the table
  // could never fit, and must not widen it forever.
  const [labelMinWidth, setLabelMinWidth] = useState<number | null>(null);
  const labelGrowSteps = useRef(0);
  useLayoutEffect(() => {
    if (!split) return;
    return () => {
      labelGrowSteps.current = 0;
      setLabelMinWidth(null);
    };
  }, [split]);
  // Re-measured on every render while split (`head` is a new element each
  // time): a sort, a shown/hidden column or new rows can move the columns
  // without resizing the table. Before paint, so the strip never shows unsized.
  useLayoutEffect(() => {
    const body = ref.current;
    const table = body?.firstElementChild;
    const headRow = bodyHeadRef.current?.rows[0];
    if (!split || !body || !(table instanceof HTMLElement) || !headRow) return;
    const update = () => {
      const cells = Array.from(headRow.cells);
      const tableWidth = table.getBoundingClientRect().width;
      const overflowRatio = Math.max(
        1,
        ...cells.map((cell) => {
          const width = cell.getBoundingClientRect().width;
          return width > 0 ? headerContentWidth(cell) / width : 1;
        }),
      );
      if (overflowRatio > 1.01 && labelGrowSteps.current < 3) {
        labelGrowSteps.current += 1;
        setLabelMinWidth(Math.ceil(tableWidth * overflowRatio));
      }
      const next: SplitLayout = {
        tableWidth,
        scrollWidth: body.scrollWidth,
        columns: cells.map((cell) => cell.getBoundingClientRect().width),
        spacer: proxyRef.current
          ? scrollProxySpacerWidth(body.scrollWidth, body.clientWidth, proxyRef.current.clientWidth)
          : 0,
      };
      setLayout((prev) => (sameLayout(prev, next) ? prev : next));
    };
    update();
    const observer = new ResizeObserver(update);
    observer.observe(body);
    observer.observe(table);
    for (const cell of Array.from(headRow.cells)) observer.observe(cell);
    return () => observer.disconnect();
  }, [split, head]);
  // The strip and the proxy follow the body's offset (also once they mount).
  useLayoutEffect(() => {
    if (split && ref.current) syncScroll(ref.current);
  }, [split, layout]);

  // Mirror one scroller's offset onto the other two. Only real changes are
  // written, so the scroll events this causes settle at once.
  function syncScroll(source: HTMLElement) {
    const left = source.scrollLeft;
    for (const el of [ref.current, stripRef.current, proxyRef.current]) {
      if (el && el !== source && Math.abs(el.scrollLeft - left) >= 1) el.scrollLeft = left;
    }
  }

  const tableClass = `w-full ${minWidth} ${
    separate ? "border-separate border-spacing-0" : "border-collapse"
  }`;
  // A thin scrollbar, not none: columns past the edge must be reachable with a
  // mouse that can't scroll sideways. A split table hides it — its proxy is
  // that scrollbar.
  const thinScrollbar =
    "[scrollbar-color:var(--surface-stroke)_transparent] [scrollbar-width:thin]";

  return (
    <div
      className="group/scroll contents"
      data-overflow={edges.overflow || undefined}
      data-under-left={edges.left || undefined}
      data-under-right={edges.right || undefined}
      style={
        pageSticky
          ? ({
              "--table-sticky-top": `${pageTop}px`,
              "--table-sticky-bottom": `${pageBottom}px`,
            } as CSSProperties)
          : undefined
      }
    >
      {split && (
        <div
          ref={stripRef}
          // Overflow hidden: a trackpad swipe over the header scrolls the body.
          onWheel={(e) => {
            if (ref.current && Math.abs(e.deltaX) > Math.abs(e.deltaY)) {
              ref.current.scrollLeft += e.deltaX;
            }
          }}
          className="sticky top-[var(--table-sticky-top,0px)] z-[2] overflow-hidden bg-surface-base"
        >
          {/* As wide as the body scrolls, so both reach the same offset. */}
          <div style={{ width: layout?.scrollWidth }}>
            <table
              className={`${tableClass} table-fixed`}
              // Inside the strip the header cells stick to the strip, not the page.
              style={
                { width: layout?.tableWidth, "--table-sticky-top": "0px" } as CSSProperties
              }
            >
              <colgroup>
                {layout?.columns.map((width, i) => <col key={i} style={{ width }} />)}
              </colgroup>
              <thead>{head}</thead>
            </table>
          </div>
        </div>
      )}
      <div
        ref={ref}
        onScroll={(e) => {
          measure(e.currentTarget);
          if (split) syncScroll(e.currentTarget);
        }}
        className={
          stickyHeader
            ? `min-h-0 flex-1 overflow-auto ${thinScrollbar}`
            : split
              ? "scrollbar-none overflow-x-auto"
              : pageSticky && !edges.overflow
                ? `overflow-x-clip ${thinScrollbar}`
                : `overflow-x-auto ${thinScrollbar}`
        }
      >
        <table
          className={`${tableClass} ${fixed ? "table-fixed" : ""}`}
          style={split && labelMinWidth != null ? { minWidth: labelMinWidth } : undefined}
        >
          {head != null && (
            <thead
              ref={bodyHeadRef}
              // While split, the strip shows the header; this copy only sizes
              // the columns.
              aria-hidden={split || undefined}
              inert={split || undefined}
              className={split ? "[visibility:collapse]" : undefined}
            >
              {head}
            </thead>
          )}
          {children}
        </table>
      </div>
      {split && (
        // Flush with the bottom of the page's scroll area, above its fade, on
        // its own opaque strip so no row shows through or under the bar; the
        // track is inset from the card's rounded corners.
        <div className="sticky bottom-[var(--table-sticky-bottom,0px)] z-[2] border-t border-surface-stroke bg-surface-base px-4 py-1.5">
          <div
            ref={proxyRef}
            aria-hidden
            tabIndex={-1}
            onScroll={(e) => syncScroll(e.currentTarget)}
            className={`overflow-x-auto overflow-y-hidden ${PROXY_SCROLLBAR}`}
          >
            <div className="h-px" style={{ width: layout?.spacer }} />
          </div>
        </div>
      )}
    </div>
  );
}

// Header cell.
export function Th({
  children,
  className,
  colSpan,
}: {
  children?: ReactNode;
  className?: string;
  colSpan?: number;
}) {
  return (
    <th
      colSpan={colSpan}
      className={`heading-section px-4 py-3 text-foreground-muted ${className ?? ""}`}
    >
      {children}
    </th>
  );
}

// Body cell. `onClick` is for cells that must OWN their clicks on a clickable
// row (e.g. a checkbox cell calling stopPropagation so selecting never also
// triggers the row's action).
export function Td({
  children,
  className,
  colSpan,
  rowSpan,
  style,
  onClick,
}: {
  children?: ReactNode;
  className?: string;
  colSpan?: number;
  rowSpan?: number;
  style?: CSSProperties;
  onClick?: (e: MouseEvent<HTMLTableCellElement>) => void;
}) {
  return (
    <td
      colSpan={colSpan}
      rowSpan={rowSpan}
      style={style}
      onClick={onClick}
      className={`body-normal px-4 py-3 text-foreground-default ${className ?? ""}`}
    >
      {children}
    </td>
  );
}

// Centered "no rows" message, rendered inside the card below the table.
export function TableEmpty({ children }: { children: ReactNode }) {
  return (
    <p className="body-normal p-6 text-center text-foreground-muted">
      {children}
    </p>
  );
}

// Loading / error line shown in place of the table.
export function TableMessage({
  children,
  tone = "muted",
}: {
  children: ReactNode;
  tone?: "muted" | "error";
}) {
  return (
    <p
      className={`body-normal ${tone === "error" ? "text-feedback-error" : "text-foreground-muted"}`}
    >
      {children}
    </p>
  );
}

// "Showing N of M <noun>" footer. Centered so it sits exactly where the pager
// row's summary sits once a table spills onto multiple pages — the footer
// doesn't jump between alignments as the pager appears/disappears.
export function TableCount({
  shown,
  total,
  noun,
}: {
  shown: number;
  total: number;
  noun: string;
}) {
  const { t } = useTranslation();
  return (
    <p className="body-small mt-3 text-center text-foreground-muted">
      {t("Showing {shown} of {total} {noun}", { shown, total, noun })}
    </p>
  );
}

// A tri-state checkbox (button-based so we can render the "mixed" state). Used
// both for the per-row select boxes and the header select-all. Clicks are
// stopped from bubbling so a row checkbox never also triggers `onRowClick`.
export function SelectCheckbox({
  checked,
  indeterminate = false,
  onChange,
  ariaLabel,
  disabled = false,
}: {
  checked: boolean;
  indeterminate?: boolean;
  onChange: (next: boolean) => void;
  ariaLabel: string;
  // Non-interactive + dimmed; e.g. a row that can't be selected.
  disabled?: boolean;
}) {
  // The mixed (some-but-not-all) state renders as an empty box, not a minus: a
  // minus reads as "remove", but clicking the header actually selects all. Only
  // a fully-checked box is filled. `aria-checked="mixed"` still exposes the real
  // state to assistive tech.
  return (
    <button
      type="button"
      role="checkbox"
      aria-checked={indeterminate ? "mixed" : checked}
      aria-label={ariaLabel}
      disabled={disabled}
      onClick={(e) => {
        e.stopPropagation();
        onChange(!checked);
      }}
      className={`flex size-[18px] shrink-0 items-center justify-center rounded-md border transition disabled:cursor-not-allowed disabled:opacity-40 ${
        checked
          ? "border-foreground-red-orange bg-foreground-red-orange text-white"
          : "border-surface-stroke bg-surface-base enabled:hover:border-foreground-red-orange/60"
      }`}
    >
      {checked && (
        <svg viewBox="0 0 16 16" className="size-3" aria-hidden>
          <path
            d="M3.5 8.5l3 3 6-6.5"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>
      )}
    </button>
  );
}

// One bulk action in the structured selection bar: an icon + a title + an
// "effect" line describing what it does to the selection, with an optional count
// badge and a destructive tone.
export type SelectionActionItem = {
  key: string;
  icon: ReactNode;
  label: string;
  // The effect line under the label (e.g. "2 users will be removed").
  description?: string;
  // Small trailing count chip next to the label (staged tags / export count).
  badge?: number;
  tone?: "default" | "destructive";
  disabled?: boolean;
  onClick?: () => void;
  // A staged action (e.g. "Add tags") whose changes the Apply button commits.
  // Staged items always render together at the end, next to Apply, regardless of
  // their position in `items`; immediate actions (Delete, Export) come first.
  staged?: boolean;
  // Sits at the very end of the bar, after Apply (e.g. a "More" menu), so the
  // checkmark stays next to the staged action it commits.
  end?: boolean;
  // For an action that opens an anchored popover (the tag picker): the trigger
  // ref to position against. The caller renders the popover via `overlay`.
  buttonRef?: Ref<HTMLButtonElement>;
};

// The commit control — rendered as a compact checkmark button (kept short so the
// bar stays narrow), with disabled + busy states.
export type SelectionApply = {
  onClick: () => void;
  disabled?: boolean;
  busy?: boolean;
  // Accessible label for the checkmark-only button.
  label?: string;
};

// The selection toolbar shown above the table once at least one row is selected.
//
// Two shapes:
// - Structured (`items` + optional `apply`): a low pill of two-line actions
//   (icon + title + effect line) split by hairline dividers, a checkmark commit
//   button, and a footnote spelling out the scope. This is the richer form.
// - Legacy (`actions`/`trailing` freeform slots): the original count + slotted
//   controls, kept for tables not yet migrated to `items`.
// While a floating selection bar is shown, toasts rise above it instead of
// covering its actions (the Toaster reads --toast-lift).
function useToastLift(lift: string) {
  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty("--toast-lift", lift);
    return () => {
      root.style.removeProperty("--toast-lift");
    };
  }, [lift]);
}

export function TableSelectionBar({
  count,
  noun,
  actions,
  trailing,
  items,
  apply,
  overlay,
  leadingIcon,
  onClear,
  compact = false,
  slim = false,
}: {
  count: number;
  noun: string;
  // Left-aligned controls, after the count (e.g. a bulk tag picker).
  actions?: ReactNode;
  // Right-aligned controls, grouped with "Clear selection" (e.g. an apply/commit
  // button that acts on the staged `actions`).
  trailing?: ReactNode;
  // Structured actions — when given, the richer two-line layout is used.
  items?: SelectionActionItem[];
  apply?: SelectionApply;
  // Popover overlays owned by an action (e.g. the tag picker), rendered in-tree.
  overlay?: ReactNode;
  // Glyph in the leading count circle (rich `items` layout). Defaults to the
  // people icon; pass an entity-appropriate glyph for non-user selections.
  leadingIcon?: ReactNode;
  onClear: () => void;
  // Phone-width form of the structured pill (mobile select mode): the leading
  // block shrinks to the count circle (still the clear control), and each
  // action is an icon over a short label (no effect line).
  compact?: boolean;
  // One-line form of the structured pill: "n selected ×", then icon + label
  // per action, no effect lines — for bars whose actions explain themselves
  // (a "More" menu carries the detail).
  slim?: boolean;
}) {
  const { t } = useTranslation();
  useToastLift("5.5rem");

  if (items) {
    // Immediate actions first, then staged ones grouped next to Apply, and a
    // `end` item (a "More" menu) and a destructive action last — after Apply, at
    // the end of the bar, a destructive one so it is
    // never the next thing to a routine one.
    const ordered = [
      ...items.filter((item) => !item.staged && !item.end && item.tone !== "destructive"),
      ...items.filter((item) => item.staged),
    ];
    const afterApply = [
      ...items.filter((item) => !item.staged && item.end && item.tone !== "destructive"),
      ...items.filter((item) => !item.staged && item.tone === "destructive"),
    ];
    if (slim) {
      return (
        <div className="pointer-events-auto w-fit max-w-full">
          <div className="flex max-w-full items-center gap-1 rounded-full bg-surface-base p-1.5 shadow-floating ring-1 ring-surface-stroke-muted">
            <button
              type="button"
              onClick={onClear}
              aria-label={t("Clear selection")}
              title={t("Clear selection")}
              className="body-prominent flex h-9 shrink-0 items-center gap-1.5 rounded-full bg-foreground-red-orange/10 pr-2.5 pl-3.5 tabular-nums text-brand-red-orange transition-colors hover:bg-foreground-red-orange/20"
            >
              {t("{count} selected", { count })}
              <XIcon className="size-3.5" />
            </button>
            <span aria-hidden className="mx-1 h-5 w-px shrink-0 bg-surface-stroke-muted" />
            {ordered.map((item) => (
              <SlimSelectionActionButton key={item.key} item={item} />
            ))}
            {apply && <SelectionApplyButton apply={apply} />}
            {afterApply.map((item) => (
              <SlimSelectionActionButton key={item.key} item={item} />
            ))}
          </div>
          {overlay}
        </div>
      );
    }
    if (compact) {
      return (
        <div className="pointer-events-auto w-fit max-w-full">
          <div className="flex max-w-full items-center gap-1 rounded-full bg-surface-base p-1.5 shadow-floating ring-1 ring-surface-stroke-muted">
            {/* The full pill's count + clear block, reduced to its circle. */}
            <button
              type="button"
              onClick={onClear}
              aria-label={t("Clear selection")}
              title={t("Clear selection")}
              className="body-prominent flex size-9 shrink-0 items-center justify-center rounded-full bg-foreground-red-orange/10 tabular-nums text-brand-red-orange transition-colors hover:bg-foreground-red-orange/20"
            >
              {count}
            </button>
            {ordered.map((item) => (
              <CompactSelectionActionButton key={item.key} item={item} />
            ))}
            {apply && <SelectionApplyButton apply={apply} />}
            {afterApply.map((item) => (
              <CompactSelectionActionButton key={item.key} item={item} />
            ))}
          </div>
          {overlay}
        </div>
      );
    }
    return (
      <div className="pointer-events-auto w-fit max-w-full">
        {/* rounded-full so each end is a true semicircle; the leading circle and
            the checkmark sit flush against the uniform p-1.5, so their centres
            land on the end-cap centres (concentric). Buttons carry no vertical
            padding, keeping the pill height ≈ circle + 2·padding. */}
        <div className="flex max-w-full items-center gap-1 rounded-full bg-surface-base p-1.5 shadow-floating ring-1 ring-surface-stroke-muted">
          {/* Leading: count + clear (circle flush to the left cap). */}
          <button
            type="button"
            onClick={onClear}
            aria-label={t("Clear selection")}
            className="flex shrink-0 items-center gap-2.5 rounded-full pr-3 text-left transition-colors hover:bg-surface-base-muted"
          >
            <span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-foreground-red-orange/10 text-brand-red-orange">
              {leadingIcon ?? <Person2FillIcon className="size-4" />}
            </span>
            <span className="flex flex-col">
              <span className="body-prominent text-foreground-default">
                {t("{count} selected", { count })}
              </span>
              <span className="body-small text-foreground-muted">
                {t("Clear selection")}
              </span>
            </span>
          </button>

          {ordered.map((item) => (
            <Fragment key={item.key}>
              <span
                aria-hidden
                className="my-1 w-px shrink-0 self-stretch bg-surface-stroke-muted"
              />
              <SelectionActionButton item={item} />
            </Fragment>
          ))}

          {apply && <SelectionApplyButton apply={apply} />}

          {afterApply.map((item) => (
            <Fragment key={item.key}>
              <span
                aria-hidden
                className="my-1 w-px shrink-0 self-stretch bg-surface-stroke-muted"
              />
              <SelectionActionButton item={item} />
            </Fragment>
          ))}
        </div>

        {overlay}
      </div>
    );
  }

  // Legacy content-hugging pill: rounded-full opaque surface with a floating
  // shadow + hairline ring; `pointer-events-auto` so the pill is clickable even
  // when its float wrapper is `pointer-events-none`. It hugs and grows with its
  // content (max-w-full + flex-wrap → wraps only when it can't fit).
  return (
    <div className="pointer-events-auto flex w-fit max-w-full flex-wrap items-center gap-3 rounded-full bg-surface-base px-4 py-2 shadow-floating ring-1 ring-surface-stroke-muted">
      {/* Neutral deselect control — a minus + the selected count; clicking it
          clears the selection. */}
      <button
        type="button"
        onClick={onClear}
        aria-label={t("Deselect {count} {noun}", { count, noun })}
        className="flex items-center gap-1.5 rounded-full bg-surface-base-muted px-2.5 py-1 text-foreground-default transition-colors hover:bg-surface-stroke"
      >
        <svg viewBox="0 0 16 16" className="size-3.5" aria-hidden>
          <path
            d="M3.5 8h9"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
          />
        </svg>
        <span className="body-prominent tabular-nums">{count}</span>
      </button>

      {actions}

      {trailing}
    </div>
  );
}

// The checkmark that commits the staged actions (e.g. the picked tags).
function SelectionApplyButton({ apply }: { apply: SelectionApply }) {
  const { t } = useTranslation();
  return (
    <button
      type="button"
      onClick={apply.onClick}
      disabled={apply.disabled || apply.busy}
      aria-label={apply.label ?? t("Apply changes")}
      className="flex size-9 shrink-0 items-center justify-center rounded-full bg-foreground-red-orange text-white shadow-sm transition hover:opacity-90 disabled:opacity-40 disabled:hover:opacity-100"
    >
      {apply.busy ? (
        <SpinnerIcon className="size-4 animate-spin" />
      ) : (
        <CheckIcon className="size-4" />
      )}
    </button>
  );
}

// One action in the compact pill: the icon over a short label, the count badge
// on the icon's corner. Same destructive tone as the full action.
function CompactSelectionActionButton({
  item: { icon, label, badge, tone, disabled, onClick, buttonRef },
}: {
  item: SelectionActionItem;
}) {
  const destructive = tone === "destructive";
  return (
    <button
      ref={buttonRef}
      type="button"
      onClick={onClick}
      disabled={disabled}
      className={`flex min-w-0 shrink-0 flex-col items-center rounded-2xl px-3 py-0.5 transition-colors hover:bg-surface-base-muted disabled:opacity-40 disabled:hover:bg-transparent ${
        destructive ? "text-feedback-error" : "text-foreground-default"
      }`}
    >
      <span
        className={`relative ${destructive ? "" : "text-foreground-muted"}`}
      >
        {icon}
        {badge != null && badge > 0 && (
          <span className="stat-small absolute -top-1.5 -right-2.5 inline-flex min-w-[1.125rem] items-center justify-center rounded-full bg-foreground-red-orange px-1 tabular-nums text-white">
            {badge}
          </span>
        )}
      </span>
      <span className="stat-small max-w-[5.5rem] truncate">{label}</span>
    </button>
  );
}

// One action in the slim pill: icon + label on one line; the effect line goes
// into the tooltip.
function SlimSelectionActionButton({
  item: { icon, label, description, badge, tone, disabled, onClick, buttonRef },
}: {
  item: SelectionActionItem;
}) {
  const destructive = tone === "destructive";
  return (
    <button
      ref={buttonRef}
      type="button"
      onClick={onClick}
      disabled={disabled}
      title={description}
      className={`body-prominent flex h-9 min-w-0 shrink-0 items-center gap-2 rounded-full px-3 transition-colors hover:bg-surface-base-muted disabled:opacity-40 disabled:hover:bg-transparent ${
        destructive ? "text-feedback-error" : "text-foreground-default"
      }`}
    >
      <span className={`shrink-0 ${destructive ? "" : "text-foreground-muted"}`}>{icon}</span>
      <span className="truncate">{label}</span>
      {badge != null && badge > 0 && (
        <span className="stat-small inline-flex min-w-[1.125rem] shrink-0 items-center justify-center rounded-full bg-foreground-red-orange px-1 tabular-nums text-white">
          {badge}
        </span>
      )}
    </button>
  );
}

// One structured bulk action: icon + title (with optional count badge) + effect
// line. Destructive tone recolours the icon + title to the error red.
function SelectionActionButton({
  item: { icon, label, description, badge, tone, disabled, onClick, buttonRef },
}: {
  item: SelectionActionItem;
}) {
  const destructive = tone === "destructive";
  return (
    <button
      ref={buttonRef}
      type="button"
      onClick={onClick}
      disabled={disabled}
      className="flex min-w-0 items-center gap-2.5 rounded-2xl px-3 text-left transition-colors hover:bg-surface-base-muted disabled:opacity-40 disabled:hover:bg-transparent"
    >
      <span
        className={`shrink-0 ${
          destructive ? "text-feedback-error" : "text-foreground-muted"
        }`}
      >
        {icon}
      </span>
      <span className="flex min-w-0 flex-col">
        <span
          className={`body-prominent flex min-w-0 items-center gap-1.5 ${
            destructive ? "text-feedback-error" : "text-foreground-default"
          }`}
        >
          <span className="truncate">{label}</span>
          {badge != null && (
            <span className="stat-small inline-flex min-w-[1.125rem] shrink-0 items-center justify-center rounded-full bg-surface-base-muted px-1 tabular-nums text-foreground-muted">
              {badge}
            </span>
          )}
        </span>
        {description && (
          <span className="body-small truncate text-foreground-muted">
            {description}
          </span>
        )}
      </span>
    </button>
  );
}
