'use client';

import { useEffect, useRef } from 'react';

/**
 * Attaches a document-level keydown listener that calls `onClose` when the
 * user presses Escape while the dialog is `open`. The listener is removed on
 * unmount or when `open` flips back to false, so closed dialogs do not
 * intercept keystrokes for the page underneath.
 *
 * The listener depends only on `open` — `onClose` is read through a ref so
 * the listener stays attached for the dialog's full open lifetime even if
 * the parent recreates the `onClose` callback on every render. Without the
 * ref, rapid parent re-renders cause subscribe/unsubscribe churn that can
 * lose an Escape keystroke arriving inside the cleanup window.
 *
 * Stacked dialogs: the listener applies to every open dialog instance — if
 * two are mounted at once, both will close on a single Escape press. The
 * surfaces this is used on today do not stack, so that's acceptable.
 */
export function useEscapeToClose(open: boolean, onClose: () => void): void {
  const onCloseRef = useRef(onClose);

  useEffect(() => {
    onCloseRef.current = onClose;
  }, [onClose]);

  useEffect(() => {
    if (!open) return;
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onCloseRef.current();
    };
    document.addEventListener('keydown', handler);
    return () => document.removeEventListener('keydown', handler);
  }, [open]);
}
