"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 design_modal_exports = {};
__export(design_modal_exports, {
  SketchDesignModal: () => SketchDesignModal
});
module.exports = __toCommonJS(design_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_types = require("./../../../ricos-types/index.js");
var import_color_with_opacity_input = require("./../../../ui-components/color-with-opacity-input/color-with-opacity-input.js");
var import_ui_components = require("./../../../ui-components/index.js");
var import_data_hooks = require("../data-hooks.js");
var import_defaults = require("../defaults.js");
var import_design_color_picker = require("./design-color-picker.js");
var import_style_grid = require("./style-grid.js");
const SectionTitle = ({ title }) => /* @__PURE__ */ import_react.default.createElement(import_design_system.Text, { size: "small", weight: "bold", ellipsis: true, maxLines: 1, showTooltip: true }, title);
const readSelectionState = (editor) => {
  const isRough = editor.isActive(import_ricos_types.Mark_Type.SKETCH);
  if (isRough) {
    const attrs = editor.getAttributes(import_ricos_types.Mark_Type.SKETCH);
    return {
      style: attrs.style ?? import_defaults.DEFAULT_STYLE,
      color: attrs.color ?? import_defaults.DEFAULT_COLOR,
      animate: attrs.animate ?? import_defaults.DEFAULT_ANIMATE
    };
  }
  const isClassic = editor.isActive(import_ricos_types.Mark_Type.COLOR_BACKGROUND);
  if (isClassic) {
    const attrs = editor.getAttributes(import_ricos_types.Mark_Type.COLOR_BACKGROUND);
    return {
      style: "CLASSIC",
      color: attrs.color ?? import_defaults.DEFAULT_COLOR,
      animate: false
    };
  }
  return { style: "NONE", color: import_defaults.DEFAULT_COLOR, animate: import_defaults.DEFAULT_ANIMATE };
};
const useEditorFromContext = () => {
  const { adapter } = (0, import_react.useContext)(import_ricos_context.EditorContext);
  return adapter.tiptapEditor;
};
const useApplyStyle = () => {
  const { adapter } = (0, import_react.useContext)(import_ricos_context.EditorContext);
  const editor = adapter.tiptapEditor;
  return (style, color, animate) => {
    const chain = editor.chain();
    chain.unsetMark(import_ricos_types.Mark_Type.SKETCH).unsetMark(import_ricos_types.Mark_Type.COLOR_BACKGROUND);
    if (style === "NONE") {
      chain.run();
      return;
    }
    if (style === "CLASSIC") {
      chain.setMark(import_ricos_types.Mark_Type.COLOR_BACKGROUND, { color }).run();
      return;
    }
    chain.setSketch({ style, color, animate }).run();
  };
};
const usePreviewStyle = () => {
  const { adapter } = (0, import_react.useContext)(import_ricos_context.EditorContext);
  const editor = adapter.tiptapEditor;
  return (style, color, animate) => {
    const { from, to } = editor.state.selection;
    if (from === to) {
      return;
    }
    editor.commands.previewSketch({ from, to, style, color, animate });
    editor.commands.previewHighlight(style === "CLASSIC" ? color : null);
  };
};
const useClearPreview = () => {
  const { adapter } = (0, import_react.useContext)(import_ricos_context.EditorContext);
  const editor = adapter.tiptapEditor;
  return () => {
    editor.commands.clearSketchPreview();
    editor.commands.previewHighlight(null);
  };
};
const SketchDesignModal = ({ config = { type: "textHighlight" }, referenceElement: _referenceElement }) => {
  const { isMobile, t } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  const zIndexService = (0, import_react.useContext)(import_ricos_context.ZIndexContext);
  const modalService = (0, import_react.useContext)(import_ricos_context.ModalServiceContext);
  const editor = useEditorFromContext();
  const colorSwatchRef = (0, import_react.useRef)(null);
  const applyStyle = useApplyStyle();
  const previewStyle = usePreviewStyle();
  const clearPreview = useClearPreview();
  const [committed, setCommitted] = (0, import_react.useState)(
    () => readSelectionState(editor)
  );
  const { style, color, animate } = committed;
  (0, import_react.useEffect)(() => {
    return () => {
      editor.commands.clearSketchPreview();
      editor.commands.previewHighlight(null);
    };
  }, [editor]);
  const onClose = () => {
    clearPreview();
    modalService.closeModal(import_data_hooks.SKETCH_COLOR_PICKER_MODAL_ID);
    modalService.closeModal(import_data_hooks.SKETCH_DESIGN_MODAL_ID);
  };
  const onColorSelected = (next) => {
    const nextColor = next ?? import_defaults.DEFAULT_COLOR;
    const targetStyle = style === "NONE" ? "CLASSIC" : style;
    clearPreview();
    applyStyle(targetStyle, nextColor, animate);
    setCommitted({ style: targetStyle, color: nextColor, animate });
  };
  const onAnimateToggle = () => {
    if (style === "NONE" || style === "CLASSIC") {
      return;
    }
    clearPreview();
    applyStyle(style, color, !animate);
    setCommitted({ style, color, animate: !animate });
  };
  const isFlat = (s) => s === "NONE" || s === "CLASSIC";
  const animateForTransition = (next) => {
    if (isFlat(next)) {
      return false;
    }
    if (isFlat(committed.style)) {
      return true;
    }
    return animate;
  };
  const onHoverStyle = (hovered) => {
    previewStyle(hovered, color, animateForTransition(hovered));
  };
  const onLeaveStyle = () => {
    clearPreview();
  };
  const onSelectStyle = (next) => {
    const nextAnimate = animateForTransition(next);
    clearPreview();
    applyStyle(next, color, nextAnimate);
    setCommitted({ style: next, color, animate: nextAnimate });
  };
  const onColorPreviewStart = (next) => {
    if (next === void 0) {
      clearPreview();
      return;
    }
    const targetStyle = style === "NONE" ? "CLASSIC" : style;
    previewStyle(targetStyle, next, animate);
  };
  const onColorPreview = (next) => {
    if (next === void 0) {
      clearPreview();
      return;
    }
    const targetStyle = style === "NONE" ? "CLASSIC" : style;
    previewStyle(targetStyle, next, false);
  };
  const onColorPreviewEnd = () => {
    clearPreview();
  };
  const openColorPicker = () => {
    if (!colorSwatchRef.current) {
      return;
    }
    const designPanelEl = document.querySelector(
      `[data-hook~="${import_data_hooks.DATA_HOOKS.DESIGN_MODAL}"]`
    );
    const positioningRef = designPanelEl ?? colorSwatchRef.current;
    modalService.togglePluginPanel({
      id: import_data_hooks.SKETCH_COLOR_PICKER_MODAL_ID,
      Component: import_design_color_picker.DesignColorPicker,
      componentProps: {
        config,
        modalId: import_data_hooks.SKETCH_COLOR_PICKER_MODAL_ID,
        currentColor: color,
        referenceElement: colorSwatchRef.current,
        onColorSelected,
        onColorPreview,
        onColorPreviewStart,
        onColorPreviewEnd
      },
      isMobile,
      // 'right-start' carries a built-in `crossAxis: -78` offset (see
      // ricos-modals/components/floating.tsx) that shifts the panel UP —
      // good for popovers anchored to a small reference, wrong here. Use
      // the dedicated 'right-start--custom-offset' variant which maps to
      // floating-ui's 'right-start' (top-aligned) but skips the crossAxis
      // shift, so the picker's top sits flush with the modal's top.
      positioning: { referenceElement: positioningRef, placement: "right-start--custom-offset" },
      onClickOutside: { on: "pointerup", handler: import_lodash.default.noop },
      focusReturnElement: colorSwatchRef.current,
      type: void 0
    });
  };
  const isStyled = style !== "NONE" && style !== "CLASSIC";
  return /* @__PURE__ */ import_react.default.createElement(import_ui_components.Panel, { closeButtonProps: { onClick: onClose }, dataHook: import_data_hooks.DATA_HOOKS.DESIGN_MODAL }, /* @__PURE__ */ import_react.default.createElement(import_ui_components.PanelHeader, { title: t("Sketch_DesignModal_Title") }), /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { direction: "vertical" }, /* @__PURE__ */ import_react.default.createElement(
    import_design_system.Accordion,
    {
      hideShadow: true,
      skin: "light",
      size: "medium",
      multiple: true,
      items: [
        (0, import_design_system.accordionItemBuilder)({
          key: "highlight-color",
          initiallyOpen: true,
          title: /* @__PURE__ */ import_react.default.createElement(SectionTitle, { title: t("Sketch_DesignModal_HighlightColor") }),
          children: /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { direction: "vertical", gap: "SP2" }, /* @__PURE__ */ import_react.default.createElement(
            import_color_with_opacity_input.ColorWithOpacityInput,
            {
              fill: {
                type: "color",
                color,
                onChange: onColorSelected,
                onChangeCommit: onColorSelected
              },
              label: t("Sketch_DesignModal_Color"),
              inputDataHook: import_data_hooks.DATA_HOOKS.COLOR_INPUT,
              fillPreviewDataHook: import_data_hooks.DATA_HOOKS.COLOR_SWATCH,
              onColorPress: openColorPicker,
              colorPickerRef: colorSwatchRef,
              zIndex: zIndexService.getZIndex("DIALOG")
            }
          ))
        }),
        (0, import_design_system.accordionItemBuilder)({
          key: "decoration",
          initiallyOpen: true,
          title: /* @__PURE__ */ import_react.default.createElement(SectionTitle, { title: t("Sketch_DesignModal_Decoration") }),
          children: /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { direction: "vertical", gap: "SP3" }, /* @__PURE__ */ import_react.default.createElement(
            import_design_system.FormField,
            {
              label: t("Sketch_DesignModal_Animated"),
              labelPlacement: "left",
              labelWidth: "1fr",
              labelAlignment: "middle"
            },
            /* @__PURE__ */ import_react.default.createElement(
              import_design_system.ToggleSwitch,
              {
                dataHook: import_data_hooks.DATA_HOOKS.ANIMATED_TOGGLE,
                checked: isStyled && animate,
                disabled: !isStyled,
                onChange: onAnimateToggle,
                size: "small"
              }
            )
          ), /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              style: {
                display: "grid",
                gridTemplateColumns: "repeat(3, 1fr)",
                gap: "8px",
                justifyItems: "center"
              }
            },
            import_style_grid.STYLE_GRID.map((entry) => /* @__PURE__ */ import_react.default.createElement("div", { key: entry.id }, /* @__PURE__ */ import_react.default.createElement(
              import_design_system.Thumbnail,
              {
                dataHook: entry.dataHook,
                width: 76,
                height: 76,
                size: "tiny",
                textPosition: "outside",
                contentAlignment: "center",
                noPadding: true,
                ellipsis: true,
                maxLines: 1,
                selected: style === entry.id,
                onClick: () => onSelectStyle(entry.id),
                title: t(entry.labelKey),
                image: entry.Icon ? /* @__PURE__ */ import_react.default.createElement(
                  entry.Icon,
                  {
                    onMouseEnter: () => onHoverStyle(entry.id),
                    onMouseLeave: onLeaveStyle
                  }
                ) : void 0
              }
            )))
          ))
        })
      ]
    }
  )));
};
//# sourceMappingURL=design-modal.js.map
