import React, { useCallback, useContext, useEffect } from "react";
import { useConverters } from "./../pm-converters/context.js";
import { generateId } from "./../ricos-content/index.js";
import { EditorContext, PluginsContext } from "./../ricos-context/index.js";
import { aiRegionPluginKey } from "./../_shared/ai-region-plugin-key.js";
import { getIsEditorEmpty } from "./../_shared/get-is-editor-empty.js";
import { findAdjustedNodeById } from "./../tiptap-editor/helpers/find-adjusted-node-by-id.js";
import { aiSuggestionsPluginKey } from "./plugin-key.js";
import { SuggestionPopover } from "./suggestion-popover.js";
import { AI_SUGGESTIONS } from "./types.js";
import { useSuggestionsRequest } from "./use-suggestions-request.js";
const SuggestionsGlobalComponent = () => {
  const editorPlugins = useContext(PluginsContext);
  const pluginConfig = editorPlugins?.getConfig(AI_SUGGESTIONS);
  const [state, setState] = React.useState(() => ({
    type: "initial",
    visible: !!pluginConfig?.initiallyVisible,
    suggestions: [],
    muted: false
  }));
  const { adapter } = useContext(EditorContext);
  const converters = useConverters();
  const getSuggestions = useSuggestionsRequest(setState);
  const handleContentChange = useCallback(
    ({ transaction: tr }) => {
      const muteSuggestions = !!aiRegionPluginKey.getState(adapter.tiptapEditor.state)?.regionList?.length;
      const action = tr.getMeta(aiSuggestionsPluginKey);
      if (action?.type === "toggle-suggestions") {
        setState((s) => ({ ...s, visible: action.visible }));
        return;
      }
      if (getIsEditorEmpty(tr.doc)) {
        setState((s) => ({
          type: "loaded",
          suggestions: [],
          visible: s.visible,
          muted: muteSuggestions
        }));
        return;
      }
      if ((tr.docChanged || state.type === "initial") && !tr.getMeta("table-node-attrs-updated") && !tr.getMeta("appendedTransaction")?.getMeta("table-node-attrs-updated")) {
        const requestId = generateId();
        getSuggestions(tr, state.suggestions, requestId);
        setState((s) => ({
          ...s,
          type: "loading",
          requestId,
          muted: muteSuggestions
        }));
        return;
      }
      setState((s) => ({
        ...s,
        muted: muteSuggestions
      }));
    },
    [state]
  );
  useEffect(() => {
    adapter.tiptapEditor.on("transaction", handleContentChange);
    return () => {
      adapter.tiptapEditor.off("transaction", handleContentChange);
    };
  }, [handleContentChange]);
  const onConfirm = (suggestion) => {
    const doc = adapter.tiptapEditor.state.doc;
    const fromNode = findAdjustedNodeById(doc, suggestion.range.from);
    const toNode = findAdjustedNodeById(doc, suggestion.range.to);
    const selection = fromNode && toNode ? doc.slice(fromNode.pos, toNode.pos + toNode.node.nodeSize) : null;
    const selectionDoc = selection ? converters.fromPm(selection.toJSON()) : { nodes: [] };
    setState((s) => {
      return {
        ...s,
        suggestions: s.suggestions.map(
          (sug) => sug.id === suggestion.id ? { ...sug, state: "loading" } : sug
        )
      };
    });
    const onDone = ({ type }) => {
      setState((s) => {
        return {
          ...s,
          suggestions: s.suggestions.map(
            (sug) => sug.id === suggestion.id ? { ...sug, state: type === "done" ? "completed" : "loaded" } : sug
          )
        };
      });
    };
    if (pluginConfig.interceptAction) {
      pluginConfig.interceptAction(suggestion.prompt, selectionDoc.nodes);
      onDone({ type: "done" });
      return;
    }
    adapter.tiptapEditor.commands.triggerInlineAi({
      prompt: suggestion.prompt,
      selection: selectionDoc.nodes,
      onDone
    });
  };
  return /* @__PURE__ */ React.createElement(React.Fragment, null, !state.muted && state.visible && state.suggestions.filter((suggestion) => !["completed", "dismissed", "loading"].includes(suggestion.state)).map((suggestion) => /* @__PURE__ */ React.createElement(
    SuggestionPopover,
    {
      key: suggestion.id,
      suggestion,
      onClick: () => onConfirm(suggestion),
      Component: pluginConfig.SuggestionComponent,
      getPortalElement: pluginConfig.getPortalElement
    }
  )));
};
export {
  SuggestionsGlobalComponent
};
//# sourceMappingURL=suggestions-global-component.js.map
