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

/**
 * Calls `handler` when a pointer press lands outside the referenced element.
 * Uses a document-level `mousedown`/`touchstart` listener (robust against
 * z-index/stacking contexts, unlike a fixed overlay). Only active while
 * `enabled` is true.
 */
export function useOnClickOutside(
  ref: RefObject<HTMLElement | null>,
  handler: () => void,
  enabled = true,
): void {
  useEffect(() => {
    if (!enabled) {
      return;
    }

    const onPointerDown = (event: MouseEvent | TouchEvent) => {
      const element = ref.current;
      if (!element || element.contains(event.target as Node)) {
        return;
      }
      handler();
    };

    document.addEventListener('mousedown', onPointerDown);
    document.addEventListener('touchstart', onPointerDown);
    return () => {
      document.removeEventListener('mousedown', onPointerDown);
      document.removeEventListener('touchstart', onPointerDown);
    };
  }, [ref, handler, enabled]);
}
