"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var cards_api_plugin_exports = {};
__export(cards_api_plugin_exports, {
  createCardsApiPlugin: () => createCardsApiPlugin
});
module.exports = __toCommonJS(cards_api_plugin_exports);
var import_lodash = __toESM(require("lodash"));
var import_ricos_content = require("./../ricos-content/index.js");
var import_v1 = require("./../ricos-schema/legacy/wix/rich_content/v1/index.js");
var import_theme_color_token = require("./../_shared/theme-color-token.js");
var import_core = require("./../tiptap/core/index.js");
var import_state = require("./../tiptap/pm/state.js");
var import_gradient_to_css = require("../_shared/gradient-to-css.js");
var import_card_settings = require("./card-settings/card-settings.js");
var import_data_hooks = require("./card-settings/data-hooks.js");
var import_shared_with_viewer = require("./shared-with-viewer.js");
const extractCardsFromContent = (content, activePageFormat) => {
  if (!content?.nodes) {
    return [];
  }
  return content.nodes.filter((node) => node.type === import_v1.Node_Type.CARD).map((node, index) => ({
    id: node.id ?? `card-${index}`,
    index,
    content: {
      nodes: [node],
      documentStyle: content.documentStyle
    },
    width: activePageFormat?.width ?? import_shared_with_viewer.CARD_DEFAULTS.width,
    height: activePageFormat?.height,
    backgroundType: node.cardData?.backgroundImage ? "image" : node.cardData?.background?.type === "COLOR" ? "color" : node.cardData?.background?.type === "GRADIENT" ? "gradient" : "none",
    backgroundFill: node.cardData?.background?.type === "COLOR" ? (0, import_theme_color_token.resolveDocumentColorToCss)(node.cardData.background.color) : node.cardData?.background?.type === "GRADIENT" && node.cardData.background.gradient ? (0, import_gradient_to_css.gradientToCss)(node.cardData.background.gradient) : void 0
  }));
};
const getSelectedCardIndexFromEditor = (editor) => {
  const cardNode = (0, import_core.findParentNode)((node) => node.type.name === import_ricos_content.TIPTAP_CARD_TYPE)(
    editor.state.selection
  );
  if (!cardNode) {
    return -1;
  }
  const { doc } = editor.state;
  let index = 0;
  let found = false;
  doc.forEach((node) => {
    if (node === cardNode.node) {
      found = true;
      return false;
    }
    if (!found) {
      index++;
    }
  });
  return index;
};
const findCardAtIndex = (editor, cardIndex) => {
  const { doc } = editor.state;
  let cardCount = 0;
  let targetNode = null;
  let targetPos = null;
  doc.descendants((node, pos) => {
    if (targetPos !== null) {
      return false;
    }
    if (node.type.name === import_ricos_content.TIPTAP_CARD_TYPE) {
      if (cardCount === cardIndex) {
        targetNode = node;
        targetPos = pos;
        return false;
      }
      cardCount++;
    }
    return true;
  });
  if (!targetNode || targetPos === null) {
    return void 0;
  }
  return { node: targetNode, pos: targetPos };
};
const createCardsApiPlugin = ({
  getCardsApi,
  editor,
  services,
  formats
}) => {
  const selectionListeners = [];
  const getStorage = () => editor.storage[import_ricos_content.TIPTAP_CARD_TYPE];
  const api = {
    commands: {
      addCardAfter: (index) => {
        editor.commands.addCardAfter(index);
      },
      duplicateCard: (index) => {
        editor.commands.duplicateCard(index);
      },
      deleteCard: (index) => {
        editor.commands.deleteCard(index);
      },
      moveCard: (fromIndex, toIndex) => {
        editor.commands.moveCard(fromIndex, toIndex);
      },
      selectCard: (index) => {
        editor.commands.selectCard(index);
      },
      insertCard: () => {
        editor.commands.insertCard();
      }
    },
    getSelectedCardIndex: () => getSelectedCardIndexFromEditor(editor),
    getCards: () => {
      const content = services.schema.getContent();
      const storage = getStorage();
      return extractCardsFromContent(content, storage.activePageFormat);
    },
    getEditorContainer: () => editor.view.dom,
    subscribeToSelectionChange: (callback) => {
      const handler = () => {
        callback();
      };
      selectionListeners.push({ callback, handler });
      editor.on("selectionUpdate", handler);
      return () => {
        editor.off("selectionUpdate", handler);
        const i = selectionListeners.findIndex((l) => l.callback === callback);
        if (i !== -1) {
          selectionListeners.splice(i, 1);
        }
      };
    },
    setPageFormat: (pageFormatName) => {
      const matchedPageFormat = formats.find((f) => f.name === pageFormatName);
      if (!matchedPageFormat) {
        return;
      }
      const storage = getStorage();
      storage.activePageFormat = matchedPageFormat;
      storage.onPageFormatChange.forEach((callback) => callback());
    },
    getActivePageFormat: () => {
      const storage = getStorage();
      return storage.activePageFormat?.name;
    },
    openCardSettings: (cardIndex, referenceElement) => {
      const result = findCardAtIndex(editor, cardIndex);
      if (!result) {
        return;
      }
      const { node } = result;
      services.modals?.togglePluginPanel({
        id: import_data_hooks.CARD_SETTINGS_MODAL_ID,
        Component: import_card_settings.CardSettings,
        componentProps: {
          nodeId: node.attrs.id,
          referenceElement
        },
        positioning: {
          referenceElement,
          placement: "right-start"
        },
        onClickOutside: {
          on: "pointerup",
          handler: import_lodash.default.noop
        },
        isMobile: !!services.editorProps.isMobile
      });
    }
  };
  return new import_state.Plugin({
    key: new import_state.PluginKey("cards-api"),
    view: () => {
      getCardsApi(api);
      return {
        destroy: () => {
          for (const { handler } of selectionListeners) {
            editor.off("selectionUpdate", handler);
          }
          selectionListeners.length = 0;
        }
      };
    }
  });
};
//# sourceMappingURL=cards-api-plugin.js.map
