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; }

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import is from 'is';
import Icon from '../../base/Icon';
import './style.css';

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 (is.fn(closeMobileMenu)) {
        closeMobileMenu();
      }
      if (is.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 React.createElement(
      'div',
      { className: 'ma__main-nav' },
      React.createElement(
        'ul',
        { className: 'ma__main-nav__items', role: 'menubar' },
        mainNav.map(function (item, index) {
          var topItemClasses = classNames({
            '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(React.createElement(
              'button',
              buttonProps,
              item.text
            ));
            var navItemClasses = classNames({
              'ma__main-nav__subitems': true,
              'is-open-react': isExpanded,
              'is-closed-react': !isExpanded
            });
            itemBody.push(
            /* eslint-disable-next-line react/no-array-index-key */
            React.createElement(
              'div',
              { className: navItemClasses, key: 'navItem' + index, 'aria-hidden': !isExpanded },
              React.createElement(
                'ul',
                { role: 'menu', 'aria-label': 'Submenu of ' + buttonId, className: 'ma__main-nav__container' },
                React.createElement(
                  'li',
                  { role: 'menuitem', className: 'ma__main-nav__subitem' },
                  React.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 */
                    React.createElement(
                      'li',
                      { className: 'ma__main-nav__subitem', key: 'liProps.' + index + '.' + subItemIndex },
                      React.createElement(
                        'button',
                        {
                          onClick: function onClick(e) {
                            return _this2.onNavigate({ e: e, href: subItem.href });
                          },
                          className: 'ma__main-nav__link'
                        },
                        subItem.text
                      )
                    )
                  );
                }),
                item.href && React.createElement(
                  'li',
                  { role: 'menuitem', className: 'ma__main-nav__subitem ma__main-nav__subitem--main' },
                  React.createElement(
                    'button',
                    {
                      onClick: function onClick(e) {
                        return _this2.onNavigate({ e: e, href: item.href });
                      },
                      className: 'ma__main-nav__link'
                    },
                    React.createElement(Icon, { name: 'arrowbent', 'aria-hidden': true }),
                    React.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(React.createElement(
              'button',
              _buttonProps,
              item.text
            ));
          }
          return (
            /* eslint-disable-next-line jsx-a11y/mouse-events-have-key-events */
            React.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;
}(Component);

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

export default MainNav;