import _isEmpty from "lodash/fp/isEmpty";
import _get from "lodash/fp/get";
import _getOr from "lodash/fp/getOr";
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { NovaCompositionNavigationBurger as BurgerIcon, NovaCompositionNavigationClose as CloseIcon, NovaCompositionCoorpacademyCog as CogIcon, NovaCompositionCoorpacademyPlacesHome24 as HomeIcon } from '@coorpacademy/nova-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import Provider from '../../atom/provider';
import Cta from '../../atom/cta';
import Select from '../../atom/select';
import Picture from '../../atom/picture';
import InputSwitch from '../../atom/input-switch';
import Link from '../../atom/link';
import Search from '../../atom/input-search';
import SearchForm from '../../molecule/search-form';
import ButtonMenuAction from '../../molecule/button-menu-action';
import { COLORS } from '../../variables/colors';
import style from './style.css';
class MoocHeader extends React.Component {
  static contextTypes = {
    translate: Provider.childContextTypes.translate,
    skin: Provider.childContextTypes.skin
  };
  constructor(props) {
    super(props);
    this.state = {
      isSettingsOpen: false,
      isMenuOpen: false,
      isFocus: false,
      isToolTipOpen: false
    };
    this.handleSettingsToggle = this.handleSettingsToggle.bind(this);
    this.handleMenuToggle = this.handleMenuToggle.bind(this);
    this._checkOnClose = this._checkOnClose.bind(this);
    this.handleLinkClick = this.handleLinkClick.bind(this);
    this.setMenuSettings = this.setMenuSettings.bind(this);
    this.handleSubmitSearch = this.handleSubmitSearch.bind(this);
    this.handleResetSearch = this.handleResetSearch.bind(this);
    this.handleOnFocus = this.handleOnFocus.bind(this);
    this.handleOnBlur = this.handleOnBlur.bind(this);
    this.handleOnMenuOpen = this.handleOnMenuOpen.bind(this);
    this.handleOnMenuClose = this.handleOnMenuClose.bind(this);
    this.handleOnMouseOver = this.handleOnMouseOver.bind(this);
    this.handleOnMouseLeave = this.handleOnMouseLeave.bind(this);
    this.handleKeyPress = this.handleKeyPress.bind(this);
  }
  componentDidUpdate(prevProps, prevState, prevContext) {
    const {
      isSettingsOpen
    } = this.state;
    if (isSettingsOpen) {
      document.addEventListener('click', this._checkOnClose);
      document.addEventListener('touchstart', this._checkOnClose);
    } else {
      document.removeEventListener('click', this._checkOnClose);
      document.removeEventListener('touchstart', this._checkOnClose);
    }
  }
  setMenuSettings(el) {
    this.menuSettings = el;
  }
  _checkOnClose(clickEvent) {
    const {
      isSettingsOpen
    } = this.state;
    if (isSettingsOpen) {
      const menu = this.menuSettings;
      if (menu && !menu.contains(clickEvent.target)) {
        this.handleSettingsToggle();
      }
    }
  }
  handleLinkClick() {
    const {
      isMenuOpen
    } = this.state;
    isMenuOpen && this.handleMenuToggle();
  }
  handleSettingsToggle() {
    this.setState(prevState => ({
      isSettingsOpen: !prevState.isSettingsOpen
    }));
  }
  handleMenuToggle() {
    const {
      isMenuOpen
    } = this.state;
    isMenuOpen ? this.handleOnMenuClose() : this.handleOnMenuOpen();
  }
  handleSubmitSearch() {
    const {
      onSubmitSearch
    } = this.props;
    if (onSubmitSearch) {
      onSubmitSearch();
    }
  }
  handleResetSearch() {
    const {
      onResetSearch
    } = this.props;
    if (onResetSearch) {
      onResetSearch();
    }
  }
  handleOnFocus() {
    this.setState(prevState => ({
      isFocus: true
    }));
  }
  handleOnBlur() {
    this.setState(prevState => ({
      isFocus: false
    }));
  }
  handleOnMenuOpen() {
    const {
      onMenuOpen
    } = this.props;
    if (onMenuOpen) {
      onMenuOpen();
    }
    this.setState(() => ({
      isMenuOpen: true
    }));
  }
  handleOnMenuClose() {
    const {
      onMenuClose
    } = this.props;
    if (onMenuClose) {
      onMenuClose();
    }
    this.setState(() => ({
      isMenuOpen: false
    }));
  }
  handleOnMouseOver() {
    this.setState(() => ({
      isToolTipOpen: true
    }));
  }
  handleOnMouseLeave() {
    this.setState(() => ({
      isToolTipOpen: false
    }));
  }
  handleKeyPress(event) {
    if (event.key === 'Enter') {
      this.setState(() => ({
        isToolTipOpen: true
      }));
    } else if (event.key === 'Tab' || event.key === 'Escape') {
      this.setState(() => ({
        isToolTipOpen: false
      }));
    }
  }
  createMenuButtons = (items, primaryColor) => {
    return items.map(item => ({
      label: item.title,
      disabled: item.disabled,
      type: 'defaultLeft',
      link: {
        href: item.href
      },
      'data-name': `item-more-${item.name}`,
      customStyle: {
        padding: '0 16px',
        ...(item.selected && {
          color: primaryColor
        })
      }
    }));
  };
  render() {
    if (_isEmpty(this.props)) return null;
    const {
      logo = {},
      pages: items,
      settings,
      user,
      links,
      search,
      'search-reset-aria-label': searchResetAriaLabel,
      'settings-aria-label': settingsAriaLabel,
      'active-page-aria-label': activePageAriaLabel,
      'group-settings-aria-label': groupAriaLbale
    } = this.props;
    const {
      isFocus,
      isSettingsOpen,
      isMenuOpen,
      isToolTipOpen
    } = this.state;
    const {
      translate,
      skin
    } = this.context;
    const {
      'aria-label': logoAriaLabel,
      closeMenuAriaLabel,
      openMenuAriaLabel,
      toolTipText,
      closeToolTipInformationTextAriaLabel
    } = logo;
    const logoUrl = _get('src', logo) || _get('images.logo', skin);
    const logoMobileUrl = _get('srcMobile', logo) || _getOr(logoUrl, 'images.logo-mobile', skin);
    let pagesView = null;
    let linksView = null;
    let userView = null;
    let settingsView = null;
    let notificationsView = null;
    let searchFormView = null;
    const moreAriaLabel = translate('More');
    const primaryColor = _get('common.primary', skin);
    const mediumColor = _get('common.medium', skin);
    const darkColor = _get('common.dark', skin);
    if (items) {
      const displayedPages = items.displayed.map((item, index) => {
        const activeColor = item.selected ? {
          color: primaryColor
        } : null;
        const {
          'page-count-aria-label': pageCountAriaLabel
        } = item;
        const itemLabel = item.selected ? `${item.title}. ${activePageAriaLabel}` : item.title;
        const pageBadge = item.counter > 0 ? /*#__PURE__*/React.createElement(Link, {
          href: item.href,
          "data-name": "item-badge",
          disabled: item.disabled,
          className: classnames(style.itemBadge, item.selected && style.activePage, item.disabled && style.disabled),
          "aria-label": pageCountAriaLabel
        }, /*#__PURE__*/React.createElement("span", {
          className: style.counter
        }, item.counter > 99 ? '99+' : item.counter)) : null;
        const {
          name: itemName = index
        } = item;
        return /*#__PURE__*/React.createElement(Link, {
          key: itemName,
          "data-name": `item-${itemName}`,
          href: item.href,
          disabled: item.disabled,
          className: classnames(style.item, item.disabled && item.selected && style.activePage, item.disabled && style.disabled),
          hoverColor: item.disabled ? '' : _getOr(COLORS.brand, 'common.primary', skin),
          onClick: this.handleLinkClick,
          target: item.target || null,
          "aria-label": itemLabel,
          style: {
            ...activeColor
          }
        }, item.title, pageBadge, /*#__PURE__*/React.createElement("span", {
          className: style.bar,
          style: {
            backgroundColor: primaryColor
          }
        }));
      });
      const optionsView = items.more.map((item, index) => {
        const activeColor = item.selected ? {
          color: primaryColor
        } : null;
        const itemLabel = item.selected ? `${item.title}. ${activePageAriaLabel}` : item.title;
        const {
          name: itemName = index
        } = item;
        return /*#__PURE__*/React.createElement(Link, {
          href: item.href,
          key: itemName,
          disabled: item.disabled,
          className: classnames(style.option, item.disabled && style.disabled),
          "data-name": `item-more-${itemName}`,
          target: item.target || null,
          "aria-label": itemLabel,
          onClick: this.handleLinkClick,
          hoverColor: item.disabled ? '' : _getOr(COLORS.brand, 'common.primary', skin),
          style: {
            ...activeColor
          }
        }, item.title, /*#__PURE__*/React.createElement("span", {
          className: style.line,
          style: {
            backgroundColor: primaryColor
          }
        }));
      });
      pagesView = /*#__PURE__*/React.createElement("div", {
        className: search.value || isFocus ? style.noItems : style.items
      }, displayedPages, items.more ? /*#__PURE__*/React.createElement("div", {
        className: style.desktopOnlyMoreMenu
      }, /*#__PURE__*/React.createElement(ButtonMenuAction, {
        button: {
          label: moreAriaLabel,
          'aria-label': moreAriaLabel,
          'data-name': 'item-more'
        },
        type: "link",
        primaryColor: primaryColor,
        containerCustom: {
          alignItems: 'flex-start'
        },
        menuWrapper: {
          customStyle: {
            top: '30px'
          }
        },
        menu: {
          buttons: this.createMenuButtons(items.more, primaryColor)
        }
      })) : null, /*#__PURE__*/React.createElement("div", {
        className: style.tabletOnlyMoreMenu
      }, /*#__PURE__*/React.createElement("div", {
        className: style.optionsGroup
      }, optionsView)));
    }
    if (links) {
      const ctas = links.map((cta, index) => {
        return /*#__PURE__*/React.createElement(Cta, _extends({}, cta, {
          key: index,
          className: index + 1 === links.length ? null : style.ctaLink
        }));
      });
      linksView = /*#__PURE__*/React.createElement("div", {
        className: style.links
      }, ctas);
    }
    if (user) {
      const nbNotifications = _getOr(0, 'notifications.value', user);
      const notificationsAriaLabel = _getOr('', 'notifications.aria-label', user);
      notificationsView = nbNotifications > 0 ? /*#__PURE__*/React.createElement(Link, {
        href: user.notifications.href,
        "data-name": "user-notifications",
        className: style.notifications
      }, nbNotifications > 99 ? '99+' : nbNotifications) : null;
      const notificationPageView = /*#__PURE__*/React.createElement(Link, {
        className: classnames(style.notification, nbNotifications > 0 ? style.active : null),
        "data-name": "stat-notifications",
        href: user.notifications.href,
        "aria-label": notificationsAriaLabel
      }, /*#__PURE__*/React.createElement(FontAwesomeIcon, {
        icon: "bell",
        style: {
          color: nbNotifications > 0 ? COLORS.negative_700 : COLORS.neutral_500
        }
      }), notificationsView);
      userView = /*#__PURE__*/React.createElement("div", {
        className: style.user
      }, /*#__PURE__*/React.createElement("div", {
        className: style.stats
      }, /*#__PURE__*/React.createElement(Link, {
        className: style.stat,
        "data-name": "stat-stars",
        href: user.stats.stars.href,
        onClick: this.handleLinkClick,
        "aria-label": user.stats.stars['aria-label']
      }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(FontAwesomeIcon, {
        icon: "star",
        style: {
          color: COLORS.yellow_500
        },
        className: style.stars
      })), /*#__PURE__*/React.createElement("div", {
        "data-name": "value",
        className: style.label
      }, user.stats.stars.label)), /*#__PURE__*/React.createElement(Link, {
        className: style.stat,
        "data-name": "stat-ranking",
        href: user.stats.ranking.href,
        onClick: this.handleLinkClick,
        "aria-label": user.stats.ranking['aria-label']
      }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(FontAwesomeIcon, {
        icon: "ranking-star",
        className: style.ranking,
        style: {
          color: primaryColor
        }
      })), /*#__PURE__*/React.createElement("div", {
        "data-name": "value",
        className: style.label
      }, user.stats.ranking.label)), /*#__PURE__*/React.createElement(Link, {
        className: style.stat,
        "data-name": "stat-badge",
        href: user.stats.badge.href,
        onClick: this.handleLinkClick,
        "aria-label": user.stats.badge['aria-label']
      }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(FontAwesomeIcon, {
        icon: "trophy",
        className: style.badge,
        style: {
          color: COLORS.neutral_400
        }
      })), /*#__PURE__*/React.createElement("div", {
        className: style.label
      }, user.stats.badge.label))), /*#__PURE__*/React.createElement("div", {
        className: style.avatarWrapper
      }, notificationPageView, /*#__PURE__*/React.createElement("div", {
        className: style.avatar,
        "data-name": "user-avatar"
      }, /*#__PURE__*/React.createElement(Link, {
        href: user.href,
        className: style.userLink,
        onClick: this.handleLinkClick,
        "aria-label": user['picture-aria-label']
      }, /*#__PURE__*/React.createElement(Picture, {
        src: user.picture,
        alt: user.profileAvatarAlt
      })))));
    }
    if (settings) {
      const settingsElements = settings.map((setting, index) => {
        let settingView = null;
        const {
          options,
          type,
          title,
          name: settingName = index,
          color,
          hoverColor,
          'aria-label': ariaLabel
        } = setting;
        switch (type) {
          case 'link':
            {
              settingView = /*#__PURE__*/React.createElement("div", {
                "data-name": `setting-${settingName}`,
                className: style.setting,
                key: settingName
              }, /*#__PURE__*/React.createElement(Link, {
                className: style.link,
                href: options.href,
                hoverColor: hoverColor,
                onClick: this.handleLinkClick,
                target: options.target || null,
                "aria-label": ariaLabel || title,
                style: {
                  color
                }
              }, title));
              break;
            }
          case 'select':
            {
              const selectProps = {};
              selectProps.options = options.values;
              selectProps.title = '';
              selectProps.theme = 'header';
              selectProps.onChange = options.onChange;
              selectProps.className = style.languageSelect;
              settingView = /*#__PURE__*/React.createElement("div", {
                "data-name": `setting-${settingName}`,
                className: classnames(style.setting, style.selectBoxes),
                key: settingName
              }, /*#__PURE__*/React.createElement("span", {
                className: style.label
              }, title), /*#__PURE__*/React.createElement(Select, _extends({}, selectProps, {
                "aria-label": ariaLabel || title
              })));
              break;
            }
          case 'switch':
            {
              const switchProps = {};
              switchProps.value = options.value;
              switchProps.id = `input-switch-${index}`;
              switchProps.onChange = options.onChange;
              settingView = /*#__PURE__*/React.createElement("div", {
                "data-name": `setting-${settingName}`,
                className: style.setting,
                key: settingName,
                "aria-label": ariaLabel || title
              }, /*#__PURE__*/React.createElement(InputSwitch, _extends({}, switchProps, {
                "aria-labelledby": `title-id-${settingName}`
              })), /*#__PURE__*/React.createElement("span", {
                id: `title-id-${settingName}`,
                className: style.label
              }, title));
              break;
            }
        }
        return settingView;
      });
      settingsView = /*#__PURE__*/React.createElement("div", {
        className: style.settings,
        ref: this.setMenuSettings
      }, /*#__PURE__*/React.createElement(CogIcon, {
        "data-name": "settings-toggle",
        style: {
          color: darkColor
        },
        className: style.settingsToggle,
        onClick: this.handleSettingsToggle,
        "aria-expanded": isSettingsOpen,
        "aria-label": settingsAriaLabel
      }), /*#__PURE__*/React.createElement("div", {
        className: isSettingsOpen ? style.settingsWrapper : style.settingsWrapperHidden
      }, /*#__PURE__*/React.createElement("div", {
        "data-name": "settings",
        className: style.settingsGroup,
        role: "group",
        "aria-label": groupAriaLbale
      }, settingsElements)));
    }
    if (search) {
      searchFormView = /*#__PURE__*/React.createElement("div", {
        "data-name": "Search-Bar",
        className: isMenuOpen ? style.hiddenSearchBar : style.searchBar
      }, /*#__PURE__*/React.createElement(SearchForm, {
        search: search,
        onSubmit: this.handleSubmitSearch,
        onReset: this.handleResetSearch,
        onSearchFocus: this.handleOnFocus,
        onSearchBlur: this.handleOnBlur,
        "search-reset-aria-label": searchResetAriaLabel
      }));
    }
    return /*#__PURE__*/React.createElement("header", {
      className: style.wrapper
    }, /*#__PURE__*/React.createElement("div", {
      "data-name": "moocHeader",
      "data-open": isMenuOpen,
      className: isMenuOpen ? style.open : style.header
    }, /*#__PURE__*/React.createElement("div", {
      className: style.logoWrapper,
      "aria-label": toolTipText,
      onMouseOver: this.handleOnMouseOver,
      onMouseLeave: this.handleOnMouseLeave
    }, /*#__PURE__*/React.createElement("div", {
      className: style.navMobile,
      "data-name": "nav-mobile"
    }, /*#__PURE__*/React.createElement(BurgerIcon, {
      role: "button",
      "data-name": "nav-mobile-open",
      style: {
        color: mediumColor
      },
      className: isMenuOpen ? style.burgerHidden : style.burger,
      onClick: this.handleOnMenuOpen,
      "aria-label": openMenuAriaLabel
    }), /*#__PURE__*/React.createElement(CloseIcon, {
      "data-name": "nav-mobile-close",
      style: {
        color: mediumColor
      },
      className: isMenuOpen ? style.close : style.closeHidden,
      onClick: this.handleOnMenuClose,
      "aria-label": closeMenuAriaLabel
    }), /*#__PURE__*/React.createElement(Link, {
      "data-name": "logo-mobile",
      href: logo.href
    }, /*#__PURE__*/React.createElement(Picture, {
      src: logoMobileUrl,
      alt: logoAriaLabel
    }))), /*#__PURE__*/React.createElement(Link, {
      className: style.logo,
      "data-name": "logo",
      id: "logo",
      href: logo.href,
      onKeyDown: this.handleKeyPress,
      tabIndex: 0,
      "data-testid": "brand-logo"
    }, /*#__PURE__*/React.createElement(Picture, {
      src: logoUrl,
      alt: logoAriaLabel
    }), isToolTipOpen ? /*#__PURE__*/React.createElement("div", {
      "aria-label": toolTipText,
      tabIndex: 0,
      "data-testid": "home-tooltip"
    }, /*#__PURE__*/React.createElement("div", {
      "aria-label": `${toolTipText} ${closeToolTipInformationTextAriaLabel}`,
      role: "tooltip",
      className: style.tooltipIconContainer,
      tabIndex: 0
    }, /*#__PURE__*/React.createElement(HomeIcon, {
      className: style.homeIcon,
      style: {
        color: primaryColor
      }
    }), /*#__PURE__*/React.createElement("p", {
      className: style.toolTipText
      // eslint-disable-next-line react/no-danger
      ,
      dangerouslySetInnerHTML: {
        __html: toolTipText
      },
      style: {
        color: primaryColor
      }
    }))) : null)), searchFormView, /*#__PURE__*/React.createElement("nav", {
      className: isMenuOpen ? style.menuWrapper : style.hiddenMenuWrapper,
      "data-name": "menu-wrapper"
    }, pagesView, userView || linksView, settingsView)));
  }
}
MoocHeader.propTypes = process.env.NODE_ENV !== "production" ? {
  logo: PropTypes.shape({
    src: PropTypes.string,
    srcMobile: PropTypes.string,
    href: PropTypes.string,
    'aria-label': PropTypes.string,
    'button-aria-label': PropTypes.string,
    toolTipText: PropTypes.string,
    closeToolTipInformationTextAriaLabel: PropTypes.string
  }),
  search: PropTypes.shape(Search.propTypes),
  'search-reset-aria-label': PropTypes.string,
  onSubmitSearch: PropTypes.func,
  onResetSearch: PropTypes.func,
  pages: PropTypes.shape({
    displayed: PropTypes.arrayOf(PropTypes.shape({
      target: PropTypes.oneOf(['_self', '_blank', '_parent', '_top']),
      title: PropTypes.string,
      name: PropTypes.string,
      href: PropTypes.string,
      selected: PropTypes.bool,
      disabled: PropTypes.bool,
      counter: PropTypes.number,
      'page-count-aria-label': PropTypes.string
    })),
    more: PropTypes.arrayOf(PropTypes.shape({
      target: PropTypes.oneOf(['_self', '_blank', '_parent', '_top']),
      title: PropTypes.string,
      name: PropTypes.string,
      href: PropTypes.string,
      selected: PropTypes.bool,
      disabled: PropTypes.bool,
      counter: PropTypes.number
    }))
  }),
  links: PropTypes.arrayOf(PropTypes.shape(Cta.propTypes)),
  user: PropTypes.shape({
    picture: PropTypes.string,
    'picture-aria-label': PropTypes.string,
    profileAvatarAlt: PropTypes.string,
    href: PropTypes.string,
    notifications: PropTypes.shape({
      href: PropTypes.string,
      value: PropTypes.number,
      'aria-label': PropTypes.string
    }),
    stats: PropTypes.shape({
      stars: PropTypes.shape({
        href: PropTypes.string,
        label: PropTypes.string,
        'aria-label': PropTypes.string
      }),
      ranking: PropTypes.shape({
        href: PropTypes.string,
        label: PropTypes.string,
        'aria-label': PropTypes.string
      }),
      badge: PropTypes.shape({
        href: PropTypes.string,
        label: PropTypes.string,
        'aria-label': PropTypes.string
      })
    })
  }),
  'settings-aria-label': PropTypes.string,
  'active-page-aria-label': PropTypes.string,
  'group-settings-aria-label': PropTypes.string,
  settings: PropTypes.arrayOf(PropTypes.shape({
    title: PropTypes.string,
    name: PropTypes.string,
    type: PropTypes.oneOf(['select', 'switch', 'link']),
    color: PropTypes.string,
    'aria-label': PropTypes.string,
    options: PropTypes.shape({
      href: PropTypes.string,
      onChange: PropTypes.func,
      value: PropTypes.bool,
      target: PropTypes.oneOf(['_self', '_blank', '_parent', '_top']),
      values: PropTypes.arrayOf(PropTypes.shape({
        value: PropTypes.string,
        name: PropTypes.string,
        selected: PropTypes.bool
      }))
    })
  })),
  onMenuOpen: PropTypes.func,
  onMenuClose: PropTypes.func
} : {};
export default MoocHeader;
//# sourceMappingURL=index.js.map