/**
 * It returns a ref, a boolean, and a function that toggles the boolean
 * @param initialIsVisible - The initial state of the component.
 * @returns The return value is an object with three properties:
 */
import { useState, useEffect, useRef } from "react";

export default function useOutsideDropdown() {
  const [isComponentVisible, setIsComponentVisible] = useState<any>();
  const ref: any = useRef(null);

  const isReactSelectClick = (target: EventTarget | null) => {
    if (!(target instanceof Element)) return false;

    // react-select elements (including selected value remove buttons)
    // can render outside the dropdown container.
    return Boolean(
      target.closest('[class*="custom-select__"]')
    );
  };

  const handleClickOutside = (event: MouseEvent) => {
    if (isReactSelectClick(event.target)) return;

    // Ignore clicks on elements that open the sidebar (e.g. influencer cards).
    if (event.target instanceof Element && event.target.closest('[data-sidebar-trigger]')) {
      return;
    }

    // Ignore modal overlays (in-tree Need Help confirm, or ConfirmationModal portaled to body).
    // Those clicks are outside the sidebar ref and would otherwise unmount the sidebar.
    if (
      event.target instanceof Element &&
      (event.target.closest('#modal-overlay') || event.target.closest('[data-keep-sidebar-open]'))
    ) {
      return;
    }

    if (ref.current && !ref.current.contains(event.target)) {
      setIsComponentVisible(false);
    }
  };

  // Bubble phase so nested "close" handlers (e.g. modal backdrop onClick) run before
  // this fires. Capture phase would unmount those nodes first and skip clearing paired state.
  useEffect(() => {
    document.addEventListener("click", handleClickOutside, false);
    return () => {
      document.removeEventListener("click", handleClickOutside, false);
    };
  }, []);

  return { ref, isComponentVisible, setIsComponentVisible };
}
