import { SparklesSmall } from "@wix/wix-ui-icons-common";
import { TextSelection } from "prosemirror-state";
import React from "react";
import { ToolbarType, quickActionsModalSections } from "./../ricos-types/index.js";
import { isAlwaysVisible } from "./../_shared/resolvers/is-always-visible.js";
import { isNodeOrCaptionSelected } from "./../_shared/resolvers/is-node-or-caption-selected.js";
import { minMax } from "./../tiptap/index.js";
import { AiActionsModal } from "./ai-actions-modal/ai-actions-modal.js";
import { AiContentModal } from "./ai-content-modal/ai-content-modal.js";
import { AiFlowSelectionModal } from "./ai-flow-selection-modal/ai-flow-selection-modal.js";
import { AiImageModal } from "./ai-image-modal/ai-image-modal.js";
import { TEXT_BUTTON_AI } from "./data-hooks.js";
import { DiscardConfirmationModal } from "./discard-confirmation-modal/discard-confirmation-modal.js";
import { createAltTextInput } from "./exports/image-alt-text-input/alt-text-input.js";
import { createCaptionTrigger } from "./exports/image-caption-integration/caption-trigger.js";
import { FloatingToolbarButton } from "./floating-toolbar-button/floating-toolbar-button.js";
import { tiptapExtensions } from "./tiptap/extensions.js";
import { ToolbarButtonSmall } from "./toolbar/toolbar-button-small.js";
import { ToolbarButton } from "./toolbar/toolbar-button.js";
import {
  AI_ACTIONS_MODAL_ID,
  AI_DISCARD_MODAL_ID,
  AI_FLOW_SELECTION_MODAL_ID,
  AI_IMAGE_MODAL_ID,
  AI_MODAL_ID,
  AI_TYPE
} from "./types.js";
import { getPromptBiValue } from "./utils/get-prompt-bi.js";
const DEFAULT_CONFIG = {
  type: "ai",
  appDefId: "",
  showToolbarButtonText: true,
  enableImageGeneration: true,
  enableImageCaptionExport: true,
  enableImageAltTextExport: true,
  selectParentNodeOnToolbarClick: true
};
const pluginAi = (pluginConfig) => {
  const config = { ...DEFAULT_CONFIG, ...pluginConfig };
  const openDiscardModal = (modalsService, referenceElement) => {
    return new Promise((resolve) => {
      modalsService.openModal({
        id: AI_DISCARD_MODAL_ID,
        Component: DiscardConfirmationModal,
        componentProps: {
          closeModal: (confirmed) => {
            modalsService.closeModal(AI_DISCARD_MODAL_ID);
            resolve(confirmed);
          }
        },
        onClickOutside: () => {
          modalsService.closeModal(AI_DISCARD_MODAL_ID);
          resolve({ confirmed: false });
        },
        layout: "dialog",
        positioning: {
          referenceElement
        },
        disableArrowNavigation: true,
        returnFocusToEditor: true
      });
    });
  };
  const toggleAiModal = (entryType) => (editor, modalsService, initialPrompt) => modalsService.togglePluginPanel({
    id: AI_MODAL_ID,
    Component: AiContentModal,
    componentProps: {
      closeModal: () => modalsService.closeModal(AI_MODAL_ID),
      openDiscardModal: (referenceElement) => openDiscardModal(modalsService, referenceElement),
      config,
      initialPromptOptions: initialPrompt ? { prompt: initialPrompt, autoTrigger: true } : void 0
    },
    isMobile: false,
    onClickOutside: () => {
    },
    positioning: {
      referenceElement: getFakeReferenceElement(editor),
      placement: "right-start"
    },
    dropdownValue: initialPrompt ? getPromptBiValue(initialPrompt) : void 0,
    entryType,
    returnFocusToEditor: false
  });
  const toggleToolbarModal = (entryType, modalType) => (_editor, modalsService, referenceElement) => {
    modalsService.isModalOpen(AI_ACTIONS_MODAL_ID) ? modalsService.closeModal(AI_ACTIONS_MODAL_ID) : modalsService.openModal({
      id: AI_ACTIONS_MODAL_ID,
      Component: AiActionsModal,
      componentProps: {
        toggleAiContentModal: toggleAiModal(entryType),
        toggleAiImageModal: toggleAiImageModal(entryType),
        enableImageGeneration: config.enableImageGeneration,
        config
      },
      layout: referenceElement ? "floating" : "dialog",
      positioning: {
        referenceElement,
        placement: "bottom-start"
      },
      type: modalType,
      entryType,
      disableArrowNavigation: true,
      returnFocusToEditor: false,
      autoFocus: false
    });
  };
  const toggleAiFlowSelectionModal = (entryType) => (_editor, modalsService, referenceElement) => {
    modalsService.isModalOpen(AI_FLOW_SELECTION_MODAL_ID) ? modalsService.closeModal(AI_FLOW_SELECTION_MODAL_ID) : modalsService.openModal({
      id: AI_FLOW_SELECTION_MODAL_ID,
      Component: AiFlowSelectionModal,
      componentProps: {
        toggleAiContentModal: toggleAiModal("FLOW_SELECTION"),
        toggleAiImageModal: toggleAiImageModal("FLOW_SELECTION"),
        config
      },
      layout: referenceElement ? "floating" : "dialog",
      positioning: {
        referenceElement,
        placement: "bottom-start"
      },
      type: "exclusive",
      entryType,
      disableArrowNavigation: true,
      returnFocusToEditor: false,
      autoFocus: false
    });
  };
  const toggleAiImageModal = (entryType) => (editor, modalsService, convertSelectionToPrompt) => modalsService.togglePluginPanel({
    id: AI_IMAGE_MODAL_ID,
    Component: AiImageModal,
    componentProps: {
      closeModal: () => modalsService.closeModal(AI_IMAGE_MODAL_ID),
      openDiscardModal: (referenceElement) => openDiscardModal(modalsService, referenceElement),
      convertSelectionToPrompt,
      config,
      insertActions: entryType === "FLOW_SELECTION" ? "single" : "both"
    },
    onClickOutside: () => {
    },
    positioning: {
      referenceElement: getFakeReferenceElement(editor),
      placement: "right-end"
    },
    entryType,
    isMobile: false,
    returnFocusToEditor: true
  });
  const checkContextualMode = ({
    editorQuery,
    nodeId
  }) => {
    if (editorQuery.isEmptyTextBlock()) {
      return false;
    }
    if (editorQuery.isOnlySlashInParagraph()) {
      return false;
    }
    if (nodeId) {
      if (editorQuery.isChildSingleTextBlockEmpty(nodeId)) {
        return false;
      }
      return editorQuery.isChildSingleTextBlock(nodeId);
    }
    return editorQuery.isMultipleSelection() || editorQuery.isSingleRootTextBlock() || editorQuery.isListItem();
  };
  return {
    config,
    type: AI_TYPE,
    tiptapExtensions,
    textButtons: [
      {
        id: AI_TYPE,
        type: "modal",
        presentation: {
          dataHook: TEXT_BUTTON_AI,
          tooltip: "AIPlugin_ToolbarButton_Tooltip",
          component: (props) => /* @__PURE__ */ React.createElement(ToolbarButton, { ...props, showLabel: config.showToolbarButtonText }),
          getIcon: ({ t }) => () => /* @__PURE__ */ React.createElement(ToolbarButtonSmall, { showLabel: config.showToolbarButtonText ?? false, t })
        },
        attributes: {
          visible: isAlwaysVisible,
          disabled: isNodeOrCaptionSelected
        },
        command: ({ editor, modalService, editorQuery, referenceElement }) => (event) => {
          const target = event?.target ?? referenceElement;
          if (checkContextualMode({ editorQuery: editorQuery.query }) && target && // No activeElement in JSDOM tests, always assume editor is focused
          (event?.view?.document ? event.view.document.activeElement === editor.view.dom : true)) {
            const { from, to } = editor.state.selection;
            if (from === to) {
              if (config.selectParentNodeOnToolbarClick) {
                editor.commands.selectParentNode();
              } else {
                if (config.enableImageGeneration) {
                  toggleAiFlowSelectionModal(ToolbarType.FORMATTING)(
                    editor,
                    modalService,
                    target
                  );
                  return false;
                }
                toggleAiModal(ToolbarType.FORMATTING)(editor, modalService);
                return false;
              }
            }
            toggleToolbarModal(ToolbarType.FORMATTING)(editor, modalService, target);
          } else {
            if (config.enableImageGeneration) {
              toggleAiFlowSelectionModal(ToolbarType.FORMATTING)(editor, modalService, target);
              return false;
            }
            toggleAiModal(ToolbarType.FORMATTING)(editor, modalService);
          }
          return false;
        }
      }
    ],
    floatingToolbarButton: {
      Component: ({ position, className }) => /* @__PURE__ */ React.createElement(
        FloatingToolbarButton,
        {
          toggleToolbarModal: toggleToolbarModal(ToolbarType.SIDE, "exclusive"),
          toggleAiModal: toggleAiModal(ToolbarType.SIDE),
          position,
          className,
          checkContextualMode
        }
      ),
      priority: 1,
      isVisible: checkContextualMode
    },
    getQuickActions: ({ pluginServices }) => pluginServices?.context.isMobile ? [] : [
      {
        id: "writeWithAi",
        title: "QuickActionsPlugin_ActionTitle_WriteWithAI",
        icon: SparklesSmall,
        section: quickActionsModalSections.AI,
        tags: ["generate text", "content", "write", "writer", "automated"],
        command: ({ modalService, editor }) => {
          const { $anchor } = editor.view.state.selection;
          const range = $anchor.blockRange();
          if (range) {
            const selectedText = TextSelection.create(
              editor.view.state.doc,
              range?.start + 1,
              range?.end - 1
            );
            editor.view.dispatch(editor.view.state.tr.setSelection(selectedText));
          }
          modalService.togglePluginPanel({
            Component: AiContentModal,
            id: AI_MODAL_ID,
            componentProps: {
              closeModal: () => modalService.closeModal(AI_MODAL_ID),
              openDiscardModal: (referenceElement) => openDiscardModal(modalService, referenceElement),
              config,
              initialPromptOptions: void 0
            },
            positioning: {
              referenceElement: getFakeReferenceElement(editor),
              placement: "right-start"
            },
            onClickOutside: () => {
            },
            isMobile: false
          });
        }
      },
      ...config.enableImageGeneration ? [
        {
          id: "createImageWithAi",
          title: "QuickActionsPlugin_ActionTitle_CreateImageWithAI",
          icon: SparklesSmall,
          section: quickActionsModalSections.AI,
          tags: [
            "generate image",
            "AI art",
            "AI generated image",
            "create art",
            "AI design",
            "digital art",
            "image generator"
          ],
          command: ({ modalService, editor }) => {
            const { $anchor } = editor.view.state.selection;
            const range = $anchor.blockRange();
            if (range) {
              const selectedText = TextSelection.create(
                editor.view.state.doc,
                range?.start + 1,
                range?.end - 1
              );
              editor.view.dispatch(editor.view.state.tr.setSelection(selectedText));
            }
            modalService.togglePluginPanel({
              Component: AiImageModal,
              id: AI_IMAGE_MODAL_ID,
              componentProps: {
                closeModal: () => modalService.closeModal(AI_IMAGE_MODAL_ID),
                openDiscardModal: (referenceElement) => openDiscardModal(modalService, referenceElement),
                config,
                insertActions: "both",
                convertSelectionToPrompt: true
              },
              positioning: {
                referenceElement: getFakeReferenceElement(editor),
                placement: "right-start"
              },
              onClickOutside: () => {
              },
              isMobile: false
            });
          }
        }
      ] : []
    ],
    exports: {
      aiIntegrations: {
        image: {
          captionTrigger: config.enableImageCaptionExport ? createCaptionTrigger(config.appDefId ?? "", openDiscardModal) : void 0,
          altTextInput: config.enableImageAltTextExport ? createAltTextInput(config) : void 0
        }
      },
      ...config.enableImageGeneration ? {
        modals: {
          AI_IMAGE: (editor, services) => toggleAiImageModal("EXTERNAL")(editor, services.modals)
        }
      } : {}
    }
  };
};
const getFakeReferenceElement = (editor) => {
  const { view } = editor;
  const { from, to } = view.state.selection;
  return {
    getBoundingClientRect: () => posToDOMRect(view, from, to),
    focus: () => view.focus()
  };
};
const posToDOMRect = (view, from, to) => {
  const editorRect = view.dom.getBoundingClientRect();
  const minPos = 0;
  const maxPos = view.state.doc.content.size;
  const resolvedFrom = minMax(from, minPos, maxPos);
  const resolvedEnd = minMax(to, minPos, maxPos);
  const start = view.coordsAtPos(resolvedFrom);
  const end = view.coordsAtPos(resolvedEnd, -1);
  const top = Math.min(start.top, end.top);
  const bottom = Math.max(start.bottom, end.bottom);
  const left = editorRect.left;
  const right = editorRect.right;
  const width = right - left;
  const height = bottom - top;
  const x = left;
  const y = top;
  const data = {
    top,
    bottom,
    left,
    right,
    width,
    height,
    x,
    y
  };
  return {
    ...data,
    toJSON: () => data
  };
};
export {
  pluginAi
};
//# sourceMappingURL=editor.js.map
