import {
  BorderWidth,
  ChevronLeft,
  ColorBucket,
  Duplicate,
  Objects,
  Replace
} from "@wix/wix-ui-icons-common";
import React from "react";
import { createColorButton } from "./../_shared/plugin-toolbar/create-color-button.js";
import { createDeleteButton } from "./../_shared/plugin-toolbar/create-delete-button.js";
import { createSeparator } from "./../_shared/plugin-toolbar/separator/create-separator.js";
import { PmNodeType } from "./../_shared/pm-node-types.js";
import { getNodeInSelection } from "./../_shared/resolvers/get-node-in-selection.js";
import { NodeSelection } from "./../tiptap/pm/state.js";
import { FLOATING_PLUGIN_TOOLBAR } from "./../toolbars-v3/index.js";
import { SmartBlockShapePickerModal } from "./components/smart-block-shape-picker-modal.js";
import { DATA_HOOKS } from "./data-hooks.js";
import {
  BorderSettings,
  SMART_BLOCK_BORDER_COLOR_PICKER_MODAL_ID,
  SMART_BLOCK_BORDER_SETTINGS_MODAL_ID
} from "./modals/border-settings.js";
import { ColorPicker } from "./modals/color-picker.js";
import { SMART_BLOCK_VARIANT_PICKER_MODAL_ID, VariantPicker } from "./modals/variant-picker.js";
import {
  AddIconButton,
  BorderSettingsButton,
  DuplicateCellButton,
  ReplaceShapeButton,
  SelectBlockButton,
  SmartBlockColorButton,
  SmartBlockShapeColorButton,
  VariantSwitcherButton
} from "./toolbar/buttons/index.js";
import { createAddCellDropdownButton } from "./toolbar/create-add-cell-dropdown-button.js";
import { createColumnSizeButton } from "./toolbar/create-column-size-button.js";
import { createNumberedModeDropdownButton } from "./toolbar/create-numbered-mode-dropdown-button.js";
import { createOrientationDropdownButton } from "./toolbar/create-orientation-dropdown-button.js";
import { createTextAlignmentButton } from "./toolbar/create-text-alignment-button.js";
import {
  canAddCell,
  getParentVariant,
  getSelectedSmartNode,
  getSmartBlockNode,
  isBorderSupported,
  isCellInLabelVariantWithImage,
  isCellInLabelVariantWithoutImage,
  isCellOrLayoutSelected,
  isCellSelected,
  isLayoutInLabelVariantWithImage,
  isLayoutSelected
} from "./toolbar/resolvers.js";
import { getShapeColors } from "./toolbar/shape-colors.js";
import { getCellColorAttr } from "./utils/variant-features.js";
const SMART_BLOCK_COLOR_PICKER_MODAL_ID = "smart-block-color-picker-modal";
const SMART_BLOCK_CELL_SHAPE_COLOR_PICKER_MODAL_ID = "smart-block-cell-shape-color-picker-modal";
const getToolbarButtons = (_config, services) => {
  const { modals } = services;
  const variantSwitcher = {
    id: "smartBlockVariant",
    type: "modal",
    icon: Replace,
    label: "SmartBlock_Toolbar_SwitchLayout_Label",
    tooltip: "SmartBlock_Toolbar_SwitchLayout_Tooltip",
    dataHook: DATA_HOOKS.VARIANT_BUTTON_DATA_HOOK,
    attributes: {
      selectedNode: getSmartBlockNode,
      visible: isLayoutSelected,
      active: () => Boolean(modals.getModal(SMART_BLOCK_VARIANT_PICKER_MODAL_ID))
    },
    command: ({ referenceElement, attributes, tiptapEditor }) => {
      const selectedNode = attributes.selectedNode;
      if (!selectedNode) {
        return;
      }
      modals.togglePluginPanel({
        id: SMART_BLOCK_VARIANT_PICKER_MODAL_ID,
        Component: VariantPicker,
        componentProps: {
          currentType: selectedNode.attrs.type,
          nodeId: selectedNode.attrs.id,
          onSelect: (variant, isPreview) => tiptapEditor.commands.switchSmartBlockVariant(variant, { isPreview })
        },
        isMobile: services.context.isMobile,
        positioning: {
          referenceElement: referenceElement?.closest(`[data-hook~=${FLOATING_PLUGIN_TOOLBAR}]`) ?? referenceElement,
          placement: "right-start"
        }
      });
    },
    renderer: (toolbarItem) => /* @__PURE__ */ React.createElement(VariantSwitcherButton, { toolbarItem })
  };
  const columnSizeDropdown = createColumnSizeButton({ services });
  const addCellDropdown = createAddCellDropdownButton({ services });
  const textAlignmentButton = createTextAlignmentButton({ services });
  const orientationDropdown = createOrientationDropdownButton({ services });
  const numberedModeDropdown = createNumberedModeDropdownButton({ services });
  const colorButton = {
    id: "smartBlockColor",
    type: "modal",
    icon: ColorBucket,
    tooltip: "SmartBlock_Toolbar_Color_Tooltip",
    dataHook: DATA_HOOKS.COLOR_BUTTON,
    attributes: {
      selectedNode: getSelectedSmartNode,
      visible: isCellOrLayoutSelected,
      active: () => Boolean(modals.getModal(SMART_BLOCK_COLOR_PICKER_MODAL_ID)),
      variant: (_, __, editor) => {
        if (!editor?.state) {
          return void 0;
        }
        const sel = editor.state.selection;
        if (sel instanceof NodeSelection && sel.node?.type?.name === PmNodeType.SMART_BLOCK_CELL) {
          return getParentVariant(editor);
        }
        return getSmartBlockNode(_, __, editor)?.attrs?.type;
      },
      colors: (_, __, editor) => {
        if (!editor?.state) {
          return [];
        }
        const sel = editor.state.selection;
        if (sel instanceof NodeSelection && sel.node?.type?.name === PmNodeType.SMART_BLOCK_CELL) {
          const variant = getParentVariant(editor);
          if (!variant) {
            return [];
          }
          const c = sel.node.attrs[getCellColorAttr(variant)];
          return c ? [c] : [];
        }
        const node = getSmartBlockNode(_, __, editor);
        if (!node) {
          return [];
        }
        const colorAttr = getCellColorAttr(node.attrs.type);
        const colors = /* @__PURE__ */ new Set();
        node.forEach((child) => {
          const c = child.attrs[colorAttr];
          if (c) {
            colors.add(c);
          }
        });
        return [...colors];
      }
    },
    command: ({ referenceElement, attributes, tiptapEditor }) => {
      const selectedNode = attributes.selectedNode;
      if (!selectedNode) {
        return;
      }
      const variant = selectedNode.attrs.type;
      if (!variant) {
        return;
      }
      const colorAttr = getCellColorAttr(variant);
      const isCellSelected2 = tiptapEditor.state.selection instanceof NodeSelection && tiptapEditor.state.selection.node?.type?.name === PmNodeType.SMART_BLOCK_CELL;
      const toolbarReferenceElement = referenceElement?.closest(
        `[data-hook~=${FLOATING_PLUGIN_TOOLBAR}]`
      ) ?? referenceElement;
      const cellNodeId = isCellSelected2 ? selectedNode.attrs.id : selectedNode.firstChild?.attrs?.id ?? selectedNode.attrs.id;
      clearPreviewOnModalClose(modals, tiptapEditor, SMART_BLOCK_COLOR_PICKER_MODAL_ID);
      modals.togglePluginPanel({
        id: SMART_BLOCK_COLOR_PICKER_MODAL_ID,
        Component: ColorPicker,
        componentProps: {
          modalId: SMART_BLOCK_COLOR_PICKER_MODAL_ID,
          nodeId: cellNodeId,
          colorAttr,
          variant,
          referenceElement,
          // Preview during drag (no doc change → no undo entries); commit once on release.
          onColorPreview: (color) => {
            tiptapEditor.commands.setSmartBlockColorPreview({ attr: colorAttr, color });
          },
          onColorPreviewEnd: () => {
            tiptapEditor.commands.clearSmartBlockColorPreview();
          },
          onColorSelected: (color) => {
            tiptapEditor.commands.clearSmartBlockColorPreview();
            if (isCellSelected2) {
              tiptapEditor.chain().focus(void 0, { scrollIntoView: false }).command(({ tr }) => {
                const pos = tiptapEditor.state.selection.from;
                tr.setNodeAttribute(pos, colorAttr, color ?? null);
                return true;
              }).run();
              return;
            }
            tiptapEditor.commands.applyDesignToAllCells({ color });
          }
        },
        isMobile: services.context.isMobile,
        positioning: {
          referenceElement: toolbarReferenceElement,
          placement: "bottom"
        }
      });
    },
    renderer: (toolbarItem) => /* @__PURE__ */ React.createElement(SmartBlockColorButton, { toolbarItem })
  };
  const borderButton = {
    id: "smartBlockBorder",
    type: "modal",
    icon: BorderWidth,
    tooltip: "SmartBlock_Toolbar_Borders_Tooltip",
    dataHook: DATA_HOOKS.DESIGN_BUTTON,
    attributes: {
      selectedNode: getSelectedSmartNode,
      visible: isBorderSupported,
      active: () => Boolean(modals.getModal(SMART_BLOCK_BORDER_SETTINGS_MODAL_ID))
    },
    command: ({ referenceElement, attributes, tiptapEditor }) => {
      const sel = tiptapEditor.state.selection;
      const toolbar = referenceElement?.closest(`[data-hook~=${FLOATING_PLUGIN_TOOLBAR}]`) ?? referenceElement;
      const selectedNode = attributes.selectedNode;
      if (!selectedNode) {
        return;
      }
      modals.togglePluginPanel({
        id: SMART_BLOCK_BORDER_SETTINGS_MODAL_ID,
        Component: BorderSettings,
        componentProps: {
          nodeId: sel instanceof NodeSelection && sel.node?.type?.name === PmNodeType.SMART_BLOCK_CELL ? selectedNode.attrs.id : void 0
        },
        isMobile: services.context.isMobile,
        positioning: { referenceElement: toolbar, placement: "bottom" },
        onClickOutside: {
          on: "pointerup",
          handler: (e) => {
            if (modals.isModalOpen(SMART_BLOCK_BORDER_COLOR_PICKER_MODAL_ID)) {
              return;
            }
            if (!referenceElement?.contains?.(e.target)) {
              modals.closeModal(SMART_BLOCK_BORDER_SETTINGS_MODAL_ID);
            }
          }
        }
      });
    },
    renderer: (toolbarItem) => /* @__PURE__ */ React.createElement(BorderSettingsButton, { toolbarItem })
  };
  const blockSeparator = createSeparator();
  const deleteSeparator = createSeparator();
  const deleteButton = createDeleteButton({
    attributes: {
      selectedNode: getSelectedSmartNode,
      visible: isCellOrLayoutSelected
    },
    command: ({ tiptapEditor, attributes }) => {
      const sel = tiptapEditor.state.selection;
      if (sel instanceof NodeSelection && sel.node?.type?.name === PmNodeType.SMART_BLOCK_CELL) {
        const cellId = attributes.selectedNode?.attrs?.id;
        if (cellId) {
          tiptapEditor.commands.removeSmartBlockCell(cellId);
        }
      } else {
        tiptapEditor.chain().focus().deleteNode(attributes.selectedNode?.attrs?.id).run();
      }
    }
  });
  const addIconButton = {
    id: "smartBlockCellAddIcon",
    type: "modal",
    icon: Objects,
    tooltip: "SmartBlock_CellAddShape_Label",
    dataHook: DATA_HOOKS.CELL_ADD_ICON_BUTTON,
    attributes: {
      selectedNode: getNodeInSelection,
      visible: isCellInLabelVariantWithoutImage,
      active: () => Boolean(modals.getModal(DATA_HOOKS.CELL_SHAPE_PICKER))
    },
    command: ({ referenceElement, attributes }) => {
      const cellId = attributes.selectedNode?.attrs?.id;
      if (!cellId) {
        return;
      }
      modals.togglePluginPanel({
        id: DATA_HOOKS.CELL_SHAPE_PICKER,
        Component: SmartBlockShapePickerModal,
        componentProps: { cellId },
        isMobile: services.context.isMobile,
        positioning: {
          referenceElement: referenceElement?.closest(`[data-hook~=${FLOATING_PLUGIN_TOOLBAR}]`) ?? referenceElement,
          placement: "right-start"
        }
      });
    },
    renderer: (toolbarItem) => /* @__PURE__ */ React.createElement(AddIconButton, { toolbarItem })
  };
  const replaceShapeButton = {
    id: "smartBlockCellReplaceShape",
    type: "toggle",
    icon: Replace,
    tooltip: "SmartBlock_CellReplaceShape_Label",
    dataHook: DATA_HOOKS.CELL_REPLACE_SHAPE_BUTTON,
    attributes: {
      selectedNode: getNodeInSelection,
      visible: isCellInLabelVariantWithImage,
      active: () => Boolean(modals.getModal(DATA_HOOKS.CELL_SHAPE_PICKER))
    },
    command: ({ referenceElement, attributes }) => {
      const cellId = attributes.selectedNode?.attrs?.id;
      if (!cellId) {
        return;
      }
      modals.togglePluginPanel({
        id: DATA_HOOKS.CELL_SHAPE_PICKER,
        Component: SmartBlockShapePickerModal,
        componentProps: { cellId },
        isMobile: services.context.isMobile,
        positioning: {
          referenceElement: referenceElement?.closest(`[data-hook~=${FLOATING_PLUGIN_TOOLBAR}]`) ?? referenceElement,
          placement: "right-start"
        }
      });
    },
    renderer: (toolbarItem) => /* @__PURE__ */ React.createElement(ReplaceShapeButton, { toolbarItem })
  };
  const shapeColorButton = {
    ...createColorButton({
      getColors: getShapeColors,
      tooltip: "SmartBlock_ShapeColor_Label",
      modalId: SMART_BLOCK_CELL_SHAPE_COLOR_PICKER_MODAL_ID,
      dataHook: DATA_HOOKS.CELL_SHAPE_COLOR_BUTTON,
      command: ({ referenceElement, attributes: { selectedNode }, tiptapEditor }) => {
        if (!selectedNode) {
          return;
        }
        const variant = selectedNode.attrs.type;
        if (!variant) {
          return;
        }
        const isCellSelection = tiptapEditor.state.selection instanceof NodeSelection && tiptapEditor.state.selection.node?.type?.name === PmNodeType.SMART_BLOCK_CELL;
        const toolbarReferenceElement = referenceElement?.closest(
          `[data-hook~=${FLOATING_PLUGIN_TOOLBAR}]`
        ) ?? referenceElement;
        const cellNodeId = isCellSelection ? selectedNode.attrs.id : selectedNode.firstChild?.attrs?.id ?? selectedNode.attrs.id;
        clearPreviewOnModalClose(
          modals,
          tiptapEditor,
          SMART_BLOCK_CELL_SHAPE_COLOR_PICKER_MODAL_ID
        );
        modals.togglePluginPanel({
          id: SMART_BLOCK_CELL_SHAPE_COLOR_PICKER_MODAL_ID,
          Component: ColorPicker,
          componentProps: {
            modalId: SMART_BLOCK_CELL_SHAPE_COLOR_PICKER_MODAL_ID,
            nodeId: cellNodeId,
            colorAttr: "shapeColor",
            variant,
            referenceElement,
            // Preview during drag (no doc change → no undo entries); commit once on release.
            onColorPreview: (color) => {
              tiptapEditor.commands.setSmartBlockColorPreview({ attr: "shapeColor", color });
            },
            onColorPreviewEnd: () => {
              tiptapEditor.commands.clearSmartBlockColorPreview();
            },
            onColorSelected: (color) => {
              tiptapEditor.commands.clearSmartBlockColorPreview();
              if (isCellSelection) {
                tiptapEditor.chain().focus(void 0, { scrollIntoView: false }).command(({ tr }) => {
                  const pos = tiptapEditor.state.selection.from;
                  tr.setNodeAttribute(pos, "shapeColor", color ?? null);
                  return true;
                }).run();
                return;
              }
              tiptapEditor.commands.setShapeColorForAllCells(color ?? null);
            }
          },
          isMobile: services.context.isMobile,
          positioning: {
            referenceElement: toolbarReferenceElement,
            placement: "bottom"
          }
        });
      }
    }),
    attributes: {
      selectedNode: getSelectedSmartNode,
      active: () => Boolean(modals.getModal(SMART_BLOCK_CELL_SHAPE_COLOR_PICKER_MODAL_ID)),
      visible: (_, __, editor) => isCellInLabelVariantWithImage(_, __, editor) || isLayoutInLabelVariantWithImage(_, __, editor)
    },
    renderer: (toolbarItem) => /* @__PURE__ */ React.createElement(SmartBlockShapeColorButton, { toolbarItem })
  };
  const duplicateButton = {
    id: "smartBlockCellDuplicate",
    type: "toggle",
    icon: Duplicate,
    tooltip: "SmartBlock_CellDuplicate_Tooltip",
    dataHook: DATA_HOOKS.CELL_DUPLICATE_BUTTON,
    attributes: {
      selectedNode: getNodeInSelection,
      visible: isCellSelected,
      canAddCell
    },
    command: ({ tiptapEditor, attributes }) => {
      const cellId = attributes.selectedNode?.attrs?.id;
      if (cellId) {
        tiptapEditor.commands.duplicateSmartBlockCell(cellId);
      }
    },
    renderer: (toolbarItem) => /* @__PURE__ */ React.createElement(DuplicateCellButton, { toolbarItem })
  };
  const selectBlockButton = {
    id: "smartBlockSelectBlock",
    type: "toggle",
    icon: ChevronLeft,
    tooltip: "SmartBlock_SelectBlock_Tooltip",
    dataHook: DATA_HOOKS.SELECT_BLOCK_BUTTON,
    attributes: { visible: isCellSelected },
    command: ({ tiptapEditor }) => {
      tiptapEditor.commands.selectSmartBlock();
    },
    renderer: (toolbarItem) => /* @__PURE__ */ React.createElement(SelectBlockButton, { toolbarItem })
  };
  return [
    selectBlockButton,
    // cell toolbar
    blockSeparator,
    addIconButton,
    // cell toolbar
    replaceShapeButton,
    // cell toolbar
    variantSwitcher,
    blockSeparator,
    columnSizeDropdown,
    textAlignmentButton,
    numberedModeDropdown,
    orientationDropdown,
    addCellDropdown,
    // cell toolbar
    duplicateButton,
    // cell toolbar
    deleteSeparator,
    colorButton,
    shapeColorButton,
    // cell toolbar
    borderButton,
    deleteSeparator,
    deleteButton
  ];
};
const clearPreviewOnModalClose = (modals, tiptapEditor, modalId) => {
  const sub = modals.onModalClosed((modal) => {
    if (modal.id === modalId) {
      tiptapEditor.commands.clearSmartBlockColorPreview();
      sub.cancel();
    }
  });
};
export {
  SMART_BLOCK_CELL_SHAPE_COLOR_PICKER_MODAL_ID,
  SMART_BLOCK_COLOR_PICKER_MODAL_ID,
  getToolbarButtons
};
//# sourceMappingURL=get-toolbar-buttons.js.map
