import { Box, Text } from "@wix/design-system";
import lodash from "lodash";
import React, { useContext, useRef } from "react";
import { BackgroundSection } from "./../../ricos-common-plugins/layout/shared-settings-components/background-section.js";
import { EditorContext, ModalServiceContext, RicosContext } from "./../../ricos-context/index.js";
import { Background_Type } from "./../../ricos-schema/next-schema/index.js";
import { useBiNext } from "./../../_shared/bi-context-provider/bi-context-provider.js";
import { TRANSPARENT_HEX_COLOR } from "./../../_shared/colors.js";
import { logInvariant } from "./../../_shared/log-invariant.js";
import { PmNodeType } from "./../../_shared/pm-node-types.js";
import { schemaGradientToCss } from "./../../_shared/schema-gradient-to-css.js";
import { useEditorProps } from "./../../_shared/some-editor-props-context.js";
import { useNodeAttrs } from "./../../_shared/use-node-attrs.js";
import {
  Panel,
  PanelHeader,
  useClickOutside,
  usePanelContainerElement
} from "./../../ui-components/index.js";
import { findNodeById } from "./../../tiptap-editor/helpers/index.js";
import { CardColorPicker, getCardBackgroundColor } from "./card-color-picker.js";
import {
  CARD_SETTINGS_MODAL_ID,
  CARD_SETTINGS_COLOR_PICKER_MODAL_ID,
  CARD_SETTINGS_BACKGROUND_TYPE_TOGGLE,
  CARD_SETTINGS_BACKGROUND_COLOR_INPUT,
  CARD_SETTINGS_BACKGROUND_COLOR_PICKER,
  CARD_SETTINGS_BACKGROUND_IMAGE_VIEWER,
  CARD_SETTINGS_BACKGROUND_SCALING_SELECT,
  CARD_SETTINGS_BACKGROUND_POSITION_SELECT,
  CARD_SETTINGS_BACKGROUND_BLUR_INPUT
} from "./data-hooks.js";
import { handleCardImageUpload } from "./handle-card-image-upload.js";
const CardSettings = ({ nodeId, referenceElement }) => {
  const { t, isMobile, theme } = useContext(RicosContext);
  const modalService = useContext(ModalServiceContext) || {};
  const containerEl = usePanelContainerElement();
  const { pmNodeAttrs, patchPmNodeAttrs } = useNodeAttrs(nodeId, PmNodeType.CARD);
  const logBi = useBiNext({ modalId: CARD_SETTINGS_MODAL_ID, pluginId: "card", nodeId });
  const { getPublicCommands, adapter } = useContext(EditorContext);
  const editorProps = useEditorProps();
  const backgroundColorPickerRef = useRef(null);
  const closeModal = () => modalService.closeModal(CARD_SETTINGS_MODAL_ID);
  const isColorPickerModalOpen = () => modalService.isModalOpen(CARD_SETTINGS_COLOR_PICKER_MODAL_ID);
  useClickOutside({
    containerRef: { current: containerEl },
    onClickOutside: (e) => {
      const target = e.target;
      if (referenceElement?.contains(target)) {
        return;
      }
      closeModal();
    },
    disable: isColorPickerModalOpen()
  });
  if (!pmNodeAttrs) {
    logInvariant(new Error("Card settings: node attrs not found"));
    return null;
  }
  const backgroundGradient = pmNodeAttrs.background?.type === Background_Type.GRADIENT ? schemaGradientToCss(pmNodeAttrs.background.gradient, theme.colorPalette) : void 0;
  const backgroundColor = getCardBackgroundColor(
    pmNodeAttrs.background?.type === Background_Type.COLOR ? pmNodeAttrs.background.color : void 0,
    theme?.customStyles?.card?.backgroundColor,
    Boolean(pmNodeAttrs.backgroundImage)
  );
  const onValueSelected = (value) => {
    if (!value || value.color !== void 0) {
      const colorToUse = value?.color ?? TRANSPARENT_HEX_COLOR;
      patchPmNodeAttrs({ background: { type: Background_Type.COLOR, color: colorToUse } });
    } else if (value.gradient) {
      patchPmNodeAttrs({
        background: { type: Background_Type.GRADIENT, gradient: value.gradient }
      });
    }
  };
  const openColorPicker = (referenceEl) => {
    const modalId = CARD_SETTINGS_COLOR_PICKER_MODAL_ID;
    modalService.togglePluginPanel({
      id: modalId,
      Component: CardColorPicker,
      componentProps: {
        modalId,
        nodeId,
        colorType: "background",
        referenceElement: referenceEl,
        onValueSelected
      },
      isMobile,
      positioning: {
        referenceElement: referenceEl,
        placement: "left"
      },
      type: void 0,
      onClickOutside: {
        on: "pointerup",
        handler: lodash.noop
      },
      focusReturnElement: referenceEl ?? void 0
    });
  };
  const onBgImageRequest = async () => {
    const pickImage = editorProps.pickMedia?.pickImage;
    if (!pickImage) {
      return;
    }
    await handleCardImageUpload({
      pickImage,
      publicCommands: getPublicCommands(),
      nodeId
    });
  };
  const onBgImageRemove = () => {
    patchPmNodeAttrs({ backgroundImage: void 0 });
  };
  const onBackgroundChange = (newValue) => {
    const tr = adapter.tiptapEditor.view.state.tr;
    const freshAttrs = findNodeById(tr, nodeId)[0]?.node.attrs ?? pmNodeAttrs;
    const currentImage = freshAttrs.backgroundImage;
    const updates = {};
    if ("image" in newValue) {
      updates.backgroundImage = newValue.image;
    }
    if ("color" in newValue) {
      updates.background = { type: Background_Type.COLOR, color: newValue.color };
    }
    if ("imageScaling" in newValue && currentImage) {
      updates.backgroundImage = {
        ...updates.backgroundImage ?? currentImage,
        scaling: newValue.imageScaling
      };
    }
    if ("imagePosition" in newValue && currentImage) {
      updates.backgroundImage = {
        ...updates.backgroundImage ?? currentImage,
        position: newValue.imagePosition
      };
    }
    if ("imageBlur" in newValue && currentImage) {
      updates.backgroundImage = {
        ...updates.backgroundImage ?? currentImage,
        blur: newValue.imageBlur
      };
    }
    patchPmNodeAttrs(updates);
  };
  return /* @__PURE__ */ React.createElement(
    Panel,
    {
      onCloseButtonClick: closeModal,
      dataHook: CARD_SETTINGS_MODAL_ID,
      maxHeight: isMobile ? void 0 : 590
    },
    /* @__PURE__ */ React.createElement(PanelHeader, { title: t("Card_SettingsModal_Header") }),
    /* @__PURE__ */ React.createElement(Box, { direction: "vertical", overflow: "auto" }, /* @__PURE__ */ React.createElement(Box, { direction: "vertical", padding: "SP4", paddingTop: "SP3", paddingBottom: "SP3", gap: "SP2" }, /* @__PURE__ */ React.createElement(Box, { paddingBottom: "SP1" }, /* @__PURE__ */ React.createElement(Text, { size: "small", weight: "bold" }, t("Card_SettingsModal_Tab_Design_Background_Label"))), /* @__PURE__ */ React.createElement(
      BackgroundSection,
      {
        imageLoading: pmNodeAttrs.loading?.backgroundImage,
        image: pmNodeAttrs.backgroundImage,
        imageScaling: pmNodeAttrs.backgroundImage?.scaling ?? "CONTAIN",
        imagePosition: pmNodeAttrs.backgroundImage?.position ?? "CENTER",
        imageBlur: pmNodeAttrs.backgroundImage?.blur ?? 0,
        color: backgroundColor,
        gradient: backgroundGradient,
        onChange: onBackgroundChange,
        openColorPicker: () => {
          openColorPicker(backgroundColorPickerRef.current);
          logBi({ dataHook: CARD_SETTINGS_BACKGROUND_COLOR_PICKER });
        },
        colorPickerRef: backgroundColorPickerRef,
        backgroundTypeToggleDataHook: CARD_SETTINGS_BACKGROUND_TYPE_TOGGLE,
        colorDataHook: CARD_SETTINGS_BACKGROUND_COLOR_INPUT,
        colorPickerDataHook: CARD_SETTINGS_BACKGROUND_COLOR_PICKER,
        imageDataHook: CARD_SETTINGS_BACKGROUND_IMAGE_VIEWER,
        imageScalingDataHook: CARD_SETTINGS_BACKGROUND_SCALING_SELECT,
        imagePositionDataHook: CARD_SETTINGS_BACKGROUND_POSITION_SELECT,
        imageBlurDataHook: CARD_SETTINGS_BACKGROUND_BLUR_INPUT,
        onImageRequest: onBgImageRequest,
        onImageRemove: onBgImageRemove,
        logBi
      }
    )))
  );
};
export {
  CardSettings
};
//# sourceMappingURL=card-settings.js.map
