import { useEffect } from "react";

/**
 * Hook for detecting clicks outside of the select component.
 * Handles both the trigger element and the menu, including submenus.
 *
 * @param {Object} params
 * @param {boolean} params.isOpen - Whether the menu is open
 * @param {React.RefObject} params.containerRef - Ref to the main container element
 * @param {React.RefObject} params.menuRef - Ref to the menu element (for portal mode)
 * @param {boolean} params.isCloseWhenClickOutside - Whether to close on outside click
 * @param {Function} params.onClose - Callback when clicking outside
 */
export const useClickOutside = ({
  isOpen,
  containerRef,
  menuRef,
  isCloseWhenClickOutside = true,
  onClose,
}) => {
  useEffect(() => {
    if (!isOpen || !isCloseWhenClickOutside) {
      return;
    }

    const handleClickOutside = (event) => {
      const target = event.target;

      // Check if click is inside the main container
      const isInsideContainer = containerRef?.current?.contains(target);

      // Check if click is inside the menu (for portal mode)
      const isInsideMenu = menuRef?.current?.contains(target);

      // Check if click is inside a submenu (they may be rendered outside the main menu)
      const isInsideSubmenu = target.closest?.(".ia-select-submenu");

      // Check if click is inside the styled menu (portal container)
      const isInsideStyledMenu = target.closest?.(
        ".ia-select-container-v3-styled-menu"
      );

      if (
        !isInsideContainer &&
        !isInsideMenu &&
        !isInsideSubmenu &&
        !isInsideStyledMenu
      ) {
        onClose?.(event);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isOpen, containerRef, menuRef, isCloseWhenClickOutside, onClose]);
};

export default useClickOutside;
