import React, { forwardRef } from "react";
import { Version } from "./../../ricos-content/index.js";
import { isRichContentEqual } from "./../../ricos-content/lib/is-rich-content-equal.js";
import {
  EditorContextConsumer,
  RicosContextConsumer,
  SchemaContextConsumer
} from "./../../ricos-context/index.js";
import { addDevToolsClickListener } from "./../../wix-rich-content-common/index.js";
import {
  RicosDevToolsLazy,
  shouldShowDebuggingInfo
} from "./../../wix-rich-content-common/lib/dev-tools.js";
import {
  EditorEvents,
  EditorEventsContext
} from "./../../editor-common/editor-events-context.js";
import { editorFocusDescriptionId } from "./../../tiptap-editor/components/RicosTiptapEditor/ricos-tiptap-editor.js";
import { RicosTiptapEditor } from "./../../tiptap-editor/index.js";
import { invokeAtomicBlockFocus } from "../../_shared/invoke-atomic-block-focus.js";
import { updatePlaceholder } from "../../tiptap-extensions/placeholder.js";
import editorCss from "../statics/styles/editor-styles-scss.js";
import { publishBI } from "../utils/bi/publish.js";
import { createEditorStyleClasses } from "../utils/create-editor-style-classes.js";
const PUBLISH_DEPRECATION_WARNING_v9 = `Please provide the postId via RicosEditor biSettings prop and use editorEvents.publish() APIs for publishing.
The getContent(postId, isPublishing) API is deprecated and will be removed in ricos v9.0.0`;
class RicosEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      htmlAttributes: {}
    };
    this.isLastChangeEdit = false;
    this.firstEdit = false;
    this.focus = (focusPosition) => {
      this.tiptapAdapter.focus(focusPosition);
    };
    this.blur = () => {
      this.tiptapAdapter.blur();
    };
    this.undo = () => {
      this.tiptapAdapter.tiptapEditor.chain().focus().undo().run();
    };
    this.redo = () => {
      this.tiptapAdapter.tiptapEditor.chain().focus().redo().run();
    };
    this.setContent = (content) => {
      this.props.schema.setContent(content);
    };
    this.openModal = (options) => {
      this.tiptapAdapter.openModal(options);
    };
    this.getContent = async (postId, forPublish) => {
      const content = Promise.resolve(this.props.schema.getContent());
      if (postId && forPublish) {
        console.warn(PUBLISH_DEPRECATION_WARNING_v9);
        const onPublish = this.props.helpers?.onPublish;
        publishBI(content, onPublish, postId);
      }
      return content;
    };
    this.getContentPromise = ({ publishId } = {}) => this.getContent(publishId, !!publishId);
    this.getContentTraits = () => {
      return {
        isEmpty: this.props.schema.isEmpty(),
        isContentChanged: this.props.schema.isContentChanged(),
        isLastChangeEdit: this.isLastChangeEdit
      };
    };
    this.getToolbarProps = (type) => this.tiptapAdapter.getToolbarProps(type);
    this.useToolbarProps = (type) => this.tiptapAdapter.useToolbarProps(type);
    this.useToolbarWixelProps = () => this.tiptapAdapter.useToolbarWixelProps();
    this.useInlineAiState = (invocationId) => this.tiptapAdapter.useInlineAiState(invocationId);
    this.useUndoState = () => this.tiptapAdapter.useUndoState();
    this.getEditorCommands = () => {
      return this.tiptapAdapter.getEditorCommands();
    };
    this.getEditorContainer = () => {
      return this.tiptapAdapter.tiptapEditor.view.dom;
    };
    this.onSelectionUpdate = ({ selectedNodes, content, pmContent }) => {
      const { onAtomicBlockFocus, onChange, onInternalBusyChange } = this.props;
      this.isLastChangeEdit = false;
      invokeAtomicBlockFocus({
        selectedNodes,
        onAtomicBlockFocus
      });
      if (onChange) {
        onChange(content, { source: "selection" });
      }
      if (onInternalBusyChange) {
        onInternalBusyChange(pmContent);
      }
    };
    this.onUpdate = ({ content, pmContent }) => {
      if (!this.firstEdit) {
        this.firstEdit = true;
        this.props.editor.publishFirstEdit();
      }
      this.isLastChangeEdit = true;
      this.props.onChange?.(content, { source: "edit" });
      this.props.onInternalBusyChange?.(pmContent);
    };
    this.onPublish = async () => {
      const content = Promise.resolve(this.props.schema.getContent());
      const onPublish = this.props.helpers?.onPublish;
      publishBI(content, onPublish);
      this.props.editor.publishContentSaved();
      console.log("editor publish callback");
      return {
        type: "EDITOR_PUBLISH",
        data: await content
      };
    };
    this.prePublish = async () => {
      if (this.props.editorEvents) {
        await this.props.editorEvents.dispatch(EditorEvents.PUBLISH);
      }
      const content = this.props.schema.getContent();
      const onPublish = this.props.helpers?.onPublish;
      publishBI(Promise.resolve(content), onPublish);
      this.props.editor.publishContentSaved();
      return content;
    };
    const { isMobile, experiments, theme, ricosContext } = props;
    this.editorStyleClasses = createEditorStyleClasses({
      isMobile,
      experiments,
      editorCss,
      theme
    });
    this.tiptapAdapter = props.editor.adapter;
    const editorDomElement = this.tiptapAdapter.tiptapEditor.view.dom;
    editorDomElement.setAttribute("role", "textbox");
    editorDomElement.setAttribute("aria-multiline", "true");
    editorDomElement.setAttribute(
      "aria-label",
      this.props.htmlAttributes?.ariaLabel || ricosContext.t("Editor_Main_AriaLabel")
    );
    editorDomElement.setAttribute("aria-describedby", editorFocusDescriptionId);
  }
  componentWillReceiveProps(newProps) {
    if (newProps.injectedContent) {
      if (!isRichContentEqual(
        this.props.injectedContent,
        newProps.injectedContent
      )) {
        const content = newProps.injectedContent;
        setTimeout(() => {
          this.props.schema?.setContent(content);
        }, 0);
      }
    }
    if (this.props.placeholder !== newProps.placeholder) {
      updatePlaceholder(this.tiptapAdapter.tiptapEditor, newProps.placeholder || "");
    }
  }
  getHtmlAttributes() {
    return {
      autoCapitalize: this.props.htmlAttributes?.autoCapitalize || "off",
      spellCheck: this.props.htmlAttributes?.spellCheck === false ? "false" : "true",
      autoComplete: this.props.htmlAttributes?.autoComplete || "off",
      autoCorrect: this.props.htmlAttributes?.autoCorrect || "off",
      tabIndex: this.props.htmlAttributes?.tabIndex || 0
    };
  }
  componentDidMount() {
    const htmlAttributes = this.getHtmlAttributes();
    this.setState({
      htmlAttributes
    });
    this.props.editorEvents?.subscribe(EditorEvents.RICOS_PUBLISH, this.onPublish);
    addDevToolsClickListener(
      this.tiptapAdapter.tiptapEditor.view.dom,
      () => this.setState({ debugInvokedWithMouse: true })
    );
    this.props.editor.publishLoaded();
  }
  componentWillUnmount() {
    this.props.editorEvents?.unsubscribe(EditorEvents.RICOS_PUBLISH, this.onPublish);
  }
  render() {
    const { ricosContext, onLoad, schema } = this.props;
    const { htmlAttributes } = this.state;
    const initialContent = schema.getTiptapContent();
    if (!initialContent) {
      return null;
    }
    return /* @__PURE__ */ React.createElement(
      RicosTiptapEditor,
      {
        onLoad,
        editor: this.tiptapAdapter.tiptapEditor,
        content: initialContent,
        t: ricosContext.t,
        onUpdate: this.onUpdate,
        onSelectionUpdate: this.onSelectionUpdate,
        htmlAttributes,
        editorStyleClasses: this.editorStyleClasses,
        devToolsElement: this.state.debugInvokedWithMouse || shouldShowDebuggingInfo(ricosContext.debugMode?.includes("all")) ? /* @__PURE__ */ React.createElement(React.Suspense, null, /* @__PURE__ */ React.createElement(
          RicosDevToolsLazy,
          {
            version: Version.currentVersion,
            mode: "editor",
            contentState: schema.getContent(),
            ricosProps: this.props,
            autoOpen: this.state.debugInvokedWithMouse ?? false,
            editorView: this.tiptapAdapter.tiptapEditor.view
          }
        )) : void 0
      }
    );
  }
}
const RicosEditorWithForwardRef = forwardRef(
  (props, ref) => /* @__PURE__ */ React.createElement(RicosContextConsumer, null, (ricosContext) => /* @__PURE__ */ React.createElement(SchemaContextConsumer, null, (schema) => /* @__PURE__ */ React.createElement(EditorContextConsumer, null, (editor) => /* @__PURE__ */ React.createElement(EditorEventsContext.Consumer, null, (editorEvents) => /* @__PURE__ */ React.createElement(
    RicosEditor,
    {
      ...props,
      ref,
      ricosContext,
      editor,
      schema,
      editorEvents
    }
  )))))
);
export {
  RicosEditorWithForwardRef
};
//# sourceMappingURL=ricos-editor.js.map
