import { Box, Divider, Input, Text } from "@wix/design-system";
import { LayoutFullSmall, LayoutTwoColumnsSplitSmall } from "@wix/wix-ui-icons-common";
import lodash from "lodash";
import React, { useContext, useRef } from "react";
import { LAYOUT_DEFAULTS } from "./../../../ricos-common-plugins/layout/shared-with-viewer.js";
import { RICOS_LAYOUT_TYPE } from "./../../../ricos-content/index.js";
import {
  EditorContext,
  ModalServiceContext,
  RicosContext,
  UploadContext,
  ZIndexContext,
  useDevService
} from "./../../../ricos-context/index.js";
import { useTheme } from "./../../../ricos-styles/theme-provider.js";
import { useBiNext } from "./../../../_shared/bi-context-provider/bi-context-provider.js";
import { TRANSPARENT_HEX_COLOR } from "./../../../_shared/colors.js";
import { useWixInstanceService } from "./../../../_shared/request-service-provider/wix-instance-context.js";
import { resolveBackwardCompatOverlay } from "./../../../_shared/resolve-backward-compat-overlay.js";
import { resolveColorToDisplayHex } from "./../../../_shared/resolve-color-to-display-hex.js";
import { schemaGradientToCss } from "./../../../_shared/schema-gradient-to-css.js";
import { useEditorProps } from "./../../../_shared/some-editor-props-context.js";
import { TogglesWithLabel } from "./../../../_shared/toggles-with-label.js";
import { combineHexWithOpacity, getOpacityFromHex } from "./../../../wix-rich-content-common/index.js";
import {
  ColorWithOpacityInput,
  NumberInputWithLabel,
  ToggleButton,
  usePanelContainerElement
} from "./../../../ui-components/index.js";
import { findNodeById } from "./../../../tiptap-editor/helpers/index.js";
import {
  CELL_SETTINGS_COLOR_PICKER_MODAL_ID,
  LAYOUT_SETTINGS_BACKDROP_COLOR_INPUT,
  LAYOUT_SETTINGS_BACKDROP_COLOR_PICKER,
  LAYOUT_SETTINGS_BACKDROP_BLUR_INPUT,
  LAYOUT_SETTINGS_BACKDROP_IMAGE_VIEWER,
  LAYOUT_SETTINGS_BACKDROP_POSITION_SELECT,
  LAYOUT_SETTINGS_BACKDROP_SCALING_SELECT,
  LAYOUT_SETTINGS_BACKDROP_TOGGLE,
  LAYOUT_SETTINGS_BACKDROP_TYPE_TOGGLE,
  LAYOUT_SETTINGS_BACKGROUND_COLOR_INPUT,
  LAYOUT_SETTINGS_BACKGROUND_COLOR_PICKER,
  LAYOUT_SETTINGS_BACKGROUND_BLUR_INPUT,
  LAYOUT_SETTINGS_BACKGROUND_IMAGE_VIEWER,
  LAYOUT_SETTINGS_BACKGROUND_POSITION_SELECT,
  LAYOUT_SETTINGS_BACKGROUND_SCALING_SELECT,
  LAYOUT_SETTINGS_BACKGROUND_TYPE_TOGGLE,
  LAYOUT_SETTINGS_BORDER_COLOR_INPUT,
  LAYOUT_SETTINGS_BORDER_COLOR_PICKER,
  LAYOUT_SETTINGS_BORDER_RADIUS_INPUT,
  LAYOUT_SETTINGS_BORDER_WIDTH_INPUT,
  LAYOUT_SETTINGS_DESIGN_TARGET_CELL,
  LAYOUT_SETTINGS_DESIGN_TARGET_LAYOUT,
  LAYOUT_SETTINGS_MODAL_ID
} from "../data-hooks.js";
import { handleLayoutImageUpload } from "../handle-layout-image-upload.js";
import {
  clearTransparentLayoutFill,
  getLayoutFillPatch,
  getResolvedLayoutFillColor,
  hasVisibleLayoutFill,
  resolveLayoutFill,
  toLayoutFill
} from "../layout-fill.js";
import { BackgroundSection } from "../shared-settings-components/background-section.js";
import { LayoutColorPicker } from "../shared-settings-components/layout-color-picker.js";
import { DEFAULT_BACKDROP_VERTICAL_SPACING } from "../shared.js";
const DesignTab = ({
  pmNodeAttrs,
  patchPmNodeAttrs,
  nodeId,
  config
}) => {
  const { t, isMobile } = useContext(RicosContext);
  const { getPublicCommands, adapter } = useContext(EditorContext);
  const wixInstance = useWixInstanceService();
  const editorProps = useEditorProps();
  const { uploadService } = useContext(UploadContext);
  const devService = useDevService();
  const containerEl = usePanelContainerElement();
  const zIndexService = useContext(ZIndexContext);
  const zIndex = zIndexService.getZIndex("DIALOG");
  const modalService = useContext(ModalServiceContext);
  const theme = useTheme();
  const currentBackground = resolveLayoutFill(pmNodeAttrs.background, pmNodeAttrs.backgroundColor);
  const currentBackdrop = resolveLayoutFill(pmNodeAttrs.backdrop, pmNodeAttrs.backdropColor);
  const getFreshAttrs = () => {
    const tr = adapter.tiptapEditor.view.state.tr;
    const fresh = findNodeById(tr, nodeId)[0]?.node.attrs;
    return fresh ?? pmNodeAttrs;
  };
  const logBi = useBiNext({
    modalId: LAYOUT_SETTINGS_MODAL_ID,
    pluginId: "layout",
    nodeId
  });
  const [showBackdropSection, setShowBackdropSection] = React.useState(() => {
    const hasBackdropPadding = pmNodeAttrs.backdropPaddingTop || pmNodeAttrs.backdropPaddingBottom;
    return !!(pmNodeAttrs.backdropImage || hasVisibleLayoutFill(currentBackdrop) || hasBackdropPadding);
  });
  const [prevBackdrop, setPrevBackdrop] = React.useState(currentBackdrop);
  const [prevBackdropImage, setPrevBackdropImage] = React.useState(pmNodeAttrs.backdropImage);
  const [prevBackdropPaddingTop] = React.useState(pmNodeAttrs.backdropPaddingTop);
  const [prevBackdropPaddingBottom] = React.useState(pmNodeAttrs.backdropPaddingBottom);
  const backgroundColorPickerRef = useRef(null);
  const backdropColorPickerRef = useRef(null);
  const borderColorPickerRef = useRef(null);
  const openColorPicker = (colorType, referenceElement, fallbackColor) => {
    const modalId = CELL_SETTINGS_COLOR_PICKER_MODAL_ID;
    const allowGradient = colorType === "backgroundColor" || colorType === "backdropColor";
    modalService.togglePluginPanel({
      id: modalId,
      Component: LayoutColorPicker,
      componentProps: {
        modalId,
        nodeId,
        referenceElement,
        colorType,
        fallbackColor,
        onValueSelected: onValueChange(colorType),
        allowGradient
      },
      isMobile,
      positioning: {
        referenceElement,
        placement: "left"
      },
      type: void 0,
      onClickOutside: {
        on: "pointerup",
        handler: lodash.noop
      },
      focusReturnElement: referenceElement ?? void 0
    });
  };
  const hasNoExistingOverlay = (bgKey) => {
    const fresh = getFreshAttrs();
    const legacyColor = fresh[bgKey === "background" ? "backgroundColor" : "backdropColor"];
    const overlayColor = getResolvedLayoutFillColor(fresh[bgKey], legacyColor ?? void 0);
    return !overlayColor || overlayColor === TRANSPARENT_HEX_COLOR;
  };
  const onValueChange = (colorType) => (value) => {
    const applyOverlayAutoAlpha = (v) => {
      if (v?.color && !v.gradient && getOpacityFromHex(v.color) === 100) {
        return { ...v, color: combineHexWithOpacity(v.color, 50) ?? v.color };
      }
      return v;
    };
    const freshAttrs = getFreshAttrs();
    if (colorType === "backgroundColor") {
      const hasImage = !!freshAttrs.backgroundImage;
      const adjusted = hasImage && hasNoExistingOverlay("background") ? applyOverlayAutoAlpha(value) : value;
      patchPmNodeAttrs({
        ...getLayoutFillPatch("background", toLayoutFill(adjusted)),
        // Neutralize old imageOpacity so backward compat no longer overrides user alpha
        ...hasImage && {
          backgroundImage: { ...freshAttrs.backgroundImage, opacity: 100 }
        }
      });
    } else if (colorType === "backdropColor") {
      const hasImage = !!freshAttrs.backdropImage;
      const adjusted = hasImage && hasNoExistingOverlay("backdrop") ? applyOverlayAutoAlpha(value) : value;
      patchPmNodeAttrs({
        ...getLayoutFillPatch("backdrop", toLayoutFill(adjusted)),
        ...hasImage && {
          backdropImage: { ...freshAttrs.backdropImage, opacity: 100 }
        }
      });
    } else {
      const currentBorderWidth = pmNodeAttrs.borderWidth ?? LAYOUT_DEFAULTS.borderWidth;
      const borderWidthUpdate = currentBorderWidth === 0 ? { borderWidth: 1 } : {};
      patchPmNodeAttrs({
        borderColor: value?.color ?? TRANSPARENT_HEX_COLOR,
        ...borderWidthUpdate
      });
    }
  };
  const onColorChange = (colorType) => (color) => onValueChange(colorType)(color ? { color } : void 0);
  const onBgImageRequest = async (key) => {
    await handleLayoutImageUpload({
      services: {
        devService,
        uploadService,
        editorProps,
        wixInstance,
        modals: modalService
      },
      config,
      publicCommands: getPublicCommands(),
      nodeId,
      nodeType: RICOS_LAYOUT_TYPE,
      attributeKey: key
    });
  };
  const onBgImageRemove = (key) => patchPmNodeAttrs({ [key]: void 0 });
  const onBackgroundChange = (newValue, key) => {
    const bgKey = key === "backgroundImage" ? "background" : "backdrop";
    const freshAttrs = getFreshAttrs();
    const currentImage = freshAttrs[key];
    const hasImage = !!currentImage;
    const shouldAutoAlpha = hasImage && hasNoExistingOverlay(bgKey);
    const colorPatch = "color" in newValue && newValue.color && shouldAutoAlpha && getOpacityFromHex(newValue.color) === 100 ? getLayoutFillPatch(
      bgKey,
      toLayoutFill({ color: combineHexWithOpacity(newValue.color, 50) ?? newValue.color })
    ) : "color" in newValue ? getLayoutFillPatch(bgKey, toLayoutFill({ color: newValue.color })) : void 0;
    patchPmNodeAttrs({
      ...colorPatch,
      // Neutralize old imageOpacity so backward compat no longer overrides user alpha
      ...colorPatch && currentImage && { [key]: { ...currentImage, opacity: 100 } },
      ..."image" in newValue && { [key]: newValue.image },
      ..."imageScaling" in newValue && currentImage && {
        [key]: {
          ...currentImage,
          scaling: newValue.imageScaling
        }
      },
      ..."imagePosition" in newValue && currentImage && {
        [key]: {
          ...currentImage,
          position: newValue.imagePosition
        }
      },
      ..."imageBlur" in newValue && currentImage && {
        [key]: {
          ...currentImage,
          blur: newValue.imageBlur
        }
      }
    });
  };
  const onBorderWidthChange = (width) => patchPmNodeAttrs({ borderWidth: width ?? 0 });
  const onBorderRadiusChange = (radius) => patchPmNodeAttrs({ borderRadius: radius ?? 0 });
  const backgroundGradient = currentBackground?.type === "GRADIENT" ? schemaGradientToCss(currentBackground.gradient, theme.colorPalette) : void 0;
  const themeBackgroundColor = resolveColorToDisplayHex(
    "var(--ricos-custom-layout-background-color)",
    containerEl
  );
  const rawBackgroundColor = (currentBackground?.type === "COLOR" ? currentBackground.color : void 0) ?? themeBackgroundColor;
  const backgroundColorValue = rawBackgroundColor ? resolveBackwardCompatOverlay(
    rawBackgroundColor,
    pmNodeAttrs.backgroundImage?.opacity ?? 100,
    100
  ) : rawBackgroundColor;
  const backdropGradient = currentBackdrop?.type === "GRADIENT" ? schemaGradientToCss(currentBackdrop.gradient, theme.colorPalette) : void 0;
  const themeBackdropColor = resolveColorToDisplayHex(
    "var(--ricos-custom-layout-backdrop-color)",
    containerEl
  );
  const rawBackdropColor = (currentBackdrop?.type === "COLOR" ? currentBackdrop.color : void 0) ?? themeBackdropColor;
  const backdropColorValue = rawBackdropColor ? resolveBackwardCompatOverlay(rawBackdropColor, pmNodeAttrs.backdropImage?.opacity ?? 100, 100) : rawBackdropColor;
  return /* @__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("Layout_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: backgroundColorValue ?? TRANSPARENT_HEX_COLOR,
      gradient: backgroundGradient,
      onChange: (newValue) => onBackgroundChange(newValue, "backgroundImage"),
      openColorPicker: () => {
        openColorPicker(
          "backgroundColor",
          backgroundColorPickerRef.current,
          backgroundColorValue
        );
        logBi({ dataHook: LAYOUT_SETTINGS_BACKGROUND_COLOR_PICKER });
      },
      colorPickerRef: backgroundColorPickerRef,
      backgroundTypeToggleDataHook: LAYOUT_SETTINGS_BACKGROUND_TYPE_TOGGLE,
      colorDataHook: LAYOUT_SETTINGS_BACKGROUND_COLOR_INPUT,
      colorPickerDataHook: LAYOUT_SETTINGS_BACKGROUND_COLOR_PICKER,
      imageDataHook: LAYOUT_SETTINGS_BACKGROUND_IMAGE_VIEWER,
      imageScalingDataHook: LAYOUT_SETTINGS_BACKGROUND_SCALING_SELECT,
      imagePositionDataHook: LAYOUT_SETTINGS_BACKGROUND_POSITION_SELECT,
      imageBlurDataHook: LAYOUT_SETTINGS_BACKGROUND_BLUR_INPUT,
      onImageRequest: () => onBgImageRequest("backgroundImage"),
      onImageRemove: () => onBgImageRemove("backgroundImage"),
      logBi
    }
  ), /* @__PURE__ */ React.createElement(
    ColorWithOpacityInput,
    {
      label: t("Layout_SettingsModal_Tab_Design_Container_BorderColor"),
      fill: {
        type: "color",
        color: pmNodeAttrs.borderColor ?? TRANSPARENT_HEX_COLOR,
        onChange: onColorChange("borderColor"),
        allowTransparent: true
      },
      onColorPress: () => openColorPicker("borderColor", borderColorPickerRef.current),
      colorPickerRef: borderColorPickerRef,
      inputDataHook: LAYOUT_SETTINGS_BORDER_COLOR_INPUT,
      fillPreviewDataHook: LAYOUT_SETTINGS_BORDER_COLOR_PICKER,
      zIndex,
      logBi
    }
  ), /* @__PURE__ */ React.createElement(
    NumberInputWithLabel,
    {
      label: t("Layout_SettingsModal_Tab_Design_Container_BorderWidth"),
      dataHook: LAYOUT_SETTINGS_BORDER_WIDTH_INPUT,
      suffix: /* @__PURE__ */ React.createElement(Input.Affix, null, t("Common_Units_PX")),
      value: pmNodeAttrs.borderWidth ?? LAYOUT_DEFAULTS.borderWidth,
      min: 0,
      max: 15,
      onChange: onBorderWidthChange,
      logBi,
      zIndex
    }
  ), /* @__PURE__ */ React.createElement(
    NumberInputWithLabel,
    {
      label: t("Layout_SettingsModal_Tab_Design_Container_BorderRadius"),
      dataHook: LAYOUT_SETTINGS_BORDER_RADIUS_INPUT,
      suffix: /* @__PURE__ */ React.createElement(Input.Affix, null, t("Common_Units_PX")),
      value: pmNodeAttrs.borderRadius ?? LAYOUT_DEFAULTS.borderRadius,
      min: 0,
      max: 30,
      onChange: onBorderRadiusChange,
      logBi,
      zIndex
    }
  ), /* @__PURE__ */ React.createElement(
    TogglesWithLabel,
    {
      label: t("Layout_SettingsModal_Tab_Layout_Design_Target_Label"),
      value: pmNodeAttrs.designTarget || LAYOUT_DEFAULTS.designTarget,
      options: [
        {
          label: t("Layout_SettingsModal_Tab_Layout_Design_Target_Cell"),
          value: "LAYOUT",
          icon: /* @__PURE__ */ React.createElement(LayoutFullSmall, { height: "100%" }),
          dataHook: LAYOUT_SETTINGS_DESIGN_TARGET_LAYOUT
        },
        {
          label: t("Layout_SettingsModal_Tab_Layout_Design_Target_Layout"),
          value: "CELL",
          icon: /* @__PURE__ */ React.createElement(LayoutTwoColumnsSplitSmall, { height: "100%" }),
          dataHook: LAYOUT_SETTINGS_DESIGN_TARGET_CELL
        }
      ],
      onChange: (value) => patchPmNodeAttrs({ designTarget: value })
    }
  )), /* @__PURE__ */ React.createElement(Divider, null), /* @__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("Layout_SettingsModal_Tab_Design_Backdrop_Label"))), /* @__PURE__ */ React.createElement(
    ToggleButton,
    {
      checked: showBackdropSection,
      title: t("Layout_SettingsModal_Tab_Design_Backdrop_Toggle_Label"),
      size: "small",
      dataHook: LAYOUT_SETTINGS_BACKDROP_TOGGLE,
      onChange: () => {
        setShowBackdropSection((prev) => !prev);
        if (!showBackdropSection) {
          patchPmNodeAttrs({
            ...getLayoutFillPatch("backdrop", clearTransparentLayoutFill(prevBackdrop)),
            backdropPaddingTop: prevBackdropPaddingTop || DEFAULT_BACKDROP_VERTICAL_SPACING,
            backdropPaddingBottom: prevBackdropPaddingBottom || DEFAULT_BACKDROP_VERTICAL_SPACING,
            backdropImage: prevBackdropImage
          });
          return;
        }
        setPrevBackdrop(currentBackdrop);
        setPrevBackdropImage(pmNodeAttrs.backdropImage);
        patchPmNodeAttrs({
          ...getLayoutFillPatch("backdrop", void 0),
          backdropImage: void 0,
          backdropPaddingTop: void 0,
          backdropPaddingBottom: void 0
        });
      },
      infoContent: t("Layout_SettingsModal_Tab_Design_Backdrop_Toggle_Tooltip"),
      tooltipAppendTo: containerEl
    }
  ), showBackdropSection && /* @__PURE__ */ React.createElement(
    BackgroundSection,
    {
      imageLoading: pmNodeAttrs.loading?.backdropImage,
      image: pmNodeAttrs.backdropImage,
      imageScaling: pmNodeAttrs.backdropImage?.scaling ?? "CONTAIN",
      imagePosition: pmNodeAttrs.backdropImage?.position ?? "CENTER",
      imageBlur: pmNodeAttrs.backdropImage?.blur ?? 0,
      color: backdropColorValue ?? TRANSPARENT_HEX_COLOR,
      gradient: backdropGradient,
      onChange: (newValue) => onBackgroundChange(newValue, "backdropImage"),
      openColorPicker: () => {
        openColorPicker("backdropColor", backdropColorPickerRef.current, backdropColorValue);
        logBi({ dataHook: LAYOUT_SETTINGS_BACKDROP_COLOR_PICKER });
      },
      colorPickerRef: backdropColorPickerRef,
      backgroundTypeToggleDataHook: LAYOUT_SETTINGS_BACKDROP_TYPE_TOGGLE,
      colorDataHook: LAYOUT_SETTINGS_BACKDROP_COLOR_INPUT,
      colorPickerDataHook: LAYOUT_SETTINGS_BACKDROP_COLOR_PICKER,
      imageDataHook: LAYOUT_SETTINGS_BACKDROP_IMAGE_VIEWER,
      imageScalingDataHook: LAYOUT_SETTINGS_BACKDROP_SCALING_SELECT,
      imagePositionDataHook: LAYOUT_SETTINGS_BACKDROP_POSITION_SELECT,
      imageBlurDataHook: LAYOUT_SETTINGS_BACKDROP_BLUR_INPUT,
      onImageRequest: () => onBgImageRequest("backdropImage"),
      onImageRemove: () => onBgImageRemove("backdropImage"),
      logBi
    }
  )));
};
export {
  DesignTab
};
//# sourceMappingURL=design-tab.js.map
