import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import React__default, { useRef } from 'react';
import { isNotPresent, humanize, noop } from '@bigbinary/neeto-cist';
import useHotkeys from '@bigbinary/neeto-hotkeys';
import Modal from '@bigbinary/neetoui/Modal';
import { prop, isEmpty } from 'ramda';
import classnames from 'classnames';
import Typography from '@bigbinary/neetoui/Typography';
import NoData from '@bigbinary/neetoui/NoData';
import { useTranslation } from 'react-i18next';
import { Link as Link$1 } from 'react-router-dom';
import { jsx, jsxs } from 'react/jsx-runtime';
import { n } from './inject-css-C2dztUxs.js';
import Down from '@bigbinary/neeto-icons/Down';
import Up from '@bigbinary/neeto-icons/Up';
import { withT } from '@bigbinary/neeto-commons-frontend/react-utils';
import Button from '@bigbinary/neetoui/Button';
import Spinner from '@bigbinary/neetoui/Spinner';
import Search from './Search.js';
import '@babel/runtime/helpers/slicedToArray';
import '@bigbinary/neeto-commons-frontend/react-utils/useFuncDebounce';
import '@bigbinary/neeto-commons-frontend/react-utils/useQueryParams';
import '@bigbinary/neeto-commons-frontend/react-utils/useUpdateEffect';
import '@bigbinary/neeto-commons-frontend/utils/general';
import '@bigbinary/neeto-icons/Search';
import '@bigbinary/neetoui/Input';
import '@bigbinary/neeto-commons-frontend/utils';

var _excluded$1 = ["to", "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 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__*/jsx(Link$1, _objectSpread$1(_objectSpread$1({}, rest), {}, {
    to: "".concat(url.pathname).concat(url.search),
    children: children
  }));
};

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__*/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__*/jsxs(React__default.Fragment, {
      children: [highlightMatch(line, searchTerm), /*#__PURE__*/jsx("br", {})]
    }, index);
  });
};

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 = useTranslation(),
    t = _useTranslation.t;
  var isDataEmpty = isNotPresent(data) || Object.values(data).every(isNotPresent);
  if (isDataEmpty && !loading) {
    return /*#__PURE__*/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__*/jsx(NoData, {
        description: t("neetoMolecules.finderModal.noDataDesc"),
        title: t("neetoMolecules.finderModal.noDataTitle")
      })
    });
  }
  return /*#__PURE__*/jsx(Modal.Body, {
    className: "neeto-molecules-finder-modal__body h-96 overflow-y-auto px-4 py-6",
    children: /*#__PURE__*/jsx("div", {
      className: "flex flex-col gap-y-4",
      ref: containerRef,
      children: Object.keys(data).map(function (key) {
        if (isNotPresent(data[key])) return null;
        return /*#__PURE__*/jsxs("div", {
          className: "w-full",
          children: [/*#__PURE__*/jsx(Typography, {
            className: "mb-2",
            style: "h6",
            textTransform: "uppercase",
            children: humanize(key)
          }), /*#__PURE__*/jsx("div", {
            className: "w-full",
            children: data[key].map(function (item) {
              var Icon = iconComponentMap[key] || iconComponentMap["default"];
              var nameContent = htmlToText(item.name);
              var bodyContent = htmlToText(item.body);
              var filteredBodyContent = filterAndHighlightContent(bodyContent, searchTerm);
              return /*#__PURE__*/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__*/jsx(Icon, {
                  className: "neeto-ui-text-gray-500 min-w-fit",
                  size: 16
                }), /*#__PURE__*/jsxs("div", {
                  className: "line-clamp-1 flex flex-col",
                  children: [nameContent && /*#__PURE__*/jsx(Typography, {
                    className: "neeto-ui-text-black text-sm font-medium",
                    children: highlightMatch(nameContent, searchTerm)
                  }), bodyContent && /*#__PURE__*/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);
            })
          })]
        }, key);
      })
    })
  });
};

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))}";
n(css,{});

var ModalFooter = function ModalFooter(_ref) {
  var enableAdvancedSearch = _ref.enableAdvancedSearch;
  var _useTranslation = 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__*/jsx(Up, {
      className: "neeto-ui-text-gray-800",
      size: 12
    }, "up"), /*#__PURE__*/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__*/jsx(Modal.Footer, {
    className: "neeto-ui-border-gray-300 neeto-molecules-finder-modal__footer border-t px-4 py-3",
    children: /*#__PURE__*/jsx("div", {
      className: "neeto-ui-text-xxs flex items-center justify-end gap-4",
      children: shortcuts.filter(prop("isVisible")).map(function (_ref2, index) {
        var label = _ref2.label,
          keys = _ref2.keys;
        return /*#__PURE__*/jsxs("div", {
          className: "flex items-center gap-1",
          children: [/*#__PURE__*/jsx(Typography, {
            component: "span",
            style: "nano",
            children: label
          }), keys.map(function (key, index) {
            return /*#__PURE__*/jsx(Typography, {
              className: "neeto-ui-bg-gray-200 neeto-ui-rounded-sm p-1",
              component: "span",
              style: "nano",
              children: key
            }, index);
          })]
        }, index);
      })
    })
  });
};

var ModalHeader = withT(function (_ref) {
  var t = _ref.t,
    enableAdvancedSearch = _ref.enableAdvancedSearch,
    loading = _ref.loading,
    onSearch = _ref.onSearch,
    onGoToAdvanced = _ref.onGoToAdvanced;
  return /*#__PURE__*/jsx(Modal.Header, {
    className: "neeto-molecules-finder-modal__header neeto-ui-border-gray-200 border-b px-0 py-0",
    children: /*#__PURE__*/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__*/jsxs("div", {
        className: "ms-3 flex items-center",
        children: [/*#__PURE__*/jsx("div", {
          className: "h-4 w-4 flex-shrink-0",
          children: loading && /*#__PURE__*/jsx(Spinner, {
            size: "small"
          })
        }), enableAdvancedSearch && /*#__PURE__*/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 ? noop : _ref$onGoToAdvanced,
    props = _objectWithoutProperties(_ref, _excluded);
  var containerRef = useRef();
  var mutables = 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 (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__*/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__*/jsx(ModalHeader, {
      enableAdvancedSearch: enableAdvancedSearch,
      onGoToAdvanced: onGoToAdvanced,
      loading: isFetching,
      onSearch: setSearchTerm
    }), /*#__PURE__*/jsx(ModalBody, {
      containerRef: containerRef,
      data: data,
      iconComponentMap: iconComponentMap,
      onClose: onClose,
      searchTerm: searchTerm,
      loading: isFetching
    }), /*#__PURE__*/jsx(ModalFooter, {
      enableAdvancedSearch: enableAdvancedSearch
    })]
  }));
};

export { FinderModal as default };
//# sourceMappingURL=FinderModal.js.map
