import _extends from '@babel/runtime/helpers/extends';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import 'core-js/modules/es.symbol.js';
import 'core-js/modules/es.array.concat.js';
import 'core-js/modules/es.array.filter.js';
import 'core-js/modules/es.array.from.js';
import 'core-js/modules/es.array.map.js';
import 'core-js/modules/es.object.get-own-property-descriptor.js';
import 'core-js/modules/es.object.get-own-property-descriptors.js';
import 'core-js/modules/es.object.keys.js';
import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/es.string.iterator.js';
import 'core-js/modules/web.dom-collections.for-each.js';
import React__default, { useRef, useState, useMemo, useCallback, useLayoutEffect } from 'react';
import { HeaderGlobalBar, OverflowMenuItem } from '@carbon/react';
import PropTypes from 'prop-types';
import ReactDOM__default from 'react-dom';
import { useLangDirection } from '../../utils/useLangDirection.js';
import { OverflowMenu } from '../OverflowMenu/index.js';
import { settings } from '../../constants/Settings.js';
import HeaderAction from './HeaderAction/HeaderAction.js';
import { HeaderActionItemPropTypes } from './HeaderPropTypes.js';
import { Close, OverflowMenuVertical } from '@carbon/icons-react';

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var iotPrefix = settings.iotPrefix,
  prefix = settings.prefix;
var propTypes = {
  actionItems: PropTypes.arrayOf(PropTypes.shape(HeaderActionItemPropTypes)).isRequired,
  i18n: PropTypes.shape({
    closeMenu: PropTypes.string,
    openMenu: PropTypes.string
  }),
  testId: PropTypes.string,
  /** Returns true, if the icon should be shown. (actionItem) => {} */
  isActionItemVisible: PropTypes.func.isRequired,
  showCloseIconWhenPanelExpanded: PropTypes.bool
};
var defaultProps = {
  i18n: {
    closeMenu: 'Close menu',
    openMenu: 'Open menu'
  },
  testId: 'header-action-group',
  showCloseIconWhenPanelExpanded: false
};
var findFirstVisible = function findFirstVisible(el) {
  if (!el || !el.childNodes.length === 0) {
    return undefined;
  }
  var visibleChildren = Array.from(el.childNodes).filter(function (child) {
    return child.offsetParent !== null;
  });
  return visibleChildren.shift();
};
/**
 * Keeps track of the state of which header menu item is currently expanded
 *
 * Renders all the actions that can be clicked to navigate, open header panels (side panels),
 * or dropdown menus, passing an onToggleExpansion to each action
 */
var HeaderActionGroup = function HeaderActionGroup(_ref) {
  var actionItems = _ref.actionItems,
    i18n = _ref.i18n,
    testId = _ref.testId,
    isActionItemVisible = _ref.isActionItemVisible,
    showCloseIconWhenPanelExpanded = _ref.showCloseIconWhenPanelExpanded;
  var overFlowContainerRef = useRef(null);
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    overflowItems = _useState2[0],
    setOverflowItems = _useState2[1];
  var breakpoint = useRef(null);
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    overflowOpen = _useState4[0],
    setOverflowOpen = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    showMenu = _useState6[0],
    setShowMenu = _useState6[1];
  var _useState7 = useState(null),
    _useState8 = _slicedToArray(_useState7, 2),
    menu = _useState8[0],
    setMenu = _useState8[1];
  var mergedI18n = useMemo(function () {
    return _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  }, [i18n]);
  var langDir = useLangDirection();
  var checkForOverflow = useCallback(function () {
    /* istanbul ignore else */
    if (overFlowContainerRef.current) {
      var _findFirstVisible, _overFlowContainerRef, _overFlowContainerRef2;
      var firstButtonInGroupRef = (_findFirstVisible = findFirstVisible((_overFlowContainerRef = overFlowContainerRef.current) === null || _overFlowContainerRef === void 0 ? void 0 : _overFlowContainerRef.lastChild)) === null || _findFirstVisible === void 0 ? void 0 : _findFirstVisible.getBoundingClientRect();
      var nameDivRef = (_overFlowContainerRef2 = overFlowContainerRef.current) === null || _overFlowContainerRef2 === void 0 || (_overFlowContainerRef2 = _overFlowContainerRef2.previousSibling) === null || _overFlowContainerRef2 === void 0 ? void 0 : _overFlowContainerRef2.getBoundingClientRect();

      /* istanbul ignore else */
      if (firstButtonInGroupRef && nameDivRef) {
        var windowWidth = window.innerWidth || document.documentElement.clientWidth;
        // check that it's also greater than zero to prevent collapsing in jest where all the values are 0.
        var tooBig = langDir === 'ltr' ? nameDivRef.right > 0 && nameDivRef.right >= firstButtonInGroupRef.left : firstButtonInGroupRef.right > 0 && firstButtonInGroupRef.right >= nameDivRef.left;
        var previousBreakpoint = breakpoint.current;
        if (tooBig && actionItems.length > 0 && overflowItems.length === 0) {
          breakpoint.current = windowWidth;
          setOverflowItems(actionItems);
        } else if (windowWidth > previousBreakpoint) {
          setOverflowItems([]);
        }
      }
    }
  }, [actionItems, langDir, overflowItems.length]);
  useLayoutEffect(function () {
    // Check for SSR
    if (typeof window !== 'undefined') {
      checkForOverflow();
      window.addEventListener('resize', checkForOverflow);
    }
    return function () {
      // Check for SSR
      if (typeof window !== 'undefined') {
        window.removeEventListener('resize', checkForOverflow);
      }
    };
  }, [checkForOverflow]);
  return (
    /*#__PURE__*/
    // added extra div here, because HeaderGlobalBar doesn't support refs
    React__default.createElement("div", {
      ref: overFlowContainerRef,
      className: "".concat(prefix, "--header__global")
    }, /*#__PURE__*/React__default.createElement(HeaderGlobalBar, {
      "data-testid": testId
    },
    // if we have overflow items and are not showing a header action submenu
    // then render the overflow menu
    overflowItems.length > 0 && !showMenu ? /*#__PURE__*/React__default.createElement("div", {
      className: "".concat(iotPrefix, "--header__overflow-menu-container"),
      "data-floating-menu-container": true
    }, /*#__PURE__*/React__default.createElement(OverflowMenu, {
      useAutoPositioning: true,
      onClick: function onClick(_ref2) {
        var target = _ref2.target;
        if (target.tagName === 'BUTTON') {
          setOverflowOpen(function (prev) {
            return !prev;
          });
        } else {
          /**
           * This is a hack to get around the onClick event firing twice when clicking
           * directly on the svg within the button instead of the button itself. A stopPropagation
           * makes the overflow not open, so we have to resort to reading the aria-expanded value to
           * know whether the OverflowMenu is open and adjust the icons accordingly. This double-click
           * only occurs when changing the icon. If the same icon is always used it works as expected.
           * My guess is this is because of the outsideClickClosing that the overflow menu does. WHen the
           * icon is change it is "outside" of the element for a moment and causes a close--that or a re-render that
           * is triggered when the icon changes.
           */
          var button = target.closest('button');
          setTimeout(function () {
            var expanded = (button === null || button === void 0 ? void 0 : button.getAttribute('aria-expanded')) === 'true';
            setOverflowOpen(expanded);
          }, 0);
        }
      },
      open: overflowOpen,
      renderIcon: function renderIcon(iconProps) {
        return overflowOpen ? /*#__PURE__*/React__default.createElement(Close, _extends({}, iconProps, {
          "aria-label": mergedI18n.closeMenu,
          description: mergedI18n.closeMenu
        })) : /*#__PURE__*/React__default.createElement(OverflowMenuVertical, _extends({}, iconProps, {
          "aria-label": mergedI18n.openMenu,
          description: mergedI18n.openMenu
        }));
      }
    }, overflowItems.map(function (child, i) {
      if (!isActionItemVisible(child)) {
        return null;
      }
      if (child.hasHeaderPanel || Array.isArray(child.childContent) && child.childContent.length > 0) {
        /*#__PURE__*/ReactDOM__default.createPortal([/*#__PURE__*/React__default.createElement(HeaderAction, {
          item: child,
          index: i,
          key: "header-action-item-".concat(child.label, "-").concat(i),
          testId: "header-action-item-".concat(child.label)
          // used to render only the label in the overflow menu instead of the icon
          ,
          renderLabel: true,
          i18n: mergedI18n
        })], overFlowContainerRef.current.parentNode);
      }
      return /*#__PURE__*/React__default.createElement(OverflowMenuItem, {
        title: child.label,
        key: "".concat(child.label, "-").concat(i),
        "data-testid": "".concat(testId, "-overflow-menu-item-").concat(i),
        onClick: function onClick(event) {
          // because these items are passed an href="#" we want to prevent the default action
          event.preventDefault();

          // if a header action has a submenu, we need to capture that submenu
          // and replace the main overflow menu icon with it per design specs
          // this saves the menu item on click, closes the overflow menu, and
          // instead shows the header action menu.
          /* istanbul ignore else */
          if (Array.isArray(child.childContent) && child.childContent.length > 0) {
            setMenu(child);
            setOverflowOpen(false);
            setShowMenu(true);
          }
          if (typeof child.onClick === 'function') {
            child.onClick(event);
            setOverflowOpen(false);
          }
        },
        itemText: child.label
      });
    }))) :
    // if the user clicked on a header action with a menu
    // show that menu in place of the overflow menu.
    showMenu ? /*#__PURE__*/React__default.createElement(HeaderAction, {
      item: menu,
      index: 0,
      key: "header-action-item-".concat(menu.label, "-", 0),
      testId: "header-action-item-".concat(menu.label)
      // force this menu menu to be open
      ,
      defaultExpanded: true
      // close the menu and restore the overflow menu button
      ,
      onClose: function onClose() {
        setShowMenu(false);
        setMenu(null);
      },
      inOverflow: overflowItems.length > 0
    }) :
    // otherwise, if we have enough space to show all the items,
    // simple render them in the header as expected.
    actionItems.filter(function (item) {
      return isActionItemVisible(item);
    }).map(function (item, i) {
      return /*#__PURE__*/React__default.createElement(HeaderAction, {
        item: item,
        index: i,
        key: "header-action-item-".concat(item.label, "-").concat(i),
        testId: "header-action-item-".concat(item.label),
        showCloseIconWhenPanelExpanded: showCloseIconWhenPanelExpanded
      });
    })))
  );
};
HeaderActionGroup.propTypes = propTypes;
HeaderActionGroup.defaultProps = defaultProps;
HeaderActionGroup.__docgenInfo = {
  "description": "Keeps track of the state of which header menu item is currently expanded\n\nRenders all the actions that can be clicked to navigate, open header panels (side panels),\nor dropdown menus, passing an onToggleExpansion to each action",
  "methods": [],
  "displayName": "HeaderActionGroup",
  "props": {
    "i18n": {
      "defaultValue": {
        "value": "{\n  closeMenu: 'Close menu',\n  openMenu: 'Open menu',\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "closeMenu": {
            "name": "string",
            "required": false
          },
          "openMenu": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "'header-action-group'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "showCloseIconWhenPanelExpanded": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "actionItems": {
      "description": "",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "shape",
          "value": "import { HeaderActionItemPropTypes } from './HeaderPropTypes';",
          "computed": true
        }
      },
      "required": true
    },
    "isActionItemVisible": {
      "description": "Returns true, if the icon should be shown. (actionItem) => {}",
      "type": {
        "name": "func"
      },
      "required": true
    }
  }
};
var HeaderActionGroup$1 = HeaderActionGroup;

export { HeaderActionGroup$1 as default };
