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 ResponsiveControlV2 from "../../ResponsiveControlV2";
import { useResponsiveTabV2 } from "../../ResponsiveTabContextV2";
import { __experimentalUnitControl as UnitControl } from "@wordpress/components";
import PanelBodyWithSync from "../../PanelBodyWithSync";
import ProFeatureOverlay from "../../ProFeatureOverlay";
import { getEnabledBreakpoints } from "../../../../../core/breakpoints";

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 ThumbnailSettingV6 = ({ attributes, setAttributes, title, initialOpen = false, isHoverState = false, onSync, onSyncImage, onSyncColor, onSyncSize, onSyncRadius, onSyncPosition, panelStates = {}, onTogglePanel, isPro = false }) => {
  const suffix = isHoverState ? "Hover" : "";
  const responsiveAttrName = `responsiveThumbnail${suffix}`;
  const responsiveColorAttrName = `responsiveThumbnailColor${suffix}`;
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const responsiveColorEnabled = attributes[responsiveColorAttrName] !== undefined ? attributes[responsiveColorAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  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 handleResponsiveToggle = (value) => {
    setAttributes({ [responsiveAttrName]: value });

    const syncAttrs = {};
    enabledBreakpoints.slice(1).forEach(bp => {
      syncAttrs[`thumbnailUrl${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailUrlPC${suffix}`];
      syncAttrs[`thumbnailFocalPosition${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailFocalPositionPC${suffix}`];
      syncAttrs[`thumbnailOffsetX${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailOffsetXPC${suffix}`];
      syncAttrs[`thumbnailOffsetXUnit${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailOffsetXUnitPC${suffix}`];
      syncAttrs[`thumbnailOffsetY${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailOffsetYPC${suffix}`];
      syncAttrs[`thumbnailOffsetYUnit${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailOffsetYUnitPC${suffix}`];
      syncAttrs[`thumbnailBgWidth${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailBgWidthPC${suffix}`];
      syncAttrs[`thumbnailBgWidthUnit${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailBgWidthUnitPC${suffix}`];
      syncAttrs[`thumbnailBgHeight${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailBgHeightPC${suffix}`];
      syncAttrs[`thumbnailBgHeightUnit${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailBgHeightUnitPC${suffix}`];
      syncAttrs[`thumbnailFrameWidth${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailFrameWidthPC${suffix}`];
      syncAttrs[`thumbnailFrameWidthUnit${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailFrameWidthUnitPC${suffix}`];
      syncAttrs[`thumbnailFrameHeight${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailFrameHeightPC${suffix}`];
      syncAttrs[`thumbnailFrameHeightUnit${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailFrameHeightUnitPC${suffix}`];
      syncAttrs[`thumbnailBorderRadius${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailBorderRadiusPC${suffix}`];
      syncAttrs[`thumbnailBorderRadiusUnit${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailBorderRadiusUnitPC${suffix}`];
      syncAttrs[`thumbnailObjectFit${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailObjectFitPC${suffix}`];
    });
    setAttributes(syncAttrs);
  };

  const handleResponsiveColorToggle = (value) => {
    setAttributes({ [responsiveColorAttrName]: value });

    const syncAttrs = {};
    enabledBreakpoints.slice(1).forEach(bp => {
      syncAttrs[`thumbnailColor${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailColorPC${suffix}`];
      syncAttrs[`thumbnailGradient${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailGradientPC${suffix}`];
      syncAttrs[`thumbnailUseGradient${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailUseGradientPC${suffix}`];
      syncAttrs[`thumbnailColorOpacity${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailColorOpacityPC${suffix}`];
      syncAttrs[`thumbnailColorMixBlendMode${bp.toUpperCase()}${suffix}`] = attributes[`thumbnailColorMixBlendModePC${suffix}`];
    });
    setAttributes(syncAttrs);
  };

  const renderThumbnailControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const imageUrl = responsiveEnabled 
      ? (attributes[`thumbnailUrl${deviceSuffix}${suffix}`] || attributes[`thumbnailUrlPC${suffix}`] || "")
      : (attributes[`thumbnailUrlPC${suffix}`] || "");
    const focalPosition = attributes[`thumbnailFocalPosition${deviceSuffix}${suffix}`] || attributes[`thumbnailFocalPositionPC${suffix}`] || "50% 50%";
    const bgWidthRaw = attributes[`thumbnailBgWidth${deviceSuffix}${suffix}`];
    const bgHeightRaw = attributes[`thumbnailBgHeight${deviceSuffix}${suffix}`];
    const bgWidth = bgWidthRaw === "auto" ? "auto" : (bgWidthRaw || 100);
    const bgHeight = bgHeightRaw === "auto" ? "auto" : (bgHeightRaw || 100);
    const bgWidthUnit = attributes[`thumbnailBgWidthUnit${deviceSuffix}${suffix}`] || "%";
    const bgHeightUnit = attributes[`thumbnailBgHeightUnit${deviceSuffix}${suffix}`] || "%";
    const objectFit = attributes[`thumbnailObjectFit${deviceSuffix}${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" },
    ];

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

    const handleRemoveImage = () => {
      if (!responsiveEnabled) {
        const attrs = { [`thumbnailId${suffix}`]: null, [`thumbnailAlt${suffix}`]: "" };
        enabledBreakpoints.forEach(bp => {
          attrs[`thumbnailUrl${bp.toUpperCase()}${suffix}`] = "";
        });
        setAttributes(attrs);
      } else {
        setAttributes({ [`thumbnailUrl${deviceSuffix}${suffix}`]: "" });
      }
    };

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

      if (!responsiveEnabled) {
        const attrs = {};
        enabledBreakpoints.forEach(bp => {
          attrs[`thumbnailFocalPosition${bp.toUpperCase()}${suffix}`] = position;
        });
        setAttributes(attrs);
      } else {
        setAttributes({ [`thumbnailFocalPosition${deviceSuffix}${suffix}`]: position });
      }
    };

    const handleObjectFitChange = (value) => {
      if (!responsiveEnabled) {
        const attrs = {};
        enabledBreakpoints.forEach(bp => {
          attrs[`thumbnailObjectFit${bp.toUpperCase()}${suffix}`] = value;
          // フィル選択時: 横幅100%・高さautoを初期値として設定
          if (value === "fill") {
            attrs[`thumbnailBgWidth${bp.toUpperCase()}${suffix}`] = 100;
            attrs[`thumbnailBgWidthUnit${bp.toUpperCase()}${suffix}`] = "%";
            attrs[`thumbnailBgHeight${bp.toUpperCase()}${suffix}`] = "auto";
          }
        });
        setAttributes(attrs);
      } else {
        const attrs = { [`thumbnailObjectFit${deviceSuffix}${suffix}`]: value };
        // フィル選択時: 横幅100%・高さautoを初期値として設定
        if (value === "fill") {
          attrs[`thumbnailBgWidth${deviceSuffix}${suffix}`] = 100;
          attrs[`thumbnailBgWidthUnit${deviceSuffix}${suffix}`] = "%";
          attrs[`thumbnailBgHeight${deviceSuffix}${suffix}`] = "auto";
        }
        setAttributes(attrs);
      }
    };

    const handleBgWidthChange = (value, unit) => {
      if (!responsiveEnabled) {
        if (value !== undefined) {
          const attrs = {};
          enabledBreakpoints.forEach(bp => {
            attrs[`thumbnailBgWidth${bp.toUpperCase()}${suffix}`] = value;
          });
          setAttributes(attrs);
        }
        if (unit !== undefined) {
          const attrs = {};
          enabledBreakpoints.forEach(bp => {
            attrs[`thumbnailBgWidthUnit${bp.toUpperCase()}${suffix}`] = unit;
          });
          setAttributes(attrs);
        }
      } else {
        if (value !== undefined) {
          setAttributes({ [`thumbnailBgWidth${deviceSuffix}${suffix}`]: value });
        }
        if (unit !== undefined) {
          setAttributes({ [`thumbnailBgWidthUnit${deviceSuffix}${suffix}`]: unit });
        }
      }
    };

    const handleBgHeightChange = (value, unit) => {
      if (!responsiveEnabled) {
        if (value !== undefined) {
          const attrs = {};
          enabledBreakpoints.forEach(bp => {
            attrs[`thumbnailBgHeight${bp.toUpperCase()}${suffix}`] = value;
          });
          setAttributes(attrs);
        }
        if (unit !== undefined) {
          const attrs = {};
          enabledBreakpoints.forEach(bp => {
            attrs[`thumbnailBgHeightUnit${bp.toUpperCase()}${suffix}`] = unit;
          });
          setAttributes(attrs);
        }
      } else {
        if (value !== undefined) {
          setAttributes({ [`thumbnailBgHeight${deviceSuffix}${suffix}`]: value });
        }
        if (unit !== undefined) {
          setAttributes({ [`thumbnailBgHeightUnit${deviceSuffix}${suffix}`]: unit });
        }
      }
    };

    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 renderColorControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const useGradientAttr = `thumbnailUseGradient${deviceSuffix}${suffix}`;
    const useGradient = attributes[useGradientAttr];

    const handleColorChange = (color) => {
      if (!responsiveColorEnabled) {
        const attrs = {};
        enabledBreakpoints.forEach(bp => {
          attrs[`thumbnailColor${bp.toUpperCase()}${suffix}`] = color.hex;
        });
        setAttributes(attrs);
      } else {
        setAttributes({ [`thumbnailColor${deviceSuffix}${suffix}`]: color.hex });
      }
    };

    const handleGradientChange = (gradient) => {
      if (!responsiveColorEnabled) {
        const attrs = {};
        enabledBreakpoints.forEach(bp => {
          attrs[`thumbnailGradient${bp.toUpperCase()}${suffix}`] = gradient;
        });
        setAttributes(attrs);
      } else {
        setAttributes({ [`thumbnailGradient${deviceSuffix}${suffix}`]: gradient });
      }
    };

    const handleColorOpacityChange = (opacity) => {
      const numericOpacity = Number(parseFloat(opacity));
      if (!responsiveColorEnabled) {
        const attrs = {};
        enabledBreakpoints.forEach(bp => {
          attrs[`thumbnailColorOpacity${bp.toUpperCase()}${suffix}`] = numericOpacity;
        });
        setAttributes(attrs);
      } else {
        setAttributes({ [`thumbnailColorOpacity${deviceSuffix}${suffix}`]: numericOpacity });
      }
    };

    const handleColorMixBlendModeChange = (mode) => {
      if (!responsiveColorEnabled) {
        const attrs = {};
        enabledBreakpoints.forEach(bp => {
          attrs[`thumbnailColorMixBlendMode${bp.toUpperCase()}${suffix}`] = mode;
        });
        setAttributes(attrs);
      } else {
        setAttributes({ [`thumbnailColorMixBlendMode${deviceSuffix}${suffix}`]: mode });
      }
    };

    const resetThumbnailColor = () => {
      if (!responsiveColorEnabled) {
        const attrs = {};
        enabledBreakpoints.forEach(bp => {
          attrs[`thumbnailColor${bp.toUpperCase()}${suffix}`] = "transparent";
          attrs[`thumbnailGradient${bp.toUpperCase()}${suffix}`] = null;
          attrs[`thumbnailUseGradient${bp.toUpperCase()}${suffix}`] = false;
          attrs[`thumbnailColorOpacity${bp.toUpperCase()}${suffix}`] = 1;
          attrs[`thumbnailColorMixBlendMode${bp.toUpperCase()}${suffix}`] = "normal";
        });
        setAttributes(attrs);
      } else {
        setAttributes({
          [`thumbnailColor${deviceSuffix}${suffix}`]: "transparent",
          [`thumbnailGradient${deviceSuffix}${suffix}`]: null,
          [`thumbnailUseGradient${deviceSuffix}${suffix}`]: false,
          [`thumbnailColorOpacity${deviceSuffix}${suffix}`]: 1,
          [`thumbnailColorMixBlendMode${deviceSuffix}${suffix}`]: "normal",
        });
      }
    };

    return (
      <div className="zenblocks-inspector-thumbnail-color">
        <ToggleControl
          label={__("Use Gradient", "zenblocks")}
          checked={useGradient}
          onChange={(value) => {
            if (!responsiveColorEnabled) {
              const attrs = {};
              enabledBreakpoints.forEach(bp => {
                attrs[`thumbnailUseGradient${bp.toUpperCase()}${suffix}`] = value;
              });
              if (!value) {
                enabledBreakpoints.forEach(bp => {
                  attrs[`thumbnailGradient${bp.toUpperCase()}${suffix}`] = null;
                });
              } else {
                if (!attributes[`thumbnailGradientPC${suffix}`]) {
                  enabledBreakpoints.forEach(bp => {
                    attrs[`thumbnailGradient${bp.toUpperCase()}${suffix}`] = "linear-gradient(135deg, #007FD6 0%, #02439D 100%)";
                  });
                }
              }
              setAttributes(attrs);
            } else {
              setAttributes({ [useGradientAttr]: value });
              if (!value) {
                setAttributes({ [`thumbnailGradient${deviceSuffix}${suffix}`]: null });
              } else {
                const gradientAttr = `thumbnailGradient${deviceSuffix}${suffix}`;
                if (!attributes[gradientAttr]) {
                  setAttributes({ [gradientAttr]: "linear-gradient(135deg, #007FD6 0%, #02439D 100%)" });
                }
              }
            }
          }}
        />
        {useGradient ? (
          <GradientPicker 
            value={attributes[`thumbnailGradient${deviceSuffix}${suffix}`]} 
            onChange={handleGradientChange}
            className="zenblocks-inspector-thumbnail-color__gradient-picker"
          />
        ) : (
          <ColorPicker 
            color={attributes[`thumbnailColor${deviceSuffix}${suffix}`]} 
            onChangeComplete={handleColorChange} 
            disableAlpha
            className="zenblocks-inspector-thumbnail-color__color-picker"
          />
        )}
        <RangeControl 
          label={__("Opacity", "zenblocks")} 
          value={attributes[`thumbnailColorOpacity${deviceSuffix}${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${deviceSuffix}${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>
    );
  };

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

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

    const handleFrameWidthChange = (value, unit) => {
      if (!responsiveEnabled) {
        if (value !== undefined) {
          const attrs = {};
          enabledBreakpoints.forEach(bp => {
            attrs[`thumbnailFrameWidth${bp.toUpperCase()}${suffix}`] = value;
          });
          setAttributes(attrs);
        }
        if (unit !== undefined) {
          const attrs = {};
          enabledBreakpoints.forEach(bp => {
            attrs[`thumbnailFrameWidthUnit${bp.toUpperCase()}${suffix}`] = unit;
          });
          setAttributes(attrs);
        }
      } else {
        if (value !== undefined) {
          setAttributes({ [`thumbnailFrameWidth${deviceSuffix}${suffix}`]: value });
        }
        if (unit !== undefined) {
          setAttributes({ [`thumbnailFrameWidthUnit${deviceSuffix}${suffix}`]: unit });
        }
      }
    };

    const handleFrameHeightChange = (value, unit) => {
      if (!responsiveEnabled) {
        if (value !== undefined) {
          const attrs = {};
          enabledBreakpoints.forEach(bp => {
            attrs[`thumbnailFrameHeight${bp.toUpperCase()}${suffix}`] = value;
          });
          setAttributes(attrs);
        }
        if (unit !== undefined) {
          const attrs = {};
          enabledBreakpoints.forEach(bp => {
            attrs[`thumbnailFrameHeightUnit${bp.toUpperCase()}${suffix}`] = unit;
          });
          setAttributes(attrs);
        }
      } else {
        if (value !== undefined) {
          setAttributes({ [`thumbnailFrameHeight${deviceSuffix}${suffix}`]: value });
        }
        if (unit !== undefined) {
          setAttributes({ [`thumbnailFrameHeightUnit${deviceSuffix}${suffix}`]: unit });
        }
      }
    };

    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 = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const borderRadius = attributes[`thumbnailBorderRadius${deviceSuffix}${suffix}`] || 0;
    const borderRadiusUnit = attributes[`thumbnailBorderRadiusUnit${deviceSuffix}${suffix}`] || "px";

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

    const handleRadiusChange = (value, unit) => {
      if (!responsiveEnabled) {
        if (value !== undefined) {
          const attrs = {};
          enabledBreakpoints.forEach(bp => {
            attrs[`thumbnailBorderRadius${bp.toUpperCase()}${suffix}`] = value;
          });
          setAttributes(attrs);
        }
        if (unit !== undefined) {
          const attrs = {};
          enabledBreakpoints.forEach(bp => {
            attrs[`thumbnailBorderRadiusUnit${bp.toUpperCase()}${suffix}`] = unit;
          });
          setAttributes(attrs);
        }
      } else {
        if (value !== undefined) {
          setAttributes({ [`thumbnailBorderRadius${deviceSuffix}${suffix}`]: value });
        }
        if (unit !== undefined) {
          setAttributes({ [`thumbnailBorderRadiusUnit${deviceSuffix}${suffix}`]: unit });
        }
      }
    };

    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 = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const offsetX = attributes[`thumbnailOffsetX${deviceSuffix}${suffix}`] || 0;
    const offsetY = attributes[`thumbnailOffsetY${deviceSuffix}${suffix}`] || 0;
    const offsetXUnit = attributes[`thumbnailOffsetXUnit${deviceSuffix}${suffix}`] || "%";
    const offsetYUnit = attributes[`thumbnailOffsetYUnit${deviceSuffix}${suffix}`] || "%";

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

    const handleOffsetXChange = (value, unit) => {
      if (!responsiveEnabled) {
        if (value !== undefined) {
          const attrs = {};
          enabledBreakpoints.forEach(bp => {
            attrs[`thumbnailOffsetX${bp.toUpperCase()}${suffix}`] = value;
          });
          setAttributes(attrs);
        }
        if (unit !== undefined) {
          const attrs = {};
          enabledBreakpoints.forEach(bp => {
            attrs[`thumbnailOffsetXUnit${bp.toUpperCase()}${suffix}`] = unit;
          });
          setAttributes(attrs);
        }
      } else {
        if (value !== undefined) {
          setAttributes({ [`thumbnailOffsetX${deviceSuffix}${suffix}`]: value });
        }
        if (unit !== undefined) {
          setAttributes({ [`thumbnailOffsetXUnit${deviceSuffix}${suffix}`]: unit });
        }
      }
    };

    const handleOffsetYChange = (value, unit) => {
      if (!responsiveEnabled) {
        if (value !== undefined) {
          const attrs = {};
          enabledBreakpoints.forEach(bp => {
            attrs[`thumbnailOffsetY${bp.toUpperCase()}${suffix}`] = value;
          });
          setAttributes(attrs);
        }
        if (unit !== undefined) {
          const attrs = {};
          enabledBreakpoints.forEach(bp => {
            attrs[`thumbnailOffsetYUnit${bp.toUpperCase()}${suffix}`] = unit;
          });
          setAttributes(attrs);
        }
      } else {
        if (value !== undefined) {
          setAttributes({ [`thumbnailOffsetY${deviceSuffix}${suffix}`]: value });
        }
        if (unit !== undefined) {
          setAttributes({ [`thumbnailOffsetYUnit${deviceSuffix}${suffix}`]: unit });
        }
      }
    };

    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 content = (
    <>
      <PanelBodyWithSync title={__("Image Selection", "zenblocks")} opened={panelStates.thumbnailImage} onToggle={() => onTogglePanel && onTogglePanel("thumbnailImage")} onSync={onSyncImage} className="zenblocks-nested-panel">
        <ResponsiveControlV2
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderThumbnailControls(tabName)}
        </ResponsiveControlV2>
      </PanelBodyWithSync>
      <PanelBodyWithSync title={__("Color", "zenblocks")} opened={panelStates.thumbnailColor} onToggle={() => onTogglePanel && onTogglePanel("thumbnailColor")} onSync={onSyncColor} className="zenblocks-nested-panel">
        <ResponsiveControlV2
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveColorEnabled}
          onResponsiveToggle={handleResponsiveColorToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={responsiveColorAttrName}
        >
          {(tabName) => renderColorControls(tabName)}
        </ResponsiveControlV2>
      </PanelBodyWithSync>
      <PanelBodyWithSync title={__("Size", "zenblocks")} opened={panelStates.thumbnailSize} onToggle={() => onTogglePanel && onTogglePanel("thumbnailSize")} onSync={onSyncSize} className="zenblocks-nested-panel">
        <ResponsiveControlV2
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderSizeControls(tabName)}
        </ResponsiveControlV2>
      </PanelBodyWithSync>
      <PanelBodyWithSync title={__("Border Radius", "zenblocks")} opened={panelStates.thumbnailRadius} onToggle={() => onTogglePanel && onTogglePanel("thumbnailRadius")} onSync={onSyncRadius} className="zenblocks-nested-panel">
        <ResponsiveControlV2
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderRadiusControls(tabName)}
        </ResponsiveControlV2>
      </PanelBodyWithSync>
      <PanelBodyWithSync title={__("Position", "zenblocks")} opened={panelStates.thumbnailPosition} onToggle={() => onTogglePanel && onTogglePanel("thumbnailPosition")} onSync={onSyncPosition} className="zenblocks-nested-panel">
        <ResponsiveControlV2
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderPositionControls(tabName)}
        </ResponsiveControlV2>
      </PanelBodyWithSync>
      <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>
    </>
  );

  return (
    <PanelBody title={title} initialOpen={initialOpen} className="zenblocks-nested-panel">
      {isPro ? <ProFeatureOverlay featureName="サムネイル設定">{content}</ProFeatureOverlay> : content}
    </PanelBody>
  );
};

export default ThumbnailSettingV6;
