import { RefObject, useEffect } from 'react';

/**
 * Hook to detect clicks outside of specified elements
 * @param refs - Array of refs to check if click is outside
 * @param handler - Callback to execute when click is detected outside
 * @param enabled - Whether the hook is active (default: true)
 */
export function useClickOutside(
  refs: RefObject<HTMLElement>[],
  handler: () => void,
  enabled = true,
): void {
  useEffect(() => {
    if (!enabled) {
      return;
    }

    const listener = (event: MouseEvent | TouchEvent): void => {
      const target = event.target as Node;

      // Check if click is outside all provided refs
      const isOutside = refs.every(
        (ref) => ref.current && !ref.current.contains(target),
      );

      if (isOutside) {
        handler();
      }
    };

    document.addEventListener('mousedown', listener);
    document.addEventListener('touchstart', listener);

    return () => {
      document.removeEventListener('mousedown', listener);
      document.removeEventListener('touchstart', listener);
    };
  }, [refs, handler, enabled]);
}
