import { Box, SidePanel, Tabs, TextButton } from "@wix/design-system";
import { RevertSmall } from "@wix/wix-ui-icons-common";
import React, { useContext, useEffect, useRef, useState } from "react";
import { ModalServiceContext, RicosContext } from "./../../../ricos-context/index.js";
import { TRANSPARENT_HEX_COLOR } from "./../../../_shared/colors.js";
import {
  getThemeColorTokenOpacity,
  isThemeColorToken,
  setThemeColorTokenOpacity
} from "./../../../_shared/theme-color-token.js";
import {
  combineHexWithOpacity,
  getHexColorFromAlpha,
  getOpacityFromHex
} from "./../../../wix-rich-content-common/index.js";
import {
  Panel,
  useClickOutside,
  usePanelContainerElement
} from "./../../index.js";
import { PanelHeader } from "../../panel-header/panel-header.js";
import { GradientPicker } from "./components/gradient-picker/index.js";
import { SimpleColorPicker } from "./components/simple-color-picker/index.js";
import {
  COLOR_PICKER_COLOR_ADDED,
  COLOR_PICKER_COLOR_PREVIEW,
  COLOR_PICKER_COLOR_SELECTED,
  FLOATING_COLOR_SWATCHES,
  RESET_BUTTON,
  SAVE_GRADIENT_BUTTON
} from "./data-hooks.js";
import classes from "./new-color-picker-scss.js";
const GRADIENT_STOP_COLOR_PICKER_MODAL_ID = "GRADIENT_STOP_COLOR_PICKER_MODAL";
const normalizeThemeColorToken = (color) => typeof color === "string" && isThemeColorToken(color.toLowerCase()) ? color.toLowerCase() : color;
const createSimpleGradient = (color) => ({
  type: "LINEAR",
  stops: [
    { color: 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) => getOpacityFromHex(color) === 0 ? "#FFFFFF" : getHexColorFromAlpha(color) ?? "#FFFFFF";
const getColorOpacity = (color) => color && isThemeColorToken(color) ? getThemeColorTokenOpacity(color) : getOpacityFromHex(color);
const applyOpacity = (color, opacity) => {
  if (!color) {
    return color;
  }
  return isThemeColorToken(color) ? setThemeColorTokenOpacity(color, opacity) : 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 } = useContext(RicosContext);
  const modalService = useContext(ModalServiceContext);
  const containerEl = usePanelContainerElement();
  const pointerDownStartedInGradientStopPickerRef = useRef(false);
  const isGradient = typeof currentColorProp === "object" && currentColorProp !== null;
  const [activeTab, setActiveTab] = useState(
    isGradient ? "gradient" : "color"
  );
  const [previousColor, setPreviousColor] = useState(
    () => getColorTabValue(currentColorProp, fallbackColor)
  );
  const [previousGradient, setPreviousGradient] = useState(
    () => getGradient(currentColorProp)
  );
  useEffect(() => {
    if (isGradient) {
      setPreviousGradient(currentColorProp);
    } else {
      setPreviousColor(getColorTabValue(currentColorProp, fallbackColor));
    }
  }, [currentColorProp, fallbackColor, isGradient]);
  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 = useRef(currentGradient);
  currentGradientRef.current = currentGradient;
  const currentColorOpacity = getColorOpacity(currentColor);
  const preserveCurrentOpacity = (color) => {
    const selectedColorOpacity = getColorOpacity(color);
    if (selectedColorOpacity === 100 && currentColorOpacity !== selectedColorOpacity && currentColor !== TRANSPARENT_HEX_COLOR && currentColor !== "#FFFFFF00") {
      return applyOpacity(color, currentColorOpacity);
    }
    return color;
  };
  const handleColorSelected = (color) => {
    const colorToUse = preserveCurrentOpacity(color);
    setPreviousColor(colorToUse);
    onColorSelected(colorToUse);
    logBi({ dataHook: COLOR_PICKER_COLOR_SELECTED, value: colorToUse });
  };
  const handleGradientSelected = (gradient) => {
    setPreviousGradient(gradient);
    if (onGradientSelected) {
      onGradientSelected(gradient);
      logBi({ dataHook: COLOR_PICKER_COLOR_SELECTED, value: JSON.stringify(gradient) });
    }
  };
  const onColorAdded = (color) => {
    onColorAddedProp(color);
    logBi({ dataHook: COLOR_PICKER_COLOR_ADDED, value: color });
  };
  const onColorPreviewStart = (color) => {
    if (onColorPreviewStartProp) {
      const colorToUse = preserveCurrentOpacity(color);
      onColorPreviewStartProp(colorToUse);
      logBi({ dataHook: COLOR_PICKER_COLOR_PREVIEW, value: colorToUse });
    }
  };
  const handleColorPreview = (color) => {
    onColorPreview?.(preserveCurrentOpacity(color));
  };
  const onResetColor = () => {
    if (onResetColorProp) {
      onResetColorProp();
      logBi({ dataHook: RESET_BUTTON });
    }
  };
  const handleGradientSaved = (gradient) => {
    setPreviousGradient(gradient);
    if (onGradientAdded) {
      onGradientAdded(gradient);
      logBi({ dataHook: 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__ */ React.createElement("div", { "data-hook": `gradient-color-picker-${originalIndex}` }, /* @__PURE__ */ React.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);
    }
  };
  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__ */ React.createElement(
    Panel,
    {
      closeButtonProps: { onClick: onCloseButtonClick },
      dataHook: FLOATING_COLOR_SWATCHES,
      width: isMobile ? "100%" : 288,
      maxHeight: isMobile ? void 0 : 590,
      height: isMobile ? "100dvh" : "fit-content"
    },
    /* @__PURE__ */ React.createElement(PanelHeader, { title, className: classes.pickerHeader }),
    allowGradient && /* @__PURE__ */ React.createElement(
      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__ */ React.createElement(Box, { direction: "vertical", overflow: "auto" }, activeTab === "color" && /* @__PURE__ */ React.createElement(
      SimpleColorPicker,
      {
        currentColor,
        themeColors,
        customColors,
        onColorSelected: handleColorSelected,
        onColorPreview: onColorPreview ? handleColorPreview : void 0,
        onColorPreviewStart,
        onColorPreviewEnd,
        onColorAdded,
        onColorDeleted,
        allowTransparent
      }
    ), activeTab === "gradient" && allowGradient && /* @__PURE__ */ React.createElement(
      GradientPicker,
      {
        value: currentGradient,
        onChange: handleGradientSelected,
        customGradients,
        onGradientAdded: onGradientAdded ? handleGradientSaved : void 0,
        onGradientDeleted,
        onColorPickerOpen: openGradientStopColorPicker
      }
    )),
    !!onResetColorProp && activeTab === "color" && /* @__PURE__ */ React.createElement(SidePanel.Footer, { showDivider: true }, /* @__PURE__ */ React.createElement(Box, { align: "center" }, /* @__PURE__ */ React.createElement(
      TextButton,
      {
        onClick: onResetColor,
        weight: "normal",
        size: "small",
        dataHook: RESET_BUTTON,
        prefixIcon: /* @__PURE__ */ React.createElement(RevertSmall, null)
      },
      t("ColorPicker_SetToDefault_ButtonLabel")
    )))
  );
};
export {
  NewColorPicker
};
//# sourceMappingURL=new-color-picker.js.map
