import { Box, ColorPicker as ColorPickerBase, Divider, Text } from "@wix/design-system";
import React, { useContext, useEffect, useMemo, useState } from "react";
import { RicosContext } from "./../../../../../ricos-context/index.js";
import { TRANSPARENT_HEX_COLOR } from "./../../../../../_shared/colors.js";
import { resolveColorToDisplayHex } from "./../../../../../_shared/resolve-color-to-display-hex.js";
import {
  isThemeColorToken,
  themeColorTokenToHex
} from "./../../../../../_shared/theme-color-token.js";
import {
  getHexColorFromAlpha,
  getOpacityFromHex,
  resolveColorsPalette
} from "./../../../../../wix-rich-content-common/index.js";
import { usePanelContainerElement } from "./../../../../ui-components-provider.js";
import { CUSTOM_SWATCHES, SIMPLE_COLOR_PICKER, THEME_SWATCHES } from "../../data-hooks.js";
import { NewColorSwatches } from "../new-color-swatches/new-color-swatches.js";
import classes from "./simple-color-picker-scss.js";
const THEME_COLORS_GRID_ID = "simple-picker-theme-colors-grid";
const SAVED_COLORS_GRID_ID = "simple-picker-saved-colors-grid";
const getColorHex = (color) => typeof color === "string" ? color : color.hex();
const SimpleColorPicker = ({
  currentColor,
  themeColors,
  customColors,
  onColorSelected,
  onColorPreview,
  onColorPreviewStart,
  onColorPreviewEnd,
  onColorAdded,
  onColorDeleted,
  allowTransparent
}) => {
  const { t, theme } = useContext(RicosContext);
  const palette = theme.colorPalette;
  const panelContainerEl = usePanelContainerElement();
  const [containerElement, setContainerElement] = useState(null);
  const colorResolverElement = panelContainerEl ?? containerElement;
  const resolveThemeTokenToHex = (token) => {
    if (!palette) {
      return void 0;
    }
    return themeColorTokenToHex(token, palette)?.toUpperCase();
  };
  const resolvedThemeColors = useMemo(
    () => themeColors.flatMap((swatch) => {
      const hex = resolveColorToDisplayHex(swatch.hex, colorResolverElement);
      return hex ? [{ ...swatch, hex }] : [];
    }),
    [themeColors, colorResolverElement]
  );
  const themeHexToToken = useMemo(() => {
    const map = /* @__PURE__ */ new Map();
    for (const swatch of resolvedThemeColors) {
      if (swatch.token) {
        map.set(swatch.hex.toUpperCase(), swatch.token);
      }
    }
    return map;
  }, [resolvedThemeColors]);
  const resolvedCurrentColor = currentColor && isThemeColorToken(currentColor) && palette ? resolveThemeTokenToHex(currentColor) : currentColor;
  const isTransparentColor = getOpacityFromHex(resolvedCurrentColor) === 0;
  const isCurrentColorToken = !!currentColor && isThemeColorToken(currentColor);
  const currentColorAsHex = isTransparentColor ? void 0 : getHexColorFromAlpha(resolvedCurrentColor)?.toUpperCase();
  const pickerDisplayColor = currentColorAsHex ?? "";
  const selectedThemeSwatchColor = isCurrentColorToken ? currentColorAsHex : void 0;
  const selectedSavedSwatchColor = isTransparentColor ? TRANSPARENT_HEX_COLOR : isCurrentColorToken ? void 0 : currentColorAsHex;
  const [pickerColor, setPickerColor] = useState(pickerDisplayColor);
  useEffect(() => {
    setPickerColor(pickerDisplayColor);
  }, [pickerDisplayColor]);
  const setPickerColorFromSwatch = (color) => {
    setPickerColor(
      getOpacityFromHex(color) === 0 ? "" : getHexColorFromAlpha(color)?.toUpperCase() ?? ""
    );
  };
  const usesDeferredCommit = Boolean(onColorPreview);
  const pendingColorRef = React.useRef(pickerDisplayColor || void 0);
  const isDraggingRef = React.useRef(false);
  const removeDragEndListenersRef = React.useRef(void 0);
  useEffect(
    () => () => {
      removeDragEndListenersRef.current?.();
    },
    []
  );
  const commitColor = (color) => {
    isDraggingRef.current = false;
    pendingColorRef.current = color;
    onColorSelected(color);
  };
  const handleColorChange = (newColor) => {
    const color = getColorHex(newColor);
    setPickerColor(color);
    pendingColorRef.current = color;
    if (usesDeferredCommit) {
      onColorPreview?.(color);
      return;
    }
    onColorSelected(color);
    onColorPreviewStart?.(color);
  };
  const handleColorAdd = (newColor) => {
    const color = getColorHex(newColor);
    setPickerColor(color);
    commitColor(color);
    if (onColorAdded && !customColors.includes(color.toUpperCase())) {
      onColorAdded(color.toUpperCase());
    }
  };
  const handleThemeSwatchSelected = (color) => {
    setPickerColorFromSwatch(color);
    const token = color ? themeHexToToken.get(color.toUpperCase()) : void 0;
    commitColor(token ?? color);
  };
  const handleSavedSwatchSelected = (color) => {
    setPickerColorFromSwatch(color);
    commitColor(color);
  };
  const handleSwatchPreviewStart = (color) => {
    if (usesDeferredCommit) {
      onColorPreview?.(color);
    }
    onColorPreviewStart?.(color);
  };
  const handlePickerPointerUp = () => {
    if (!usesDeferredCommit || !isDraggingRef.current) {
      return;
    }
    commitColor(pendingColorRef.current);
  };
  const handleColorDeleted = (color) => {
    onColorDeleted?.(color.toUpperCase());
  };
  const handleColorPickerInteractionStart = (event) => {
    const activeElement = event.currentTarget.ownerDocument.activeElement;
    if (activeElement instanceof HTMLInputElement && event.currentTarget.contains(activeElement) && event.target !== activeElement) {
      activeElement.blur();
    }
    if (!usesDeferredCommit) {
      return;
    }
    removeDragEndListenersRef.current?.();
    isDraggingRef.current = true;
    const ownerDocument = event.currentTarget.ownerDocument;
    const handleDocumentPointerUp = () => {
      removeDragEndListenersRef.current?.();
      if (!isDraggingRef.current) {
        return;
      }
      commitColor(pendingColorRef.current);
    };
    removeDragEndListenersRef.current = () => {
      ownerDocument.removeEventListener("pointerup", handleDocumentPointerUp, true);
      ownerDocument.removeEventListener("pointercancel", handleDocumentPointerUp, true);
      removeDragEndListenersRef.current = void 0;
    };
    ownerDocument.addEventListener("pointerup", handleDocumentPointerUp, true);
    ownerDocument.addEventListener("pointercancel", handleDocumentPointerUp, true);
  };
  const savedColors = [
    ...allowTransparent ? [TRANSPARENT_HEX_COLOR] : [],
    ...resolveColorsPalette(customColors, void 0)
  ];
  const hasThemeColors = resolvedThemeColors.length > 0;
  const hasSavedColors = savedColors.length > 0;
  return /* @__PURE__ */ React.createElement("div", { className: classes.container, "data-hook": SIMPLE_COLOR_PICKER, ref: setContainerElement }, /* @__PURE__ */ React.createElement(
    Box,
    {
      direction: "vertical",
      paddingTop: "SP3",
      paddingLeft: "SP4",
      paddingRight: "SP4",
      paddingBottom: "SP3",
      gap: "SP2"
    },
    /* @__PURE__ */ React.createElement(
      "div",
      {
        className: classes.colorPicker,
        onPointerDown: handleColorPickerInteractionStart,
        onPointerUp: handlePickerPointerUp
      },
      /* @__PURE__ */ React.createElement(Box, { align: "center" }, /* @__PURE__ */ React.createElement(
        ColorPickerBase,
        {
          allowEmpty: true,
          value: pickerColor,
          showConverter: false,
          showEyeDropper: true,
          showActionButtons: false,
          onChange: handleColorChange,
          onAdd: handleColorAdd,
          addTooltipContent: t("ColorPickerAddCustomColor_Tooltip"),
          emptyPlaceholder: t("CustomColorPicker_Empty_Placeholder")
        }
      ))
    ),
    hasThemeColors && /* @__PURE__ */ React.createElement(
      NewColorSwatches,
      {
        colors: resolvedThemeColors.map((swatch) => swatch.hex),
        selectedColor: selectedThemeSwatchColor,
        onColorSelected: handleThemeSwatchSelected,
        onColorPreviewStart: handleSwatchPreviewStart,
        onColorPreviewEnd,
        dataHook: THEME_SWATCHES,
        labelledById: THEME_COLORS_GRID_ID
      }
    )
  ), hasSavedColors && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(Box, { direction: "vertical", padding: "SP3", paddingLeft: "SP4", paddingRight: "SP4", gap: "SP3" }, /* @__PURE__ */ React.createElement(Text, { size: "small", weight: "bold", id: SAVED_COLORS_GRID_ID }, t("Color_Picker_SavedColor_Title")), /* @__PURE__ */ React.createElement(
    NewColorSwatches,
    {
      colors: savedColors,
      deletableColors: customColors,
      selectedColor: selectedSavedSwatchColor,
      onColorSelected: handleSavedSwatchSelected,
      onColorPreviewStart: handleSwatchPreviewStart,
      onColorPreviewEnd,
      onColorDeleted: onColorDeleted ? handleColorDeleted : void 0,
      dataHook: CUSTOM_SWATCHES,
      labelledById: SAVED_COLORS_GRID_ID
    }
  ))));
};
export {
  SimpleColorPicker
};
//# sourceMappingURL=simple-color-picker.js.map
