"use client";

import {
  Fragment,
  useEffect,
  useMemo,
  useState,
  useSyncExternalStore,
} from "react";
import { formatRelativeDayDateTime } from "@enode/core/format/date-time";
import { isAthleteRole, isOwnerRole } from "@enode/core/auth/role";
import { useHasPrivilege } from "@enode/core/auth/use-privilege";
import { fetchPlanUsage } from "@enode/core/api/plan-usage";
import type { UserDeviceSessionReturnDto } from "@enode/core/api/dtos/user-device-sessions";
import {
  deleteDeviceSession,
  getOwnDeviceSessions,
  signOutOtherOwnDeviceSessions,
  signOutOwnDeviceSession,
  updateDeviceSession,
  type OwnDeviceSession,
} from "@enode/core/api/user-device-sessions";
import { getDeviceId } from "@enode/core/api/storage";
import { ApiError } from "@enode/core/errors/types";
import { useCurrentUser } from "@enode/core/current-user/hooks";
import {
  useDeviceSessions,
  useOwnDeviceSession,
} from "@enode/core/device-session/hooks";
import {
  loadDeviceSession,
  removeDeviceSessionLocal,
  upsertDeviceSessionLocal,
} from "@enode/core/device-session/store";
import { useUsers } from "@enode/core/users/hooks";
import { suggestAlternatives } from "@enode/core/search/suggest";
import { getTextContent } from "@enode/core/text-content/store";
import { useTextContentsVersion } from "@enode/core/text-content/useTextContentsVersion";
import {
  useTranslation,
  type TranslateFn,
} from "@enode/core/translations/hooks";
import { ConfirmDialog } from "@enode/ui/confirm-dialog";
import { Skeleton } from "@enode/ui/feedback/skeleton";
import { toast } from "@enode/ui/feedback/toast-store";
import { presentError } from "@enode/ui/feedback/use-error-presenter";
import { TrashIcon } from "@enode/ui/icons";
import { LottieCircle } from "@enode/ui/LottieCircle";
import { StalenessHint } from "@enode/ui/feedback/staleness-hint";
import { SearchAndFilterCard } from "@enode/ui/search-and-filter-card";
import { TourAutoStart } from "@enode/ui/tour/tour-provider";
import { AthleteAvatar } from "@enode/ui/athlete-avatar";
import { LOOK } from "@enode/ui/live/look";
import { stationsFreedLine } from "@enode/ui/settings/sign-out-device";
import {
  DataTable,
  type DataTableColumn,
  type SortState,
} from "../../../../components/data-table-view";
import {
  NAME_CELL_MAX_W,
  SelectCheckbox,
} from "../../../../components/data-table";
import {
  ConnectionCard,
  useShowConnectionCard,
} from "../../../../components/notices/connection-card";
import { TOUR_TARGET } from "../../../../tours/tour-targets";
import { loadInBackground } from "../../../../components/background-load";
import { useDevicesTour } from "../../../../tours/use-devices-tour";
import { DeviceDrawer } from "../../devices/device-drawer";
import { DeviceKindIcon } from "../../devices/device-kind-icon";
import { devicesSubtitle } from "../../devices/devices-subtitle";
import {
  deviceKind,
  deviceRoleLabel,
  deviceSubline,
  filterDeviceRows,
  isOwnDeviceRow,
  isWebDevice,
  orderDeviceRowsByLastUsed,
  selectableDeviceIDs,
  type DeviceRoleKey,
  type DeviceRowFilter,
} from "../../devices/device-rows";
import { DevicesEmptyState } from "../../devices/devices-empty-state";
import { StationCapacityCard } from "../../devices/station-capacity-card";
import { StationHoldersCard } from "../../devices/station-holders-card";
import {
  coachStationsView,
  holdersFromSessions,
  isSignedInAs,
  ownSessionRow,
  stationsInUse,
  sumStations,
  type PlanUsageRead,
  type StationHolder,
} from "../../devices/station-holders";
import { useInitialSearchParams, usePageReset, useSyncSearchParams } from "../../url-state";
import {
  devicesViewParams,
  readDevicesView,
  type StationFacet,
} from "./devices-view-state";

// Stable empty selection / no-op for the tag-filter facet the Devices search
// doesn't use — the search card shows only its search row when given no tags.
const NOOP = () => {};

// The browser device id never changes while the page is open, so there is
// nothing to subscribe to; the server snapshot is "" (no localStorage).
const subscribeNever = () => NOOP;
const serverDeviceId = () => "";

// Tighter vertical cell padding for the devices table — the bare (circle-less)
// device glyph lets the rows sit flatter than the shared `py-3`. `!` overrides
// the DataTable cell's default padding; applied to every column so the whole
// row is dense.
const DENSE_CELL = "py-2!";

// Phones list this many device cards, then "Show more" (the table pages at 25).
const MOBILE_PAGE_SIZE = 25;

// The red text button of the own-session sign-outs (row and "all other").
const SIGN_OUT_BUTTON =
  "body-prominent rounded-lg px-2 py-1 text-feedback-error hover:bg-surface-base-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground-red-orange disabled:cursor-not-allowed disabled:opacity-50";

// The station-usage filter chips: "Uses stations" (weight > 0) and "No stations"
// (feedback-only). Multi-select toggles like the Users page role chips — none
// pressed (or both) means all devices.

/**
 * The Account › Devices tab. What it lists depends on the role:
 *
 * - Owner: every device session of the organisation (GET
 *   /user_device_sessions) with search, filters, the station-capacity card,
 *   the edit drawer and (with `writeDeviceSession`) single and bulk remove.
 * - Coach: only their own sessions (`?scope=mine`, like the app), plus a
 *   "Training stations" card naming the organisation's station holders.
 * - Athlete (and any other role): only their own sessions, without training
 *   stations (no column, count or station row in the drawer) — athletes
 *   don't hold or manage them.
 *
 * Every list starts sorted by last use, newest first, with this device on top.
 * A sign-out confirm names the training stations a device frees.
 *
 * Each other own device has a "Sign out" (the own-session endpoint), and
 * "Sign out of all other devices" sits above the list. Rendered inside the
 * Account layout, which provides title, tabs and width.
 */
export function DevicesView() {
  const { t, locale } = useTranslation();
  // First-visit spotlight tour (see <TourAutoStart> below); tours are
  // re-armed from the Settings page ("Tips & what's new").
  const devicesTour = useDevicesTour();
  // Editing device sessions (rename / delete) is gated on its privilege
  // (debug-adjustable); without it the table is read-only (no multi-select).
  const canWriteDeviceSession = useHasPrivilege("writeDeviceSession");
  // Shared device-session store, loaded on mount. `state` is the load lifecycle:
  // skeletons on the FIRST load; a failed refresh over cached rows is a hint.
  const { sessions, state } = useDeviceSessions();
  // This browser's own session — pinned first and badged "This device".
  const ownSession = useOwnDeviceSession();
  // This browser's device id (`enode.deviceId`): "" in the prerender and
  // during hydration, so both agree, then the real id. The own session's id
  // wins once the store has matched it.
  const browserDeviceId = useSyncExternalStore(
    subscribeNever,
    getDeviceId,
    serverDeviceId,
  );
  const ownDeviceId = ownSession?.deviceId || browserDeviceId;

  // License device limit for the stations total. The capacity view (meter card,
  // "m / x" subtitle, full-plan highlighting) and the organisation-wide list
  // are owner-only: the backend may return a license and team rows for other
  // roles too, so gate on the role explicitly.
  // (The sidebar already refreshes the current user.)
  const user = useCurrentUser();
  const isOwner = isOwnerRole(user?.role);
  // Coach here means everyone who manages but does not own: coaches and the
  // other staff roles (administrator, facility) — not athletes.
  const isCoach = user != null && !isOwner && !isAthleteRole(user.role);
  // Training stations (column, counts, station rows, sign-out lines) are the
  // owner's and the coach's; athletes don't hold or manage them.
  const showStations = isOwner || isCoach;
  // Owners manage the organisation's devices; everyone else lists their own.
  const orgMode = isOwner;
  const userID = user?.id ?? null;

  // The own-sessions read (`?scope=mine`): the list for non-owners, and for
  // everyone its server-side `isCurrent` names this device's row; the read
  // also teaches the API module whether the own-session sign-out endpoints
  // exist. A failure falls back to the org list's own rows and the device-id
  // match. `ownReload` re-runs it after a sign-out or a retry.
  const [ownList, setOwnList] = useState<OwnDeviceSession[] | null>(null);
  const [ownFailed, setOwnFailed] = useState(false);
  const [ownReload, setOwnReload] = useState(0);
  useEffect(() => {
    if (!userID) return;
    let active = true;
    getOwnDeviceSessions(userID).then(
      (res) => {
        if (!active) return;
        setOwnList(res.sessions);
        setOwnFailed(false);
      },
      () => {
        if (active) setOwnFailed(true);
      },
    );
    return () => {
      active = false;
    };
  }, [userID, ownReload]);
  // The plan-usage read's retry counter (declared here so `reload` re-reads
  // it too; the read itself is below).
  const [usageReload, setUsageReload] = useState(0);
  const reload = () => {
    loadInBackground(loadDeviceSession);
    setOwnReload((n) => n + 1);
    setUsageReload((n) => n + 1);
  };
  const serverCurrentID = ownList?.find((s) => s.isCurrent)?.id ?? null;

  // A non-owner's rows: the own list, each row taken from the org list when it
  // is there (it carries the media, type text and live session) and built
  // from the own-session fields otherwise. Without the own list, the org
  // list's rows signed in as this user.
  const isMine = (device: UserDeviceSessionReturnDto) =>
    isSignedInAs(device.userID, userID);
  const ownRows = useMemo<UserDeviceSessionReturnDto[]>(() => {
    if (!ownList) return sessions.filter(isMine);
    const byID = new Map(sessions.map((s) => [s.id, s]));
    return ownList.map(
      (own) => byID.get(own.id) ?? ownSessionRow(own, userID ?? ""),
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ownList, sessions, userID]);
  const rows = orgMode ? sessions : ownRows;

  // Load lifecycle. Owner: the org list store. Others: the own list, or —
  // when that read failed — the org list it falls back to.
  const storeFirstLoad = state.status === "idle" || state.status === "loading";
  const ownPending = !ownFailed && ownList == null;
  const firstLoad =
    user == null ||
    (orgMode
      ? storeFirstLoad
      : ownPending || (ownList == null && storeFirstLoad));
  const storeFailed = state.status === "error" && (orgMode || ownList == null);
  const dataless = !firstLoad && storeFailed && rows.length === 0;
  const stale = !firstLoad && storeFailed && rows.length > 0;
  // Failed, or still loading while reachability already says we're down.
  const showConnection = useShowConnectionCard(firstLoad, dataless);

  const currentRowID =
    (serverCurrentID && rows.some((s) => s.id === serverCurrentID)
      ? serverCurrentID
      : null) ??
    rows.find((s) => isOwnDeviceRow(s, ownDeviceId))?.id ??
    null;
  const isCurrentRow = (device: UserDeviceSessionReturnDto) =>
    device.id === currentRowID;
  // The signed-in person's other sessions: these get "Sign out".
  const isOtherOwnRow = (device: UserDeviceSessionReturnDto) =>
    isMine(device) && !isCurrentRow(device);
  const otherOwnRows = rows.filter(isOtherOwnRow);
  const currentRow = rows.find(isCurrentRow) ?? null;

  // Multi-select (bulk remove) is the owner's, with the write privilege.
  const canSelect = orgMode && canWriteDeviceSession;
  // Every row but this browser's own session may be selected for removal.
  const selectableIDs = useMemo(() => {
    const ids = selectableDeviceIDs(sessions, ownDeviceId);
    if (currentRowID) ids.delete(currentRowID);
    return ids;
  }, [sessions, ownDeviceId, currentRowID]);

  // The server's count of the plan (GET /user_licenses/usage, like Plan &
  // usage): the owner's station total and the coach's "Training stations"
  // card. Athletes are refused, so they don't ask. A failure (an older server
  // answers 404) falls back to the device rows. Re-read when the rows'
  // stations change (a save in the drawer, "Take 1") and on a retry.
  const mayReadUsage = showStations;
  const rowsStationSum = sumStations(sessions);
  const [usageRead, setUsageRead] = useState<PlanUsageRead>({
    status: "loading",
  });
  useEffect(() => {
    if (!mayReadUsage) return;
    let active = true;
    fetchPlanUsage().then(
      (usage) => {
        if (active) setUsageRead({ status: "ready", usage });
      },
      () => {
        if (active) setUsageRead({ status: "failed" });
      },
    );
    return () => {
      active = false;
    };
  }, [mayReadUsage, usageReload, rowsStationSum]);

  // Header stats: "n devices • m / x stations" — m the stations in use (the
  // owner: the server's count, the rows' weight sum as fallback; everyone
  // else: their own rows), x the license `deviceLimit`. When the limit is
  // unavailable, or unlimited (over 100; the count alone, as the tracking
  // app's Plan & usage — owner feedback 17.11.26 on "7 / Unlimited
  // stations"), just the used count.
  const stationsUsed = isOwner
    ? stationsInUse(usageRead, rows)
    : sumStations(rows);
  const deviceLimit = isOwner ? (user?.license?.deviceLimit ?? null) : null;
  const stationsLabel =
    deviceLimit == null || deviceLimit > 100
      ? t("{count, plural, one {# station} other {# stations}}", {
          count: stationsUsed,
        })
      : t("{used} / {total} stations", {
          used: stationsUsed,
          total: deviceLimit,
        });
  const subtitle = devicesSubtitle({
    firstLoad,
    dataless,
    devices: rows.length,
    stations: showStations ? stationsLabel : undefined,
    t,
  });

  // The station-capacity card only makes sense on a finite, owner-visible plan:
  // a null limit (non-owner / not loaded) or an "Unlimited" one (> 100) has no
  // scarcity to surface. Held back until we actually have the list so the meter
  // isn't drawn against a not-yet-loaded (or errored-empty) count.
  const showCapacity =
    !firstLoad && !dataless && deviceLimit != null && deviceLimit <= 100;

  // Who holds the stations: rows with weight > 0 grouped by the signed-in
  // person (users store by `userID`), falling back to the device name.
  // Also feeds the "Signed in as" column and the Mine/Coaches/Athletes chips.
  const { users } = useUsers({ includeArchived: true });
  const userByID = useMemo(() => {
    const map = new Map<string, NonNullable<typeof users>[number]>();
    for (const u of users ?? []) map.set(u.id, u);
    return map;
  }, [users]);
  const roleOf = (id: string): DeviceRoleKey => {
    const key = userByID.get(id)?.role?.key;
    return key === "owner" || key === "coach" || key === "athlete"
      ? key
      : "other";
  };
  // The devices holding stations (biggest first). The drawer offers "Take 1
  // from …" on them when the plan has none free; the owner's capacity card
  // names them, a name opening that device's drawer.
  const stationHolders = useMemo(
    () => (showStations ? holdersFromSessions(sessions) : []),
    [showStations, sessions],
  );
  const holders = useMemo(
    () =>
      stationHolders.map((h) => ({
        id: h.id,
        name: h.deviceName || t("Unknown device"),
        stations: h.stations,
      })),
    [stationHolders, t],
  );

  // The coach's "Training stations" card: the server's holder list
  // (GET /user_licenses/usage, P7-B15) or — when that read fails or answers
  // a filtered list — the org list's station rows (coaches get those
  // read-only, P7-B04). Decided once both reads have settled.
  const coachView = coachStationsView({
    usage: usageRead,
    sessions: storeFirstLoad
      ? { status: "loading" }
      : state.status === "error" && sessions.length === 0
        ? { status: "error" }
        : { status: "ready", rows: sessions },
  });

  // When every granted station is in use, spotlight the devices carrying the
  // most stations — the quickest ones to trim to free capacity back up.
  const isFull =
    deviceLimit != null && deviceLimit <= 100 && stationsUsed >= deviceLimit;
  const maxWeight = sessions.reduce(
    (max, s) => Math.max(max, s.weight ?? 0),
    0,
  );
  const isTopConsumer = (device: UserDeviceSessionReturnDto) =>
    isFull && (device.weight ?? 0) > 0 && (device.weight ?? 0) === maxWeight;

  // Whether any device is currently a training station (hosts ≥ 1 station) —
  // when none are, the empty state points at the enode apps to set one up.
  const hasAppStation = sessions.some((s) => (s.weight ?? 0) > 0);

  // The filter chips only earn their space once there's a list to slice — hidden
  // on first load / a dataless error.
  const showFilters = orgMode && !firstLoad && !dataless && sessions.length > 0;

  // The view the list opens with — from the address (devices-view-state.ts),
  // so a reload or Back keeps the search, chips, sort and page.
  const params = useInitialSearchParams();
  const [initialView] = useState(() => readDevicesView(params));
  const [query, setQuery] = useState(initialView.query);
  // Station-usage filter chips (multi-select toggles, like the Users page role
  // chips): empty set — or both — means all devices.
  const [stationFacets, setStationFacets] = useState<ReadonlySet<StationFacet>>(
    () => new Set(initialView.stationFacets),
  );
  // Multi-select — the view owns the selected-id set; the only bulk action is
  // delete (mirroring the Users page's selection toolbar).
  const [selected, setSelected] = useState<ReadonlySet<string>>(
    () => new Set(),
  );
  // Who-chips: Mine / Coaches / Athletes (union; none pressed = all).
  const [whoFacets, setWhoFacets] = useState<ReadonlySet<DeviceRowFilter>>(
    () => new Set(initialView.whoFacets),
  );
  // How many cards the phone list shows (the table paginates itself).
  const [mobileLimit, setMobileLimit] = useState(MOBILE_PAGE_SIZE);
  const [confirmDelete, setConfirmDelete] = useState(false);
  const [deleting, setDeleting] = useState(false);
  // Row click opens the edit drawer for that device session.
  const [editing, setEditing] = useState<UserDeviceSessionReturnDto | null>(
    null,
  );
  // Own-session sign-out: one other device, or all of them.
  const [confirmSignOut, setConfirmSignOut] =
    useState<UserDeviceSessionReturnDto | null>(null);
  const [confirmSignOutAll, setConfirmSignOutAll] = useState(false);
  const [signingOut, setSigningOut] = useState(false);
  // Coach "Take 1": the holder awaiting confirmation, and the one running.
  const [confirmTakeOne, setConfirmTakeOne] = useState<StationHolder | null>(
    null,
  );
  const [takingID, setTakingID] = useState<string | null>(null);

  // The selection minus this browser's own session (never removable here).
  const removeIDs = [...selected].filter((id) => selectableIDs.has(id));
  // The signed-in person for a row, or null when they're not in the users list.
  const personOf = (device: UserDeviceSessionReturnDto) => {
    // The signed-in person's own rows, even when the users list (which an
    // athlete may not read) doesn't hold them.
    const person =
      userByID.get(device.userID) ?? (isMine(device) ? user : undefined);
    const name = person?.name?.trim();
    if (!person || !name) return null;
    return {
      name,
      roleLabel: deviceRoleLabel(roleOf(device.userID), t),
      isMe: person.id === user?.id,
    };
  };

  function unselect(id: string) {
    setSelected((prev) => {
      if (!prev.has(id)) return prev;
      const next = new Set(prev);
      next.delete(id);
      return next;
    });
  }

  // Bulk remove: no batch endpoint, so loop DELETE per session and prune the
  // store as it goes. Always gated behind the confirm dialog.
  async function runBulkDelete() {
    if (removeIDs.length === 0) return;
    const count = removeIDs.length;
    setDeleting(true);
    try {
      for (const id of removeIDs) {
        try {
          await deleteDeviceSession(id);
        } catch (err) {
          // Already gone (removed from another browser, or by the app's
          // sign-out): that is the outcome this loop wants, so it carries on
          // with the remaining devices instead of stopping at the first one.
          if (!(err instanceof ApiError && err.status === 404)) throw err;
        }
        removeDeviceSessionLocal(id);
      }
      toast.success(
        t(
          "{n, plural, one {Signed out on # device} other {Signed out on # devices}}",
          { n: count },
        ),
      );
      setConfirmDelete(false);
      setSelected(new Set());
    } catch (err) {
      // Some may already be gone; surface behind the prompt and allow a retry.
      setConfirmDelete(false);
      presentError(err, t, { onRetry: runBulkDelete });
    } finally {
      setDeleting(false);
    }
  }

  // Signs the person out on one of their other devices (own-session endpoint,
  // no device-session write privilege needed) and drops the row.
  async function runSignOut(device: UserDeviceSessionReturnDto) {
    setSigningOut(true);
    try {
      await signOutOwnDeviceSession(device.id);
      removeDeviceSessionLocal(device.id);
      setOwnList((prev) => prev?.filter((s) => s.id !== device.id) ?? null);
      unselect(device.id);
      toast.success(
        t("Signed out on {device}", {
          device: device.deviceName?.trim() || t("Unknown device"),
        }),
      );
    } catch (err) {
      presentError(err, t, { onRetry: () => runSignOut(device) });
    } finally {
      setSigningOut(false);
      setConfirmSignOut(null);
    }
  }

  // Signs the person out everywhere but here, then reloads the list.
  async function runSignOutAll() {
    if (!userID) return;
    const count = otherOwnRows.length;
    setSigningOut(true);
    try {
      await signOutOtherOwnDeviceSessions(userID);
      for (const row of otherOwnRows) unselect(row.id);
      toast.success(
        t(
          "{n, plural, one {Signed out on # device} other {Signed out on # devices}}",
          { n: count },
        ),
      );
    } catch (err) {
      presentError(err, t, { onRetry: runSignOutAll });
    } finally {
      setSigningOut(false);
      setConfirmSignOutAll(false);
      reload();
    }
  }

  // Coach: take one station back from another person's device — the one
  // change the backend allows there (weight − 1, name unchanged; P7-B04).
  async function runTakeOne(holder: StationHolder) {
    const row = sessions.find((s) => s.id === holder.id);
    if (!row) return;
    setTakingID(holder.id);
    try {
      const lowered = { ...row, weight: Math.max(row.weight - 1, 0) };
      await updateDeviceSession(lowered);
      upsertDeviceSessionLocal(lowered);
      toast.success(
        t("Took 1 station from {device}", {
          device: row.deviceName?.trim() || t("Unknown device"),
        }),
      );
      setUsageReload((n) => n + 1);
    } catch (err) {
      presentError(err, t, { onRetry: () => runTakeOne(holder) });
    } finally {
      setTakingID(null);
      setConfirmTakeOne(null);
    }
  }

  function toggleStationFacet(facet: StationFacet) {
    setStationFacets((prev) => {
      const next = new Set(prev);
      if (next.has(facet)) next.delete(facet);
      else next.add(facet);
      return next;
    });
  }

  function toggleWhoFacet(facet: DeviceRowFilter) {
    setWhoFacets((prev) => {
      const next = new Set(prev);
      if (next.has(facet)) next.delete(facet);
      else next.add(facet);
      return next;
    });
  }

  const otherFiltersActive = stationFacets.size > 0 || whoFacets.size > 0;
  function clearFilters() {
    setQuery("");
    setStationFacets(new Set());
    setWhoFacets(new Set());
  }

  // Re-run search once the text-content table loads (localized types resolve).
  const textContentsVersion = useTextContentsVersion();

  // Station-usage facet only (a union — "Uses stations" + "No stations" = all),
  // no search. The base for both the table search and the suggestions.
  const scoped = useMemo(() => {
    // Own lists have no filters.
    if (!orgMode) return rows;
    const byWho = filterDeviceRows(sessions, whoFacets, {
      currentUserID: user?.id,
      roleOf,
    });
    if (stationFacets.size === 0) return byWho;
    return byWho.filter((device) => {
      const weight = device.weight ?? 0;
      return (
        (stationFacets.has("with") && weight > 0) ||
        (stationFacets.has("without") && weight <= 0)
      );
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [orgMode, rows, sessions, stationFacets, whoFacets, user?.id, userByID]);

  // Multi-token AND search over the device name + its localized type.
  const filtered = useMemo(() => {
    const tokens = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
    if (tokens.length === 0) return [...scoped];
    return scoped.filter((device) => {
      const type =
        getTextContent(device.nameTextContentID) ?? device.deviceType ?? "";
      const haystack = `${device.deviceName ?? ""} ${type}`.toLowerCase();
      return tokens.every((token) => haystack.includes(token));
    });
    // textContentsVersion re-runs the filter once localized types resolve.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [scoped, query, textContentsVersion]);

  // When the search comes up empty, offer the closest device names in scope;
  // picking one re-runs the search on that device.
  const suggestions = useMemo(() => {
    if (query.trim() === "" || filtered.length > 0) return [];
    return suggestAlternatives(
      query,
      scoped,
      (device) => device.deviceName ?? "",
      {
        limit: 3,
      },
    ).map((s) => ({
      key: s.item.id,
      label: s.label,
      onSelect: () => setQuery(s.label),
    }));
  }, [query, filtered, scoped]);

  // List order (table and phone cards): this device first ("Now"), then by
  // last use, newest first (stable). The table starts on that sort.
  const orderedRows = useMemo(
    () => orderDeviceRowsByLastUsed(filtered, currentRowID),
    [filtered, currentRowID],
  );
  // Starts on last use, newest first (this device, "Now", on top) unless the
  // address names another sort.
  const [sort, setSort] = useState<SortState | null>(initialView.sort);
  // The table's page, held here so it can live in the address.
  const [page, setPage] = useState(initialView.page);
  // A new filter starts the table over at page 1.
  usePageReset(JSON.stringify([query, [...stationFacets], [...whoFacets]]), () =>
    setPage(1),
  );
  // Keep the view in the address as it changes (written in place, so Back
  // leaves the page rather than undoing a filter).
  useSyncSearchParams(
    devicesViewParams({
      query,
      stationFacets: [...stationFacets],
      whoFacets: [...whoFacets],
      sort,
      page,
    }),
  );
  // The table keeps this device on top under any column sort.
  const pinnedRowKeys = useMemo(
    () =>
      currentRowID && orderedRows.some((d) => d.id === currentRowID)
        ? [currentRowID]
        : [],
    [orderedRows, currentRowID],
  );
  const mobileRows = orderedRows;
  // Phone cards show checkboxes once anything on the list can be selected.
  const mobileSelection = canSelect && selectableIDs.size > 0;
  const mobileVisible = mobileRows.slice(0, mobileLimit);

  // "You" / "Name · Role" / generic fallback — the plain-text twin of the
  // "Signed in as" cell for the phone cards' meta line.
  const signedInText = (device: UserDeviceSessionReturnDto) => {
    const person = userByID.get(device.userID);
    if (person && person.id === user?.id) return t("You");
    if (!person) return t("Someone in your team");
    const roleLabel = deviceRoleLabel(roleOf(device.userID), t);
    return [person.name?.trim(), roleLabel].filter(Boolean).join(" · ");
  };
  // The phone card's meta line: who (owner view only — an own list is all
  // "You"), stations (not for browsers, which never record, nor for
  // athletes; none reads "Feedback only", as in the drawer), last used.
  const metaText = (device: UserDeviceSessionReturnDto) =>
    [
      orgMode ? signedInText(device) : null,
      !showStations || isWebDevice(device)
        ? null
        : (device.weight ?? 0) > 0
          ? t("{count, plural, one {# station} other {# stations}}", {
              count: device.weight ?? 0,
            })
          : t("Feedback only"),
      isCurrentRow(device)
        ? t("Now")
        : formatLastUsed(device.lastUsedAt, locale),
    ]
      .filter(Boolean)
      .join(" · ");

  // The table's device cell: glyph + name + type, with "This device" beside
  // the name on this browser's own session. The glyph renders bare (no avatar
  // circle) so the rows sit flatter. Phone rows lay out their own grid.
  const renderName = (device: UserDeviceSessionReturnDto) => {
    const chip = isCurrentRow(device) ? (
      <span className="body-small inline-block shrink-0 rounded-full bg-foreground-red-orange/10 px-2 py-0.5 text-brand-red-orange">
        {t("This device")}
      </span>
    ) : null;
    return (
      <div className={`flex items-center gap-2.5 ${NAME_CELL_MAX_W}`}>
        <LottieCircle
          media={device.media}
          variant="equipmentIcon"
          bare
          size={28}
          padding={0}
          fallback={<DeviceKindIcon deviceType={device.deviceType} />}
        />
        <span className="min-w-0">
          <span className="body-prominent block truncate text-foreground-default">
            {device.deviceName?.trim() || t("Unknown device")}
          </span>
          <span className="body-small block truncate text-foreground-muted">
            {deviceSubline(device, t)}
          </span>
        </span>
        {chip}
      </div>
    );
  };

  const columns: DataTableColumn<UserDeviceSessionReturnDto>[] = [
    {
      key: "name",
      header: t("Device"),
      sortAccessor: (device) => device.deviceName ?? "",
      cellClassName: DENSE_CELL,
      // Media (the session-category Lottie icon; the device-kind line glyph
      // when there is none) + name + type, "This device" beside it.
      cell: (device) => renderName(device),
    },
    {
      key: "signedInAs",
      header: t("Signed in as"),
      sortAccessor: (device) => userByID.get(device.userID)?.name ?? "",
      cellClassName: DENSE_CELL,
      // The current user's rows read just a muted "You" (they repeat row after
      // row); other people get avatar + name + a muted role word.
      cell: (device) => {
        const person = userByID.get(device.userID);
        if (person && person.id === user?.id) {
          return <span className="text-foreground-muted">{t("You")}</span>;
        }
        if (!person) {
          return (
            <span className="text-foreground-muted">
              {t("Someone in your team")}
            </span>
          );
        }
        const roleLabel = deviceRoleLabel(roleOf(device.userID), t);
        return (
          <div className={`flex items-center gap-2 ${NAME_CELL_MAX_W}`}>
            <AthleteAvatar userID={person.id} name={person.name} size={24} />
            <span className="truncate text-foreground-default">
              {person.name?.trim()}
            </span>
            {roleLabel && (
              <span className="body-small shrink-0 text-foreground-muted">
                {roleLabel}
              </span>
            )}
          </div>
        );
      },
    },
    {
      key: "stations",
      header: t("Training stations"),
      align: "end",
      cellClassName: DENSE_CELL,
      sortAccessor: (device) => device.weight,
      // `weight` = the number of stations this device may record in (0–3); 0
      // reads a muted "Feedback only", the drawer's word for it. At the limit,
      // the biggest consumers wear a red-orange pill so they stand out as the
      // rows to trim. Browsers never record.
      cell: (device) =>
        isWebDevice(device) ? (
          <span
            className="text-foreground-muted"
            title={t("Browsers don't record")}
            aria-label={t("Browsers don't record")}
          >
            —
          </span>
        ) : isTopConsumer(device) ? (
          <span
            className="inline-flex items-center justify-center rounded-full bg-foreground-red-orange/12 px-2 py-0.5 font-medium text-brand-red-orange"
            title={t("One of the devices using the most stations")}
          >
            {device.weight}
          </span>
        ) : (device.weight ?? 0) > 0 ? (
          device.weight
        ) : (
          <span className="text-foreground-muted">
            {t("Feedback only")}
          </span>
        ),
    },
    {
      key: "lastUsed",
      header: t("Last used"),
      // This device reads "Now"; an unknown time sorts last.
      sortAccessor: (device) =>
        isCurrentRow(device)
          ? Number.MAX_SAFE_INTEGER
          : Number.isFinite(device.lastUsedAt)
            ? device.lastUsedAt
            : null,
      cellClassName: DENSE_CELL,
      cell: (device) =>
        isCurrentRow(device)
          ? t("Now")
          : formatLastUsed(device.lastUsedAt, locale),
    },
    {
      key: "liveSession",
      header: t("In live session"),
      headerClassName: "hidden md:table-cell",
      cellClassName: `hidden md:table-cell ${DENSE_CELL}`,
      sortAccessor: (device) => device.workoutLiveSessionName ?? "",
      cell: (device) => device.workoutLiveSessionName?.trim() || null,
    },
    {
      key: "actions",
      header: <span className="sr-only">{t("Actions")}</span>,
      headerClassName: "text-right",
      cellClassName: `text-right ${DENSE_CELL}`,
      // The person's own other devices sign out right here; every other row
      // is removed from the drawer or the multi-select.
      cell: (device) =>
        isOtherOwnRow(device) ? (
          <button
            type="button"
            className={SIGN_OUT_BUTTON}
            aria-label={t("Sign out on {device}", {
              device: device.deviceName?.trim() || t("Unknown device"),
            })}
            disabled={signingOut}
            onClick={(e) => {
              // Never also open the row's drawer.
              e.stopPropagation();
              setConfirmSignOut(device);
            }}
          >
            {t("Sign out")}
          </button>
        ) : null,
    },
  ];

  // In an own list — or with only "Mine" pressed — every row is the current
  // user's: the "Signed in as" column would just repeat "You", so it is left
  // out. Athletes get no training-stations column.
  const onlyMine =
    !orgMode || (whoFacets.size === 1 && whoFacets.has("mine"));
  const visibleColumns = columns.filter(
    (column) =>
      !(onlyMine && column.key === "signedInAs") &&
      !(!showStations && column.key === "stations"),
  );

  const confirmSignOutName =
    confirmSignOut?.deviceName?.trim() || t("Unknown device");

  // "{device} holds 2 training stations; they become free." for each device a
  // sign-out would take off the plan's count (none for athletes).
  const stationsFreedLines = (
    devices: readonly (UserDeviceSessionReturnDto | undefined)[],
  ) =>
    showStations
      ? devices.flatMap((device) => {
          if (!device) return [];
          const line = stationsFreedLine(
            device.deviceName?.trim() || t("Unknown device"),
            device.weight,
            t,
          );
          return line ? [{ id: device.id, line }] : [];
        })
      : [];
  const confirmSignOutLine = confirmSignOut
    ? stationsFreedLines([confirmSignOut])[0]?.line
    : undefined;
  const bulkStationLines = stationsFreedLines(
    removeIDs.map((id) => sessions.find((s) => s.id === id)),
  );
  const signOutAllStationLines = stationsFreedLines(otherOwnRows);

  return (
    <div>
      {/* The tour narrates the organisation-wide list — owners only. */}
      {orgMode && <TourAutoStart tour={devicesTour} />}
      {/* Counts on the left; the own-session "sign out everywhere else" on the
          right, once there is another own device. On a phone they stack, the
          button pulled left by its padding so its text lines up with the
          counts. */}
      {(firstLoad || subtitle || otherOwnRows.length > 0) && (
        <div className="mb-3 flex flex-col items-start gap-1 sm:min-h-8 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
          {/* While loading, the counts' height is reserved so the search and
              table don't shift down when they arrive. */}
          {firstLoad ? (
            <Skeleton className="h-4 w-40" />
          ) : (
            <p className="body-small text-foreground-muted">{subtitle}</p>
          )}
          {otherOwnRows.length > 0 && (
            <button
              type="button"
              className={`${SIGN_OUT_BUTTON} -ml-2 min-h-11 shrink-0 sm:ml-0 sm:min-h-0`}
              disabled={signingOut}
              onClick={() => setConfirmSignOutAll(true)}
            >
              {t("Sign out of all other devices")}
            </button>
          )}
        </div>
      )}
      {/* Hint (top): the station-capacity meter / soft paywall. */}
      {showCapacity && deviceLimit != null && (
        <div data-tour={TOUR_TARGET.devicesCapacity} className="mb-4">
          <StationCapacityCard
            used={stationsUsed}
            total={deviceLimit}
            holders={holders}
            onOpenHolder={(id) => {
              const device = sessions.find((s) => s.id === id);
              if (device) setEditing(device);
            }}
          />
        </div>
      )}

      {/* Coach: who holds the organisation's training stations (read-only,
          plus "Take 1" on another person's device). */}
      {isCoach && (
        <div className="mb-4">
          <StationHoldersCard
            view={coachView}
            onRetry={reload}
            currentUserID={userID}
            onOpenOwn={(id) => {
              const device = rows.find((s) => s.id === id);
              if (device) setEditing(device);
            }}
            canTakeOne={(h) =>
              canWriteDeviceSession && sessions.some((s) => s.id === h.id)
            }
            onTakeOne={setConfirmTakeOne}
            busyID={takingID}
          />
        </div>
      )}

      {/* Search bar — the owner's list only; an own list is a handful. */}
      {orgMode && (
        <div data-tour={TOUR_TARGET.devicesSearch} className="mb-3">
          {/* The filter bar (docs/components.md, "Search and filter bars"):
              search plus "Filters" — whose devices and station use, shown once
              there's a list to slice. */}
          <SearchAndFilterCard
            search={query}
            onSearch={setQuery}
            filterGroups={
              showFilters
                ? [
                    {
                      key: "owner",
                      label: t("Owner"),
                      options: [
                        {
                          id: "mine",
                          label: t("Mine"),
                          active: whoFacets.has("mine"),
                          onToggle: () => toggleWhoFacet("mine"),
                        },
                        {
                          id: "coaches",
                          label: t("Coaches"),
                          active: whoFacets.has("coaches"),
                          onToggle: () => toggleWhoFacet("coaches"),
                        },
                        {
                          id: "athletes",
                          label: t("Athletes"),
                          active: whoFacets.has("athletes"),
                          onToggle: () => toggleWhoFacet("athletes"),
                        },
                      ],
                    },
                    {
                      key: "stations",
                      label: t("Stations"),
                      options: [
                        {
                          id: "with",
                          label: t("Uses stations"),
                          active: stationFacets.has("with"),
                          onToggle: () => toggleStationFacet("with"),
                        },
                        {
                          id: "without",
                          label: t("No stations"),
                          active: stationFacets.has("without"),
                          onToggle: () => toggleStationFacet("without"),
                        },
                      ],
                    },
                  ]
                : undefined
            }
            onClearFilters={clearFilters}
            placeholder={t("Search devices by name…")}
          />
        </div>
      )}

      {/* Refresh failed but the cached list is usable — a hint, not an error. */}
      {stale && (
        <div className="mb-3">
          <StalenessHint onRetry={reload} />
        </div>
      )}

      {/* The load failed with nothing cached (or reachability is down while it
          still loads) — keep the skeletons ("still trying") and name the cause
          in the shared connection card. */}
      {showConnection && (
        <div className="mb-3">
          <ConnectionCard
            error={state.lastError}
            onRetry={reload}
          />
        </div>
      )}

      {/* List — or, once loaded with no rows, the empty state (which points at
          the enode apps when nothing is acting as a training station). One
          wrapper carries the tour anchor for both. */}
      <div data-tour={TOUR_TARGET.devicesTable}>
        {!firstLoad && !dataless && filtered.length === 0 ? (
          <DevicesEmptyState
            query={query}
            otherFiltersActive={otherFiltersActive}
            suggestions={suggestions}
            hasAppStation={hasAppStation}
            showStations={showStations}
            onClearSearch={() => setQuery("")}
            onClearFilters={clearFilters}
          />
        ) : (
          <>
            {/* Phones: one compact card per device; the table does not fit. */}
            <div className="md:hidden">
              {canSelect && removeIDs.length > 0 && (
                <div className="mb-2 flex items-center justify-between gap-2">
                  <button
                    type="button"
                    className={SIGN_OUT_BUTTON}
                    onClick={() => setConfirmDelete(true)}
                  >
                    {t("Sign out {count}", { count: removeIDs.length })}
                  </button>
                  <button
                    type="button"
                    className="body-prominent text-foreground-muted hover:text-foreground-default"
                    onClick={() => setSelected(new Set())}
                  >
                    {t("Clear selection")}
                  </button>
                </div>
              )}
              {firstLoad || dataless ? (
                <ul aria-busy="true" aria-label={t("Loading devices…")}>
                  {Array.from({ length: 4 }).map((_, i) => (
                    <li
                      key={i}
                      className="border-surface-stroke flex flex-col gap-2 border-b py-3 last:border-b-0"
                    >
                      <span className="block h-4 w-2/3 animate-pulse rounded-md bg-surface-base-muted" />
                      <span className="block h-3 w-full animate-pulse rounded-md bg-surface-base-muted" />
                    </li>
                  ))}
                </ul>
              ) : (
                <ul className={`divide-y divide-surface-stroke overflow-hidden ${LOOK.panel}`}>
                  {mobileVisible.map((device) => {
                    const liveSession = device.workoutLiveSessionName?.trim();
                    const name =
                      device.deviceName?.trim() || t("Unknown device");
                    const toggleSelected = () =>
                      setSelected((prev) => {
                        const set = new Set(prev);
                        if (set.has(device.id)) set.delete(device.id);
                        else set.add(device.id);
                        return set;
                      });
                    return (
                      <li
                        key={device.id}
                        className={`flex items-center gap-1 py-1 pr-1 ${
                          mobileSelection ? "pl-1" : "pl-2"
                        } ${
                          isTopConsumer(device)
                            ? "bg-foreground-red-orange/[0.04]"
                            : ""
                        }`}
                      >
                        {/* Selection mode keeps one 44 px checkbox column: a
                            row without one (this device) reserves its width
                            so every icon and name lines up. The whole cell
                            toggles — the 18 px box alone is too small to
                            hit; the box itself stays the focusable control. */}
                        {mobileSelection &&
                          (selectableIDs.has(device.id) ? (
                            <span
                              className="flex size-11 shrink-0 cursor-pointer items-center justify-center"
                              onClick={toggleSelected}
                            >
                              <SelectCheckbox
                                checked={selected.has(device.id)}
                                onChange={toggleSelected}
                                ariaLabel={t("Select {name}", { name })}
                              />
                            </span>
                          ) : (
                            <span aria-hidden className="size-11 shrink-0" />
                          ))}
                        {/* Two columns: the glyph, then name / kind / meta —
                            every text line starts at the same edge. */}
                        <button
                          type="button"
                          className="grid min-h-11 min-w-0 flex-1 grid-cols-[28px_minmax(0,1fr)] items-start gap-x-3 rounded-xl px-2 py-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground-red-orange"
                          onClick={() => setEditing(device)}
                        >
                          <span className="pt-0.5">
                            <LottieCircle
                              media={device.media}
                              variant="equipmentIcon"
                              bare
                              size={28}
                              padding={0}
                              fallback={
                                <DeviceKindIcon deviceType={device.deviceType} />
                              }
                            />
                          </span>
                          <span className="min-w-0">
                            <span className="body-prominent block truncate text-foreground-default">
                              {name}
                            </span>
                            <span className="body-small flex min-w-0 items-center gap-2 text-foreground-muted">
                              <span className="truncate">
                                {deviceSubline(device, t)}
                              </span>
                              {isCurrentRow(device) && (
                                <span className="shrink-0 rounded-full bg-foreground-red-orange/10 px-2 text-brand-red-orange">
                                  {t("This device")}
                                </span>
                              )}
                            </span>
                            {/* Each part stays whole ("Oct 28, 2026" never
                                breaks); the line wraps between parts. */}
                            <span className="body-small block text-foreground-muted">
                              {metaText(device)
                                .split(" · ")
                                .map((part, i) => (
                                  <Fragment key={i}>
                                    {i > 0 && " · "}
                                    <span className="whitespace-nowrap">
                                      {part}
                                    </span>
                                  </Fragment>
                                ))}
                            </span>
                            {liveSession && (
                              <span className="body-small block truncate text-foreground-muted">
                                {t("In live session: {name}", {
                                  name: liveSession,
                                })}
                              </span>
                            )}
                          </span>
                        </button>
                        {isOtherOwnRow(device) && (
                          <button
                            type="button"
                            className="body-small min-h-11 shrink-0 rounded-lg px-3 text-foreground-muted hover:bg-surface-base-muted hover:text-foreground-default focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground-red-orange disabled:cursor-not-allowed disabled:opacity-50"
                            aria-label={t("Sign out on {device}", {
                              device: name,
                            })}
                            disabled={signingOut}
                            onClick={() => setConfirmSignOut(device)}
                          >
                            {t("Sign out")}
                          </button>
                        )}
                      </li>
                    );
                  })}
                </ul>
              )}
              {mobileRows.length > mobileLimit && !firstLoad && !dataless && (
                <button
                  type="button"
                  className="body-prominent mt-2 w-full rounded-lg py-2 text-foreground-muted hover:text-foreground-default"
                  onClick={() => setMobileLimit((n) => n + MOBILE_PAGE_SIZE)}
                >
                  {t("Show more")}
                </button>
              )}
            </div>
            <div className="hidden md:block">
              <DataTable
                flat
                columns={visibleColumns}
                rows={orderedRows}
                sortState={{ value: sort, onChange: setSort }}
                paginate={{ per: 25 }}
                pageState={{ value: page, onChange: setPage }}
                rowKey={(device) => device.id}
                pinnedRowKeys={
                  pinnedRowKeys.length > 0 ? pinnedRowKeys : undefined
                }
                onRowClick={(device) => setEditing(device)}
                // At the limit, faintly tint the biggest station consumers so the eye
                // lands on the rows worth trimming.
                rowClassName={(device) =>
                  isTopConsumer(device) ? "bg-foreground-red-orange/[0.04]" : ""
                }
                loading={firstLoad || dataless}
                loadingMessage={t("Loading devices…")}
                count={{ total: rows.length, noun: t("devices") }}
                // Multi-select (bulk remove) only when device sessions may be written;
                // this browser's own row has no checkbox and select-all skips it.
                selection={
                  canSelect
                    ? {
                        selectedKeys: selected,
                        onChange: setSelected,
                        isSelectable: (id) => selectableIDs.has(id),
                        noun: t("devices"),
                        items: [
                          {
                            key: "delete",
                            icon: <TrashIcon className="size-5" />,
                            label: t("Sign out {count}", {
                              count: removeIDs.length,
                            }),
                            description: t(
                              "{count, plural, one {# device} other {# devices}} will be signed out",
                              { count: removeIDs.length },
                            ),
                            tone: "destructive",
                            onClick: () => setConfirmDelete(true),
                          },
                        ],
                      }
                    : undefined
                }
              />
            </div>
          </>
        )}
      </div>

      <ConfirmDialog
        open={confirmDelete}
        destructive
        title={t(
          "{n, plural, one {Sign out # device} other {Sign out # devices}}?",
          { n: removeIDs.length },
        )}
        message={t(
          "{count, plural, one {# device will be signed out. Anything not uploaded on it stays there until whoever uses it signs in again.} other {# devices will be signed out. Anything not uploaded on them stays on them until whoever uses them signs in again.}}",
          { count: removeIDs.length },
        )}
        confirmLabel={deleting ? t("Signing out…") : t("Sign out")}
        busy={deleting}
        onConfirm={runBulkDelete}
        onCancel={() => setConfirmDelete(false)}
      >
        {/* Per target: whose device it is and which device. */}
        <ul className="body-normal mt-3 space-y-1 text-foreground-default">
          {removeIDs.map((id) => {
            const device = sessions.find((s) => s.id === id);
            if (!device) return null;
            const deviceName = device.deviceName?.trim() || t("Unknown device");
            return (
              <li key={id}>
                {t("{name} on {device}", {
                  name: personOf(device)?.name ?? t("Someone in your team"),
                  device: deviceName,
                })}
              </li>
            );
          })}
        </ul>
        <StationsFreedList lines={bulkStationLines} />
      </ConfirmDialog>

      <ConfirmDialog
        open={confirmSignOut != null}
        title={t("Sign out on {device}?", { device: confirmSignOutName })}
        message={[
          t(
            "The enode app on {device} goes back to the sign-in screen. Anything not uploaded on it stays there until someone signs in again.",
            { device: confirmSignOutName },
          ),
          confirmSignOutLine,
        ]
          .filter(Boolean)
          .join(" ")}
        cancelLabel={t("Cancel")}
        confirmLabel={t("Sign out")}
        busy={signingOut}
        onCancel={() => setConfirmSignOut(null)}
        onConfirm={() => {
          if (confirmSignOut) void runSignOut(confirmSignOut);
        }}
      />

      <ConfirmDialog
        open={confirmSignOutAll}
        title={t("Sign out of all other devices?")}
        message={signOutAllMessage(currentRow, otherOwnRows.length, t)}
        cancelLabel={t("Cancel")}
        confirmLabel={t(
          "{n, plural, one {Sign out # device} other {Sign out # devices}}",
          { n: otherOwnRows.length },
        )}
        busy={signingOut}
        onCancel={() => setConfirmSignOutAll(false)}
        onConfirm={() => void runSignOutAll()}
      >
        <ul className="body-small mt-2 list-disc pl-5 text-foreground-muted">
          {otherOwnRows.map((s) => (
            <li key={s.id}>
              {s.deviceName?.trim() || t("Unknown device")} ·{" "}
              {deviceSubline(s, t)}
            </li>
          ))}
        </ul>
        <StationsFreedList lines={signOutAllStationLines} />
      </ConfirmDialog>

      <ConfirmDialog
        open={confirmTakeOne != null}
        title={t("Take 1 station from {device}?", {
          device: confirmTakeOne?.deviceName || t("Unknown device"),
        })}
        message={t(
          "{device} keeps {count, plural, =0 {no training station and only gives live feedback} one {# training station} other {# training stations}}. The station is free for another device.",
          {
            device: confirmTakeOne?.deviceName || t("Unknown device"),
            count: Math.max((confirmTakeOne?.stations ?? 1) - 1, 0),
          },
        )}
        cancelLabel={t("Cancel")}
        confirmLabel={t("Take 1")}
        busy={takingID != null}
        onCancel={() => setConfirmTakeOne(null)}
        onConfirm={() => {
          if (confirmTakeOne) void runTakeOne(confirmTakeOne);
        }}
      />

      {/* Edit drawer — rendered unconditionally with a nullable target so the
          slide-out plays on close. Store mutations drive the list; on delete we
          also prune the row from the multi-select. */}
      <DeviceDrawer
        target={
          editing
            ? {
                device: editing,
                isOwn: isCurrentRow(editing),
                person: personOf(editing),
              }
            : null
        }
        onClose={() => setEditing(null)}
        onDeleted={unselect}
        stationsUsed={stationsInUse(usageRead, sessions)}
        takeHolders={stationHolders}
        onTakeOne={setConfirmTakeOne}
        takingID={takingID}
      />
    </div>
  );
}

/**
 * Under a sign-out confirm's device list: which of those devices hold training
 * stations, one "… holds n training stations; they become free." each.
 */
function StationsFreedList({
  lines,
}: {
  lines: readonly { id: string; line: string }[];
}) {
  if (lines.length === 0) return null;
  return (
    <ul className="body-normal mt-3 space-y-1 text-foreground-default">
      {lines.map(({ id, line }) => (
        <li key={id}>{line}</li>
      ))}
    </ul>
  );
}

/**
 * Body of the "Sign out of all other devices?" confirm: what stays (this
 * device, and its training stations) and how many devices go back to sign-in.
 */
function signOutAllMessage(
  current: Pick<UserDeviceSessionReturnDto, "deviceType" | "weight"> | null,
  otherCount: number,
  t: TranslateFn,
): string {
  const goBack = t(
    "{n, plural, one {This # device goes back to the sign-in screen:} other {These # devices go back to the sign-in screen:}}",
    { n: otherCount },
  );
  const stations = current?.weight ?? 0;
  const kind = deviceKind({ deviceType: current?.deviceType });
  let stay: string;
  if (stations > 0) {
    if (kind === "tablet") {
      stay = t(
        "{n, plural, one {You stay signed in on this tablet, and it keeps its # training station.} other {You stay signed in on this tablet, and it keeps its # training stations.}}",
        { n: stations },
      );
    } else if (kind === "phone") {
      stay = t(
        "{n, plural, one {You stay signed in on this phone, and it keeps its # training station.} other {You stay signed in on this phone, and it keeps its # training stations.}}",
        { n: stations },
      );
    } else {
      stay = t(
        "{n, plural, one {You stay signed in on this browser, and it keeps its # training station.} other {You stay signed in on this browser, and it keeps its # training stations.}}",
        { n: stations },
      );
    }
  } else if (kind === "tablet") {
    stay = t("You stay signed in on this tablet.");
  } else if (kind === "phone") {
    stay = t("You stay signed in on this phone.");
  } else {
    stay = t("You stay signed in on this browser.");
  }
  return `${stay} ${goBack}`;
}

// `lastUsedAt` is milliseconds-since-epoch on the wire. Today / yesterday read
// as a capitalised day plus the time; older dates in the History date format. A
// missing/invalid value falls back to a dash.
function formatLastUsed(ms: number, locale: string): string {
  if (!Number.isFinite(ms)) return "—";
  return formatRelativeDayDateTime(ms, locale);
}
