import lodash from "lodash";
import { TIPTAP_CARD_TYPE } from "./../ricos-content/index.js";
import { Node_Type } from "./../ricos-schema/legacy/wix/rich_content/v1/index.js";
import { resolveDocumentColorToCss } from "./../_shared/theme-color-token.js";
import { findParentNode } from "./../tiptap/core/index.js";
import { Plugin, PluginKey } from "./../tiptap/pm/state.js";
import { gradientToCss } from "../_shared/gradient-to-css.js";
import { CardSettings } from "./card-settings/card-settings.js";
import { CARD_SETTINGS_MODAL_ID } from "./card-settings/data-hooks.js";
import { CARD_DEFAULTS } from "./shared-with-viewer.js";
const extractCardsFromContent = (content, activePageFormat) => {
  if (!content?.nodes) {
    return [];
  }
  return content.nodes.filter((node) => node.type === Node_Type.CARD).map((node, index) => ({
    id: node.id ?? `card-${index}`,
    index,
    content: {
      nodes: [node],
      documentStyle: content.documentStyle
    },
    width: activePageFormat?.width ?? 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" ? resolveDocumentColorToCss(node.cardData.background.color) : node.cardData?.background?.type === "GRADIENT" && node.cardData.background.gradient ? gradientToCss(node.cardData.background.gradient) : void 0
  }));
};
const getSelectedCardIndexFromEditor = (editor) => {
  const cardNode = findParentNode((node) => node.type.name === 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 === 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[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: CARD_SETTINGS_MODAL_ID,
        Component: CardSettings,
        componentProps: {
          nodeId: node.attrs.id,
          referenceElement
        },
        positioning: {
          referenceElement,
          placement: "right-start"
        },
        onClickOutside: {
          on: "pointerup",
          handler: lodash.noop
        },
        isMobile: !!services.editorProps.isMobile
      });
    }
  };
  return new Plugin({
    key: new PluginKey("cards-api"),
    view: () => {
      getCardsApi(api);
      return {
        destroy: () => {
          for (const { handler } of selectionListeners) {
            editor.off("selectionUpdate", handler);
          }
          selectionListeners.length = 0;
        }
      };
    }
  });
};
export {
  createCardsApiPlugin
};
//# sourceMappingURL=cards-api-plugin.js.map
