"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var insert_ai_generated_content_exports = {};
__export(insert_ai_generated_content_exports, {
  insertAiGeneratedContent: () => insertAiGeneratedContent
});
module.exports = __toCommonJS(insert_ai_generated_content_exports);
var import_core = require("./../../tiptap/core/index.js");
var import_state = require("./../../tiptap/pm/state.js");
var import_transform = require("./../../tiptap/pm/transform.js");
const isFragment = (nodeOrFragment) => {
  return nodeOrFragment.toString().startsWith("<");
};
const isReplaceStep = (step) => {
  return step instanceof import_transform.ReplaceStep;
};
const insertAiGeneratedContent = (value, options) => ({ tr, dispatch, editor }) => {
  const position = { from: tr.selection.from, to: tr.selection.to };
  if (options?.position === "before") {
    position.to = position.from;
  }
  if (options?.position === "after") {
    position.from = position.to;
  }
  if (dispatch) {
    insertContent({
      value,
      tr,
      editor,
      position,
      options
    });
    try {
      setSelectionToInsertedContent(tr);
    } catch (e) {
      console.error("Error setting selection to inserted content", e);
    }
  }
  return true;
};
const insertContent = ({
  value,
  tr,
  editor,
  position,
  options
}) => {
  const contentValue = value.plainContent === value.htmlContent ? value.plainContent : value.content;
  const content = (0, import_core.createNodeFromContent)(contentValue, editor.schema);
  if (content.toString() === "<>") {
    return true;
  }
  let { from, to } = position;
  let isOnlyTextContent = true;
  let isOnlyBlockContent = true;
  const nodes = isFragment(content) ? content : [content];
  nodes.forEach((node) => {
    node.check();
    isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false;
    isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false;
  });
  if (from === to && isOnlyBlockContent) {
    const { parent } = tr.doc.resolve(from);
    const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount;
    if (isEmptyTextBlock) {
      from -= 1;
      to += 1;
    }
  }
  const blockRange = tr.selection.$from.blockRange(tr.selection.$to);
  const shouldReplaceBlock = tr.selection.$from === tr.selection.$to && tr.selection.$from.parent.textContent === " ";
  const isStartOfBlock = tr.selection.$from.parentOffset === 0;
  const isEndOfBlock = tr.selection.$to.parentOffset === tr.selection.$to.parent.content.size;
  if (options?.position === "before") {
    const pos = blockRange?.start ?? from;
    const depth = tr.selection.$from.depth;
    const offset = depth - 1;
    tr.insert(Math.max(pos - offset, 0), content);
    return;
  }
  if (options?.position === "after") {
    const pos = blockRange?.end ?? to;
    const depth = tr.selection.$to.depth;
    const offset = !isOnlyTextContent || depth === 1 ? 0 : 1;
    tr.insert(pos + offset, content);
    return;
  }
  if (isOnlyTextContent) {
    if (Array.isArray(contentValue)) {
      tr.insertText(contentValue.map((v) => v.text || "").join(""), from, to);
    } else if (typeof contentValue === "object" && !!value && !!contentValue.text) {
      tr.insertText(contentValue.text, from, to);
    }
    tr.insertText(contentValue, from, to);
    return;
  }
  if (options?.position === "replace") {
    const offsetForInlineReplace = canReplaceInline(tr, content) ? 1 : 0;
    const modifiedFromPosition = Math.max((blockRange?.start ?? from) - 1, 0) + offsetForInlineReplace;
    const modifiedEndPosition = (blockRange?.end ?? to) - offsetForInlineReplace;
    tr.replaceWith(
      shouldReplaceBlock || isStartOfBlock ? modifiedFromPosition : from,
      shouldReplaceBlock || isEndOfBlock ? modifiedEndPosition : to,
      content
    );
    return;
  }
};
const setSelectionToInsertedContent = (tr) => {
  const lastStep = tr.steps[tr.steps.length - 1];
  if (lastStep && isReplaceStep(lastStep)) {
    tr.setSelection(
      import_state.TextSelection.between(
        tr.doc.resolve(lastStep.from),
        tr.doc.resolve(lastStep.slice.content.size + lastStep.from)
      )
    );
  }
};
const canReplaceInline = (tr, content) => {
  try {
    const isNested = tr.selection.$from.depth > 1;
    const typeName = isFragment(content) ? content.child(0).type.name : content.content.child(0).type.name;
    return isNested && typeName === tr.selection.$from.parent.type.name;
  } catch {
    return false;
  }
};
//# sourceMappingURL=insert-ai-generated-content.js.map
