/* istanbul ignore file */

import React from 'react';
import PropTypes from 'prop-types';
import { connectHits, connectStateResults, Snippet } from 'react-instantsearch-dom';

import Pagination from '../Pagination';

import Title from '../../../../components/Title';

import classes from './style.module.scss';

// custom results
var Results = connectStateResults(function (_ref) {
  var searchState = _ref.searchState,
      searchResults = _ref.searchResults,
      children = _ref.children;

  // welcome state
  if (searchState && !searchState.query) {
    return React.createElement(
      'div',
      { className: [classes.SearchResults, classes.SearchResults_empty].join(' ') },
      React.createElement('i', { className: 'icon icon-search' }),
      React.createElement(
        Title,
        { level: 6 },
        'Start typing to search\u2026'
      )
    );
  }

  // empty state (no results)
  if (searchResults && searchResults.nbHits === 0) {
    return React.createElement(
      'div',
      { className: [classes.SearchResults, classes.SearchResults_empty].join(' ') },
      React.createElement(
        Title,
        { level: 6 },
        'Try a different search.'
      ),
      React.createElement(
        'div',
        null,
        'No results for \u2018',
        searchState.query,
        '\u2019.'
      )
    );
  }

  return children;
});

var determineResultDisplay = function determineResultDisplay(hit) {
  var snippet = hit._snippetResult;

  var fullMatch = Object.entries(snippet).sort(function (a, b) {
    var aVal = a[1];
    var bVal = b[1];

    if (aVal.matchLevel === 'full' && (bVal.matchLevel === 'partial' || bVal.matchLevel === 'none')) return -1;else if (aVal.matchLevel === bVal.matchLevel) return 0;
    return 1;
  });
  return fullMatch[0][0];
};

var handleArrowFocus = function handleArrowFocus(e) {
  var key = e.key,
      target = e.target;

  var hitList = target.querySelector('.SearchResults-list') || target.parentElement;
  var focusAt = document.querySelector('a:focus');

  var focusTo = void 0;
  if (!focusAt) focusTo = hitList.firstElementChild.focus();else if (key && (key === 'ArrowUp' || key === 'ArrowDown')) {
    if (key === 'ArrowUp') focusTo = focusAt.previousElementSibling || hitList.lastElementChild;
    if (key === 'ArrowDown') focusTo = focusAt.nextElementSibling || hitList.firstElementChild;
    e.preventDefault();
  }

  if (focusTo) focusTo.focus();
};

var createCustomHitsComponent = function createCustomHitsComponent(subdomains, onReload, UrlManager) {
  var Hits = function Hits(_ref2) {
    var hits = _ref2.hits;

    // if there are no results within the current filters
    if (hits.length === 0) {
      return React.createElement(
        'div',
        { className: [classes.SearchResults, classes.SearchResults_empty].join(' ') },
        React.createElement(
          Title,
          { level: 6 },
          'No results.'
        ),
        React.createElement(
          'div',
          null,
          'Try a different filter or tab.'
        )
      );
    }

    // if there are results
    if (typeof onReload === 'function') onReload(); // callback
    var results = hits.map(function (hit) {
      // Build hitUrl
      var hitUrl = void 0;
      if (window.location.hash) {
        hitUrl = UrlManager.remove('hash', window.location.href);
      }
      hitUrl = UrlManager.upsert('slugs', hit.internalLink.split('/'), hitUrl);

      // Enterprise only: Populate child if project has parent & hit is from a different child project
      if (UrlManager.options.parent && subdomains[hit.project] !== UrlManager.options.project.subdomain) {
        hitUrl = UrlManager.upsert('child', subdomains[hit.project], hitUrl);
        // Remove version if hit is from a different child project
        if (UrlManager.options.version) {
          hitUrl = UrlManager.remove('version', hitUrl);
        }
      }

      var attribute = determineResultDisplay(hit);
      var title = hit.isReference && hit.method ? '(' + hit.method.toUpperCase() + ') ' + hit.title : hit.title;

      return React.createElement(
        'a',
        { key: hit.objectID, className: classes['SearchResults-Result'], href: hitUrl, tabIndex: 0 },
        React.createElement(
          'header',
          { className: classes['SearchResults-Result-Header'], title: title },
          hit.isReference && React.createElement(
            'span',
            {
              className: [classes['SearchResults-Method'], classes['SearchResults-Method_' + hit.method]].join(' ')
            },
            hit.method
          ),
          React.createElement(
            'span',
            { className: classes['SearchResults-Result-Title'] },
            hit.title,
            Object.keys(subdomains).length <= 1 || React.createElement(
              'span',
              { className: classes['SearchResults-Result-Project'] },
              hit.subdomain
            )
          ),
          hit.link_url && React.createElement(
            'small',
            { className: classes['SearchResults-Result-Link'] },
            React.createElement('i', { className: 'fa fa-external-link-alt' })
          )
        ),
        React.createElement(
          'div',
          { className: classes['SearchResults-Result-Excerpt'], title: title },
          React.createElement(Snippet, { attribute: attribute, hit: hit })
        )
      );
    });

    return React.createElement(
      'div',
      { className: [classes.SearchResults, classes.SearchResults_default].join(' ') },
      React.createElement('div', { className: classes['SearchResults-ScrollTo'] }),
      React.createElement(
        'div',
        { className: 'SearchResults-list', onKeyDownCapture: handleArrowFocus },
        results
      ),
      React.createElement(Pagination, null)
    );
  };
  Hits.propTypes = process.env.NODE_ENV !== "production" ? {
    hits: PropTypes.array
  } : {};
  return Hits;
};

var SearchResults = function SearchResults(_ref3) {
  var subdomains = _ref3.subdomains,
      onReload = _ref3.onReload,
      UrlManager = _ref3.UrlManager;

  var Hits = createCustomHitsComponent(subdomains, onReload, UrlManager);
  var CustomHits = connectHits(Hits);
  return React.createElement(
    Results,
    null,
    React.createElement(CustomHits, { hitComponent: Hits })
  );
};

SearchResults.propTypes = process.env.NODE_ENV !== "production" ? {
  onReload: PropTypes.func,
  subdomains: PropTypes.object,
  tab: PropTypes.string,
  UrlManager: PropTypes.object
} : {};

SearchResults.defaultProps = {
  subdomains: {}
};

export default SearchResults;