import React, { useEffect, useRef, useCallback } from 'react';
import { focusOnFirstDescendent, focusOnLastDescendent, isHTMLElement } from './utils';

var FocusRing = function FocusRing(_ref) {
  var topFocusBumperRef = _ref.topFocusBumperRef,
      bottomFocusBumperRef = _ref.bottomFocusBumperRef,
      children = _ref.children;
  return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("div", {
    ref: topFocusBumperRef,
    tabIndex: 0
  }), children, /*#__PURE__*/React.createElement("div", {
    ref: bottomFocusBumperRef,
    tabIndex: 0
  }));
};

var openFocusTraps = new Set();

var getLastItemInSet = function getLastItemInSet(set) {
  var array = Array.from(set);
  return array[array.length - 1];
};

var useFocusTrap = function useFocusTrap(_ref2) {
  var active = _ref2.active,
      _ref2$returnFocusToSo = _ref2.returnFocusToSource,
      returnFocusToSource = _ref2$returnFocusToSo === void 0 ? true : _ref2$returnFocusToSo,
      initialFocusRef = _ref2.initialFocusRef;
  var ref = useRef(null);
  var topFocusBumperRef = useRef(null);
  var bottomFocusBumperRef = useRef(null);
  var InternalFocusRing = useCallback(function (_ref3) {
    var children = _ref3.children;
    return /*#__PURE__*/React.createElement(FocusRing, {
      topFocusBumperRef: topFocusBumperRef,
      bottomFocusBumperRef: bottomFocusBumperRef
    }, children);
  }, []);
  useEffect(function () {
    if (active) {
      var sourceFocusElement = returnFocusToSource && document.activeElement;
      var currentFocusRef = ref.current;

      if (!currentFocusRef) {
        return;
      }

      if (openFocusTraps.size > 0) {
        document.removeEventListener('focusin', getLastItemInSet(openFocusTraps), true);
      }

      if (initialFocusRef) {
        var currentInitialFocusRef = initialFocusRef.current;

        if (currentInitialFocusRef) {
          var foundFocus = focusOnFirstDescendent(currentInitialFocusRef);

          if (!foundFocus) {
            focusOnFirstDescendent(topFocusBumperRef.current);
          }
        }
      } else if (typeof initialFocusRef === 'undefined') {
        focusOnFirstDescendent(currentFocusRef);
      } else {
        focusOnFirstDescendent(topFocusBumperRef.current);
      }

      var trapFocus = function trapFocus(event) {
        var eventTarget = event.target; // If focus is called on CkeEditor Element (for example Link dialog), we want to keep focus there, not back in our dialog

        var isCkEditorElement = eventTarget.className.includes('cke');

        if (!isCkEditorElement && !currentFocusRef.contains(eventTarget)) {
          if (document.activeElement === event.target) {
            if (event.target === topFocusBumperRef.current) {
              // Reset the focus to the last element when focusing in reverse (shift-tab)
              focusOnLastDescendent(currentFocusRef);
            } else {
              // Reset the focus to the first element after reaching
              // the last element or any other element outside of the focus trap
              focusOnFirstDescendent(currentFocusRef);
            }
          }
        }
      };

      openFocusTraps.add(trapFocus);
      document.addEventListener('focusin', trapFocus, true);
      return function cleanup() {
        document.removeEventListener('focusin', trapFocus, true);
        openFocusTraps.delete(trapFocus);

        if (sourceFocusElement && isHTMLElement(sourceFocusElement)) {
          sourceFocusElement.focus();
        }

        if (openFocusTraps.size > 0) {
          document.addEventListener('focusin', getLastItemInSet(openFocusTraps), true);
        }
      };
    }
  }, [active, returnFocusToSource, ref, initialFocusRef]);
  return {
    ref: ref,
    FocusRing: InternalFocusRing
  };
};

export default useFocusTrap;