"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 create_text_alignment_button_exports = {};
__export(create_text_alignment_button_exports, {
  createTextAlignmentButton: () => createTextAlignmentButton
});
module.exports = __toCommonJS(create_text_alignment_button_exports);
var import_react = __toESM(require("react"));
var import_consts = require("./../../ricos-common-plugins/text-align/dropdown/consts.js");
var import_text_alignment_dropdown = __toESM(require("./../../ricos-common-plugins/text-align/dropdown/text-alignment-dropdown.js"));
var import_get_enum_by_style = require("./../../ricos-common-plugins/text-align/get-enum-by-style.js");
var import_ricos_context = require("./../../ricos-context/index.js");
var import_modal_service_provider = require("./../../ricos-modals/modal-service-provider.js");
var import_v1 = require("./../../ricos-schema/legacy/wix/rich_content/v1/index.js");
var import_create_plugin_toolbar_button = require("./../../_shared/create-plugin-toolbar-button.js");
var import_dropdown_button = require("./../../_shared/dropdown-button.js");
var import_pm_node_types = require("./../../_shared/pm-node-types.js");
var import_core = require("./../../tiptap/core/index.js");
var import_state = require("./../../tiptap/pm/state.js");
var import_data_hooks = require("../data-hooks.js");
var import_cell_position = require("../utils/cell-position.js");
var import_resolvers = require("./resolvers.js");
const CIRCLE_SIDE_TO_ALIGNMENT = {
  left: "right",
  right: "left",
  bottom: "center"
};
const SMART_BLOCK_TEXT_ALIGNMENT_MODAL_ID = "smart-block-text-alignment-modal";
const createTextAlignmentButton = ({ services }) => (0, import_create_plugin_toolbar_button.createPluginToolbarButton)({
  id: "smartBlockTextAlignment",
  type: "dropdown",
  tooltip: "AlignTextDropdownButton_Tooltip",
  getIcon: ({ attributes }) => {
    const alignment = attributes?.selectedAlignment || "left";
    return import_consts.ALIGNMENT_BUTTON_CONFIGS[alignment]?.icon;
  },
  dataHook: import_data_hooks.DATA_HOOKS.TEXT_ALIGN_DROPDOWN_BUTTON,
  attributes: {
    visible: import_resolvers.isCellOrLayoutSelected,
    selectedAlignment: (_, __, editor) => {
      const scope = resolveAlignmentScope(editor);
      if (!scope) {
        return "left";
      }
      const fallback = editor ? getCircleCellFallbackAlignment(editor, scope) : "left";
      return getScopedAlignment(scope.targetNode, fallback);
    }
  },
  renderer: (toolbarItem) => /* @__PURE__ */ import_react.default.createElement(SmartBlockTextAlignmentButton, { toolbarItem }),
  // Cast so `getComponentProps` is typed to return `options` (the shape the wixel
  // alignment branch in asset-header reads — matches DIVIDER.alignment). The `command`
  // below converts `options` → `dropdownOptions` before handing them to the actual
  // TextAlignmentDropdown component for the ricos-native modal.
  Component: import_text_alignment_dropdown.default,
  command: (props) => {
    const {
      modals,
      referenceElement,
      getComponentProps,
      tiptapEditor,
      attributes,
      publicCommands
    } = props;
    const componentProps = getComponentProps?.({
      tiptapEditor,
      attributes,
      publicCommands,
      t: services.t,
      modals,
      languageDir: services.context.languageDir
    });
    if (!componentProps) {
      return;
    }
    const { options, ...rest } = componentProps;
    modals.togglePluginPanel({
      id: SMART_BLOCK_TEXT_ALIGNMENT_MODAL_ID,
      Component: import_text_alignment_dropdown.default,
      componentProps: {
        ...rest,
        dropdownOptions: options.map(({ id, dataHook, label, icon, iconMobile }) => ({
          id,
          dataHook,
          label,
          icon,
          iconMobile
        }))
      },
      isMobile: services.context.isMobile,
      positioning: { referenceElement, placement: "bottom" }
    });
  },
  getComponentProps: ({ tiptapEditor, attributes, t, modals }) => {
    const scope = resolveAlignmentScope(tiptapEditor);
    return {
      options: Object.values(import_consts.ALIGNMENT_BUTTON_CONFIGS).map((item) => ({
        type: "button",
        id: item.commandKey,
        dataHook: item.dataHook,
        label: t(item.text),
        icon: item.icon,
        iconMobile: item.iconMobile
      })),
      onSelect: (alignment) => {
        if (!scope) {
          return;
        }
        applyAlignmentInScope(scope, alignment, tiptapEditor);
      },
      selectedId: attributes?.selectedAlignment || "left",
      closeModal: () => modals.closeModal(SMART_BLOCK_TEXT_ALIGNMENT_MODAL_ID)
    };
  }
});
const ALIGNABLE_NODE_TYPES = /* @__PURE__ */ new Set([
  import_pm_node_types.PmNodeType.PARAGRAPH,
  import_pm_node_types.PmNodeType.HEADING,
  import_pm_node_types.PmNodeType.LIST_ITEM,
  import_pm_node_types.PmNodeType.CODE_BLOCK,
  import_pm_node_types.PmNodeType.BLOCKQUOTE,
  import_pm_node_types.PmNodeType.CAPTION
]);
const resolveAlignmentScope = (editor) => {
  if (!editor?.state) {
    return null;
  }
  const { selection, doc } = editor.state;
  if (selection instanceof import_state.NodeSelection && selection.node?.type?.name === import_pm_node_types.PmNodeType.SMART_BLOCK_CELL) {
    return {
      type: "cell",
      selectionPos: selection.from,
      targetPos: selection.from,
      targetNode: selection.node
    };
  }
  if (selection instanceof import_state.NodeSelection && selection.node?.type?.name === import_pm_node_types.PmNodeType.SMART_BLOCK) {
    return {
      type: "block",
      selectionPos: selection.from,
      targetPos: selection.from,
      targetNode: selection.node
    };
  }
  const smartBlock = (0, import_core.findParentNodeClosestToPos)(
    doc.resolve(selection.from),
    (node) => node.type.name === import_pm_node_types.PmNodeType.SMART_BLOCK
  );
  if (!smartBlock) {
    return null;
  }
  return {
    type: "block",
    selectionPos: selection.from,
    targetPos: smartBlock.pos,
    targetNode: smartBlock.node
  };
};
const applyAlignmentInScope = (scope, alignment, editor) => {
  const textAlignment = (0, import_get_enum_by_style.getEnumByStyle)(alignment, import_v1.TextStyle_TextAlignment.UNRECOGNIZED);
  if (textAlignment === import_v1.TextStyle_TextAlignment.UNRECOGNIZED) {
    return false;
  }
  return editor.chain().focus(void 0, { scrollIntoView: false }).command(({ tr }) => {
    scope.targetNode.descendants((child, pos) => {
      if (!ALIGNABLE_NODE_TYPES.has(child.type.name)) {
        return true;
      }
      tr.setNodeMarkup(scope.targetPos + pos + 1, void 0, {
        ...child.attrs,
        textStyle: {
          ...child.attrs.textStyle ?? {},
          textAlignment
        }
      });
      return true;
    });
    if (scope.type === "cell") {
      tr.setSelection(import_state.NodeSelection.create(tr.doc, scope.selectionPos));
    } else {
      tr.setSelection(import_state.TextSelection.near(tr.doc.resolve(scope.selectionPos)));
    }
    return true;
  }).run();
};
const getNormalizedAlignment = (alignment, fallback) => {
  if (!alignment) {
    return fallback;
  }
  const normalizedAlignment = alignment.toLowerCase();
  return normalizedAlignment === "auto" ? fallback : normalizedAlignment;
};
const getScopedAlignment = (node, fallback = "left") => {
  let scopedAlignment = fallback;
  node.descendants((child) => {
    if (child.type.name !== import_pm_node_types.PmNodeType.PARAGRAPH && child.type.name !== import_pm_node_types.PmNodeType.HEADING) {
      return true;
    }
    scopedAlignment = getNormalizedAlignment(child.attrs.textStyle?.textAlignment, fallback);
    return false;
  });
  return scopedAlignment;
};
const getCircleCellFallbackAlignment = (editor, scope) => {
  if (scope.type !== "cell") {
    return "left";
  }
  const $pos = editor.state.doc.resolve(scope.targetPos);
  const parent = $pos.parent;
  if (parent.type.name !== import_pm_node_types.PmNodeType.SMART_BLOCK || parent.attrs.type !== "CIRCLE") {
    return "left";
  }
  const cellIndex = $pos.index();
  const totalCells = parent.childCount;
  return CIRCLE_SIDE_TO_ALIGNMENT[(0, import_cell_position.getCircleCellStyle)(cellIndex, totalCells).side];
};
const SmartBlockTextAlignmentButton = ({
  toolbarItem
}) => {
  const isModalOpen = (0, import_modal_service_provider.useModalState)((0, import_modal_service_provider.getIsModalOpen)(SMART_BLOCK_TEXT_ALIGNMENT_MODAL_ID));
  const [referenceElement, setReferenceElement] = (0, import_react.useState)(null);
  const { t } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  return /* @__PURE__ */ import_react.default.createElement(
    import_dropdown_button.DropdownButton,
    {
      ref: setReferenceElement,
      active: isModalOpen,
      tooltip: t("AlignTextDropdownButton_Tooltip"),
      onClick: () => toolbarItem.commands?.click({ referenceElement }),
      icon: import_consts.ALIGNMENT_BUTTON_CONFIGS[toolbarItem.attributes.selectedAlignment].icon,
      dataHook: import_data_hooks.DATA_HOOKS.TEXT_ALIGN_DROPDOWN_BUTTON,
      tabIndex: toolbarItem.presentation.tabIndex
    }
  );
};
//# sourceMappingURL=create-text-alignment-button.js.map
