/**
 * Radix moves the focus into a dialog with `preventScroll`, so in a dialog
 * taller than a phone the first button below its fold took the focus out of
 * sight (WCAG 2.4.11, ACC-542). Wraps a content's `onOpenAutoFocus`: once the
 * focus has landed, the box scrolls just enough to show it. A caller that
 * places the focus itself is left alone in every other way.
 */
export function revealOpeningFocus(handler?: (event: Event) => void) {
  return (event: Event) => {
    handler?.(event);
    const box = event.currentTarget;
    // Radix focuses right after this handler returns.
    requestAnimationFrame(() => {
      const focused = document.activeElement;
      if (
        focused instanceof HTMLElement &&
        box instanceof Node &&
        box.contains(focused)
      ) {
        focused.scrollIntoView?.({ block: "nearest" });
      }
    });
  };
}
