"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 new_color_picker_exports = {};
__export(new_color_picker_exports, {
  NewColorPicker: () => NewColorPicker
});
module.exports = __toCommonJS(new_color_picker_exports);
var import_design_system = require("@wix/design-system");
var import_wix_ui_icons_common = require("@wix/wix-ui-icons-common");
var import_react = __toESM(require("react"));
var import_ricos_context = require("./../../../ricos-context/index.js");
var import_colors = require("./../../../_shared/colors.js");
var import_theme_color_token = require("./../../../_shared/theme-color-token.js");
var import_wix_rich_content_common = require("./../../../wix-rich-content-common/index.js");
var import__ = require("./../../index.js");
var import_panel_header = require("../../panel-header/panel-header.js");
var import_gradient_picker = require("./components/gradient-picker/index.js");
var import_simple_color_picker = require("./components/simple-color-picker/index.js");
var import_data_hooks = require("./data-hooks.js");
var import_new_color_picker_scss = __toESM(require("./new-color-picker-scss.js"));
const GRADIENT_STOP_COLOR_PICKER_MODAL_ID = "GRADIENT_STOP_COLOR_PICKER_MODAL";
const normalizeThemeColorToken = (color) => typeof color === "string" && (0, import_theme_color_token.isThemeColorToken)(color.toLowerCase()) ? color.toLowerCase() : color;
const createSimpleGradient = (color) => ({
  type: "LINEAR",
  stops: [
    { color: (0, import_wix_rich_content_common.combineHexWithOpacity)(color, 100), position: 0 },
    { color: "#000000", position: 1 }
  ],
  angle: 90
});
const getSolidColor = (color) => typeof color === "string" ? color : void 0;
const getGradient = (color) => typeof color === "object" && color !== null ? color : void 0;
const getFirstGradientColor = (color) => getGradient(color)?.stops?.[0]?.color;
const getColorTabValue = (color, fallbackColor) => getSolidColor(color) ?? fallbackColor ?? getFirstGradientColor(color);
const getGradientBaseColor = (color) => (0, import_wix_rich_content_common.getOpacityFromHex)(color) === 0 ? "#FFFFFF" : (0, import_wix_rich_content_common.getHexColorFromAlpha)(color) ?? "#FFFFFF";
const getColorOpacity = (color) => color && (0, import_theme_color_token.isThemeColorToken)(color) ? (0, import_theme_color_token.getThemeColorTokenOpacity)(color) : (0, import_wix_rich_content_common.getOpacityFromHex)(color);
const applyOpacity = (color, opacity) => {
  if (!color) {
    return color;
  }
  return (0, import_theme_color_token.isThemeColorToken)(color) ? (0, import_theme_color_token.setThemeColorTokenOpacity)(color, opacity) : (0, import_wix_rich_content_common.combineHexWithOpacity)(color, opacity);
};
const NewColorPicker = ({
  title,
  themeColors,
  customColors,
  customGradients = [],
  currentColor: currentColorProp,
  fallbackColor,
  closeModal,
  onColorSelected,
  onGradientSelected,
  onColorAdded: onColorAddedProp,
  onColorDeleted,
  onGradientDeleted,
  onColorPreview,
  onColorPreviewStart: onColorPreviewStartProp,
  onColorPreviewEnd,
  onResetColor: onResetColorProp,
  onGradientAdded,
  referenceElement,
  logBi,
  allowTransparent,
  allowGradient
}) => {
  const { t, isMobile } = (0, import_react.useContext)(import_ricos_context.RicosContext);
  const modalService = (0, import_react.useContext)(import_ricos_context.ModalServiceContext);
  const containerEl = (0, import__.usePanelContainerElement)();
  const pointerDownStartedInGradientStopPickerRef = (0, import_react.useRef)(false);
  const isGradient = typeof currentColorProp === "object" && currentColorProp !== null;
  const [activeTab, setActiveTab] = (0, import_react.useState)(
    isGradient ? "gradient" : "color"
  );
  const [previousColor, setPreviousColor] = (0, import_react.useState)(
    () => getColorTabValue(currentColorProp, fallbackColor)
  );
  const [previousGradient, setPreviousGradient] = (0, import_react.useState)(
    () => getGradient(currentColorProp)
  );
  (0, import_react.useEffect)(() => {
    if (isGradient) {
      setPreviousGradient(currentColorProp);
    } else {
      setPreviousColor(getColorTabValue(currentColorProp, fallbackColor));
    }
  }, [currentColorProp, fallbackColor, isGradient]);
  (0, import_react.useEffect)(() => {
    const handlePointerDown = (event) => {
      pointerDownStartedInGradientStopPickerRef.current = Boolean(
        event.target?.closest('[data-hook^="gradient-color-picker"]')
      );
    };
    const handlePointerUp = () => {
      setTimeout(() => {
        pointerDownStartedInGradientStopPickerRef.current = false;
      }, 0);
    };
    document.addEventListener("pointerdown", handlePointerDown, true);
    document.addEventListener("pointerup", handlePointerUp, true);
    return () => {
      document.removeEventListener("pointerdown", handlePointerDown, true);
      document.removeEventListener("pointerup", handlePointerUp, true);
    };
  }, []);
  const currentColor = normalizeThemeColorToken(
    isGradient ? previousColor ?? getColorTabValue(currentColorProp, fallbackColor) : getColorTabValue(currentColorProp, fallbackColor)
  );
  const currentGradient = isGradient ? currentColorProp : previousGradient ?? createSimpleGradient(getGradientBaseColor(currentColor));
  const currentGradientRef = (0, import_react.useRef)(currentGradient);
  currentGradientRef.current = currentGradient;
  const currentColorOpacity = getColorOpacity(currentColor);
  const preserveCurrentOpacity = (color) => {
    const selectedColorOpacity = getColorOpacity(color);
    if (selectedColorOpacity === 100 && currentColorOpacity !== selectedColorOpacity && currentColor !== import_colors.TRANSPARENT_HEX_COLOR && currentColor !== "#FFFFFF00") {
      return applyOpacity(color, currentColorOpacity);
    }
    return color;
  };
  const handleColorSelected = (color) => {
    const colorToUse = preserveCurrentOpacity(color);
    setPreviousColor(colorToUse);
    onColorSelected(colorToUse);
    logBi({ dataHook: import_data_hooks.COLOR_PICKER_COLOR_SELECTED, value: colorToUse });
  };
  const handleGradientSelected = (gradient) => {
    setPreviousGradient(gradient);
    if (onGradientSelected) {
      onGradientSelected(gradient);
      logBi({ dataHook: import_data_hooks.COLOR_PICKER_COLOR_SELECTED, value: JSON.stringify(gradient) });
    }
  };
  const onColorAdded = (color) => {
    onColorAddedProp(color);
    logBi({ dataHook: import_data_hooks.COLOR_PICKER_COLOR_ADDED, value: color });
  };
  const onColorPreviewStart = (color) => {
    if (onColorPreviewStartProp) {
      const colorToUse = preserveCurrentOpacity(color);
      onColorPreviewStartProp(colorToUse);
      logBi({ dataHook: import_data_hooks.COLOR_PICKER_COLOR_PREVIEW, value: colorToUse });
    }
  };
  const handleColorPreview = (color) => {
    onColorPreview?.(preserveCurrentOpacity(color));
  };
  const onResetColor = () => {
    if (onResetColorProp) {
      onResetColorProp();
      logBi({ dataHook: import_data_hooks.RESET_BUTTON });
    }
  };
  const handleGradientSaved = (gradient) => {
    setPreviousGradient(gradient);
    if (onGradientAdded) {
      onGradientAdded(gradient);
      logBi({ dataHook: import_data_hooks.SAVE_GRADIENT_BUTTON, value: JSON.stringify(gradient) });
    }
  };
  const handleGradientStopColorSelected = (index, color) => {
    handleGradientSelected({
      ...currentGradientRef.current,
      stops: currentGradientRef.current.stops?.map(
        (stop, stopIndex) => stopIndex === index ? { ...stop, color } : stop
      )
    });
  };
  const openGradientStopColorPicker = ({
    originalIndex,
    stop,
    referenceElement: colorPickerReferenceElement
  }) => {
    if (!modalService?.togglePluginPanel) {
      return;
    }
    const modalId = GRADIENT_STOP_COLOR_PICKER_MODAL_ID;
    const GradientStopColorPicker = () => /* @__PURE__ */ import_react.default.createElement("div", { "data-hook": `gradient-color-picker-${originalIndex}` }, /* @__PURE__ */ import_react.default.createElement(
      NewColorPicker,
      {
        title,
        themeColors,
        customColors,
        currentColor: stop.color,
        closeModal: () => modalService.closeModal(modalId),
        onColorSelected: (color) => handleGradientStopColorSelected(originalIndex, color),
        onColorAdded,
        onColorDeleted,
        referenceElement: colorPickerReferenceElement,
        logBi,
        allowTransparent,
        allowGradient: false
      }
    ));
    if (modalService.isModalOpen?.(modalId)) {
      modalService.closeModal(modalId);
    }
    modalService.togglePluginPanel({
      id: modalId,
      Component: GradientStopColorPicker,
      componentProps: {},
      isMobile,
      positioning: {
        referenceElement: colorPickerReferenceElement,
        placement: "right"
      },
      type: void 0,
      focusReturnElement: colorPickerReferenceElement ?? void 0
    });
  };
  const handleTabChange = ({ id }) => {
    const newTab = id;
    if (newTab === activeTab) {
      return;
    }
    setActiveTab(newTab);
    if (newTab === "gradient") {
      handleGradientSelected(currentGradient);
    } else if (newTab === "color") {
      handleColorSelected(currentColor);
    }
  };
  (0, import__.useClickOutside)({
    containerRef: { current: containerEl },
    onClickOutside: (e) => {
      const target = e.target;
      if (pointerDownStartedInGradientStopPickerRef.current) {
        pointerDownStartedInGradientStopPickerRef.current = false;
        return;
      }
      if (target?.dataset?.hook === "tooltip-text" || target?.role === "tooltip" || containerEl?.contains(target) || referenceElement?.contains(target) || target?.closest('[data-hook^="gradient-color-picker"]')) {
        return;
      }
      closeModal();
    }
  });
  const onCloseButtonClick = () => {
    onColorPreviewEnd?.();
    modalService?.closeModal?.(GRADIENT_STOP_COLOR_PICKER_MODAL_ID);
    closeModal();
  };
  return /* @__PURE__ */ import_react.default.createElement(
    import__.Panel,
    {
      closeButtonProps: { onClick: onCloseButtonClick },
      dataHook: import_data_hooks.FLOATING_COLOR_SWATCHES,
      width: isMobile ? "100%" : 288,
      maxHeight: isMobile ? void 0 : 590,
      height: isMobile ? "100dvh" : "fit-content"
    },
    /* @__PURE__ */ import_react.default.createElement(import_panel_header.PanelHeader, { title, className: import_new_color_picker_scss.default.pickerHeader }),
    allowGradient && /* @__PURE__ */ import_react.default.createElement(
      import_design_system.Tabs,
      {
        items: [
          { id: "color", title: t("ColorPicker_Tab_Color") },
          { id: "gradient", title: t("ColorPicker_Tab_Gradient") }
        ],
        activeId: activeTab,
        onClick: handleTabChange,
        size: "small",
        type: "uniformFull",
        minWidth: 0
      }
    ),
    /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { direction: "vertical", overflow: "auto" }, activeTab === "color" && /* @__PURE__ */ import_react.default.createElement(
      import_simple_color_picker.SimpleColorPicker,
      {
        currentColor,
        themeColors,
        customColors,
        onColorSelected: handleColorSelected,
        onColorPreview: onColorPreview ? handleColorPreview : void 0,
        onColorPreviewStart,
        onColorPreviewEnd,
        onColorAdded,
        onColorDeleted,
        allowTransparent
      }
    ), activeTab === "gradient" && allowGradient && /* @__PURE__ */ import_react.default.createElement(
      import_gradient_picker.GradientPicker,
      {
        value: currentGradient,
        onChange: handleGradientSelected,
        customGradients,
        onGradientAdded: onGradientAdded ? handleGradientSaved : void 0,
        onGradientDeleted,
        onColorPickerOpen: openGradientStopColorPicker
      }
    )),
    !!onResetColorProp && activeTab === "color" && /* @__PURE__ */ import_react.default.createElement(import_design_system.SidePanel.Footer, { showDivider: true }, /* @__PURE__ */ import_react.default.createElement(import_design_system.Box, { align: "center" }, /* @__PURE__ */ import_react.default.createElement(
      import_design_system.TextButton,
      {
        onClick: onResetColor,
        weight: "normal",
        size: "small",
        dataHook: import_data_hooks.RESET_BUTTON,
        prefixIcon: /* @__PURE__ */ import_react.default.createElement(import_wix_ui_icons_common.RevertSmall, null)
      },
      t("ColorPicker_SetToDefault_ButtonLabel")
    )))
  );
};
//# sourceMappingURL=new-color-picker.js.map
