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.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/web.dom-collections.for-each.js';
import React__default, { useState, useRef, useMemo } from 'react';
import { HeaderGlobalAction } from '@carbon/react';
import classnames from 'classnames';
import { white } from '@carbon/colors';
import { keyboardKeys } from '../../../constants/KeyCodeConstants.js';
import { handleSpecificKeyDown } from '../../../utils/componentUtilityFunctions.js';
import { HeaderActionPropTypes } from '../HeaderPropTypes.js';
import HeaderActionMenu from './HeaderActionMenu.js';
import HeaderActionPanel from './HeaderActionPanel.js';
import { Close } 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; }

// const { prefix: carbonPrefix } = settings; need to upgrade carbon 11
var carbonPrefix = 'cds';
var defaultProps = {
  testId: 'header-action',
  renderLabel: false,
  defaultExpanded: false,
  onClose: null,
  i18n: {
    closeMenu: 'Close menu'
  },
  inOverflow: false,
  showCloseIconWhenPanelExpanded: false
};

/**
 * Listens to blur events and sends state changes back to the HeaderBar to determine
 * which items should be expanded
 *
 * Determines which element to render based on item
 *
 * Consists of nav buttons that can be clicked to perform actions, open header panels (side panels),
 * or dropdown menus
 */
var HeaderAction = function HeaderAction(_ref) {
  var item = _ref.item,
    index = _ref.index,
    testID = _ref.testID,
    testId = _ref.testId,
    renderLabel = _ref.renderLabel,
    defaultExpanded = _ref.defaultExpanded,
    onClose = _ref.onClose,
    i18n = _ref.i18n,
    inOverflow = _ref.inOverflow,
    showCloseIconWhenPanelExpanded = _ref.showCloseIconWhenPanelExpanded;
  var _useState = useState(defaultExpanded),
    _useState2 = _slicedToArray(_useState, 2),
    isExpanded = _useState2[0],
    setIsExpanded = _useState2[1];
  var parentContainerRef = useRef(null);
  var menuButtonRef = useRef(null);
  var actionId = item.id || "menu-item-global-action-".concat(index);
  var mergedI18n = useMemo(function () {
    return _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  }, [i18n]);

  // expanded state for HeaderAction dropdowns
  var toggleExpandedState = function toggleExpandedState() {
    setIsExpanded(function (state) {
      if (state && typeof onClose === 'function') {
        onClose();
      }
      return !state;
    });
  };

  /**
   * close header panel when focus is lost as long as we didn't enter into the child panel
   * */
  var handleHeaderClose = function handleHeaderClose(event) {
    if (!parentContainerRef.current.contains(event.relatedTarget)) {
      // Only close the header if the header is already expanded
      if (isExpanded) toggleExpandedState();
    }
  };

  /**
   * Toggles expanded state and return focus to menu button
   */
  var handleHeaderKeyDown = function handleHeaderKeyDown(event) {
    // Handle keydowns for opening and closing the menus
    if (event.key === keyboardKeys.ESCAPE && isExpanded || event.key === keyboardKeys.SPACE || event.key === keyboardKeys.ENTER) {
      event.stopPropagation();
      event.preventDefault();
      toggleExpandedState();

      // Return focus to menu button when the user hits ESC.
      /* istanbul ignore else */
      if (menuButtonRef && menuButtonRef.current) {
        menuButtonRef.current.focus();
      }
    }
  };
  if (item.hasOwnProperty('childContent')) {
    return (
      /*#__PURE__*/
      // eslint-disable-next-line jsx-a11y/no-static-element-interactions
      React__default.createElement("div", {
        "data-testid": "action-btn__group",
        className: "".concat(carbonPrefix, "--header__submenu ").concat(carbonPrefix, "--header-action-btn action-btn__group"),
        key: "submenu-".concat(index),
        onBlur: function onBlur(e) {
          return handleHeaderClose(e);
        },
        onKeyDown: handleHeaderKeyDown,
        ref: parentContainerRef
      }, item.hasOwnProperty('hasHeaderPanel') ?
      /*#__PURE__*/
      // Render a subpanel type action
      React__default.createElement(HeaderActionPanel, {
        item: item,
        onToggleExpansion: toggleExpandedState,
        isExpanded: isExpanded,
        ref: menuButtonRef,
        index: index,
        renderLabel: renderLabel,
        i18n: mergedI18n,
        inOverflow: inOverflow,
        showCloseIconWhenPanelExpanded: showCloseIconWhenPanelExpanded,
        id: actionId
      }) :
      /*#__PURE__*/
      // otherwise render a submenu type dropdown
      React__default.createElement(HeaderActionMenu, {
        className: "".concat(carbonPrefix, "--header-action-btn"),
        key: "menu-item-".concat(item.label),
        "aria-label": item.label,
        renderMenuContent: function renderMenuContent() {
          return isExpanded && inOverflow ? /*#__PURE__*/React__default.createElement(Close, {
            fill: white,
            description: mergedI18n.closeMenu
          }) : item.btnContent;
        },
        menuLinkName: item.menuLinkName ? item.menuLinkName : '',
        isExpanded: isExpanded,
        ref: menuButtonRef,
        onToggleExpansion: toggleExpandedState,
        label: item.label,
        "data-testid": testID || testId,
        title: item.label,
        childContent: item.childContent,
        id: actionId
      }))
    );
  }
  var onClick = item.onClick || function () {};
  var onKeyDown = item.onKeyDown || onClick;
  // Otherwise render a simple menu button with no wrapper div
  return /*#__PURE__*/React__default.createElement(HeaderGlobalAction, {
    className: classnames("".concat(carbonPrefix, "--header-action-btn"), item.className),
    key: "menu-item-".concat(item.label, "-global-").concat(index),
    "data-testid": "menu-item-".concat(item.label, "-global"),
    "aria-label": item.label,
    onClick: onClick,
    onKeyDown: handleSpecificKeyDown(['Enter', ' '], onKeyDown),
    href: item.href,
    rel: item.rel,
    target: item.target,
    id: actionId
  }, renderLabel ? item.label : item.btnContent);
};
HeaderAction.propTypes = HeaderActionPropTypes;
HeaderAction.defaultProps = defaultProps;
HeaderAction.__docgenInfo = {
  "description": "Listens to blur events and sends state changes back to the HeaderBar to determine\nwhich items should be expanded\n\nDetermines which element to render based on item\n\nConsists of nav buttons that can be clicked to perform actions, open header panels (side panels),\nor dropdown menus",
  "methods": [],
  "displayName": "HeaderAction",
  "props": {
    "testId": {
      "defaultValue": {
        "value": "'header-action'",
        "computed": false
      },
      "required": false
    },
    "renderLabel": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "required": false
    },
    "defaultExpanded": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "required": false
    },
    "onClose": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  closeMenu: 'Close menu',\n}",
        "computed": false
      },
      "required": false
    },
    "inOverflow": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "required": false
    },
    "showCloseIconWhenPanelExpanded": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "required": false
    }
  },
  "composes": ["../HeaderPropTypes"]
};
var HeaderAction$1 = HeaderAction;

export { HeaderAction$1 as default };
