import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import React__default, { Fragment } from 'react';
import { Spinner, Empty } from '@bigbinary/neeto-atoms';
import { CommandDialog, Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandSeparator } from '@bigbinary/neeto-atoms/primitives';
import { isNotEmpty, noop, humanize } from '@bigbinary/neeto-cist';
import useHotkeys from '@bigbinary/neeto-hotkeys';
import { prop, isEmpty } from 'ramda';
import { useTranslation } from 'react-i18next';
import { useHistory } from 'react-router-dom';
import { jsx, jsxs } from 'react/jsx-runtime';
import { c as createLucideIcon } from '../createLucideIcon-mNMhCCpf.js';
import { C as ChevronDown } from '../chevron-down-BMerqYpK.js';
import { S as Search } from '../search-DCgpNjip.js';

/**
 * @license lucide-react v1.7.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */


const __iconNode = [["path", { d: "m18 15-6-6-6 6", key: "153udz" }]];
const ChevronUp = createLucideIcon("chevron-up", __iconNode);

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(ChevronUp, {
      className: "text-muted-foreground",
      size: 12
    }, "up"), /*#__PURE__*/jsx(ChevronDown, {
      className: "text-muted-foreground",
      size: 12
    }, "down")],
    isVisible: true
  }, {
    label: t("neetoMolecules.common.actions.close"),
    keys: ["Esc"],
    isVisible: true
  }];
  return /*#__PURE__*/jsx("div", {
    className: "border-border bg-muted/40 nm-finder-modal__footer border-t px-4 py-2.5",
    children: /*#__PURE__*/jsx("div", {
      className: "text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1.5 text-xs",
      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: [keys.map(function (key, keyIndex) {
            return /*#__PURE__*/jsx("kbd", {
              className: "border-border bg-background text-foreground inline-flex h-4 min-w-4 items-center justify-center rounded border px-1 font-sans text-[10px] leading-none",
              children: key
            }, keyIndex);
          }), /*#__PURE__*/jsx("span", {
            children: label
          })]
        }, index);
      })
    })
  });
};

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("mark", {
      className: "rounded-sm bg-yellow-200 text-yellow-900",
      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 _excluded = ["enableAdvancedSearch", "data", "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 toRelativePath = function toRelativePath(url) {
  var _URL = new URL(url),
    pathname = _URL.pathname,
    search = _URL.search;
  return "".concat(pathname).concat(search);
};
var navigateToItem = function navigateToItem(_ref) {
  var history = _ref.history,
    onClose = _ref.onClose,
    relativePath = _ref.relativePath;
  onClose === null || onClose === void 0 || onClose();
  var currentPath = "".concat(history.location.pathname).concat(history.location.search);
  if (currentPath !== relativePath) {
    history.push(relativePath);
  }
};
var handleAnchorClick = function handleAnchorClick(event) {
  var isModified = event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0;
  if (isModified) {
    // Let the browser open the href natively (new tab, new window, etc.);
    // don't let cmdk's bubble handler also navigate the current tab.
    event.stopPropagation();
    return;
  }
  // Suppress the default browser navigation so cmdk's onSelect (fired via
  // the bubbled click) drives the SPA push exactly once.
  event.preventDefault();
};
var FinderModal = function FinderModal(_ref2) {
  var _ref2$enableAdvancedS = _ref2.enableAdvancedSearch,
    enableAdvancedSearch = _ref2$enableAdvancedS === void 0 ? true : _ref2$enableAdvancedS,
    _ref2$data = _ref2.data,
    data = _ref2$data === void 0 ? {} : _ref2$data,
    isFetching = _ref2.isFetching,
    isOpen = _ref2.isOpen,
    _ref2$searchTerm = _ref2.searchTerm,
    searchTerm = _ref2$searchTerm === void 0 ? "" : _ref2$searchTerm,
    setSearchTerm = _ref2.setSearchTerm,
    onClose = _ref2.onClose,
    _ref2$onGoToAdvanced = _ref2.onGoToAdvanced,
    onGoToAdvanced = _ref2$onGoToAdvanced === void 0 ? noop : _ref2$onGoToAdvanced,
    props = _objectWithoutProperties(_ref2, _excluded);
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var history = useHistory();
  var categories = Object.keys(data).filter(function (key) {
    return isNotEmpty(data[key]);
  });
  var isDataEmpty = isEmpty(categories);
  var handleOpenChange = function handleOpenChange(open) {
    if (!open) onClose === null || onClose === void 0 || onClose();
  };
  useHotkeys(["ctrl+enter", "command+enter"], onGoToAdvanced, {
    mode: "global",
    enabled: isOpen && enableAdvancedSearch
  });
  return /*#__PURE__*/jsx(CommandDialog, _objectSpread(_objectSpread({}, props), {}, {
    className: "nm-finder-modal !max-w-[calc(100%-2rem)] sm:!max-w-xl",
    open: isOpen,
    title: t("neetoMolecules.common.actions.search"),
    onOpenChange: handleOpenChange,
    children: /*#__PURE__*/jsxs(Command, {
      className: "!p-0",
      shouldFilter: false,
      children: [/*#__PURE__*/jsxs("div", {
        className: "border-border flex items-center gap-2 border-b px-3 py-2 [&_[data-slot=command-input-wrapper]]:!p-0",
        children: [/*#__PURE__*/jsx("div", {
          className: "min-w-0 flex-1",
          children: /*#__PURE__*/jsx(CommandInput, {
            placeholder: t("neetoMolecules.common.actions.search"),
            value: searchTerm,
            onValueChange: setSearchTerm
          })
        }), isFetching && /*#__PURE__*/jsx(Spinner, {
          size: "small"
        }), enableAdvancedSearch && /*#__PURE__*/jsxs("button", {
          className: "border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground flex h-8 shrink-0 items-center gap-2 rounded-md border px-2 text-xs whitespace-nowrap transition-colors",
          type: "button",
          onClick: onGoToAdvanced,
          children: [/*#__PURE__*/jsx("span", {
            children: t("neetoMolecules.finderModal.advancedSearch")
          }), /*#__PURE__*/jsx("kbd", {
            className: "border-border bg-muted inline-flex h-4 items-center rounded border px-1 font-sans text-[10px] leading-none",
            children: "\u2318\u23CE"
          })]
        })]
      }), /*#__PURE__*/jsxs(CommandList, {
        className: "nm-finder-modal__body max-h-[min(24rem,55vh)] min-h-[min(12rem,40vh)] p-2",
        children: [isDataEmpty && !isFetching && /*#__PURE__*/jsx(CommandEmpty, {
          className: "!py-8",
          children: /*#__PURE__*/jsx(Empty, {
            description: t("neetoMolecules.finderModal.noDataDesc"),
            icon: Search,
            title: t("neetoMolecules.finderModal.noDataTitle")
          })
        }), categories.map(function (category, index) {
          return /*#__PURE__*/jsxs(Fragment, {
            children: [/*#__PURE__*/jsx(CommandGroup, {
              heading: humanize(category),
              children: data[category].map(function (item) {
                var name = htmlToText(item.name);
                var body = htmlToText(item.body);
                var filteredBody = filterAndHighlightContent(body, searchTerm);
                var relativePath = toRelativePath(item.url);
                return /*#__PURE__*/jsx(CommandItem, {
                  className: "!p-0",
                  value: "".concat(category, "-").concat(item.id),
                  onSelect: function onSelect() {
                    return navigateToItem({
                      history: history,
                      onClose: onClose,
                      relativePath: relativePath
                    });
                  },
                  children: /*#__PURE__*/jsxs("a", {
                    className: "flex min-w-0 flex-1 flex-col gap-1.5 px-3 py-2.5 no-underline outline-none",
                    href: relativePath,
                    onClick: handleAnchorClick,
                    children: [name && /*#__PURE__*/jsx("span", {
                      className: "text-foreground line-clamp-1 text-sm font-medium",
                      children: highlightMatch(name, searchTerm)
                    }), body && /*#__PURE__*/jsx("span", {
                      className: "text-muted-foreground line-clamp-1 text-xs",
                      children: filteredBody || body
                    })]
                  })
                }, "".concat(category, "-").concat(item.id));
              })
            }), index < categories.length - 1 && /*#__PURE__*/jsx(CommandSeparator, {
              className: "my-1"
            })]
          }, category);
        })]
      }), /*#__PURE__*/jsx(ModalFooter, {
        enableAdvancedSearch: enableAdvancedSearch
      })]
    })
  }));
};

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