/**
 * Which dialog is on top, and who holds the page's scroll lock.
 *
 * Several dialogs can be open at once (the time-slot editor with its confirm
 * dialogs above it). Each used to bind its own document-level key handler and
 * set `body.style.overflow` on its own, so one Escape closed every dialog, the
 * focus traps pulled focus back and forth, and closing the inner dialog released
 * the scroll lock while the outer one was still open.
 *
 * - `useModalKeyboard` registers here and only the **top** dialog reacts to keys.
 * - `lockBodyScroll` / `unlockBodyScroll` are reference-counted: the page scrolls
 *   again only when the last dialog closes.
 */
const stack: symbol[] = [];

export function pushModal(): symbol {
  const id = Symbol("modal");
  stack.push(id);
  return id;
}

export function popModal(id: symbol): void {
  const index = stack.indexOf(id);
  if (index >= 0) stack.splice(index, 1);
}

export function isTopModal(id: symbol): boolean {
  return stack[stack.length - 1] === id;
}

let scrollLocks = 0;

export function lockBodyScroll(): void {
  scrollLocks += 1;
  if (scrollLocks === 1 && typeof document !== "undefined") document.body.style.overflow = "hidden";
}

export function unlockBodyScroll(): void {
  scrollLocks = Math.max(0, scrollLocks - 1);
  if (scrollLocks === 0 && typeof document !== "undefined") document.body.style.overflow = "";
}
