import { Edit } from "@wix/wix-ui-icons-common";
import lodash from "lodash";
import React, { useContext } from "react";
import {
  TIPTAP_CARD_FOOTER_TYPE,
  TIPTAP_CARD_HEADER_TYPE,
  TIPTAP_FIGURE_TYPE,
  TIPTAP_LAYOUT_CELL_TYPE,
  TIPTAP_LAYOUT_TYPE,
  generateId
} from "./../ricos-content/index.js";
import { RicosContext } from "./../ricos-context/index.js";
import { Node_Type } from "./../ricos-schema/legacy/wix/rich_content/v1/index.js";
import { TRANSPARENT_HEX_COLOR } from "./../_shared/colors.js";
import {
  PLUGIN_TOOLBAR_SET_AS_FOOTER_BUTTON,
  PLUGIN_TOOLBAR_SET_AS_HEADER_BUTTON
} from "./../_shared/data-hooks.js";
import { BannerIcon } from "./../_shared/icons/banner-icon.js";
import { FooterIcon } from "./../_shared/icons/footer-icon.js";
import { createDeleteButton } from "./../_shared/plugin-toolbar/create-delete-button.js";
import { createLinkButton } from "./../_shared/plugin-toolbar/create-link-button.js";
import { createNodeAlignmentButton } from "./../_shared/plugin-toolbar/create-node-alignment-button.js";
import { createReplaceButton } from "./../_shared/plugin-toolbar/create-replace-button.js";
import { createSettingsButton } from "./../_shared/plugin-toolbar/create-settings-button.js";
import { createNodeSizeButton } from "./../_shared/plugin-toolbar/node-size-button/create-node-size-button.js";
import { createSeparator } from "./../_shared/plugin-toolbar/separator/create-separator.js";
import { canSetAsBanner } from "./../_shared/resolvers/can-set-as-banner.js";
import { canSetAsFooter } from "./../_shared/resolvers/can-set-as-footer.js";
import { getNodeInSelection } from "./../_shared/resolvers/get-node-in-selection.js";
import { ToolbarButton as ToolbarButtonComponent } from "./../_shared/toolbar-button/toolbar-button.js";
import { FLOATING_PLUGIN_TOOLBAR } from "./../toolbars-v3/index.js";
import { findNodeById } from "./../tiptap-editor/helpers/index.js";
import { LAYOUT_DEFAULTS } from "../ricos-common-plugins/layout/shared-with-viewer.js";
import {
  DEFAULT_BANNER_VERTICAL_SPACING,
  findParentCardId,
  getImageUrl
} from "../ricos-common-plugins/layout/shared.js";
import {
  IMAGE_BUTTONS,
  IMAGE_EDITOR_MODAL_ID,
  IMAGE_SETTINGS_MODAL_ID,
  PLUGIN_TOOLBAR_BUTTON_ID_IMAGE_EDITOR,
  PLUGIN_TOOLBAR_BUTTON_ID_SET_AS_BANNER,
  PLUGIN_TOOLBAR_BUTTON_ID_SET_AS_FOOTER
} from "./consts.js";
import { PLUGIN_TOOLBAR_IMAGE_EDITOR_BUTTON } from "./data-hooks.js";
import { handleImageUpload } from "./handle-image-upload.js";
import { ImageEditorModal } from "./image-editor-modal/image-editor-modal.js";
import { Settings } from "./settings/settings.js";
import { ImageEditorButton } from "./toolbar/image-editor-button.js";
const createImageBannerLayoutContent = (position, backdropImage) => ({
  type: TIPTAP_LAYOUT_TYPE,
  attrs: {
    containerData: {},
    gap: LAYOUT_DEFAULTS.gap,
    cellPadding: [...LAYOUT_DEFAULTS.cellPadding],
    responsivenessBehaviour: LAYOUT_DEFAULTS.responsivenessBehaviour,
    responsivenessBreakpoint: LAYOUT_DEFAULTS.responsivenessBreakpoint,
    designTarget: LAYOUT_DEFAULTS.designTarget,
    id: generateId(),
    banner: { position, origin: "IMAGE" },
    backdropImage,
    backdropPaddingTop: DEFAULT_BANNER_VERTICAL_SPACING,
    backdropPaddingBottom: DEFAULT_BANNER_VERTICAL_SPACING,
    backgroundColor: TRANSPARENT_HEX_COLOR,
    backdropColor: TRANSPARENT_HEX_COLOR
  },
  content: [
    {
      type: TIPTAP_LAYOUT_CELL_TYPE,
      attrs: {
        id: generateId(),
        colSpan: 12
      },
      content: [
        {
          type: Node_Type.PARAGRAPH,
          attrs: {
            id: generateId(),
            indentation: null,
            level: null,
            textStyle: null,
            style: null
          },
          content: []
        }
      ]
    }
  ]
});
const replaceFigureWithBannerLayout = ({
  tiptapEditor,
  figureId,
  cardId,
  position,
  layoutContent
}) => {
  const wrapperType = position === "TOP" ? TIPTAP_CARD_HEADER_TYPE : TIPTAP_CARD_FOOTER_TYPE;
  return tiptapEditor.chain().focus().deleteNode(figureId).command(({ tr, commands }) => {
    if (!cardId) {
      const insertPos = position === "TOP" ? 0 : tr.doc.content.size;
      return commands.insertContentAt(insertPos, layoutContent);
    }
    const card = findNodeById(tr, cardId)[0];
    if (!card) {
      return false;
    }
    let wrapperNode;
    let wrapperPos = -1;
    card.node.forEach((child, offset) => {
      if (child.type.name === wrapperType && !wrapperNode) {
        wrapperNode = child;
        wrapperPos = card.pos + 1 + offset;
      }
    });
    const newWrapper = tr.doc.type.schema.nodeFromJSON({
      type: wrapperType,
      content: [layoutContent]
    });
    if (wrapperNode) {
      tr.replaceWith(wrapperPos, wrapperPos + wrapperNode.nodeSize, newWrapper);
    } else if (position === "TOP") {
      tr.insert(card.pos + 1, newWrapper);
    } else {
      tr.insert(card.pos + card.node.nodeSize - 1, newWrapper);
    }
    return true;
  }).run();
};
const getToolbarButtons = (config, services) => {
  const {
    modals,
    context: { isMobile }
  } = services;
  const settings = createSettingsButton({
    modalId: IMAGE_SETTINGS_MODAL_ID,
    showLabel: true,
    command: ({ referenceElement, attributes: { selectedNode } }) => {
      modals?.togglePluginPanel({
        id: IMAGE_SETTINGS_MODAL_ID,
        Component: Settings,
        componentProps: {
          referenceElement,
          nodeId: selectedNode.attrs.id,
          config
        },
        positioning: {
          referenceElement: referenceElement?.closest(`[data-hook~=${FLOATING_PLUGIN_TOOLBAR}]`) ?? referenceElement,
          placement: "right-start"
        },
        onClickOutside: {
          on: "pointerup",
          handler: lodash.noop
        },
        focusReturnElement: referenceElement,
        isMobile: services.context.isMobile
      });
    }
  });
  const separator = createSeparator({
    visible: getIsEditImageVisibleResolver(config, services, isMobile)
  });
  const nodeSize = createNodeSizeButton({
    services,
    modalId: IMAGE_BUTTONS.size,
    options: ["SMALL", "CONTENT", "FULL_WIDTH", "ORIGINAL"]
  });
  const nodeAlignment = createNodeAlignmentButton({ services, modalId: IMAGE_BUTTONS.alignment });
  const link = createLinkButton(services);
  const replace = createReplaceButton({
    tooltip: "ReplaceImageButton_Tooltip",
    command: ({ attributes: { selectedNode }, publicCommands, referenceElement }) => {
      handleImageUpload({
        services,
        config,
        publicCommands,
        nodeId: selectedNode.attrs.id,
        referenceElement
      });
    }
  });
  const imageEditor = {
    id: PLUGIN_TOOLBAR_BUTTON_ID_IMAGE_EDITOR,
    type: "modal",
    dataHook: PLUGIN_TOOLBAR_IMAGE_EDITOR_BUTTON,
    icon: Edit,
    label: "ImageEditorButton_Label",
    tooltip: "ImageEditorButton_Tooltip",
    command: ({ attributes: { selectedNode } }) => {
      modals?.openModal({
        Component: ImageEditorModal,
        id: IMAGE_EDITOR_MODAL_ID,
        componentProps: {
          nodeId: selectedNode.attrs.id,
          src: selectedNode.attrs?.image?.src?.id,
          config
        },
        positioning: { placement: "top" },
        layout: "fullscreen"
      });
    },
    renderer: (toolbarItem) => /* @__PURE__ */ React.createElement(ImageEditorButton, { toolbarItem }),
    attributes: {
      visible: getIsEditImageVisibleResolver(config, services, isMobile),
      selectedNode: getNodeInSelection
    }
  };
  const deleteButton = createDeleteButton({
    command: (data) => {
      const figures = data.tiptapEditor.$nodes(TIPTAP_FIGURE_TYPE);
      const selectedFigure = figures?.find((f) => {
        return f.firstChild?.node.attrs.id === data.attributes.selectedNode.attrs.id;
      });
      if (selectedFigure) {
        data.tiptapEditor.chain().focus().deleteNode(selectedFigure.attributes.id).run();
      }
    }
  });
  const setAsHeader = {
    id: PLUGIN_TOOLBAR_BUTTON_ID_SET_AS_BANNER,
    type: "toggle",
    icon: BannerIcon,
    tooltip: "Layouts_LayoutSetAsBanner_Tooltip",
    attributes: {
      selectedNode: getNodeInSelection,
      visible: canSetAsBanner
    },
    dataHook: PLUGIN_TOOLBAR_SET_AS_HEADER_BUTTON,
    renderer: (toolbarItem) => /* @__PURE__ */ React.createElement(ImageSetAsHeaderButton, { toolbarItem }),
    command: ({ tiptapEditor, attributes: { selectedNode } }) => {
      const imageData = selectedNode.attrs.image;
      if (!imageData) {
        return;
      }
      const figures = tiptapEditor.$nodes(TIPTAP_FIGURE_TYPE);
      const selectedFigure = figures?.find((f) => {
        return f.firstChild?.node.attrs.id === selectedNode.attrs.id;
      });
      if (!selectedFigure) {
        return;
      }
      const backdropImage = {
        media: {
          src: imageData.src,
          width: imageData.width,
          height: imageData.height
        },
        opacity: 100,
        scaling: "COVER",
        position: "CENTER"
      };
      if (backdropImage.media?.src?.id) {
        const backgroundImage = new Image();
        backgroundImage.src = getImageUrl(backdropImage.media);
      }
      const layoutContent = createImageBannerLayoutContent("TOP", backdropImage);
      const cardId = findParentCardId(tiptapEditor.state.doc, selectedFigure.pos);
      replaceFigureWithBannerLayout({
        tiptapEditor,
        figureId: selectedFigure.attributes.id,
        cardId,
        position: "TOP",
        layoutContent
      });
    }
  };
  const setAsFooter = {
    id: PLUGIN_TOOLBAR_BUTTON_ID_SET_AS_FOOTER,
    type: "toggle",
    icon: FooterIcon,
    tooltip: "Layouts_LayoutSetAsFooter_Tooltip",
    attributes: {
      selectedNode: getNodeInSelection,
      visible: canSetAsFooter
    },
    dataHook: PLUGIN_TOOLBAR_SET_AS_FOOTER_BUTTON,
    renderer: (toolbarItem) => /* @__PURE__ */ React.createElement(ImageSetAsFooterButton, { toolbarItem }),
    command: ({ tiptapEditor, attributes: { selectedNode } }) => {
      const imageData = selectedNode.attrs.image;
      if (!imageData) {
        return;
      }
      const figures = tiptapEditor.$nodes(TIPTAP_FIGURE_TYPE);
      const selectedFigure = figures?.find((f) => {
        return f.firstChild?.node.attrs.id === selectedNode.attrs.id;
      });
      if (!selectedFigure) {
        return;
      }
      const backdropImage = {
        media: {
          src: imageData.src,
          width: imageData.width,
          height: imageData.height
        },
        opacity: 100,
        scaling: "COVER",
        position: "CENTER"
      };
      if (backdropImage.media?.src?.id) {
        const backgroundImage = new Image();
        backgroundImage.src = getImageUrl(backdropImage.media);
      }
      const layoutContent = createImageBannerLayoutContent("BOTTOM", backdropImage);
      const cardId = findParentCardId(tiptapEditor.state.doc, selectedFigure.pos);
      replaceFigureWithBannerLayout({
        tiptapEditor,
        figureId: selectedFigure.attributes.id,
        cardId,
        position: "BOTTOM",
        layoutContent
      });
    }
  };
  if (services.context.environment === "wixel") {
    return [
      settings,
      setAsHeader,
      setAsFooter,
      link,
      replace,
      nodeSize,
      nodeAlignment,
      deleteButton
    ];
  }
  return [
    settings,
    separator,
    setAsHeader,
    setAsFooter,
    nodeSize,
    nodeAlignment,
    link,
    replace,
    imageEditor,
    separator,
    deleteButton
  ];
};
const getIsEditImageVisibleResolver = (config, services, isMobile) => () => config.imageEditor && Boolean(services.wixInstance()?.uid) && !isMobile;
const ImageSetAsHeaderButton = ({ toolbarItem }) => {
  const { t } = useContext(RicosContext) || {};
  const onClick = toolbarItem.commands.click;
  const tooltip = toolbarItem.presentation.tooltip;
  const tooltipKey = typeof tooltip === "function" ? tooltip({ isActive: false }) : tooltip;
  return /* @__PURE__ */ React.createElement(
    ToolbarButtonComponent,
    {
      prefix: BannerIcon,
      onClick: () => onClick?.(),
      dataHook: PLUGIN_TOOLBAR_SET_AS_HEADER_BUTTON,
      label: t(tooltipKey),
      tooltip: t(tooltipKey),
      tabIndex: toolbarItem.presentation.tabIndex
    }
  );
};
const ImageSetAsFooterButton = ({ toolbarItem }) => {
  const { t } = useContext(RicosContext) || {};
  const onClick = toolbarItem.commands.click;
  const tooltip = toolbarItem.presentation.tooltip;
  const tooltipKey = typeof tooltip === "function" ? tooltip({ isActive: false }) : tooltip;
  return /* @__PURE__ */ React.createElement(
    ToolbarButtonComponent,
    {
      prefix: FooterIcon,
      onClick: () => onClick?.(),
      dataHook: PLUGIN_TOOLBAR_SET_AS_FOOTER_BUTTON,
      label: t(tooltipKey),
      tooltip: t(tooltipKey),
      tabIndex: toolbarItem.presentation.tabIndex
    }
  );
};
export {
  getToolbarButtons
};
//# sourceMappingURL=get-toolbar-buttons.js.map
