'use strict';

exports.__esModule = true;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _is = require('is');

var _is2 = _interopRequireDefault(_is);

var _Icon = require('../../base/Icon');

var _Icon2 = _interopRequireDefault(_Icon);

require('./style.css');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var MainNav = function (_Component) {
  _inherits(MainNav, _Component);

  function MainNav(props) {
    _classCallCheck(this, MainNav);

    var _this = _possibleConstructorReturn(this, _Component.call(this, props));

    _this.onKeyDown = function (e) {
      var updateHeaderState = _this.props.updateHeaderState;

      if (e.key === 'Enter') {
        updateHeaderState({
          navSelected: -1
        });
      }
      if (e.key === 'Escape') {
        updateHeaderState({
          navSelected: -1
        });
      }
    };

    _this.onNavigate = function (_ref) {
      var e = _ref.e,
          href = _ref.href;

      e.stopPropagation();
      var _this$props = _this.props,
          onNavigateCallBack = _this$props.onNavigateCallBack,
          closeMobileMenu = _this$props.closeMobileMenu,
          updateHeaderState = _this$props.updateHeaderState;

      if (_is2.default.fn(closeMobileMenu)) {
        closeMobileMenu();
      }
      if (_is2.default.fn(onNavigateCallBack)) {
        onNavigateCallBack(href);
      } else if (typeof window !== 'undefined') {
        window.location.assign(href);
      }
      updateHeaderState({
        navSelected: -1
      });
    };

    _this.checkDesktopMode = function () {
      if (typeof window !== 'undefined') {
        if (window.innerWidth > 840) {
          return true;
        }
      }
      return false;
    };

    _this.updateDesktopMode = function () {
      _this.setState({
        isDesktop: _this.checkDesktopMode()
      });
    };

    _this.openSubNav = function (e) {
      var updateHeaderState = _this.props.updateHeaderState;

      var bodyClass = document.querySelector('body').classList;
      bodyClass.toggle('show-submenu');
      updateHeaderState({
        navSelected: e.currentTarget.id
      });
    };

    _this.closeSubNav = function () {
      var updateHeaderState = _this.props.updateHeaderState;

      var bodyClass = document.querySelector('body').classList;
      bodyClass.toggle('show-submenu');
      updateHeaderState({
        navSelected: -1
      });
    };

    _this.openSubNavHover = function (e) {
      var isDesktop = _this.state.isDesktop;

      if (isDesktop) {
        _this.openSubNav(e);
      }
    };

    _this.closeSubNavHover = function () {
      var isDesktop = _this.state.isDesktop;

      if (isDesktop) {
        _this.closeSubNav();
      }
    };

    _this.state = {
      isDesktop: _this.checkDesktopMode()
    };
    return _this;
  }

  MainNav.prototype.componentDidMount = function componentDidMount() {
    if (typeof window !== 'undefined') {
      window.addEventListener('resize', this.updateDesktopMode);
    }
  };

  MainNav.prototype.componentWillUnmount = function componentWillUnmount() {
    if (typeof window !== 'undefined') {
      window.removeEventListener('resize', this.updateDesktopMode);
    }
  };

  MainNav.prototype.render = function render() {
    var _this2 = this;

    var _props = this.props,
        mainNav = _props.mainNav,
        navSelected = _props.navSelected;

    return _react2.default.createElement(
      'div',
      { className: 'ma__main-nav' },
      _react2.default.createElement(
        'ul',
        { className: 'ma__main-nav__items', role: 'menubar' },
        mainNav.map(function (item, index) {
          var topItemClasses = (0, _classnames2.default)({
            'ma__main-nav__item': true,
            'is-active': item.active,
            'has-subnav': item.subNav
          });
          var buttonId = 'button' + index;
          var liId = 'li' + index;
          var isExpanded = navSelected === liId;
          var itemBody = [];
          if (item.subNav) {
            var buttonProps = {
              id: buttonId,
              index: index,
              className: 'ma__main-nav__top-link',
              'aria-expanded': '' + isExpanded,
              'aria-haspopup': 'true',
              role: 'menuitem',
              'aria-label': isExpanded ? 'Hide submenu for ' + item.text : 'Show submenu for ' + item.text,
              key: buttonId
            };
            itemBody.push(_react2.default.createElement(
              'button',
              buttonProps,
              item.text
            ));
            var navItemClasses = (0, _classnames2.default)({
              'ma__main-nav__subitems': true,
              'is-open-react': isExpanded,
              'is-closed-react': !isExpanded
            });
            itemBody.push(
            /* eslint-disable-next-line react/no-array-index-key */
            _react2.default.createElement(
              'div',
              { className: navItemClasses, key: 'navItem' + index, 'aria-hidden': !isExpanded },
              _react2.default.createElement(
                'ul',
                { role: 'menu', 'aria-label': 'Submenu of ' + buttonId, className: 'ma__main-nav__container' },
                _react2.default.createElement(
                  'li',
                  { role: 'menuitem', className: 'ma__main-nav__subitem' },
                  _react2.default.createElement(
                    'button',
                    {
                      onClick: function onClick(e) {
                        return _this2.onNavigate({ e: e, href: item.href });
                      },
                      className: 'ma__main-nav__link',
                      tabIndex: !isExpanded ? -1 : null
                    },
                    item.text
                  )
                ),
                item.subNav.map(function (subItem, subItemIndex) {
                  return (
                    /* eslint-disable-next-line react/no-array-index-key */
                    _react2.default.createElement(
                      'li',
                      { className: 'ma__main-nav__subitem', key: 'liProps.' + index + '.' + subItemIndex },
                      _react2.default.createElement(
                        'button',
                        {
                          onClick: function onClick(e) {
                            return _this2.onNavigate({ e: e, href: subItem.href });
                          },
                          className: 'ma__main-nav__link'
                        },
                        subItem.text
                      )
                    )
                  );
                }),
                item.href && _react2.default.createElement(
                  'li',
                  { role: 'menuitem', className: 'ma__main-nav__subitem ma__main-nav__subitem--main' },
                  _react2.default.createElement(
                    'button',
                    {
                      onClick: function onClick(e) {
                        return _this2.onNavigate({ e: e, href: item.href });
                      },
                      className: 'ma__main-nav__link'
                    },
                    _react2.default.createElement(_Icon2.default, { name: 'arrowbent', 'aria-hidden': true }),
                    _react2.default.createElement(
                      'span',
                      null,
                      item.text
                    )
                  )
                )
              )
            ));
          } else {
            var _buttonProps = {
              id: buttonId,
              className: 'ma__main-nav__top-link',
              'aria-haspopup': 'true',
              key: buttonId,
              role: 'menuitem',
              'aria-label': isExpanded ? 'Hide submenu for ' + item.text : 'Show submenu for ' + item.text
            };
            itemBody.push(_react2.default.createElement(
              'button',
              _buttonProps,
              item.text
            ));
          }
          return (
            /* eslint-disable-next-line jsx-a11y/mouse-events-have-key-events */
            _react2.default.createElement(
              'li',
              {
                className: topItemClasses
                /* eslint-disable-next-line react/no-array-index-key */
                , key: 'liClasses' + index,
                id: liId,
                role: 'menuitem',
                onKeyDown: _this2.onKeyDown,
                onMouseOver: _this2.openSubNavHover,
                onMouseLeave: _this2.closeSubNavHover,
                onClick: _this2.openSubNav
              },
              itemBody
            )
          );
        })
      )
    );
  };

  return MainNav;
}(_react.Component);

MainNav.propTypes = process.env.NODE_ENV !== "production" ? {
  /** navSelected state tracked in Header, passed from Header */
  navSelected: _propTypes2.default.oneOfType([
  // Id of the nav li selected
  _propTypes2.default.string,
  // none of nav li is selected
  _propTypes2.default.oneOf([-1])]),
  /** set navSelected state in Header, passed from Header */
  updateHeaderState: _propTypes2.default.func,
  /** closeMobileMenu passed from Header */
  closeMobileMenu: _propTypes2.default.func,
  /** Callback that is triggered on subnav item click */
  onNavigateCallBack: _propTypes2.default.func,
  /** An array of navigation objects to display in the main nav */
  mainNav: _propTypes2.default.arrayOf(_propTypes2.default.shape({
    href: _propTypes2.default.string,
    text: _propTypes2.default.string.isRequired,
    active: _propTypes2.default.bool,
    subNav: _propTypes2.default.arrayOf(_propTypes2.default.shape({
      href: _propTypes2.default.string.isRequired,
      text: _propTypes2.default.string.isRequired
    }))
  }))
} : {};

exports.default = MainNav;
module.exports = exports['default'];