import { flow } from "fp-ts-esm/function";
import { not } from "fp-ts-esm/Predicate";
import { useContext, useMemo } from "react";
import {
  EditorContext,
  PluginsContext,
  PluginsEventsContext,
  RicosContext,
  ShortcutsContext
} from "./../../../ricos-context/index.js";
import { getToolbarSettings, useToolbarSettings } from "./../../../ricos-context/toolbar-context.js";
import { useModalService } from "./../../../ricos-modals/index.js";
import { getButtonsListFromConfig } from "./../../../ricos-plugins/toolbar-utils/get-buttons-list-from-config.js";
import { StylesContext } from "./../../../ricos-styles/index.js";
import { Node_Type } from "./../../../ricos-types/index.js";
import { isAlwaysVisible } from "./../../../_shared/resolvers/is-always-visible.js";
import { defaultToolbarItemsConfigs } from "../../default-toolbar-items-configs.js";
import { mapButtonsFromConfig } from "../../map-buttons-from-config.js";
import { toResolvedAttributes } from "../../to-resolved-attributes.js";
import { toSchemaBasedId } from "../../to-schema-base-id.js";
const useToolbarsItemsConfig = (toolbarType, options) => {
  const { isMobile, t, platform } = useContext(RicosContext);
  const plugins = useContext(PluginsContext);
  const pluginsEvents = useContext(PluginsEventsContext);
  const shortcuts = useContext(ShortcutsContext);
  const modalService = useModalService();
  const toolbarSettingsFunctions = useToolbarSettings(getToolbarSettings(toolbarType));
  const { styles } = useContext(StylesContext);
  const {
    getPublicCommands,
    adapter: { tiptapEditor }
  } = useContext(EditorContext);
  return useMemo(() => {
    return toToolbarItemsConfig({
      buttons: plugins.getTextButtons(),
      toolbarSettingsFunctions,
      toolbarType,
      isMobile,
      publicCommands: getPublicCommands(),
      editor: tiptapEditor,
      modals: modalService,
      pluginsEvents,
      t,
      shortcuts,
      platform,
      options,
      styles
    });
  }, [
    plugins,
    isMobile,
    getPublicCommands,
    tiptapEditor,
    options?.disabled,
    pluginsEvents,
    shortcuts,
    t,
    modalService,
    toolbarType,
    styles
  ]);
};
const toToolbarItemsConfig = ({
  buttons,
  toolbarSettingsFunctions,
  toolbarType,
  publicCommands,
  editor,
  modals,
  pluginsEvents,
  t,
  isMobile,
  shortcuts,
  platform,
  options,
  styles
}) => {
  const toolbarItemConfigs = [
    ...buttons.map(
      (button) => toToolbarItemConfig({
        button,
        publicCommands,
        editor,
        toolbarType,
        modals,
        pluginsEvents,
        t,
        isMobile,
        options,
        tooltipHint: shortcuts.getShortcutDisplayData(
          button.id,
          t,
          platform
        ).tooltipHint,
        styles
      })
    ),
    ...defaultToolbarItemsConfigs
  ];
  const toolbarItemsConfig = toTiptapToolbarItemsConfig(
    toolbarSettingsFunctions,
    toolbarItemConfigs,
    toolbarType,
    isMobile ? "mobile" : "desktop"
  );
  return cleanSeparators(toolbarItemsConfig);
};
const toToolbarItemConfig = ({
  button,
  publicCommands,
  editor,
  toolbarType,
  modals,
  pluginsEvents,
  t,
  isMobile,
  tooltipHint,
  options,
  styles
}) => {
  const attributes = toResolvedAttributes(button, options);
  if (button.type === "separator") {
    return {
      ...button,
      presentation: {
        ...button.presentation || {}
      },
      attributes,
      commands: {}
    };
  }
  return {
    ...button,
    presentation: {
      ...button.presentation || {},
      icon: "getIcon" in button.presentation ? button.presentation.getIcon({ publicCommands, t }) : button.presentation?.icon,
      tooltip: `${t(button.presentation.tooltip)} ${tooltipHint ? `(${tooltipHint})` : ""}`
    },
    attributes,
    commands: {
      click: ({ editorQuery }) => ({ referenceElement, ...rest } = {}) => {
        pluginsEvents.publishers.byTopic("ricos.toolbars.functionality.buttonClick").publish({
          toolbarType,
          buttonId: button.id
        });
        if ("command" in button && button.command) {
          return button.command?.({
            publicCommands,
            modalService: modals,
            editor,
            editorQuery,
            referenceElement,
            isMobile,
            componentProps: "getComponentProps" in button.presentation ? button.presentation.getComponentProps({
              publicCommands,
              t,
              modals,
              styles,
              editor
            }) : void 0
          })(rest);
        }
      }
    }
  };
};
const toTiptapToolbarItemsConfig = (toolbarConfig, tiptapToolbarConfig, toolbarType, buttonsType) => {
  if (!toolbarConfig) {
    console.error(`${toolbarType} doesn't exists`);
    return [];
  }
  const buttonsListFromConfig = getButtonsListFromConfig(toolbarConfig, buttonsType);
  const customButtons = toolbarConfig.getTextPluginButtons?.()?.[buttonsType];
  const buttonsList = buttonsListFromConfig.map(mapButtonsFromConfig);
  const tiptapToolbarItemsConfig = buttonsList.flatMap((button) => {
    const buttonConfig = tiptapToolbarConfig.find((config) => config.id === toSchemaBasedId(button));
    if (buttonConfig) {
      return [buttonConfig];
    }
    if (customButtons?.[button]) {
      return [
        {
          id: button,
          type: "custom",
          attributes: {
            visible: isAlwaysVisible
          },
          commands: {},
          presentation: {
            component: customButtons[button].component,
            dataHook: "customButton"
          }
        }
      ];
    }
    return [];
  });
  const finalTiptapToolbarItemsConfig = cleanTitleIfNeeded(tiptapToolbarItemsConfig);
  return finalTiptapToolbarItemsConfig;
};
const cleanTitleIfNeeded = (tiptapToolbarItemsConfig) => {
  if (tiptapToolbarItemsConfig.some((button) => button.id === `${Node_Type.HEADING}.dropdown`) && tiptapToolbarItemsConfig.some((button) => button.id === `${Node_Type.HEADING}.title`)) {
    return tiptapToolbarItemsConfig.filter((button) => button.id !== `${Node_Type.HEADING}.title`);
  } else {
    return tiptapToolbarItemsConfig;
  }
};
const isSeparator = (button) => button && button.id === "separator";
const notSeparator = not(isSeparator);
const filterAdjacent = (buttons) => buttons.filter(
  (b, i) => notSeparator(buttons[i - 1]) && isSeparator(b) || isSeparator(buttons[i - 1]) && notSeparator(b) || notSeparator(buttons[i - 1]) && notSeparator(b)
);
const filterEdges = (buttons) => buttons.filter(
  (b, i) => !(isSeparator(b) && i === 0) && !(isSeparator(b) && i === buttons.length - 1)
);
const cleanSeparators = flow(filterAdjacent, filterEdges);
export {
  useToolbarsItemsConfig
};
//# sourceMappingURL=use-toolbars-items-config.js.map
