import { useEffect } from 'react';

export default function useDismissibleLayer(open, refs, onDismiss) {
  useEffect(() => {
    if (!open) return undefined;

    const handlePointerDown = (event) => {
      const inside = refs.some((ref) => ref.current?.contains(event.target));
      if (!inside) onDismiss();
    };
    const handleKeyDown = (event) => {
      if (event.key === 'Escape') onDismiss();
    };

    document.addEventListener('pointerdown', handlePointerDown);
    document.addEventListener('keydown', handleKeyDown);
    return () => {
      document.removeEventListener('pointerdown', handlePointerDown);
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [open, refs, onDismiss]);
}
