import { Box, Divider, FieldSet, FillPreview, Input, Tabs, Text } from "@wix/design-system";
import { DropdownListSmall, ListSmall } from "@wix/wix-ui-icons-common";
import React, { useContext, useMemo, useState } from "react";
import { ModalServiceContext, RicosContext, ZIndexContext } from "./../../ricos-context/index.js";
import { useBiNext } from "./../../_shared/bi-context-provider/bi-context-provider.js";
import {
  handleColorAdded,
  handleColorDeleted,
  resolveThemeColorsPalette,
  useResolvedCustomColors
} from "./../../_shared/color-manager-utils.js";
import { logInvariant } from "./../../_shared/log-invariant.js";
import { resolveColorToDisplayHex } from "./../../_shared/resolve-color-to-display-hex.js";
import { TogglesWithLabel } from "./../../_shared/toggles-with-label.js";
import { useNodeAttrs } from "./../../_shared/use-node-attrs.js";
import { NewColorPicker } from "./../../ui-components/color-picker/new-color-picker/index.js";
import {
  NumberInputWithLabel,
  Panel,
  PanelHeader,
  SelectWithLabel,
  useClickOutside,
  usePanelContainerElement
} from "./../../ui-components/index.js";
import { TOC_SETTINGS_MODAL } from "../data-hooks.js";
import { TOC_DEFAULTS } from "../defaults.js";
const TOC_COLOR_PICKER_MODAL = "toc-color-picker-modal";
const DEFAULT_FONT_SIZE = 16;
const DEFAULT_ITEM_SPACING = 12;
const listStyleKeys = {
  BULLETED: "TocPlugin_Settings_ListStyle_Bulleted",
  NUMBERED: "TocPlugin_Settings_ListStyle_Numbered",
  LETTERS: "TocPlugin_Settings_ListStyle_Letters",
  ROMAN: "TocPlugin_Settings_ListStyle_Roman",
  PLAIN: "TocPlugin_Settings_ListStyle_Plain",
  ALPHABETICAL_INDEX: "TocPlugin_Settings_ListStyle_AlphabeticalIndex",
  ALPHABETICAL_INDEX_COMPACT: "TocPlugin_Settings_ListStyle_AlphabeticalIndexCompact"
};
const listStyleOptions = Object.keys(listStyleKeys);
const resolveNumberValue = (value, fallback) => {
  const normalizedValue = typeof value === "string" ? Number.parseFloat(value) : value;
  return typeof normalizedValue === "number" && Number.isFinite(normalizedValue) ? normalizedValue : fallback;
};
const resolveDefaultColor = (theme) => theme.customStyles?.toc?.color ?? theme.customStyles?.link?.color ?? (theme.palette && typeof theme.palette === "object" && "actionColor" in theme.palette ? theme.palette.actionColor : void 0) ?? "#162D3D";
const buildIncludedHeadingsRange = (start, end) => {
  const minLevel = Math.min(start, end);
  const maxLevel = Math.max(start, end);
  return Array.from({ length: maxLevel - minLevel + 1 }, (_, index) => minLevel + index);
};
const ColorPicker = ({ modalId, nodeId, referenceElement, defaultColor, onColorSelected }) => {
  const modalService = useContext(ModalServiceContext);
  const { t, theme, colorManager } = useContext(RicosContext);
  const { pmNodeAttrs } = useNodeAttrs(nodeId, "TOC");
  if (!pmNodeAttrs) {
    logInvariant(new Error("Table of Contents: node attrs not found"));
    return null;
  }
  const currentColor = pmNodeAttrs.color ?? defaultColor;
  const themeColors = useMemo(() => resolveThemeColorsPalette(theme), [theme]);
  const customColors = useResolvedCustomColors(colorManager);
  const closeModal = () => modalService.closeModal(modalId);
  const onColorAdded = (color) => {
    handleColorAdded(color, colorManager);
    onColorSelected(color);
  };
  const onColorDeleted = (color) => {
    handleColorDeleted(color, colorManager);
  };
  const onResetColor = () => onColorSelected(void 0);
  return /* @__PURE__ */ React.createElement(
    NewColorPicker,
    {
      themeColors,
      customColors,
      currentColor,
      title: t("ButtonColourModal_Title") || "Color",
      closeModal,
      onColorSelected,
      onColorAdded,
      onColorDeleted,
      onResetColor,
      referenceElement,
      allowTransparent: false,
      logBi: () => {
      }
    }
  );
};
const TocSettingsModal = ({ nodeId }) => {
  const { t, theme, isMobile } = useContext(RicosContext);
  const modalService = useContext(ModalServiceContext) || {};
  const zIndexService = useContext(ZIndexContext);
  const containerEl = usePanelContainerElement();
  const { patchPmNodeAttrs, pmNodeAttrs } = useNodeAttrs(nodeId, "TOC");
  const colorPickerToggleRef = React.useRef(null);
  if (!pmNodeAttrs || !patchPmNodeAttrs) {
    return null;
  }
  const closeModal = () => modalService.closeModal(TOC_SETTINGS_MODAL);
  const includedHeadings = pmNodeAttrs.includedHeadings;
  const defaultColor = resolveDefaultColor(theme);
  const logBi = useBiNext({
    modalId: TOC_SETTINGS_MODAL,
    pluginId: "toc",
    nodeId
  });
  const zIndex = zIndexService.getZIndex("DIALOG");
  const startHeadingLevel = includedHeadings[0] ?? TOC_DEFAULTS.includedHeadings[0];
  const endHeadingLevel = includedHeadings[includedHeadings.length - 1] ?? TOC_DEFAULTS.includedHeadings[TOC_DEFAULTS.includedHeadings.length - 1];
  const currentListStyle = pmNodeAttrs.listStyle ?? "PLAIN";
  const isAlphabeticalListStyle = currentListStyle === "ALPHABETICAL_INDEX" || currentListStyle === "ALPHABETICAL_INDEX_COMPACT";
  const openColorPicker = () => {
    const referenceElement = colorPickerToggleRef.current ?? void 0;
    modalService.togglePluginPanel?.({
      id: TOC_COLOR_PICKER_MODAL,
      Component: ColorPicker,
      componentProps: {
        modalId: TOC_COLOR_PICKER_MODAL,
        nodeId,
        referenceElement,
        defaultColor,
        onColorSelected: (color) => patchPmNodeAttrs({ color })
      },
      isMobile,
      positioning: {
        referenceElement,
        placement: "left"
      },
      type: void 0,
      onClickOutside: {
        on: "pointerup",
        handler: () => void 0
      },
      focusReturnElement: referenceElement ?? void 0
    });
  };
  useClickOutside({
    containerRef: { current: containerEl },
    onClickOutside: () => closeModal(),
    disable: modalService.isModalOpen?.(TOC_COLOR_PICKER_MODAL)
  });
  const [activeTab, setActiveTab] = useState("settings");
  const displayColor = resolveColorToDisplayHex(pmNodeAttrs.color ?? void 0, containerEl) ?? resolveColorToDisplayHex(defaultColor, containerEl);
  return /* @__PURE__ */ React.createElement(Panel, { onCloseButtonClick: closeModal, dataHook: TOC_SETTINGS_MODAL }, /* @__PURE__ */ React.createElement(PanelHeader, { title: t("TocPlugin_Settings_Title") }), /* @__PURE__ */ React.createElement(
    Tabs,
    {
      minWidth: "100%",
      alignment: "center",
      type: "uniformFull",
      size: "small",
      items: [
        { id: "settings", title: t("TocPlugin_Settings_Tab_Settings") },
        { id: "design", title: t("TocPlugin_Settings_Tab_Design") }
      ],
      activeId: activeTab,
      onClick: (value) => setActiveTab(value.id)
    }
  ), /* @__PURE__ */ React.createElement(Box, { direction: "vertical", gap: "SP2", padding: "SP3", overflow: "auto" }, activeTab === "settings" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Text, { size: "small", weight: "bold" }, t("TocPlugin_Settings_HeadingsToInclude")), /* @__PURE__ */ React.createElement(
    SelectWithLabel,
    {
      label: t("TocPlugin_Settings_StartFrom"),
      dataHook: "toc-start-heading-select",
      value: startHeadingLevel,
      options: [1, 2, 3, 4, 5, 6].map((level) => ({
        id: level,
        value: t("TocPlugin_Settings_HeadingLevel", { level })
      })),
      onChange: (value) => {
        const nextStart = Number(value);
        const nextEnd = Math.max(nextStart, endHeadingLevel);
        patchPmNodeAttrs({
          includedHeadings: buildIncludedHeadingsRange(nextStart, nextEnd)
        });
      },
      logBi,
      zIndex
    }
  ), /* @__PURE__ */ React.createElement(
    SelectWithLabel,
    {
      label: t("TocPlugin_Settings_ShowUpTo"),
      dataHook: "toc-end-heading-select",
      value: endHeadingLevel,
      options: [1, 2, 3, 4, 5, 6].map((level) => ({
        id: level,
        value: t("TocPlugin_Settings_HeadingLevel", { level })
      })),
      onChange: (value) => {
        const nextEnd = Number(value);
        const nextStart = Math.min(startHeadingLevel, nextEnd);
        patchPmNodeAttrs({
          includedHeadings: buildIncludedHeadingsRange(nextStart, nextEnd)
        });
      },
      logBi,
      zIndex
    }
  ), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(Text, { size: "small", weight: "bold" }, t("TocPlugin_Settings_ListType")), /* @__PURE__ */ React.createElement(
    SelectWithLabel,
    {
      label: t("TocPlugin_Settings_ListType"),
      dataHook: "toc-list-style-select",
      value: currentListStyle,
      options: listStyleOptions.map((style) => ({
        id: style,
        value: t(listStyleKeys[style])
      })),
      onChange: (value) => patchPmNodeAttrs({ listStyle: value }),
      logBi,
      zIndex
    }
  ), isAlphabeticalListStyle ? null : /* @__PURE__ */ React.createElement(
    TogglesWithLabel,
    {
      label: t("TocPlugin_Settings_Indentation"),
      value: pmNodeAttrs.indentation !== "FLAT" ? "NESTED" : "FLAT",
      options: [
        {
          label: t("TocPlugin_Settings_Indentation_Nested"),
          value: "NESTED",
          icon: /* @__PURE__ */ React.createElement(DropdownListSmall, { height: "100%" }),
          dataHook: "toc-layout-nested"
        },
        {
          label: t("TocPlugin_Settings_Indentation_Flat"),
          value: "FLAT",
          icon: /* @__PURE__ */ React.createElement(ListSmall, { height: "100%" }),
          dataHook: "toc-layout-flat"
        }
      ],
      onChange: (value) => patchPmNodeAttrs({ indentation: value })
    }
  )) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Text, { size: "small", weight: "bold" }, t("TocPlugin_Settings_Appearance")), currentListStyle !== "ALPHABETICAL_INDEX_COMPACT" ? /* @__PURE__ */ React.createElement(
    NumberInputWithLabel,
    {
      label: t("TocPlugin_Settings_GapBetweenItems"),
      dataHook: "toc-item-spacing-input",
      suffix: /* @__PURE__ */ React.createElement(Input.Affix, null, "px"),
      value: pmNodeAttrs.itemSpacing ?? resolveNumberValue(theme.customStyles?.toc?.itemSpacing, DEFAULT_ITEM_SPACING),
      min: 0,
      max: 64,
      onChange: (value) => patchPmNodeAttrs({ itemSpacing: value }),
      logBi,
      zIndex
    }
  ) : null, /* @__PURE__ */ React.createElement(
    NumberInputWithLabel,
    {
      label: t("TocPlugin_Settings_FontSize"),
      dataHook: "toc-font-size-input",
      suffix: /* @__PURE__ */ React.createElement(Input.Affix, null, "px"),
      value: pmNodeAttrs.fontSize ?? resolveNumberValue(theme.customStyles?.toc?.fontSize, DEFAULT_FONT_SIZE),
      min: 8,
      max: 72,
      onChange: (value) => patchPmNodeAttrs({ fontSize: value }),
      logBi,
      zIndex
    }
  ), /* @__PURE__ */ React.createElement(
    FieldSet,
    {
      legend: t("TocPlugin_Settings_Color"),
      legendPlacement: "left",
      columns: "auto 30px",
      alignment: "center"
    },
    /* @__PURE__ */ React.createElement("div", null),
    /* @__PURE__ */ React.createElement(
      FillPreview,
      {
        fill: displayColor,
        onClick: () => openColorPicker(),
        ref: colorPickerToggleRef,
        dataHook: "toc-color-input"
      }
    )
  ))));
};
export {
  TocSettingsModal
};
//# sourceMappingURL=settings-modal.js.map
