"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 card_normalizing_exports = {};
__export(card_normalizing_exports, {
  createCardNormalizingTransactionPlugin: () => createCardNormalizingTransactionPlugin
});
module.exports = __toCommonJS(card_normalizing_exports);
var import_ricos_content = require("./../ricos-content/index.js");
var import_state = require("./../tiptap/pm/state.js");
var import_transform = require("./../tiptap/pm/transform.js");
var import_shared_with_viewer = require("./shared-with-viewer.js");
const buildCardWrappingTr = (state) => {
  const rangesToWrap = [];
  let rangeStart = null;
  let rangeEnd = null;
  state.doc.forEach((node, pos) => {
    if (node.type.name !== import_ricos_content.TIPTAP_CARD_TYPE) {
      if (rangeStart === null) {
        rangeStart = pos;
      }
      rangeEnd = pos + node.nodeSize;
    } else if (rangeStart !== null && rangeEnd !== null) {
      rangesToWrap.push({ from: rangeStart, to: rangeEnd });
      rangeStart = null;
      rangeEnd = null;
    }
  });
  if (rangeStart !== null && rangeEnd !== null) {
    rangesToWrap.push({ from: rangeStart, to: rangeEnd });
  }
  if (rangesToWrap.length === 0) {
    return null;
  }
  const tr = state.tr;
  for (let i = rangesToWrap.length - 1; i >= 0; i--) {
    const { from, to } = rangesToWrap[i];
    const $from = tr.doc.resolve(from);
    const $to = tr.doc.resolve(to);
    const nodeRange = $from.blockRange($to);
    const wrapping = nodeRange && (0, import_transform.findWrapping)(nodeRange, state.schema.nodes[import_ricos_content.TIPTAP_CARD_TYPE], {
      width: import_shared_with_viewer.CARD_DEFAULTS.width,
      height: import_shared_with_viewer.CARD_DEFAULTS.height
    });
    if (wrapping) {
      tr.wrap(nodeRange, wrapping);
    }
  }
  return tr;
};
const buildStaleWrapperCleanupTr = (state) => {
  const toDelete = [];
  state.doc.descendants((node, pos) => {
    if (node.type.name !== import_ricos_content.TIPTAP_CARD_TYPE) {
      return true;
    }
    node.forEach((child, childOffset) => {
      const isHeader = child.type.name === import_ricos_content.TIPTAP_CARD_HEADER_TYPE;
      const isFooter = child.type.name === import_ricos_content.TIPTAP_CARD_FOOTER_TYPE;
      if (!isHeader && !isFooter) {
        return;
      }
      const expectedPosition = isHeader ? "TOP" : "BOTTOM";
      const layoutChild = child.firstChild;
      const banner = layoutChild?.attrs?.banner;
      const hasBanner = layoutChild?.type.name === import_ricos_content.TIPTAP_LAYOUT_TYPE && banner !== null && (banner.position === expectedPosition || isHeader && !banner.position);
      if (!hasBanner) {
        const wrapperStart = pos + 1 + childOffset;
        toDelete.push({ from: wrapperStart, to: wrapperStart + child.nodeSize });
      }
    });
    return false;
  });
  if (toDelete.length === 0) {
    return null;
  }
  const tr = state.tr;
  for (let i = toDelete.length - 1; i >= 0; i--) {
    tr.delete(toDelete[i].from, toDelete[i].to);
  }
  return tr;
};
const createCardNormalizingTransactionPlugin = () => {
  return new import_state.Plugin({
    key: new import_state.PluginKey("normalize-card"),
    appendTransaction: (_, oldState, newState) => {
      if (newState.doc.eq(oldState.doc)) {
        return;
      }
      const cleanupTr = buildStaleWrapperCleanupTr(newState);
      if (cleanupTr) {
        return cleanupTr;
      }
      return buildCardWrappingTr(newState);
    },
    // The editor's initial doc may already contain unwrapped top-level nodes
    // (e.g., a paragraph + image that the converter emits without CARD).
    // `appendTransaction` only fires for *user-driven* transactions, so a
    // toolbar action triggered before any keystroke would see an unwrapped
    // doc — `findParentCardId` returns undefined and the action runs at
    // doc-level instead of inside the card. Dispatch the wrap on mount so
    // every code path observes the normalized shape.
    view(editorView) {
      const tr = buildCardWrappingTr(editorView.state);
      if (tr) {
        editorView.dispatch(tr);
      }
      return {};
    }
  });
};
//# sourceMappingURL=card-normalizing.js.map
