'use strict';

exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _is = require('is');

var _is2 = _interopRequireDefault(_is);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _UtilityNav = require('../UtilityNav');

var _UtilityNav2 = _interopRequireDefault(_UtilityNav);

var _MainNav = require('../../molecules/MainNav');

var _MainNav2 = _interopRequireDefault(_MainNav);

var _HeaderSearch = require('../../molecules/HeaderSearch');

var _HeaderSearch2 = _interopRequireDefault(_HeaderSearch);

var _SiteLogo = require('../../atoms/media/SiteLogo');

var _SiteLogo2 = _interopRequireDefault(_SiteLogo);

var _stateseal = require('../../../assets/images/stateseal.png');

var _stateseal2 = _interopRequireDefault(_stateseal);

require('./styles.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 Header = function (_Component) {
  _inherits(Header, _Component);

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

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

    _this.updateSubNav = function (_ref) {
      var navSelected = _ref.navSelected;

      _this.setState({
        navSelected: navSelected
      });
    };

    _this.menuButtonClicked = function () {
      var afterButtonSearch = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      // eslint-disable-next-line no-undef
      var body = document.querySelector('body');
      var bodyClass = void 0;
      if (body.hasAttribute('class')) {
        bodyClass = body.getAttribute('class');
        if (bodyClass) {
          if (bodyClass.indexOf('show-menu') !== -1) {
            bodyClass = bodyClass.split(' ').filter(function (val) {
              return val !== 'show-menu';
            }).join(' ');
          } else {
            bodyClass += ' show-menu';
          }
          body.setAttribute('class', bodyClass);
        } else {
          bodyClass = 'show-menu';
          body.setAttribute('class', 'show-menu');
        }
      } else {
        bodyClass = 'show-menu';
        body.setAttribute('class', 'show-menu');
      }
      var newState = bodyClass ? { utilNavOpen: false } : { utilNavOpen: true };
      if (afterButtonSearch) {
        _this.setState(newState, _this.afterButtonSearch);
      } else {
        _this.setState(newState);
      }
      _this.updateSubNav({
        navSelected: -1
      });
    };

    _this.afterButtonSearch = function () {
      document.getElementById('nav-search').focus();
      var headerSearch = _this.props.headerSearch;

      if (_is2.default.fn(headerSearch.buttonSearch.onClick)) {
        headerSearch.buttonSearch.onClick();
      }
    };

    _this.defaultButtonSearchOnClick = function (e) {
      e.preventDefault();
      var searchRedirect = _this.props.searchRedirect;
      var _this$state = _this.state,
          shouldNavigateBottom = _this$state.shouldNavigateBottom,
          shouldNavigateTop = _this$state.shouldNavigateTop;

      if (e && e.currentTarget === _this.buttonRefTop.current) {
        if (shouldNavigateTop) {
          var query = _this.searchInputTop.current.value;
          if (query.length > 0) {
            var _extends2;

            var baseUrl = searchRedirect.baseUrl,
                searchTermParam = searchRedirect.searchTermParam,
                _searchRedirect$query = searchRedirect.queryParams,
                queryParams = _searchRedirect$query === undefined ? {} : _searchRedirect$query;

            var searchQuery = new URLSearchParams(_extends((_extends2 = {}, _extends2[searchTermParam] = query, _extends2), queryParams));
            // If in an iframe, change parent window location.
            if (window.location !== window.parent.location) {
              window.parent.location.assign(baseUrl + '?' + searchQuery.toString());
            } else {
              window.location.assign(baseUrl + '?' + searchQuery.toString());
            }
          }
        } else {
          // Only toggle the menu for the top input if it's hidden (on mobile).
          var computedStyle = getComputedStyle(_this.searchInputTop.current, null);
          if (computedStyle.display === 'none') {
            _this.menuButtonClicked(true);
          }
        }
      }
      if (e && e.currentTarget === _this.buttonRefBottom.current) {
        if (shouldNavigateBottom) {
          var _query = _this.searchInputBottom.current.value;
          if (_query.length > 0) {
            var _extends3;

            var _baseUrl = searchRedirect.baseUrl,
                _searchTermParam = searchRedirect.searchTermParam,
                _searchRedirect$query2 = searchRedirect.queryParams,
                _queryParams = _searchRedirect$query2 === undefined ? {} : _searchRedirect$query2;

            var _searchQuery = new URLSearchParams(_extends((_extends3 = {}, _extends3[_searchTermParam] = _query, _extends3), _queryParams));
            // If in an iframe, change parent window location.
            if (window.location !== window.parent.location) {
              window.parent.location.assign(_baseUrl + '?' + _searchQuery.toString());
            } else {
              window.location.assign(_baseUrl + '?' + _searchQuery.toString());
            }
          }
        } else {
          _this.menuButtonClicked(false);
        }
      }
    };

    _this.handleChangeSearchTop = function () {
      var shouldNavigateTop = _this.searchInputTop.current.value.length > 0;
      _this.setState({ shouldNavigateTop: shouldNavigateTop });
    };

    _this.handleChangeSearchBottom = function () {
      var shouldNavigateBottom = _this.searchInputBottom.current.value.length > 0;
      _this.setState({ shouldNavigateBottom: shouldNavigateBottom });
    };

    _this.topHeaderSearch = function () {
      var headerSearch = _this.props.headerSearch;

      var headerSearchProps = _extends({}, headerSearch, {
        buttonSearch: _extends({}, headerSearch.buttonSearch, {
          setButtonRef: _this.buttonRefTop,
          onClick: _this.defaultButtonSearchOnClick
        }),
        inputRef: _this.searchInputTop,
        onChange: _this.handleChangeSearchTop
      });
      return _react2.default.createElement(_HeaderSearch2.default, headerSearchProps);
    };

    _this.bottomHeaderSearch = function () {
      var headerSearch = _this.props.headerSearch;

      var headerSearchProps = _extends({}, headerSearch, {
        buttonSearch: _extends({}, headerSearch.buttonSearch, {
          setButtonRef: _this.buttonRefBottom,
          onClick: _this.defaultButtonSearchOnClick
        }),
        inputRef: _this.searchInputBottom,
        onChange: _this.handleChangeSearchBottom,
        id: 'nav-search'
      });
      return _react2.default.createElement(_HeaderSearch2.default, headerSearchProps);
    };

    _this.state = {
      utilNavOpen: false,
      shouldNavigateTop: false,
      shouldNavigateBottom: true,
      navSelected: -1
    };
    _this.searchInputTop = _react2.default.createRef();
    _this.searchInputBottom = _react2.default.createRef();
    _this.buttonRefTop = _react2.default.createRef();
    _this.buttonRefBottom = _react2.default.createRef();
    return _this;
  }
  // Puts focus on the mobile search input after the menu is opened via the search button.

  // On click action used for both top and bottom buttons.


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

    var _props = this.props,
        hideBackTo = _props.hideBackTo,
        siteLogo = _props.siteLogo,
        hideHeaderSearch = _props.hideHeaderSearch,
        headerSearch = _props.headerSearch,
        mainNav = _props.mainNav,
        utilityNav = _props.utilityNav;
    var _state = this.state,
        navSelected = _state.navSelected,
        utilNavOpen = _state.utilNavOpen;

    var headerClasses = (0, _classnames2.default)({
      ma__header: true,
      'ma__header--slim': !utilityNav,
      'ma__header--slim-mobile': hideHeaderSearch && !mainNav && !utilityNav
    });
    return _react2.default.createElement(
      'header',
      { className: headerClasses, id: 'header' },
      !hideBackTo && _react2.default.createElement(
        'div',
        { className: 'ma__header__backto' },
        _react2.default.createElement(
          'a',
          { href: 'http://www.mass.gov' },
          'Go to classic Mass.gov'
        )
      ),
      _react2.default.createElement(
        'a',
        { className: 'ma__header__skip-nav', href: '#main-content' },
        'skip to main content'
      ),
      _react2.default.createElement(
        'div',
        { className: 'ma__header__utility-nav ma__header__utility-nav--wide' },
        utilityNav ? _react2.default.createElement(_UtilityNav2.default, _extends({}, utilityNav, { isOpen: utilNavOpen })) : _react2.default.createElement('div', { className: 'ma__header__banner' })
      ),
      _react2.default.createElement(
        'div',
        { className: 'ma__header__container' },
        _react2.default.createElement(
          'div',
          { className: 'ma__header__logo' },
          _is2.default.fn(siteLogo) ? siteLogo() : _react2.default.createElement(_SiteLogo2.default, siteLogo)
        ),
        !hideHeaderSearch && _react2.default.createElement(
          'div',
          { className: 'ma__header__search js-header-search-menu' },
          _is2.default.fn(headerSearch) ? headerSearch() : this.topHeaderSearch()
        )
      ),
      _react2.default.createElement(
        'nav',
        { className: 'ma__header__nav', 'aria-labelledby': 'main_navigation', id: 'main-navigation' },
        _react2.default.createElement(
          'h2',
          { id: 'main_navigation', className: 'visually-hidden' },
          'Main Navigation'
        ),
        !hideHeaderSearch || mainNav || utilityNav ? _react2.default.createElement(
          'div',
          { className: 'ma__header__button-container' },
          navSelected !== -1 && _react2.default.createElement(
            'button',
            {
              onClick: function onClick() {
                _this2.updateSubNav({
                  navSelected: -1
                });
              },
              className: 'ma__header__back-button--react'
            },
            _react2.default.createElement(
              'span',
              null,
              'Back'
            )
          ),
          _react2.default.createElement(
            'button',
            {
              className: 'ma__header__menu-button js-header-menu-button',
              onClick: function onClick() {
                return _this2.menuButtonClicked(false);
              }
            },
            _react2.default.createElement(
              'span',
              null,
              'Menu'
            ),
            _react2.default.createElement('span', { className: 'ma__header__menu-icon' })
          )
        ) : _react2.default.createElement('div', { className: 'ma__header__banner ma__header__banner--mobile' }),
        _react2.default.createElement(
          'div',
          { className: 'ma__header__nav-container' },
          !hideHeaderSearch && _react2.default.createElement(
            'div',
            { className: 'ma__header__nav-search' },
            _is2.default.fn(headerSearch) ? headerSearch() : this.bottomHeaderSearch()
          ),
          mainNav && _react2.default.createElement(
            'div',
            { className: 'ma__header__main-nav' },
            _react2.default.createElement(_MainNav2.default, _extends({}, mainNav, {
              closeMobileMenu: function closeMobileMenu() {
                return _this2.menuButtonClicked(false);
              },
              updateHeaderState: function updateHeaderState(state) {
                return _this2.updateSubNav(state);
              },
              navSelected: navSelected
            }))
          ),
          _react2.default.createElement(
            'div',
            { className: 'ma__header__utility-nav ma__header__utility-nav--narrow' },
            utilityNav ? _react2.default.createElement(_UtilityNav2.default, _extends({}, utilityNav, { isOpen: utilNavOpen })) : _react2.default.createElement('div', { className: 'ma__header__banner' })
          )
        )
      )
    );
  };

  return Header;
}(_react.Component);

Header.propTypes = process.env.NODE_ENV !== "production" ? {
  /** imports the utilityNav component */
  utilityNav: _propTypes2.default.shape(_UtilityNav2.default.propTypes),
  /** imports the headersearch component */
  headerSearch: _propTypes2.default.oneOfType([_propTypes2.default.shape(_HeaderSearch2.default.propTypes), _propTypes2.default.func]).isRequired,
  searchRedirect: _propTypes2.default.shape({
    /** The base url that the user is redirected to when submitting a non-empty search value. */
    baseUrl: _propTypes2.default.string,
    /** The URL query parameter that will be set to the value of the search input element. */
    searchTermParam: _propTypes2.default.string,
    /** Optional extra query parameters to add to the redirect baseUrl. */
    queryParams: _propTypes2.default.object
  }),
  /** imports the mainnav component */
  mainNav: _propTypes2.default.shape(_MainNav2.default.propTypes),
  /** Adds a prop to hide header search in the header */
  hideHeaderSearch: _propTypes2.default.bool,
  /** Adds a prop to not display go back to classic.mass.gov */
  hideBackTo: _propTypes2.default.bool,
  /** siteLogo can be either a render prop or the SiteLogo component */
  siteLogo: _propTypes2.default.oneOfType([_propTypes2.default.shape(_SiteLogo2.default.propTypes), _propTypes2.default.func])
} : {};

Header.defaultProps = {
  hideHeaderSearch: false,
  hideBackTo: true,
  siteLogo: {
    url: {
      domain: 'https://www.mass.gov/'
    },
    image: {
      src: _stateseal2.default,
      alt: 'Massachusetts state seal',
      width: 45,
      height: 45
    },
    siteName: 'Mass.gov',
    title: 'Mass.gov homepage'
  },
  searchRedirect: {
    baseUrl: 'https://search.mass.gov',
    searchTermParam: 'q'
  }
};

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