"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 border_modal_exports = {};
__export(border_modal_exports, {
  BorderModal: () => BorderModal
});
module.exports = __toCommonJS(border_modal_exports);
var import_design_system = require("@wix/design-system");
var import_lodash = __toESM(require("lodash"));
var import_react = __toESM(require("react"));
var import_ricos_context = require("./../../ricos-context/index.js");
var import_ricos_styles = require("./../../ricos-styles/index.js");
var import_bi_context_provider = require("./../../_shared/bi-context-provider/bi-context-provider.js");
var import_color_manager_utils = require("./../../_shared/color-manager-utils.js");
var import_theme_color_token = require("./../../_shared/theme-color-token.js");
var import_use_node_attrs = require("./../../_shared/use-node-attrs.js");
var import_new_color_picker = require("./../../ui-components/color-picker/new-color-picker/index.js");
var import_ui_components = require("./../../ui-components/index.js");
var import_edge_detection = require("../borders/edge-detection.js");
var import_resolve_cell_borders = require("../borders/resolve-cell-borders.js");
var import_consts = require("../consts.js");
var import_data_hooks = require("../data-hooks.js");
var import_table_query = require("../tiptap/table-query.js");
var import_is_selection_type = require("../tiptap/utilities/is-selection-type.js");
var import_border_scope_selector = require("../toolbar/modals/border-scope-selector.js");
const ALL_SIDES = ["top", "right", "bottom", "left"];
const getSidesForScope = (scope) => {
  switch (scope) {
    case "borders":
    case "outsideBorders":
    case "inner":
      return ALL_SIDES;
    case "innerHorizontal":
      return ["top", "bottom"];
    case "innerVertical":
      return ["left", "right"];
    case "top":
    case "right":
    case "bottom":
    case "left":
      return [scope];
    default:
      return [];
  }
};
const DEFAULT_BORDER_WIDTH = 1;
const BorderModal = ({
  nodeId,
  referenceElement,
  color: _color,
  onColorPreview,
  onColorPreviewEnd,
  onColorCommit,
  borderWidth: _borderWidth = 1,
  onBorderWidthPreview,
  onBorderWidthCommit,
  borderScope = "borders",
  onBorderScopeChange,
  canInnerHorizontal = false,
  canInnerVertical = false
}) => {
  const { t, isMobile, colorManager, theme } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  const modalService = (0, import_react.useContext)(import_ricos_context.ModalServiceContext);
  const zIndexService = (0, import_react.useContext)(import_ricos_context.ZIndexContext);
  const { adapter } = (0, import_react.useContext)(import_ricos_context.EditorContext);
  const zIndex = zIndexService.getZIndex("DIALOG");
  const defaultBorderColor = (0, import_consts.resolveDefaultBorderColor)(
    adapter.tiptapEditor.view.dom
  );
  const logBi = (0, import_bi_context_provider.useBiNext)({
    modalId: import_consts.TABLE_COLOR_PICKER,
    pluginId: "table",
    nodeId
  });
  const { pmNodeAttrs } = (0, import_use_node_attrs.useNodeAttrs)(nodeId, "TABLE_CELL");
  const [localBorderScope, setLocalBorderScope] = (0, import_react.useState)(borderScope);
  const colorPickerRef = (0, import_react.useRef)(null);
  const getCellBorderColor = (side) => {
    if (!pmNodeAttrs) {
      return void 0;
    }
    return pmNodeAttrs.borderColors?.[side];
  };
  const getCellBorderWidth = (side) => {
    if (!pmNodeAttrs) {
      return DEFAULT_BORDER_WIDTH;
    }
    return pmNodeAttrs.borderWidths?.[side] ?? DEFAULT_BORDER_WIDTH;
  };
  const getScopedResolvedBorders = () => {
    const { selection } = adapter.tiptapEditor.state;
    if (!(0, import_is_selection_type.isRicosCellSelection)(selection)) {
      return null;
    }
    const table = import_table_query.TableQuery.of(selection);
    if (!table) {
      return null;
    }
    const tableNode = table.getNode();
    const tableStart = table.getStartPos();
    const tableWidth = table.getWidth();
    const tableHeight = table.getHeight();
    const cellSpacing = tableNode.attrs.tableData?.cellSpacing ?? 0;
    const resolvedBorders2 = (0, import_resolve_cell_borders.resolveCellBordersPm)(tableNode, {
      drawDefaultGrid: true,
      cellSpacing
    });
    const selectedCellIds = /* @__PURE__ */ new Set();
    selection.forEachCell((node) => {
      if (node.attrs.id) {
        selectedCellIds.add(node.attrs.id);
      }
    });
    const tableMap = table.getMap();
    const isCellSelected = (row, col) => {
      if (row < 0 || row >= tableHeight || col < 0 || col >= tableWidth) {
        return false;
      }
      const cellPos = tableMap[row * tableWidth + col];
      const cell = typeof cellPos === "number" ? tableNode.nodeAt(cellPos) : null;
      return cell ? selectedCellIds.has(cell.attrs.id) : false;
    };
    const scopedBorders = [];
    const addBorder = (node, cell, side) => {
      const border = (0, import_resolve_cell_borders.getDisplayedBorderOnSide)(
        resolvedBorders2,
        tableNode,
        node.attrs.id,
        cell,
        side
      );
      scopedBorders.push({
        color: (0, import_consts.resolveDisplayedBorderColor)(border?.color, defaultBorderColor),
        width: border?.width ?? DEFAULT_BORDER_WIDTH
      });
    };
    selection.forEachCell((node, pos) => {
      const cell = table.map.findCell(pos - tableStart);
      const sidesForBorders = () => {
        switch (localBorderScope) {
          case "borders":
            return [...ALL_SIDES];
          case "outsideBorders":
            return ALL_SIDES.filter(
              (side) => (0, import_edge_detection.isCellOuterEdge)(cell, side, tableWidth, tableHeight, isCellSelected)
            );
          case "top":
          case "right":
          case "bottom":
          case "left":
            return (0, import_edge_detection.isCellOuterEdge)(cell, localBorderScope, tableWidth, tableHeight, isCellSelected) ? [localBorderScope] : [];
          case "inner": {
            const sides = [];
            if (cell.row > 0 && isCellSelected(cell.row - 1, cell.col)) {
              sides.push("top");
            }
            if (cell.col > 0 && isCellSelected(cell.row, cell.col - 1)) {
              sides.push("left");
            }
            return sides;
          }
          case "innerHorizontal":
            return cell.row > 0 && isCellSelected(cell.row - 1, cell.col) ? ["top"] : [];
          case "innerVertical":
            return cell.col > 0 && isCellSelected(cell.row, cell.col - 1) ? ["left"] : [];
          default:
            return [];
        }
      };
      for (const side of sidesForBorders()) {
        addBorder(node, cell, side);
      }
    });
    return scopedBorders;
  };
  const getCurrentWidth = (resolvedBorders2) => {
    const allWidths = resolvedBorders2?.map(({ width }) => width) ?? (pmNodeAttrs ? getSidesForScope(localBorderScope).map(getCellBorderWidth) : []);
    if (allWidths.length === 0) {
      return DEFAULT_BORDER_WIDTH;
    }
    const firstWidth = allWidths[0];
    return allWidths.every((w) => w === firstWidth) ? firstWidth : void 0;
  };
  const getAllCurrentColors = (resolvedBorders2) => {
    if (resolvedBorders2) {
      return [...new Set(resolvedBorders2.map(({ color }) => color))];
    }
    if (!pmNodeAttrs) {
      return [];
    }
    const sides = getSidesForScope(localBorderScope);
    return [
      ...new Set(
        sides.map((side) => (0, import_consts.resolveDisplayedBorderColor)(getCellBorderColor(side), defaultBorderColor))
      )
    ];
  };
  const resolvedBorders = getScopedResolvedBorders();
  const currentWidth = getCurrentWidth(resolvedBorders);
  const allCurrentColors = getAllCurrentColors(resolvedBorders);
  const currentColor = allCurrentColors[0] ?? defaultBorderColor;
  const isMixedColor = allCurrentColors.length > 1;
  const themeColors = (0, import_color_manager_utils.resolveThemeColorsPalette)(theme);
  const customColors = (0, import_color_manager_utils.useResolvedCustomColors)(colorManager);
  const containerEl = (0, import_ui_components.usePanelContainerElement)();
  const displayedCurrentColor = (0, import_theme_color_token.resolveDocumentColorToCss)(currentColor) ?? currentColor;
  const displayedAllCurrentColors = allCurrentColors.map((color) => (0, import_theme_color_token.resolveDocumentColorToCss)(color) ?? color).filter((color) => typeof color === "string");
  const closeModal = () => {
    modalService.closeModal(import_consts.TABLE_COLOR_PICKER);
  };
  const handleBorderWidthPreview = (width) => {
    if (width === void 0) {
      return;
    }
    onBorderWidthPreview?.(width);
  };
  const handleBorderWidthCommit = (finalValue, originalValue) => {
    onBorderWidthCommit?.(finalValue, originalValue);
  };
  const handleColorPreview = (color) => {
    onColorPreview?.(color);
  };
  const handleColorCommit = (color) => {
    onColorCommit?.(color);
  };
  const handleBorderScopeChange = (scope) => {
    setLocalBorderScope(scope);
    onBorderScopeChange?.(scope);
  };
  const openColorPicker = () => {
    const modalId = "TABLE_BORDER_COLOR_PICKER_MODAL";
    const closeColorPickerModal = () => modalService.closeModal(modalId);
    modalService.togglePluginPanel({
      id: modalId,
      Component: import_new_color_picker.NewColorPicker,
      componentProps: {
        title: t("TablePlugin_Toolbar_BorderColorPicker_Title"),
        themeColors,
        customColors,
        currentColor,
        closeModal: closeColorPickerModal,
        onColorSelected: handleColorCommit,
        onColorPreview: handleColorPreview,
        onColorPreviewEnd,
        onColorAdded: (newColor) => {
          (0, import_color_manager_utils.handleColorAdded)(newColor, colorManager);
          handleColorCommit(newColor);
        },
        onColorDeleted: (color) => {
          (0, import_color_manager_utils.handleColorDeleted)(color, colorManager);
        },
        onResetColor: () => handleColorCommit(void 0),
        referenceElement: colorPickerRef.current,
        logBi,
        allowTransparent: true
      },
      isMobile,
      positioning: {
        referenceElement: colorPickerRef.current,
        placement: "left"
      },
      type: void 0,
      onClickOutside: {
        on: "pointerup",
        handler: import_lodash.default.noop
      },
      focusReturnElement: colorPickerRef.current ?? void 0
    });
  };
  const isColorPickerOpen = () => modalService.isModalOpen("TABLE_BORDER_COLOR_PICKER_MODAL");
  (0, import_ui_components.useClickOutside)({
    containerRef: { current: containerEl },
    onClickOutside: (e) => {
      const target = e.target;
      if (referenceElement?.contains(target)) {
        return;
      }
      if (target?.closest('[role="tooltip"]')) {
        return;
      }
      closeModal();
    },
    disable: isColorPickerOpen()
  });
  return /* @__PURE__ */ import_react.default.createElement(
    import_ui_components.Panel,
    {
      dataHook: import_data_hooks.TABLE_BORDER_MODAL,
      closeButtonProps: { onClick: closeModal },
      width: isMobile ? "100%" : 288,
      maxHeight: isMobile ? void 0 : 555,
      height: "fit-content"
    },
    /* @__PURE__ */ import_react.default.createElement(import_ui_components.PanelHeader, { title: t("TablePlugin_Toolbar_BorderPanel_Title") }),
    /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { direction: "vertical", overflow: "auto" }, onBorderScopeChange && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
      import_border_scope_selector.BorderScopeSelector,
      {
        selectedScope: localBorderScope,
        onScopeChange: handleBorderScopeChange,
        canInnerHorizontal,
        canInnerVertical
      }
    ), /* @__PURE__ */ import_react.default.createElement(import_design_system.Divider, null)), /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { direction: "vertical", padding: "SP4", paddingTop: "SP2", paddingBottom: "SP3", gap: "SP2" }, isMixedColor || !(0, import_ricos_styles.canTransformToHex)(currentColor) ? /* @__PURE__ */ import_react.default.createElement(
      import_design_system.FieldSet,
      {
        legend: t("TablePlugin_Toolbar_BorderColor_Label"),
        legendPlacement: "left",
        columns: "1fr 30px",
        gap: "small",
        alignment: "center",
        dataHook: import_data_hooks.TABLE_BORDER_COLOR_INPUT
      },
      /* @__PURE__ */ import_react.default.createElement("div", null),
      /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { height: 30, width: 30 }, /* @__PURE__ */ import_react.default.createElement(
        import_design_system.FillPreview,
        {
          fill: isMixedColor ? displayedAllCurrentColors : displayedCurrentColor,
          onClick: openColorPicker,
          ref: colorPickerRef,
          dataHook: import_data_hooks.TABLE_BORDER_COLOR_PICKER
        }
      ))
    ) : /* @__PURE__ */ import_react.default.createElement(
      import_ui_components.ColorWithOpacityInput,
      {
        label: t("TablePlugin_Toolbar_BorderColor_Label"),
        fill: {
          type: "color",
          color: currentColor,
          onChange: handleColorPreview,
          onChangeCommit: handleColorCommit,
          allowTransparent: true
        },
        onColorPress: openColorPicker,
        colorPickerRef,
        inputDataHook: import_data_hooks.TABLE_BORDER_COLOR_INPUT,
        fillPreviewDataHook: import_data_hooks.TABLE_BORDER_COLOR_PICKER,
        zIndex,
        logBi
      }
    ), onBorderWidthPreview && onBorderWidthCommit && /* @__PURE__ */ import_react.default.createElement(
      import_ui_components.NumberInputWithLabel,
      {
        label: t("TablePlugin_Toolbar_BorderWidth_Label"),
        dataHook: import_data_hooks.TABLE_BORDER_WIDTH_INPUT,
        suffix: /* @__PURE__ */ import_react.default.createElement(import_design_system.Input.Affix, null, "px"),
        value: currentWidth,
        min: 1,
        max: 10,
        commitUnchanged: true,
        onChange: handleBorderWidthPreview,
        onChangeCommit: handleBorderWidthCommit,
        logBi,
        zIndex
      }
    )))
  );
};
//# sourceMappingURL=border-modal.js.map
