/* eslint-disable react-hooks/rules-of-hooks */

/* eslint-disable @typescript-eslint/no-unused-vars */
import { useEffect } from 'react';
import { inBrowser } from '../utils';
import { getTargetElement } from '../utils/dom/getTargetElement'; // https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener#使用_passive_改善的滚屏性能
// eslint-disable-next-line import/no-mutable-exports

export var supportsPassive = false;

if (inBrowser) {
  try {
    var opts = {};
    Object.defineProperty(opts, 'passive', {
      get: function get() {
        supportsPassive = true;
      }
    });
    window.addEventListener('test-passive', null, opts); // eslint-disable-next-line no-empty
  } catch (e) {}
}

function useEventListener(type, listener, options) {
  if (options === void 0) {
    options = {};
  }

  if (!inBrowser) {
    return;
  }

  var _options = options,
      _options$target = _options.target,
      target = _options$target === void 0 ? window : _options$target,
      _options$passive = _options.passive,
      passive = _options$passive === void 0 ? false : _options$passive,
      _options$capture = _options.capture,
      capture = _options$capture === void 0 ? false : _options$capture,
      _options$depends = _options.depends,
      depends = _options$depends === void 0 ? [] : _options$depends;
  var attached;

  var add = function add() {
    var element = getTargetElement(target);

    if (element && !attached) {
      element.addEventListener(type, listener, supportsPassive ? {
        capture: capture,
        passive: passive
      } : capture);
      attached = true;
    }
  };

  var remove = function remove() {
    var element = getTargetElement(target);

    if (element && attached) {
      element.removeEventListener(type, listener, capture);
      attached = false;
    }
  }; // https://stackoverflow.com/questions/55265255/react-usestate-hook-event-handler-using-initial-state


  useEffect(function () {
    add();
    return function () {
      return remove();
    };
  }, [target].concat(depends));
}

export default useEventListener;