import { onMounted, onBeforeUnmount } from "vue";
import type { Ref } from "vue";

/**
 * useClickOutside composable:
 * - Detects clicks outside of a given element reference.
 * - Executes a callback when a click occurs outside the target.
 * - Automatically registers and cleans up listeners on mount/unmount.
 */

export function useClickOutside(
  elRef: Ref<HTMLElement | null>,
  callback: (event: MouseEvent) => void
): void {
  if (!elRef) return;

  // Event handler: invokes callback when click is outside the element
  const handleClick = (event: MouseEvent) => {
    if (elRef.value && !elRef.value.contains(event.target as Node)) {
      callback(event);
    }
  };

  // Register click listener on document when component mounts
  onMounted(() => {
    document.addEventListener("click", handleClick);
  });

  // Remove click listener when component unmounts
  onBeforeUnmount(() => {
    document.removeEventListener("click", handleClick);
  });
}
