'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var React = require('react');
var neetoCist = require('@bigbinary/neeto-cist');
var useHotkeys = require('@bigbinary/neeto-hotkeys');
var Modal = require('@bigbinary/neetoui/Modal');
var ramda = require('ramda');
var classnames = require('classnames');
var Typography = require('@bigbinary/neetoui/Typography');
var NoData = require('@bigbinary/neetoui/NoData');
var Tag = require('@bigbinary/neetoui/Tag');
var reactI18next = require('react-i18next');
var reactRouterDom = require('react-router-dom');
var jsxRuntime = require('react/jsx-runtime');
var injectCss = require('./inject-css-B6qYtOJe.js');
var Down = require('@bigbinary/neeto-icons/Down');
var Up = require('@bigbinary/neeto-icons/Up');
var reactUtils = require('@bigbinary/neeto-commons-frontend/react-utils');
var Button = require('@bigbinary/neetoui/Button');
var Spinner = require('@bigbinary/neetoui/Spinner');
var Search = require('./Search.js');
require('@babel/runtime/helpers/slicedToArray');
require('@bigbinary/neeto-commons-frontend/react-utils/useFuncDebounce');
require('@bigbinary/neeto-commons-frontend/react-utils/useQueryParams');
require('@bigbinary/neeto-commons-frontend/react-utils/useUpdateEffect');
require('@bigbinary/neeto-commons-frontend/utils/general');
require('@bigbinary/neeto-icons/Search');
require('@bigbinary/neetoui/Input');
require('@bigbinary/neeto-commons-frontend/utils');

var _excluded$1 = ["to", "children"];
function ownKeys$2(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$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var Link = function Link(_ref) {
  var to = _ref.to,
    children = _ref.children,
    rest = _objectWithoutProperties(_ref, _excluded$1);
  var url = new URL(to);
  url.host = "";
  return /*#__PURE__*/jsxRuntime.jsx(reactRouterDom.Link, _objectSpread$2(_objectSpread$2({}, rest), {}, {
    to: "".concat(url.pathname).concat(url.search),
    children: children
  }));
};

function ownKeys$1(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$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var minMax = function minMax(number) {
  var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Number.POSITIVE_INFINITY;
  var min = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  return Math.min(max, Math.max(min, number));
};
var htmlToText = function htmlToText(html) {
  if (!html) return null;
  var tmp = document.createElement("div");
  tmp.innerHTML = html;
  return tmp.textContent || tmp.innerText || "";
};
var highlightMatch = function highlightMatch(text, searchTerm) {
  if (!searchTerm) return text;
  var regex = new RegExp("(".concat(searchTerm, ")"), "gi");
  return text.split(regex).map(function (part, index) {
    return (part === null || part === void 0 ? void 0 : part.toLowerCase()) === searchTerm.toLowerCase() ? /*#__PURE__*/jsxRuntime.jsx("span", {
      className: "neeto-molecules-finder-matched-tag",
      children: part
    }, index) : part;
  });
};
var filterAndHighlightContent = function filterAndHighlightContent(bodyContent, searchTerm) {
  if (!searchTerm) return bodyContent;
  if (!bodyContent) return null;
  return bodyContent.split(/(.{1,130}(?:\s|$))/g).filter(function (line) {
    return line.trim();
  }).filter(function (line) {
    return line.toLowerCase().includes(searchTerm.toLowerCase());
  }).map(function (line, index) {
    return /*#__PURE__*/jsxRuntime.jsxs(React.Fragment, {
      children: [highlightMatch(line, searchTerm), /*#__PURE__*/jsxRuntime.jsx("br", {})]
    }, index);
  });
};
var flattenData = function flattenData(data) {
  if (!data) return [];
  if (Array.isArray(data)) return data;
  var result = [];
  Object.keys(data).forEach(function (key) {
    data[key].forEach(function (item) {
      result.push(_objectSpread$1(_objectSpread$1({}, item), {}, {
        category: key
      }));
    });
  });
  return result;
};
var createStylePalette = function createStylePalette(values) {
  var assignedStyles = {};
  var styleIndex = 0;
  return function (key) {
    if (assignedStyles[key]) return assignedStyles[key];
    var style = values[styleIndex];
    styleIndex = (styleIndex + 1) % values.length;
    assignedStyles[key] = style;
    return style;
  };
};

var getStyle = createStylePalette(["primary", "info", "success", "secondary", "warning"]);
var ModalBody = function ModalBody(_ref) {
  var containerRef = _ref.containerRef,
    data = _ref.data,
    iconComponentMap = _ref.iconComponentMap,
    onClose = _ref.onClose,
    loading = _ref.loading,
    searchTerm = _ref.searchTerm;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var flattenedData = flattenData(data);
  var isDataEmpty = neetoCist.isNotPresent(flattenedData);
  if (isDataEmpty && !loading) {
    return /*#__PURE__*/jsxRuntime.jsx(Modal.Body, {
      className: "neeto-molecules-finder-modal__body flex h-96 items-center justify-center overflow-y-auto px-4 py-6",
      children: /*#__PURE__*/jsxRuntime.jsx(NoData, {
        description: t("neetoMolecules.finderModal.noDataDesc"),
        title: t("neetoMolecules.finderModal.noDataTitle")
      })
    });
  }
  return /*#__PURE__*/jsxRuntime.jsx(Modal.Body, {
    className: "neeto-molecules-finder-modal__body h-96 overflow-y-auto px-4 py-6",
    children: /*#__PURE__*/jsxRuntime.jsx("div", {
      className: "flex flex-col gap-y-2",
      ref: containerRef,
      children: flattenedData.map(function (item) {
        var Icon = item.category && iconComponentMap[item.category] || iconComponentMap["default"];
        var nameContent = htmlToText(item.name);
        var bodyContent = htmlToText(item.body);
        var filteredBodyContent = filterAndHighlightContent(bodyContent, searchTerm);
        return /*#__PURE__*/jsxRuntime.jsxs(Link, {
          className: "neeto-molecules-search-result-item hover:neeto-ui-bg-accent-100 focus:neeto-ui-bg-accent-100 neeto-ui-rounded flex w-full cursor-pointer items-center gap-2 p-2 text-xs",
          to: item.url,
          onClick: onClose,
          children: [/*#__PURE__*/jsxRuntime.jsx(Icon, {
            className: "neeto-ui-text-gray-500 min-w-fit",
            size: 16
          }), /*#__PURE__*/jsxRuntime.jsxs("div", {
            className: "line-clamp-1 flex flex-col",
            children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
              className: "flex items-center gap-2",
              children: [nameContent && /*#__PURE__*/jsxRuntime.jsx(Typography, {
                className: "neeto-ui-text-black text-sm font-medium",
                children: highlightMatch(nameContent, searchTerm)
              }), item.category && /*#__PURE__*/jsxRuntime.jsx(Tag, {
                size: "small",
                style: getStyle(item.category),
                children: neetoCist.humanize(item.category)
              })]
            }), bodyContent && /*#__PURE__*/jsxRuntime.jsx(Typography, {
              className: classnames("truncate", {
                "neeto-ui-text-gray-600 text-xs": nameContent,
                "neeto-ui-text-black text-sm font-medium": !nameContent
              }),
              children: filteredBodyContent || bodyContent
            })]
          })]
        }, item.id);
      })
    })
  });
};

var css = ".neeto-molecules-finder-modal__search .neeto-ui-input--naked input{padding-inline-start:4px}.neeto-molecules-finder-modal-backdrop{grid-template-columns:100%}.neeto-molecules-finder-modal-backdrop .neeto-ui-modal__wrapper.neeto-molecules-finder-modal{margin-inline-end:auto;margin-inline-start:auto;max-width:740px;width:100%}.neeto-molecules-finder-matched-tag{background-color:#fbe48f!important}.neeto-molecules-finder-modal__footer{--neeto-ui-modal-footer-bg:rgb(var(--neeto-ui-white))}";
injectCss.n(css,{});

var ModalFooter = function ModalFooter(_ref) {
  var enableAdvancedSearch = _ref.enableAdvancedSearch;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var shortcuts = [{
    label: t("neetoMolecules.finderModal.advancedSearch"),
    keys: ["Cmd/Ctrl", "Return"],
    isVisible: enableAdvancedSearch
  }, {
    label: t("neetoMolecules.common.actions.open"),
    keys: ["Return"],
    isVisible: true
  }, {
    label: t("neetoMolecules.common.actions.move"),
    keys: [/*#__PURE__*/jsxRuntime.jsx(Up, {
      className: "neeto-ui-text-gray-800",
      size: 12
    }, "up"), /*#__PURE__*/jsxRuntime.jsx(Down, {
      className: "neeto-ui-text-gray-800",
      size: 12
    }, "down")],
    isVisible: true
  }, {
    label: t("neetoMolecules.common.actions.close"),
    keys: ["Esc"],
    isVisible: true
  }];
  return /*#__PURE__*/jsxRuntime.jsx(Modal.Footer, {
    className: "neeto-ui-border-gray-300 neeto-molecules-finder-modal__footer border-t px-4 py-3",
    children: /*#__PURE__*/jsxRuntime.jsx("div", {
      className: "neeto-ui-text-xxs flex items-center justify-end gap-4",
      children: shortcuts.filter(ramda.prop("isVisible")).map(function (_ref2, index) {
        var label = _ref2.label,
          keys = _ref2.keys;
        return /*#__PURE__*/jsxRuntime.jsxs("div", {
          className: "flex items-center gap-1",
          children: [/*#__PURE__*/jsxRuntime.jsx(Typography, {
            component: "span",
            style: "nano",
            children: label
          }), keys.map(function (key, index) {
            return /*#__PURE__*/jsxRuntime.jsx(Typography, {
              className: "neeto-ui-bg-gray-200 neeto-ui-rounded-sm p-1",
              component: "span",
              style: "nano",
              children: key
            }, index);
          })]
        }, index);
      })
    })
  });
};

var ModalHeader = reactUtils.withT(function (_ref) {
  var t = _ref.t,
    enableAdvancedSearch = _ref.enableAdvancedSearch,
    loading = _ref.loading,
    onSearch = _ref.onSearch,
    onGoToAdvanced = _ref.onGoToAdvanced;
  return /*#__PURE__*/jsxRuntime.jsx(Modal.Header, {
    className: "neeto-molecules-finder-modal__header neeto-ui-border-gray-200 border-b px-0 py-0",
    children: /*#__PURE__*/jsxRuntime.jsx(Search, {
      onSearch: onSearch,
      nakedInput: true,
      autoComplete: "off",
      className: "neeto-molecules-finder-modal__search px-3 py-1.5",
      name: "term",
      placeholder: t("neetoMolecules.common.actions.search"),
      suffix: /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "ms-3 flex items-center",
        children: [/*#__PURE__*/jsxRuntime.jsx("div", {
          className: "h-4 w-4 flex-shrink-0",
          children: loading && /*#__PURE__*/jsxRuntime.jsx(Spinner, {
            size: "small"
          })
        }), enableAdvancedSearch && /*#__PURE__*/jsxRuntime.jsx(Button, {
          className: "ms-3 whitespace-nowrap",
          label: t("neetoMolecules.finderModal.advancedSearch"),
          size: "small",
          style: "secondary",
          onClick: onGoToAdvanced
        })]
      })
    })
  });
});

var _excluded = ["enableAdvancedSearch", "data", "iconComponentMap", "isFetching", "isOpen", "searchTerm", "setSearchTerm", "onClose", "onGoToAdvanced"];
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), true).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; }
var FinderModal = function FinderModal(_ref) {
  var _ref$enableAdvancedSe = _ref.enableAdvancedSearch,
    enableAdvancedSearch = _ref$enableAdvancedSe === void 0 ? true : _ref$enableAdvancedSe,
    data = _ref.data,
    iconComponentMap = _ref.iconComponentMap,
    isFetching = _ref.isFetching,
    isOpen = _ref.isOpen,
    searchTerm = _ref.searchTerm,
    setSearchTerm = _ref.setSearchTerm,
    onClose = _ref.onClose,
    _ref$onGoToAdvanced = _ref.onGoToAdvanced,
    onGoToAdvanced = _ref$onGoToAdvanced === void 0 ? neetoCist.noop : _ref$onGoToAdvanced,
    props = _objectWithoutProperties(_ref, _excluded);
  var containerRef = React.useRef();
  var mutables = React.useRef({
    focusIndex: -1
  }).current;
  var onFocusChange = function onFocusChange(offset) {
    var container = containerRef.current;
    if (!container) return;
    var nodes = container.querySelectorAll("a.neeto-molecules-search-result-item");
    if (ramda.isEmpty(nodes)) return;
    mutables.focusIndex = minMax(mutables.focusIndex + offset, nodes.length - 1);
    var targetNode = nodes[mutables.focusIndex];
    if (targetNode) {
      targetNode.focus();
    }
  };
  useHotkeys(["up", "down"], function (event) {
    event.preventDefault();
    if (event.code === "ArrowUp") onFocusChange(-1);else if (event.code === "ArrowDown") onFocusChange(1);
  }, {
    mode: "global",
    enabled: isOpen
  });
  useHotkeys(["ctrl+enter", "command+enter"], onGoToAdvanced, {
    mode: "global",
    enabled: isOpen && enableAdvancedSearch
  });
  return /*#__PURE__*/jsxRuntime.jsxs(Modal, _objectSpread(_objectSpread({
    isOpen: isOpen,
    onClose: onClose,
    closeButton: false
  }, props), {}, {
    backdropClassName: "neeto-molecules-finder-modal-backdrop py-10 px-4",
    className: "neeto-molecules-finder-modal",
    children: [/*#__PURE__*/jsxRuntime.jsx(ModalHeader, {
      enableAdvancedSearch: enableAdvancedSearch,
      onGoToAdvanced: onGoToAdvanced,
      loading: isFetching,
      onSearch: setSearchTerm
    }), /*#__PURE__*/jsxRuntime.jsx(ModalBody, {
      containerRef: containerRef,
      data: data,
      iconComponentMap: iconComponentMap,
      onClose: onClose,
      searchTerm: searchTerm,
      loading: isFetching
    }), /*#__PURE__*/jsxRuntime.jsx(ModalFooter, {
      enableAdvancedSearch: enableAdvancedSearch
    })]
  }));
};

module.exports = FinderModal;
//# sourceMappingURL=FinderModal.js.map
