import { DropdownBase } from "@wix/design-system";
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import { ZIndexContext } from "./../../ricos-context/index.js";
import { UiComponentsProvider } from "./../../ui-components/ui-components-provider.js";
import styles from "./emoji-suggestions-modal-scss.js";
const EmojiSuggestionsModal = ({
  command,
  items,
  query,
  messages
}) => {
  const zIndexService = useContext(ZIndexContext);
  const currElement = useRef(null);
  const [refElement, setRefElement] = useState(null);
  const [selectedId, setSelectedId] = useState();
  useEffect(() => {
    setSelectedId(items[0]?.id);
  }, [items]);
  useEffect(() => {
    const handleMessage = ({ type, payload }) => {
      if (type === "onKeyDown") {
        const { event } = payload;
        if (["ArrowUp", "ArrowDown"].includes(event.key)) {
          const direction = event.key === "ArrowUp" ? -1 : 1;
          if (!items.length) {
            return true;
          }
          setSelectedId((prev) => {
            const currIndex = items.findIndex((option) => option.id === prev);
            const nextIndex = (currIndex + direction + items.length) % items.length;
            return items[nextIndex].id;
          });
          return true;
        }
        if (["Enter", "Tab"].includes(event.key)) {
          const option = items.find((option2) => option2.id === selectedId);
          if (!option) {
            return false;
          }
          command({ emoji: option.native, query });
          return true;
        }
      }
    };
    messages?.subscribe(handleMessage);
    return () => messages?.unsubscribe(handleMessage);
  }, [messages, items, query, command, selectedId]);
  const dropdownOptions = useMemo(
    () => items.map((emoji) => ({
      as: "button",
      ellipsis: false,
      id: emoji.id,
      onClick: () => {
        command({ emoji: emoji.native, query });
      },
      optionTitle: `${emoji.native} ${emoji.shortcodes}`,
      shouldFocusWithoutScroll: true,
      title: false,
      value: "action"
    })),
    [items, query, command]
  );
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      className: styles.emojiSuggestionsModal,
      style: { zIndex: zIndexService.getZIndex("DIALOG") },
      ref: setRefElement
    },
    refElement && /* @__PURE__ */ React.createElement(UiComponentsProvider, { containerEl: refElement }, /* @__PURE__ */ React.createElement(
      DropdownBase,
      {
        ref: currElement,
        placement: "bottom-start",
        minWidth: 280,
        maxHeight: 250,
        focusOnOption: selectedId,
        options: dropdownOptions,
        onMouseDown: (e) => e.preventDefault(),
        open: true,
        listType: "action"
      }
    ))
  );
};
export {
  EmojiSuggestionsModal
};
//# sourceMappingURL=emoji-suggestions-modal.js.map
