import { PanelBody, Button, SelectControl, FocalPointPicker, RangeControl, TextControl, ToggleControl, ColorPicker, GradientPicker } from "@wordpress/components";
import { useState } from "@wordpress/element";
import { __ } from "@wordpress/i18n";
import { MediaUpload, MediaUploadCheck } from "@wordpress/block-editor";
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";
import { __experimentalUnitControl as UnitControl } from "@wordpress/components";

const TRANSITION_DEFAULT_VALUES = {
  thumbnailTransitionDuration: 300,
  thumbnailTransitionDelay: 200,
  thumbnailTransitionEasing: "ease",
};

const EASING_PRESETS = [
  { label: "ease", value: "ease" },
  { label: "ease-in", value: "ease-in" },
  { label: "ease-out", value: "ease-out" },
  { label: "ease-in-out", value: "ease-in-out" },
  { label: "linear", value: "linear" },
  { label: "cubic-bezier(0.4, 0, 0.2, 1)", value: "cubic-bezier(0.4, 0, 0.2, 1)" },
  { label: "cubic-bezier(0.4, 0, 1, 1)", value: "cubic-bezier(0.4, 0, 1, 1)" },
  { label: "cubic-bezier(0, 0, 0.2, 1)", value: "cubic-bezier(0, 0, 0.2, 1)" },
  { label: __("Custom", "zenblocks"), value: "custom" },
];

const ThumbnailSettingV3 = ({ attributes, setAttributes, title, initialOpen = false, isHoverState = false }) => {
  const suffix = isHoverState ? "Hover" : "";
  const responsiveEnabled = attributes.responsiveThumbnail !== undefined ? attributes.responsiveThumbnail : false;
  const responsiveColorEnabled = attributes[`responsiveThumbnailColor${suffix}`] !== undefined ? attributes[`responsiveThumbnailColor${suffix}`] : false;
  const { activeTab } = useResponsiveTab();

  const currentEasing = attributes.thumbnailTransitionEasing || TRANSITION_DEFAULT_VALUES.thumbnailTransitionEasing;
  const isPresetValue = EASING_PRESETS.some((preset) => preset.value === currentEasing && preset.value !== "custom");
  const [isCustomMode, setIsCustomMode] = useState(!isPresetValue);

  const handleImageChange = (image) => {
    if (!responsiveEnabled) {
      setAttributes({
        [`thumbnailUrlPC${suffix}`]: image.url,
        [`thumbnailUrlSP${suffix}`]: image.url,
        [`thumbnailId${suffix}`]: image.id || null,
        [`thumbnailAlt${suffix}`]: image.alt || "",
      });
    } else {
      setAttributes({
        [`thumbnailUrl${activeTab.toUpperCase()}${suffix}`]: image.url,
        [`thumbnailId${suffix}`]: image.id || null,
        [`thumbnailAlt${suffix}`]: image.alt || "",
      });
    }
  };

  const handleRemoveImage = () => {
    if (!responsiveEnabled) {
      setAttributes({
        [`thumbnailUrlPC${suffix}`]: "",
        [`thumbnailUrlSP${suffix}`]: "",
        [`thumbnailId${suffix}`]: null,
        [`thumbnailAlt${suffix}`]: "",
      });
    } else {
      setAttributes({
        [`thumbnailUrl${activeTab.toUpperCase()}${suffix}`]: "",
      });
    }
  };

  const handleFocalPositionChange = (focalPoint) => {
    const { x, y } = focalPoint;
    const position = `${x * 100}% ${y * 100}%`;

    if (!responsiveEnabled) {
      setAttributes({
        [`thumbnailFocalPositionPC${suffix}`]: position,
        [`thumbnailFocalPositionSP${suffix}`]: position,
      });
    } else {
      setAttributes({ [`thumbnailFocalPosition${activeTab.toUpperCase()}${suffix}`]: position });
    }
  };

  const handleOffsetXChange = (value, unit) => {
    if (!responsiveEnabled) {
      if (value !== undefined) {
        setAttributes({
          [`thumbnailOffsetXPC${suffix}`]: value,
          [`thumbnailOffsetXSP${suffix}`]: value,
        });
      }
      if (unit !== undefined) {
        setAttributes({
          [`thumbnailOffsetXUnitPC${suffix}`]: unit,
          [`thumbnailOffsetXUnitSP${suffix}`]: unit,
        });
      }
    } else {
      if (value !== undefined) {
        setAttributes({ [`thumbnailOffsetX${activeTab.toUpperCase()}${suffix}`]: value });
      }
      if (unit !== undefined) {
        setAttributes({ [`thumbnailOffsetXUnit${activeTab.toUpperCase()}${suffix}`]: unit });
      }
    }
  };

  const handleOffsetYChange = (value, unit) => {
    if (!responsiveEnabled) {
      if (value !== undefined) {
        setAttributes({
          [`thumbnailOffsetYPC${suffix}`]: value,
          [`thumbnailOffsetYSP${suffix}`]: value,
        });
      }
      if (unit !== undefined) {
        setAttributes({
          [`thumbnailOffsetYUnitPC${suffix}`]: unit,
          [`thumbnailOffsetYUnitSP${suffix}`]: unit,
        });
      }
    } else {
      if (value !== undefined) {
        setAttributes({ [`thumbnailOffsetY${activeTab.toUpperCase()}${suffix}`]: value });
      }
      if (unit !== undefined) {
        setAttributes({ [`thumbnailOffsetYUnit${activeTab.toUpperCase()}${suffix}`]: unit });
      }
    }
  };

  const handleBgWidthChange = (value, unit) => {
    if (!responsiveEnabled) {
      if (value !== undefined) {
        setAttributes({
          [`thumbnailBgWidthPC${suffix}`]: value,
          [`thumbnailBgWidthSP${suffix}`]: value,
        });
      }
      if (unit !== undefined) {
        setAttributes({
          [`thumbnailBgWidthUnitPC${suffix}`]: unit,
          [`thumbnailBgWidthUnitSP${suffix}`]: unit,
        });
      }
    } else {
      if (value !== undefined) {
        setAttributes({ [`thumbnailBgWidth${activeTab.toUpperCase()}${suffix}`]: value });
      }
      if (unit !== undefined) {
        setAttributes({ [`thumbnailBgWidthUnit${activeTab.toUpperCase()}${suffix}`]: unit });
      }
    }
  };

  const handleBgHeightChange = (value, unit) => {
    if (!responsiveEnabled) {
      if (value !== undefined) {
        setAttributes({
          [`thumbnailBgHeightPC${suffix}`]: value,
          [`thumbnailBgHeightSP${suffix}`]: value,
        });
      }
      if (unit !== undefined) {
        setAttributes({
          [`thumbnailBgHeightUnitPC${suffix}`]: unit,
          [`thumbnailBgHeightUnitSP${suffix}`]: unit,
        });
      }
    } else {
      if (value !== undefined) {
        setAttributes({ [`thumbnailBgHeight${activeTab.toUpperCase()}${suffix}`]: value });
      }
      if (unit !== undefined) {
        setAttributes({ [`thumbnailBgHeightUnit${activeTab.toUpperCase()}${suffix}`]: unit });
      }
    }
  };

  const handleFrameWidthChange = (value, unit) => {
    if (!responsiveEnabled) {
      if (value !== undefined) {
        setAttributes({
          [`thumbnailFrameWidthPC${suffix}`]: value,
          [`thumbnailFrameWidthSP${suffix}`]: value,
        });
      }
      if (unit !== undefined) {
        setAttributes({
          [`thumbnailFrameWidthUnitPC${suffix}`]: unit,
          [`thumbnailFrameWidthUnitSP${suffix}`]: unit,
        });
      }
    } else {
      if (value !== undefined) {
        setAttributes({ [`thumbnailFrameWidth${activeTab.toUpperCase()}${suffix}`]: value });
      }
      if (unit !== undefined) {
        setAttributes({ [`thumbnailFrameWidthUnit${activeTab.toUpperCase()}${suffix}`]: unit });
      }
    }
  };

  const handleFrameHeightChange = (value, unit) => {
    if (!responsiveEnabled) {
      if (value !== undefined) {
        setAttributes({
          [`thumbnailFrameHeightPC${suffix}`]: value,
          [`thumbnailFrameHeightSP${suffix}`]: value,
        });
      }
      if (unit !== undefined) {
        setAttributes({
          [`thumbnailFrameHeightUnitPC${suffix}`]: unit,
          [`thumbnailFrameHeightUnitSP${suffix}`]: unit,
        });
      }
    } else {
      if (value !== undefined) {
        setAttributes({ [`thumbnailFrameHeight${activeTab.toUpperCase()}${suffix}`]: value });
      }
      if (unit !== undefined) {
        setAttributes({ [`thumbnailFrameHeightUnit${activeTab.toUpperCase()}${suffix}`]: unit });
      }
    }
  };

  const handleRadiusChange = (value, unit) => {
    if (!responsiveEnabled) {
      if (value !== undefined) {
        setAttributes({
          [`thumbnailBorderRadiusPC${suffix}`]: value,
          [`thumbnailBorderRadiusSP${suffix}`]: value,
        });
      }
      if (unit !== undefined) {
        setAttributes({
          [`thumbnailBorderRadiusUnitPC${suffix}`]: unit,
          [`thumbnailBorderRadiusUnitSP${suffix}`]: unit,
        });
      }
    } else {
      if (value !== undefined) {
        setAttributes({ [`thumbnailBorderRadius${activeTab.toUpperCase()}${suffix}`]: value });
      }
      if (unit !== undefined) {
        setAttributes({ [`thumbnailBorderRadiusUnit${activeTab.toUpperCase()}${suffix}`]: unit });
      }
    }
  };

  const handleObjectFitChange = (value) => {
    if (!responsiveEnabled) {
      setAttributes({
        [`thumbnailObjectFitPC${suffix}`]: value,
        [`thumbnailObjectFitSP${suffix}`]: value,
      });
    } else {
      setAttributes({ [`thumbnailObjectFit${activeTab.toUpperCase()}${suffix}`]: value });
    }
  };

  const handleColorChange = (color) => {
    if (!responsiveColorEnabled) {
      setAttributes({
        [`thumbnailColorPC${suffix}`]: color.hex,
        [`thumbnailColorSP${suffix}`]: color.hex,
      });
    } else {
      setAttributes({ [`thumbnailColor${activeTab.toUpperCase()}${suffix}`]: color.hex });
    }
  };

  const handleGradientChange = (gradient) => {
    if (!responsiveColorEnabled) {
      setAttributes({
        [`thumbnailGradientPC${suffix}`]: gradient,
        [`thumbnailGradientSP${suffix}`]: gradient,
      });
    } else {
      setAttributes({ [`thumbnailGradient${activeTab.toUpperCase()}${suffix}`]: gradient });
    }
  };

  const handleColorOpacityChange = (opacity) => {
    const numericOpacity = Number(parseFloat(opacity));
    if (!responsiveColorEnabled) {
      setAttributes({
        [`thumbnailColorOpacityPC${suffix}`]: numericOpacity,
        [`thumbnailColorOpacitySP${suffix}`]: numericOpacity,
      });
    } else {
      setAttributes({ [`thumbnailColorOpacity${activeTab.toUpperCase()}${suffix}`]: numericOpacity });
    }
  };

  const handleColorMixBlendModeChange = (mode) => {
    if (!responsiveColorEnabled) {
      setAttributes({
        [`thumbnailColorMixBlendModePC${suffix}`]: mode,
        [`thumbnailColorMixBlendModeSP${suffix}`]: mode,
      });
    } else {
      setAttributes({ [`thumbnailColorMixBlendMode${activeTab.toUpperCase()}${suffix}`]: mode });
    }
  };

  const resetThumbnailColor = () => {
    if (!responsiveColorEnabled) {
      setAttributes({
        [`thumbnailColorPC${suffix}`]: "transparent",
        [`thumbnailGradientPC${suffix}`]: null,
        [`thumbnailUseGradientPC${suffix}`]: false,
        [`thumbnailColorOpacityPC${suffix}`]: 1,
        [`thumbnailColorMixBlendModePC${suffix}`]: "normal",
        [`thumbnailColorSP${suffix}`]: "transparent",
        [`thumbnailGradientSP${suffix}`]: null,
        [`thumbnailUseGradientSP${suffix}`]: false,
        [`thumbnailColorOpacitySP${suffix}`]: 1,
        [`thumbnailColorMixBlendModeSP${suffix}`]: "normal",
      });
    } else {
      setAttributes({
        [`thumbnailColor${activeTab.toUpperCase()}${suffix}`]: "transparent",
        [`thumbnailGradient${activeTab.toUpperCase()}${suffix}`]: null,
        [`thumbnailUseGradient${activeTab.toUpperCase()}${suffix}`]: false,
        [`thumbnailColorOpacity${activeTab.toUpperCase()}${suffix}`]: 1,
        [`thumbnailColorMixBlendMode${activeTab.toUpperCase()}${suffix}`]: "normal",
      });
    }
  };

  const handleResponsiveColorToggle = (value) => {
    setAttributes({ [`responsiveThumbnailColor${suffix}`]: value });

    if (!value) {
      setAttributes({
        [`thumbnailColorSP${suffix}`]: attributes[`thumbnailColorPC${suffix}`],
        [`thumbnailGradientSP${suffix}`]: attributes[`thumbnailGradientPC${suffix}`],
        [`thumbnailUseGradientSP${suffix}`]: attributes[`thumbnailUseGradientPC${suffix}`],
        [`thumbnailColorOpacitySP${suffix}`]: attributes[`thumbnailColorOpacityPC${suffix}`],
        [`thumbnailColorMixBlendModeSP${suffix}`]: attributes[`thumbnailColorMixBlendModePC${suffix}`],
      });
    }
  };

  const handleResponsiveToggle = (value) => {
    setAttributes({ responsiveThumbnail: value });

    if (!value) {
      const syncAttrs = {};

      if (attributes[`thumbnailUrlPC${suffix}`]) {
        syncAttrs[`thumbnailUrlSP${suffix}`] = attributes[`thumbnailUrlPC${suffix}`];
      }
      if (attributes[`thumbnailFocalPositionPC${suffix}`]) {
        syncAttrs[`thumbnailFocalPositionSP${suffix}`] = attributes[`thumbnailFocalPositionPC${suffix}`];
      }
      if (attributes[`thumbnailOffsetXPC${suffix}`] !== undefined) {
        syncAttrs[`thumbnailOffsetXSP${suffix}`] = attributes[`thumbnailOffsetXPC${suffix}`];
      }
      if (attributes[`thumbnailOffsetYPC${suffix}`] !== undefined) {
        syncAttrs[`thumbnailOffsetYSP${suffix}`] = attributes[`thumbnailOffsetYPC${suffix}`];
      }
      if (attributes[`thumbnailOffsetXUnitPC${suffix}`]) {
        syncAttrs[`thumbnailOffsetXUnitSP${suffix}`] = attributes[`thumbnailOffsetXUnitPC${suffix}`];
      }
      if (attributes[`thumbnailOffsetYUnitPC${suffix}`]) {
        syncAttrs[`thumbnailOffsetYUnitSP${suffix}`] = attributes[`thumbnailOffsetYUnitPC${suffix}`];
      }
      if (attributes[`thumbnailBgWidthPC${suffix}`] !== undefined) {
        syncAttrs[`thumbnailBgWidthSP${suffix}`] = attributes[`thumbnailBgWidthPC${suffix}`];
      }
      if (attributes[`thumbnailBgHeightPC${suffix}`] !== undefined) {
        syncAttrs[`thumbnailBgHeightSP${suffix}`] = attributes[`thumbnailBgHeightPC${suffix}`];
      }
      if (attributes[`thumbnailBgWidthUnitPC${suffix}`]) {
        syncAttrs[`thumbnailBgWidthUnitSP${suffix}`] = attributes[`thumbnailBgWidthUnitPC${suffix}`];
      }
      if (attributes[`thumbnailBgHeightUnitPC${suffix}`]) {
        syncAttrs[`thumbnailBgHeightUnitSP${suffix}`] = attributes[`thumbnailBgHeightUnitPC${suffix}`];
      }
      if (attributes[`thumbnailFrameWidthPC${suffix}`] !== undefined) {
        syncAttrs[`thumbnailFrameWidthSP${suffix}`] = attributes[`thumbnailFrameWidthPC${suffix}`];
      }
      if (attributes[`thumbnailFrameHeightPC${suffix}`] !== undefined) {
        syncAttrs[`thumbnailFrameHeightSP${suffix}`] = attributes[`thumbnailFrameHeightPC${suffix}`];
      }
      if (attributes[`thumbnailFrameWidthUnitPC${suffix}`]) {
        syncAttrs[`thumbnailFrameWidthUnitSP${suffix}`] = attributes[`thumbnailFrameWidthUnitPC${suffix}`];
      }
      if (attributes[`thumbnailFrameHeightUnitPC${suffix}`]) {
        syncAttrs[`thumbnailFrameHeightUnitSP${suffix}`] = attributes[`thumbnailFrameHeightUnitPC${suffix}`];
      }
      if (attributes[`thumbnailBorderRadiusPC${suffix}`] !== undefined) {
        syncAttrs[`thumbnailBorderRadiusSP${suffix}`] = attributes[`thumbnailBorderRadiusPC${suffix}`];
      }
      if (attributes[`thumbnailBorderRadiusUnitPC${suffix}`]) {
        syncAttrs[`thumbnailBorderRadiusUnitSP${suffix}`] = attributes[`thumbnailBorderRadiusUnitPC${suffix}`];
      }
      if (attributes[`thumbnailObjectFitPC${suffix}`]) {
        syncAttrs[`thumbnailObjectFitSP${suffix}`] = attributes[`thumbnailObjectFitPC${suffix}`];
      }

      if (Object.keys(syncAttrs).length > 0) {
        setAttributes(syncAttrs);
      }
    }
  };

  const renderThumbnailControls = () => {
    const imageUrl = attributes[`thumbnailUrlPC`] || "";
    const focalPosition = attributes[`thumbnailFocalPosition${activeTab.toUpperCase()}${suffix}`] || "50% 50%";
    const bgWidthRaw = attributes[`thumbnailBgWidth${activeTab.toUpperCase()}${suffix}`];
    const bgHeightRaw = attributes[`thumbnailBgHeight${activeTab.toUpperCase()}${suffix}`];
    const bgWidth = bgWidthRaw === "auto" ? "auto" : (bgWidthRaw || 100);
    const bgHeight = bgHeightRaw === "auto" ? "auto" : (bgHeightRaw || 100);
    const bgWidthUnit = attributes[`thumbnailBgWidthUnit${activeTab.toUpperCase()}${suffix}`] || "%";
    const bgHeightUnit = attributes[`thumbnailBgHeightUnit${activeTab.toUpperCase()}${suffix}`] || "%";
    const objectFit = attributes[`thumbnailObjectFit${activeTab.toUpperCase()}${suffix}`] || "cover";
    const isWidthAuto = bgWidth === "auto";
    const isHeightAuto = bgHeight === "auto";

    const [x, y] = focalPosition.split(" ").map((val) => parseFloat(val) / 100);

    const units = [
      { label: "px", value: "px" },
      { label: "%", value: "%" },
      { label: "vw", value: "vw" },
    ];

    return (
      <div className="zenblocks-inspector-thumbnail-image">
        {!isHoverState && (
          <div className="zenblocks-inspector-thumbnail-image__button-container" style={{ marginBottom: "15px" }}>
            <MediaUploadCheck>
              <MediaUpload
                onSelect={handleImageChange}
                allowedTypes={["image"]}
                value={attributes[`thumbnailId${suffix}`]}
                render={({ open }) => (
                  <Button onClick={open} isPrimary className="zenblocks-inspector-thumbnail-image__set-button">
                    {imageUrl ? __("Change Image", "zenblocks") : __("Select Image", "zenblocks")}
                  </Button>
                )}
              />
            </MediaUploadCheck>
            {imageUrl && (
              <Button isSecondary onClick={handleRemoveImage} className="zenblocks-inspector-thumbnail-image__remove-button" style={{ marginLeft: "10px" }}>
                {__("Remove Image", "zenblocks")}
              </Button>
            )}
          </div>
        )}

        {imageUrl && (
          <FocalPointPicker
            url={imageUrl}
            value={{ x, y }}
            onChange={handleFocalPositionChange}
          />
        )}

        <div className="zenblocks-inspector-thumbnail-image__settings">
          <SelectControl
            label={__("Fit Method", "zenblocks")}
            value={objectFit}
            options={[
              { label: __("Cover", "zenblocks"), value: "cover" },
              { label: __("Contain", "zenblocks"), value: "contain" },
              { label: __("Fill", "zenblocks"), value: "fill" },
              { label: __("None", "zenblocks"), value: "none" },
            ]}
            onChange={handleObjectFitChange}
            className="zenblocks-inspector-thumbnail-image__object-fit-select"
          />

          {(objectFit === "fill" || objectFit === "none") && (
            <div className="zenblocks-inspector-thumbnail-image__custom-size" style={{ marginTop: "10px" }}>
              <div className="zenblocks-inspector-thumbnail-image__width-controls" style={{ marginBottom: "12px" }}>
                <label style={{ display: "block", marginBottom: "4px", fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>
                  {__("Width", "zenblocks")}
                </label>
                <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                  <div style={{ flex: 1, opacity: isWidthAuto ? 0.5 : 1, pointerEvents: isWidthAuto ? "none" : "auto" }}>
                    <UnitControl
                      value={isWidthAuto ? "" : `${bgWidth}${bgWidthUnit}`}
                      onChange={(value) => {
                        const numValue = parseFloat(value);
                        const unit = value.replace(/[\d.-]/g, "");
                        handleBgWidthChange(numValue, unit || bgWidthUnit);
                      }}
                      units={units}
                      placeholder={isWidthAuto ? "auto" : ""}
                    />
                  </div>
                  <Button
                    isSmall
                    variant={isWidthAuto ? "primary" : "secondary"}
                    onClick={() => {
                      if (isWidthAuto) {
                        handleBgWidthChange(100, "%");
                      } else {
                        handleBgWidthChange("auto", "");
                      }
                    }}
                    style={{ flexShrink: 0 }}
                  >
                    AUTO
                  </Button>
                </div>
              </div>

              <div className="zenblocks-inspector-thumbnail-image__height-controls">
                <label style={{ display: "block", marginBottom: "4px", fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>
                  {__("Height", "zenblocks")}
                </label>
                <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                  <div style={{ flex: 1, opacity: isHeightAuto ? 0.5 : 1, pointerEvents: isHeightAuto ? "none" : "auto" }}>
                    <UnitControl
                      value={isHeightAuto ? "" : `${bgHeight}${bgHeightUnit}`}
                      onChange={(value) => {
                        const numValue = parseFloat(value);
                        const unit = value.replace(/[\d.-]/g, "");
                        handleBgHeightChange(numValue, unit || bgHeightUnit);
                      }}
                      units={units}
                      placeholder={isHeightAuto ? "auto" : ""}
                    />
                  </div>
                  <Button
                    isSmall
                    variant={isHeightAuto ? "primary" : "secondary"}
                    onClick={() => {
                      if (isHeightAuto) {
                        handleBgHeightChange(100, "%");
                      } else {
                        handleBgHeightChange("auto", "");
                      }
                    }}
                    style={{ flexShrink: 0 }}
                  >
                    AUTO
                  </Button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    );
  };

  const renderSizeControls = () => {
    const frameWidth = attributes[`thumbnailFrameWidth${activeTab.toUpperCase()}${suffix}`] || 60;
    const frameHeight = attributes[`thumbnailFrameHeight${activeTab.toUpperCase()}${suffix}`] || 60;
    const frameWidthUnit = attributes[`thumbnailFrameWidthUnit${activeTab.toUpperCase()}${suffix}`] || "px";
    const frameHeightUnit = attributes[`thumbnailFrameHeightUnit${activeTab.toUpperCase()}${suffix}`] || "px";

    const units = [
      { label: "px", value: "px" },
      { label: "%", value: "%" },
      { label: "vw", value: "vw" },
    ];

    return (
      <div className="zenblocks-inspector-thumbnail-size">
        <div className="zenblocks-inspector-thumbnail-size__controls" style={{ marginBottom: "10px" }}>
          <UnitControl
            label={__("Width", "zenblocks")}
            value={`${frameWidth}${frameWidthUnit}`}
            onChange={(value) => {
              const numValue = parseFloat(value);
              const unit = value.replace(/[\d.-]/g, "");
              handleFrameWidthChange(numValue, unit || frameWidthUnit);
            }}
            units={units}
          />
        </div>

        <div className="zenblocks-inspector-thumbnail-size__controls" style={{ marginBottom: "10px" }}>
          <UnitControl
            label={__("Height", "zenblocks")}
            value={`${frameHeight}${frameHeightUnit}`}
            onChange={(value) => {
              const numValue = parseFloat(value);
              const unit = value.replace(/[\d.-]/g, "");
              handleFrameHeightChange(numValue, unit || frameHeightUnit);
            }}
            units={units}
          />
        </div>
      </div>
    );
  };

  const renderRadiusControls = () => {
    const borderRadius = attributes[`thumbnailBorderRadius${activeTab.toUpperCase()}${suffix}`] || 0;
    const borderRadiusUnit = attributes[`thumbnailBorderRadiusUnit${activeTab.toUpperCase()}${suffix}`] || "px";

    const units = [
      { label: "px", value: "px" },
      { label: "%", value: "%" },
      { label: "vw", value: "vw" },
    ];

    return (
      <div className="zenblocks-inspector-thumbnail-radius">
        <div className="zenblocks-inspector-thumbnail-radius__controls" style={{ marginBottom: "10px" }}>
          <UnitControl
            label={__("Border Radius", "zenblocks")}
            value={`${borderRadius}${borderRadiusUnit}`}
            onChange={(value) => {
              const numValue = parseFloat(value);
              const unit = value.replace(/[\d.-]/g, "");
              handleRadiusChange(numValue, unit || borderRadiusUnit);
            }}
            units={units}
          />
        </div>
      </div>
    );
  };

  const renderPositionControls = () => {
    const offsetX = attributes[`thumbnailOffsetX${activeTab.toUpperCase()}${suffix}`] || 0;
    const offsetY = attributes[`thumbnailOffsetY${activeTab.toUpperCase()}${suffix}`] || 0;
    const offsetXUnit = attributes[`thumbnailOffsetXUnit${activeTab.toUpperCase()}${suffix}`] || "%";
    const offsetYUnit = attributes[`thumbnailOffsetYUnit${activeTab.toUpperCase()}${suffix}`] || "%";

    const units = [
      { label: "px", value: "px" },
      { label: "%", value: "%" },
      { label: "vw", value: "vw" },
    ];

    return (
      <div className="zenblocks-inspector-thumbnail-position">
        <div className="zenblocks-inspector-thumbnail-position__controls" style={{ marginBottom: "10px" }}>
          <UnitControl
            label={__("X Position", "zenblocks")}
            value={`${offsetX}${offsetXUnit}`}
            onChange={(value) => {
              const numValue = parseFloat(value);
              const unit = value.replace(/[\d.-]/g, "");
              handleOffsetXChange(numValue, unit || offsetXUnit);
            }}
            units={units}
          />
        </div>
        <div className="zenblocks-inspector-thumbnail-position__controls" style={{ marginBottom: "10px" }}>
          <UnitControl
            label={__("Y Position", "zenblocks")}
            value={`${offsetY}${offsetYUnit}`}
            onChange={(value) => {
              const numValue = parseFloat(value);
              const unit = value.replace(/[\d.-]/g, "");
              handleOffsetYChange(numValue, unit || offsetYUnit);
            }}
            units={units}
          />
        </div>
      </div>
    );
  };

  const renderColorControls = (tab) => {
    const useGradientAttr = `thumbnailUseGradient${tab.toUpperCase()}${suffix}`;
    const useGradient = attributes[useGradientAttr];

    return (
      <div className="zenblocks-inspector-thumbnail-color">
        <ToggleControl
          label={__("Use Gradient", "zenblocks")}
          checked={useGradient}
          onChange={(value) => {
            if (!responsiveColorEnabled) {
              setAttributes({
                [`thumbnailUseGradientPC${suffix}`]: value,
                [`thumbnailUseGradientSP${suffix}`]: value,
              });
              if (!value) {
                setAttributes({
                  [`thumbnailGradientPC${suffix}`]: null,
                  [`thumbnailGradientSP${suffix}`]: null,
                });
              } else {
                if (!attributes[`thumbnailGradientPC${suffix}`]) {
                  setAttributes({
                    [`thumbnailGradientPC${suffix}`]: "linear-gradient(135deg, #007FD6 0%, #02439D 100%)",
                    [`thumbnailGradientSP${suffix}`]: "linear-gradient(135deg, #007FD6 0%, #02439D 100%)",
                  });
                }
              }
            } else {
              setAttributes({ [useGradientAttr]: value });
              if (!value) {
                setAttributes({ [`thumbnailGradient${tab.toUpperCase()}${suffix}`]: null });
              } else {
                const gradientAttr = `thumbnailGradient${tab.toUpperCase()}${suffix}`;
                if (!attributes[gradientAttr]) {
                  setAttributes({ [gradientAttr]: "linear-gradient(135deg, #007FD6 0%, #02439D 100%)" });
                }
              }
            }
          }}
        />
        {useGradient ? (
          <GradientPicker 
            value={attributes[`thumbnailGradient${tab.toUpperCase()}${suffix}`]} 
            onChange={handleGradientChange}
            className="zenblocks-inspector-thumbnail-color__gradient-picker"
          />
        ) : (
          <ColorPicker 
            color={attributes[`thumbnailColor${tab.toUpperCase()}${suffix}`]} 
            onChangeComplete={handleColorChange} 
            disableAlpha
            className="zenblocks-inspector-thumbnail-color__color-picker"
          />
        )}
        <RangeControl 
          label={__("Opacity", "zenblocks")} 
          value={attributes[`thumbnailColorOpacity${tab.toUpperCase()}${suffix}`]} 
          onChange={handleColorOpacityChange} 
          min={0} 
          max={1} 
          step={0.1}
          className="zenblocks-inspector-thumbnail-color__opacity-control"
        />
        <SelectControl
          label={__("Blend Mode", "zenblocks")}
          value={attributes[`thumbnailColorMixBlendMode${tab.toUpperCase()}${suffix}`]}
          options={[
            { label: "Normal", value: "normal" },
            { label: "Multiply", value: "multiply" },
            { label: "Screen", value: "screen" },
            { label: "Overlay", value: "overlay" },
            { label: "Darken", value: "darken" },
            { label: "Lighten", value: "lighten" },
            { label: "Color Dodge", value: "color-dodge" },
            { label: "Color Burn", value: "color-burn" },
            { label: "Hard Light", value: "hard-light" },
            { label: "Soft Light", value: "soft-light" },
            { label: "Difference", value: "difference" },
            { label: "Exclusion", value: "exclusion" },
            { label: "Hue", value: "hue" },
            { label: "Saturation", value: "saturation" },
            { label: "Color", value: "color" },
            { label: "Luminosity", value: "luminosity" },
          ]}
          onChange={handleColorMixBlendModeChange}
          className="zenblocks-inspector-thumbnail-color__blend-mode-select"
        />
        <Button 
          isSecondary 
          onClick={resetThumbnailColor} 
          style={{ marginTop: "10px" }}
          className="zenblocks-inspector-thumbnail-color__reset-button"
        >
          {__("Reset to Transparent", "zenblocks")}
        </Button>
      </div>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <PanelBody title={__("Image Selection", "zenblocks")} initialOpen={true}>
        <ResponsiveControl
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName="responsiveThumbnail"
        >
          {renderThumbnailControls}
        </ResponsiveControl>
      </PanelBody>
      <PanelBody title={__("Color", "zenblocks")} initialOpen={false}>
        <ResponsiveControl
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveColorEnabled}
          onResponsiveToggle={handleResponsiveColorToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={`responsiveThumbnailColor${suffix}`}
        >
          {renderColorControls}
        </ResponsiveControl>
      </PanelBody>
      <PanelBody title={__("Size", "zenblocks")} initialOpen={false}>
        <ResponsiveControl
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName="responsiveThumbnail"
        >
          {renderSizeControls}
        </ResponsiveControl>
      </PanelBody>
      <PanelBody title={__("Border Radius", "zenblocks")} initialOpen={false}>
        <ResponsiveControl
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName="responsiveThumbnail"
        >
          {renderRadiusControls}
        </ResponsiveControl>
      </PanelBody>
      <PanelBody title={__("Position", "zenblocks")} initialOpen={false}>
        <ResponsiveControl
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName="responsiveThumbnail"
        >
          {renderPositionControls}
        </ResponsiveControl>
      </PanelBody>
      <PanelBody title={__("Transition", "zenblocks")} initialOpen={false}>
        <div style={{ marginBottom: "16px" }}>
          <RangeControl
            label={__("Duration (ms)", "zenblocks")}
            value={attributes.thumbnailTransitionDuration ?? TRANSITION_DEFAULT_VALUES.thumbnailTransitionDuration}
            onChange={(value) => setAttributes({ thumbnailTransitionDuration: value })}
            min={0}
            max={2000}
            step={50}
          />
        </div>
        <div style={{ marginBottom: "16px" }}>
          <RangeControl
            label={__("Delay (ms)", "zenblocks")}
            value={attributes.thumbnailTransitionDelay ?? TRANSITION_DEFAULT_VALUES.thumbnailTransitionDelay}
            onChange={(value) => setAttributes({ thumbnailTransitionDelay: value })}
            min={0}
            max={2000}
            step={50}
          />
        </div>
        <div style={{ marginBottom: "16px" }}>
          <SelectControl
            label={__("Easing", "zenblocks")}
            value={isCustomMode ? "custom" : currentEasing}
            options={EASING_PRESETS}
            onChange={(value) => {
              if (value === "custom") {
                setIsCustomMode(true);
              } else {
                setIsCustomMode(false);
                setAttributes({ thumbnailTransitionEasing: value });
              }
            }}
          />
          {isCustomMode && (
            <TextControl
              label={__("Custom Value", "zenblocks")}
              value={currentEasing}
              onChange={(value) => setAttributes({ thumbnailTransitionEasing: value })}
              placeholder="cubic-bezier(0.25, 0.1, 0.25, 1)"
              help={__("e.g. cubic-bezier(0.25, 0.1, 0.25, 1)", "zenblocks")}
            />
          )}
        </div>
        {(attributes.thumbnailTransitionDuration !== TRANSITION_DEFAULT_VALUES.thumbnailTransitionDuration ||
          attributes.thumbnailTransitionDelay !== TRANSITION_DEFAULT_VALUES.thumbnailTransitionDelay ||
          attributes.thumbnailTransitionEasing !== TRANSITION_DEFAULT_VALUES.thumbnailTransitionEasing) && (
          <div style={{ marginTop: "8px" }}>
            <Button
              variant="secondary"
              isSmall
              onClick={() => {
                setAttributes({
                  thumbnailTransitionDuration: TRANSITION_DEFAULT_VALUES.thumbnailTransitionDuration,
                  thumbnailTransitionDelay: TRANSITION_DEFAULT_VALUES.thumbnailTransitionDelay,
                  thumbnailTransitionEasing: TRANSITION_DEFAULT_VALUES.thumbnailTransitionEasing,
                });
                setIsCustomMode(false);
              }}
            >
              {__("Reset", "zenblocks")}
            </Button>
          </div>
        )}
      </PanelBody>
    </PanelBody>
  );
};

export default ThumbnailSettingV3;
