import { useRef, useEffect } from 'react';
import { canUseDOM } from './environment.js';
import { useWindowEvent } from './useEvent.js';

/**
 * Copyright IBM Corp. 2016, 2023
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */


const useOutsideClick = (ref, callback) => {
  const savedCallback = useRef(callback);
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // We conditionally guard the `useEvent` hook for SSR. `canUseDOM` can be
  // treated as a constant as it will be false when executed in a Node.js
  // environment and true when executed in the browser
  if (canUseDOM) {
    // TODO: https://github.com/carbon-design-system/carbon/issues/19005
    /*
    // eslint-disable-next-line react-hooks/rules-of-hooks
    */
    // eslint-disable-next-line  react-hooks/rules-of-hooks -- https://github.com/carbon-design-system/carbon/issues/20452
    useWindowEvent('click', event => {
      const {
        target
      } = event;
      if (target instanceof Node && ref.current && !ref.current.contains(target)) {
        savedCallback.current(event);
      }
    });
  }
};

export { useOutsideClick };
