const _excluded = ["key"];
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); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
/* eslint-disable react/jsx-props-no-spreading */
import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import Autosuggest from "react-autosuggest";
import { FaSearch, FaAngleDown, FaAngleUp } from "react-icons/fa";
import { IconButton, Typography } from "@mui/material";
import useTranslation from "../../utils/useTranslation";
import { setFeatureInfo, setSearchOpen } from "../../model/app/actions";
import useHasScreenSize from "../../utils/useHasScreenSize";
import "./SearchInput.scss";
import CloseButton from "../CloseButton";
import { trackEvent } from "../../utils/trackingUtils";
const mobileMapPadding = [50, 50, 50, 50];
function SearchInput() {
  const [value, setValue] = useState("");
  const [suggestions, setSuggestions] = useState([]);
  const map = useSelector(state => state.app.map);
  const featureInfo = useSelector(state => state.app.featureInfo);
  const searchService = useSelector(state => state.app.searchService);
  const activeTopic = useSelector(state => state.app.activeTopic);
  const embedded = useSelector(state => state.app.embedded);
  const isMobile = useHasScreenSize();
  const {
    t
  } = useTranslation();
  const dispatch = useDispatch();
  const isEmbedded = window !== window.parent || embedded;
  useEffect(() => {
    if (!searchService) {
      return;
    }
    searchService.setUpsert((section, items, position) => {
      setSuggestions(oldSuggestions => {
        const index = oldSuggestions.findIndex(s => s.section === section);
        const start = index === -1 ? position : index;
        const deleteCount = index === -1 ? 0 : 1;
        const newSuggestions = [...oldSuggestions];
        newSuggestions.splice(start, deleteCount, {
          section,
          items
        });
        return newSuggestions;
      });
    });
  }, [searchService, setSuggestions]);
  useEffect(() => searchService && map && searchService.setMap(map), [searchService, map]);
  if (!searchService || !Object.keys(searchService.searches || []).length) {
    return null;
  }
  return /*#__PURE__*/React.createElement(Autosuggest, {
    isEmbedded: true,
    multiSection: true,
    shouldRenderSuggestions: val => val.trim().length > 2,
    suggestions: suggestions,
    onSuggestionsFetchRequested: evt => {
      searchService.search(evt.value);
    },
    onSuggestionsClearRequested: () => {
      setSuggestions([]);
    },
    onSuggestionHighlighted: _ref => {
      let {
        suggestion
      } = _ref;
      return searchService.highlight(suggestion);
    },
    onSuggestionSelected: (e, thing) => {
      const {
        suggestion
      } = thing;
      trackEvent({
        eventType: "action",
        componentName: "search result",
        label: searchService.value(suggestion),
        variant: suggestion.section,
        location: t(activeTopic === null || activeTopic === void 0 ? void 0 : activeTopic.name, {
          lng: "de"
        }),
        eventName: e.type
      }, activeTopic);
      dispatch(setFeatureInfo());
      searchService.select(suggestion, isMobile ? mobileMapPadding : undefined);
      dispatch(setSearchOpen(false));
    },
    getSuggestionValue: suggestion => searchService.value(suggestion),
    renderSuggestion: suggestion => searchService.render(suggestion),
    renderSectionTitle: _ref2 => {
      let {
        section
      } = _ref2;
      const count = searchService.countItems(section);
      return count > 0 && /*#__PURE__*/React.createElement("div", {
        className: "wkp-search-section-opener",
        onClick: () => searchService.toggleSection(section),
        onKeyPress: () => searchService.toggleSection(section),
        role: "button",
        tabIndex: 0
      }, /*#__PURE__*/React.createElement("div", {
        className: "wkp-search-section-header"
      }, /*#__PURE__*/React.createElement(Typography, {
        variant: "h4",
        component: "span"
      }, t(section), ":", " "), /*#__PURE__*/React.createElement(Typography, {
        variant: "subtitle1",
        component: "span"
      }, t("overallResult", {
        count
      }))), searchService.sectionCollapsed(section) ? /*#__PURE__*/React.createElement(FaAngleDown, {
        focusable: false
      }) : /*#__PURE__*/React.createElement(FaAngleUp, {
        focusable: false
      }));
    },
    getSectionSuggestions: result => {
      var _result$items;
      return (result === null || result === void 0 || (_result$items = result.items) === null || _result$items === void 0 ? void 0 : _result$items.map(i => _objectSpread(_objectSpread({}, i), {}, {
        section: result.section
      }))) || [];
    },
    containerProps: {
      className: "wkp-autosuggest"
    },
    inputProps: {
      autoFocus: !isEmbedded,
      tabIndex: 0,
      "aria-label": t("Suchmaske"),
      onChange: (e, _ref3) => {
        let {
          newValue
        } = _ref3;
        return setValue(newValue);
      },
      onKeyUp: e => {
        const {
          key
        } = e;
        if (key === "Enter") {
          trackEvent({
            eventType: "action",
            componentName: "search input",
            label: t("Suche starten"),
            location: t(activeTopic === null || activeTopic === void 0 ? void 0 : activeTopic.name, {
              lng: "de"
            }),
            variant: "Suche starten"
          }, activeTopic);
          const filtered = suggestions.filter(s => s.items.length > 0);
          if (filtered.length > 0) {
            const {
              items,
              section
            } = filtered[0];
            dispatch(setSearchOpen(false));
            searchService.select(_objectSpread(_objectSpread({}, items[0]), {}, {
              section
            }), isMobile ? mobileMapPadding : undefined);
          }
        } else if (key === "ArrowDown" || key === "ArrowUp") {
          searchService.highlightSection(); // for improved accessibility
        }
      },
      placeholder: searchService.getPlaceholder(t),
      value
    },
    renderInputComponent: _ref4 => {
      let {
          key
        } = _ref4,
        inputProps = _objectWithoutProperties(_ref4, _excluded);
      return /*#__PURE__*/React.createElement("div", {
        className: "wkp-search-input",
        "data-testid": "wkp-search-input"
      }, /*#__PURE__*/React.createElement("input", _extends({}, inputProps, {
        key: key
      })), value && /*#__PURE__*/React.createElement(CloseButton, {
        tabIndex: 0,
        title: t("Suchtext löschen"),
        className: "wkp-search-button wkp-search-button-clear",
        onClick: () => {
          setValue("");
          searchService.clearHighlight();
          searchService.clearSelect();
          const searchFeatureInfos = searchService.clearPopup();

          // We remove the stations feature infos from the current list of feature infos.
          if (featureInfo !== null && featureInfo !== void 0 && featureInfo.length && searchFeatureInfos !== null && searchFeatureInfos !== void 0 && searchFeatureInfos.length) {
            (searchFeatureInfos || []).forEach(searchFeatureInfo => {
              const index = featureInfo === null || featureInfo === void 0 ? void 0 : featureInfo.findIndex(info => {
                return info === searchFeatureInfo;
              });
              if (index > -1) {
                featureInfo.splice(index, 1);
              }
            });
            dispatch(setFeatureInfo([...featureInfo]));
          }
        }
      }), /*#__PURE__*/React.createElement(IconButton, {
        tabIndex: 0,
        "aria-label": t("Suche starten"),
        title: t("Suche starten"),
        className: "wkp-search-button wkp-search-button-submit",
        onClick: () => {
          trackEvent({
            eventType: "action",
            componentName: "search button",
            label: t("Suche starten"),
            location: t(activeTopic === null || activeTopic === void 0 ? void 0 : activeTopic.name, {
              lng: "de"
            }),
            variant: "Suche starten"
          }, activeTopic);
          if (!value) {
            // Hide the search input on small screen
            dispatch(setSearchOpen(false));
          }
          if (searchService.selectItem) {
            // Will zoom on the current selected feature
            searchService.select(searchService.selectItem, isMobile ? mobileMapPadding : undefined);
          }

          // Launch a search
          if (value) {
            searchService.search(value).then(searchResults => {
              const result = searchResults.find(results => results.items.length > 0);
              if (result) {
                const {
                  items,
                  section
                } = result;
                dispatch(setSearchOpen(false));
                searchService.select(_objectSpread(_objectSpread({}, items[0]), {}, {
                  section
                }), isMobile ? mobileMapPadding : undefined);
              }
            });
          }
        }
      }, /*#__PURE__*/React.createElement(FaSearch, {
        focusable: false
      })));
    }
  });
}
export default SearchInput;
//# sourceMappingURL=SearchInput.js.map