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

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 is from 'is';
import classNames from 'classnames';
import UtilityNav from '../UtilityNav';
import MainNav from '../../molecules/MainNav';
import HeaderSearch from '../../molecules/HeaderSearch';
import SiteLogo from '../../atoms/media/SiteLogo';
import logo from '../../../assets/images/stateseal.png';

import './styles.css';

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 (is.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 React.createElement(HeaderSearch, 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 React.createElement(HeaderSearch, headerSearchProps);
    };

    _this.state = {
      utilNavOpen: false,
      shouldNavigateTop: false,
      shouldNavigateBottom: true,
      navSelected: -1
    };
    _this.searchInputTop = React.createRef();
    _this.searchInputBottom = React.createRef();
    _this.buttonRefTop = React.createRef();
    _this.buttonRefBottom = React.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 = classNames({
      ma__header: true,
      'ma__header--slim': !utilityNav,
      'ma__header--slim-mobile': hideHeaderSearch && !mainNav && !utilityNav
    });
    return React.createElement(
      'header',
      { className: headerClasses, id: 'header' },
      !hideBackTo && React.createElement(
        'div',
        { className: 'ma__header__backto' },
        React.createElement(
          'a',
          { href: 'http://www.mass.gov' },
          'Go to classic Mass.gov'
        )
      ),
      React.createElement(
        'a',
        { className: 'ma__header__skip-nav', href: '#main-content' },
        'skip to main content'
      ),
      React.createElement(
        'div',
        { className: 'ma__header__utility-nav ma__header__utility-nav--wide' },
        utilityNav ? React.createElement(UtilityNav, _extends({}, utilityNav, { isOpen: utilNavOpen })) : React.createElement('div', { className: 'ma__header__banner' })
      ),
      React.createElement(
        'div',
        { className: 'ma__header__container' },
        React.createElement(
          'div',
          { className: 'ma__header__logo' },
          is.fn(siteLogo) ? siteLogo() : React.createElement(SiteLogo, siteLogo)
        ),
        !hideHeaderSearch && React.createElement(
          'div',
          { className: 'ma__header__search js-header-search-menu' },
          is.fn(headerSearch) ? headerSearch() : this.topHeaderSearch()
        )
      ),
      React.createElement(
        'nav',
        { className: 'ma__header__nav', 'aria-labelledby': 'main_navigation', id: 'main-navigation' },
        React.createElement(
          'h2',
          { id: 'main_navigation', className: 'visually-hidden' },
          'Main Navigation'
        ),
        !hideHeaderSearch || mainNav || utilityNav ? React.createElement(
          'div',
          { className: 'ma__header__button-container' },
          navSelected !== -1 && React.createElement(
            'button',
            {
              onClick: function onClick() {
                _this2.updateSubNav({
                  navSelected: -1
                });
              },
              className: 'ma__header__back-button--react'
            },
            React.createElement(
              'span',
              null,
              'Back'
            )
          ),
          React.createElement(
            'button',
            {
              className: 'ma__header__menu-button js-header-menu-button',
              onClick: function onClick() {
                return _this2.menuButtonClicked(false);
              }
            },
            React.createElement(
              'span',
              null,
              'Menu'
            ),
            React.createElement('span', { className: 'ma__header__menu-icon' })
          )
        ) : React.createElement('div', { className: 'ma__header__banner ma__header__banner--mobile' }),
        React.createElement(
          'div',
          { className: 'ma__header__nav-container' },
          !hideHeaderSearch && React.createElement(
            'div',
            { className: 'ma__header__nav-search' },
            is.fn(headerSearch) ? headerSearch() : this.bottomHeaderSearch()
          ),
          mainNav && React.createElement(
            'div',
            { className: 'ma__header__main-nav' },
            React.createElement(MainNav, _extends({}, mainNav, {
              closeMobileMenu: function closeMobileMenu() {
                return _this2.menuButtonClicked(false);
              },
              updateHeaderState: function updateHeaderState(state) {
                return _this2.updateSubNav(state);
              },
              navSelected: navSelected
            }))
          ),
          React.createElement(
            'div',
            { className: 'ma__header__utility-nav ma__header__utility-nav--narrow' },
            utilityNav ? React.createElement(UtilityNav, _extends({}, utilityNav, { isOpen: utilNavOpen })) : React.createElement('div', { className: 'ma__header__banner' })
          )
        )
      )
    );
  };

  return Header;
}(Component);

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

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

export default Header;