import React, { useContext, useEffect } from "react";
import {
  EditorContext,
  EditorQueryContext,
  ModalServiceContext,
  PluginsEventsContext
} from "./../../ricos-context/index.js";
import { ToolbarType } from "./../../ricos-types/index.js";
import { AiPlusButton as AiPlusButtonComponent } from "./../ai-plus-button/ai-plus-button.js";
import { UiComponentsProvider } from "./../../ui-components/index.js";
import { AI_TYPE } from "../types.js";
const FloatingToolbarButton = ({
  toggleAiModal,
  toggleToolbarModal,
  className,
  position,
  checkContextualMode
}) => {
  const pluginsEvents = React.useContext(PluginsEventsContext);
  const [lockedPosition, setLockedPosition] = React.useState();
  const { adapter } = useContext(EditorContext);
  const modalService = useContext(ModalServiceContext);
  const editorQuery = useContext(EditorQueryContext);
  const [ref, setRef] = React.useState(null);
  useEffect(() => {
    const resetPosition = () => {
      setLockedPosition(null);
    };
    adapter.tiptapEditor.on("selectionUpdate", resetPosition);
    return () => {
      adapter.tiptapEditor.off("selectionUpdate", resetPosition);
    };
  }, []);
  const openModal = React.useCallback(
    (initialPrompt) => {
      toggleAiModal(adapter.tiptapEditor, modalService, initialPrompt);
    },
    [adapter.tiptapEditor, modalService]
  );
  const selectBlock = () => {
    const { from, to } = adapter.tiptapEditor.state.selection;
    if (from === to) {
      adapter.tiptapEditor.commands.selectParentNode();
    }
    if (!lockedPosition) {
      setLockedPosition(position);
    }
  };
  return /* @__PURE__ */ React.createElement("div", { className, style: lockedPosition || position, ref: setRef }, ref && /* @__PURE__ */ React.createElement(UiComponentsProvider, { containerEl: ref }, /* @__PURE__ */ React.createElement(
    AiPlusButtonComponent,
    {
      onClick: () => {
        pluginsEvents.publishPluginToolbarClick({
          pluginId: AI_TYPE,
          buttonName: "plus",
          nodeId: "",
          type: ToolbarType.SIDE
        });
        if (checkContextualMode({ editorQuery: editorQuery.query }) && ref) {
          selectBlock();
          toggleToolbarModal(adapter.tiptapEditor, modalService, ref);
        } else {
          openModal();
        }
      }
    }
  )));
};
export {
  FloatingToolbarButton
};
//# sourceMappingURL=floating-toolbar-button.js.map
