/**
 * useClickOutside - Hook for detecting clicks outside a set of refs.
 *
 * Listens for `pointerdown` events on the document (capture phase) and
 * calls the provided callback when a click occurs outside all given refs.
 * Uses a delayed listener registration to prevent the opening click from
 * immediately closing the target element.
 */

import { useEffect } from 'react';

export function useClickOutside(
  isActive: boolean,
  refs: React.RefObject<HTMLElement | null>[],
  onClickOutside: () => void,
): void {
  useEffect(() => {
    if (!isActive) return;

    const handleClickOutside = (e: Event) => {
      const target = e.target as HTMLElement | null;
      if (!target) return;

      const isInsideAnyRef = refs.some(
        ref => ref.current && ref.current.contains(target),
      );

      if (!isInsideAnyRef) {
        onClickOutside();
      }
    };

    // Delay adding the listener to prevent the same click that opened
    // the popup from immediately closing it.
    const timer = setTimeout(() => {
      document.addEventListener('pointerdown', handleClickOutside, true);
    }, 0);

    return () => {
      clearTimeout(timer);
      document.removeEventListener('pointerdown', handleClickOutside, true);
    };
  }, [isActive, refs, onClickOutside]);
}
