import { useEffect, type RefObject } from 'react';

/**
 * Closes a popover when an ancestor element scrolls.
 * Ignores scroll events from within the component itself or its portaled content.
 * Only active when `enabled` is true — pass false when the cell isn't editing
 * to avoid a capture-phase scroll listener firing on every virtual-scroll frame.
 */
export function useCloseOnAncestorScroll(
  wrapperRef: RefObject<HTMLElement | null>,
  closePopover: () => void,
  enabled: boolean,
) {
  useEffect(() => {
    if (!enabled) {
      return;
    }
    const onScroll = (e: Event) => {
      const target = e.target as Node;
      if (target.contains?.(wrapperRef.current)) {
        closePopover();
      }
    };
    document.addEventListener('scroll', onScroll, true);
    return () => document.removeEventListener('scroll', onScroll, true);
  }, [wrapperRef, closePopover, enabled]);
}
