import {
  RichText,
  useBlockProps,
  InspectorControls,
  MediaUpload,
  MediaUploadCheck,
  PanelColorSettings,
} from "@wordpress/block-editor";

import {
  PanelBody,
  TextControl,
  ToggleControl,
  Button,
  IconButton,
  __experimentalUnitControl as UnitControl,
  __experimentalBoxControl as BoxControl,
} from "@wordpress/components";
import { useEffect, useState } from "react";
import Segment from "../../components/segment/Segment";
import { RangeControl } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import { link, linkOff } from "@wordpress/icons";

// Import logos
import BubbleLogo from "../../assets/images/Bubble.svg";
import GenStarsDark from "../../assets/images/GenstarsDark.svg";
import GenStarsWhite from "../../assets/images/GenstarsWhite.svg";

// Import extracted controls
import { FontSizeControl } from "./controls/FontSizeControl";
import { ButtonSizeControls } from "./controls/ButtonSizeControls";
import { MarginControls } from "./controls/MarginControls";
import { CustomLogoUpload } from "./controls/CustomLogoUpload";

interface Attributes {
  title: string;
  customAttributes: { key: string; value: string }[];
  backgroundColor: string;
  textColor: string;
  borderRadius: number;
  buttonHeight: number;
  buttonHeightOption: "compact" | "regular" | "custom";
  logoOption: string;
  customLogoUrl: string;
  customLogos: { url: string; id: number }[];
  buttonStyle: "solid" | "animated";
  gradientColor1: string;
  gradientColor2: string;
  borderColor: string;
  fontSize: number;
  borderStyle: "solid" | "dashed" | "dotted" | "none";
  themeCustomizable: boolean;
  darkModeBackgroundColor: string;
  darkModeTextColor: string;
  darkModeLogoOption: string;
  darkModeBackgroundType: "solid" | "gradient";
  darkModeGradientColor1: string;
  darkModeGradientColor2: string;
  interactiveButton: boolean;
  interactiveTexts: string[];
  collapseAtEnd: boolean;
  borderType: "solid" | "gradient" | "none";
  borderGradientColor1: string;
  borderGradientColor2: string;
  marginTop: string;
  marginRight: string;
  marginBottom: string;
  marginLeft: string;
  marginLinked: boolean;
  marginPreset: string;
  resizeMode: "dynamic" | "static";
  forceInit: boolean;
}

interface EditProps {
  attributes: Attributes;
  setAttributes: (attributes: Partial<Attributes>) => void;
}

const Edit = ({ attributes, setAttributes }: EditProps) => {
  const blockProps = useBlockProps();

  const {
    title,
    customAttributes,
    backgroundColor,
    textColor,
    borderRadius,
    buttonHeight,
    buttonHeightOption,
    logoOption,
    customLogoUrl,
    customLogos,
    buttonStyle,
    gradientColor1,
    gradientColor2,
    borderColor,
    fontSize,
    borderStyle,
    themeCustomizable,
    darkModeBackgroundColor,
    darkModeTextColor,
    darkModeLogoOption,
    darkModeBackgroundType,
    darkModeGradientColor1,
    darkModeGradientColor2,
    interactiveButton,
    interactiveTexts,
    collapseAtEnd,
    borderType,
    borderGradientColor1,
    borderGradientColor2,
    marginTop,
    marginRight,
    marginBottom,
    marginLeft,
    marginLinked,
    marginPreset,
    resizeMode,
    forceInit,
  } = attributes;

  // Interactive button state
  const [currentTextIndex, setCurrentTextIndex] = useState(0);
  const [displayedText, setDisplayedText] = useState(interactiveTexts?.[0] || "");
  const [isTyping, setIsTyping] = useState(false);
  const [hasCompleted, setHasCompleted] = useState(false);
  const [isLogoRotating, setIsLogoRotating] = useState(false);
  const [isAnimating, setIsAnimating] = useState(false);
  const [isExpanding, setIsExpanding] = useState(false);
  const [isClosing, setIsClosing] = useState(false);

  // Margin presets
  const marginPresets = [
    { label: "None", value: "none", margin: "0px" },
    { label: "Small", value: "small", margin: "8px" },
    { label: "Medium", value: "medium", margin: "16px" },
    { label: "Large", value: "large", margin: "24px" },
    { label: "Custom", value: "custom", margin: "" },
  ];

  useEffect(() => {
    if (interactiveButton && (!interactiveTexts || interactiveTexts.length === 0)) {
      setAttributes({ interactiveTexts: [""] });
    }
  }, [interactiveButton]);

  useEffect(() => {
    if (interactiveButton && interactiveTexts && interactiveTexts.length > 0) {
      setCurrentTextIndex(0);
      setDisplayedText(interactiveTexts[0]);

      setIsLogoRotating(true);
      setTimeout(() => {
        setIsLogoRotating(false);
      }, 800);
    } else {
      setCurrentTextIndex(-1);
      setDisplayedText("");
    }
  }, [interactiveButton, interactiveTexts]);

  useEffect(() => {
    const hasSpotlight = customAttributes.some(
      (attr) => attr.key === "data-sideconvo-mode"
    );

    if (!hasSpotlight) {
      const updated = [
        ...customAttributes,
        { key: "data-sideconvo-mode", value: "CHAT" },
      ];
      setAttributes({ customAttributes: updated });
    } else {
      let spotLightMode = customAttributes.find(
        (attr) => attr.key === "data-sideconvo-mode"
      );

      if (
        spotLightMode &&
        spotLightMode.value !== spotLightMode.value.toUpperCase()
      ) {
        const updated = customAttributes.map((attr) =>
          attr.key === "data-sideconvo-mode"
            ? { ...attr, value: attr.value.toUpperCase() }
            : attr
        );
        setAttributes({ customAttributes: updated });
      }
    }
  }, [customAttributes, setAttributes]);

  const updateTitle = (value: string) => {
    setAttributes({ title: value });
  };

  const updateCustomAttributes = (
    newAttrs: { key: string; value: string }[]
  ) => {
    setAttributes({ customAttributes: newAttrs });
  };

  const handleAttrChange = (key: string, value: string) => {
    let updated = [...customAttributes];
    const index = updated.findIndex((attr) => attr.key === key);

    if (index !== -1) {
      updated[index] = { ...updated[index], value };
    } else {
      updated.push({ key, value });
    }

    updateCustomAttributes(updated);
  };

  const getAttribute = (key: string) => {
    const attr = customAttributes.find((attr) => attr.key === key);
    return attr ? attr.value : "";
  };

  const updateBorderRadius = (value: number | undefined) => {
    setAttributes({ borderRadius: value ?? 20 });
  };

  const updateLogoOption = (value: string) => {
    setAttributes({ logoOption: value });
  };

  const updateDarkModeLogoOption = (value: string) => {
    setAttributes({ darkModeLogoOption: value });
  };

  const updateButtonStyle = (style: "solid" | "animated") => {
    setAttributes({ buttonStyle: style });

    if (style === "solid") {
      setAttributes({
        backgroundColor: "#ffffff",
        textColor: "#1a1a1a",
      });
    } else if (style === "animated") {
      setAttributes({
        textColor: "#ffffff",
      });
    }
  };

  // Interactive texts management
  const addInteractiveText = () => {
    if ((interactiveTexts || []).length >= 5) {
      return;
    }
    const newTexts = [...(interactiveTexts || []), ""];
    setAttributes({ interactiveTexts: newTexts });
  };

  const updateInteractiveText = (index: number, value: string) => {
    const newTexts = [...(interactiveTexts || [])];
    newTexts[index] = value;
    setAttributes({ interactiveTexts: newTexts });
  };

  const removeInteractiveText = (index: number) => {
    if (index === 0) {
      return;
    }
    const newTexts = (interactiveTexts || []).filter((_, i) => i !== index);
    setAttributes({ interactiveTexts: newTexts });
  };

  // Logo options with images
  const logoOptions = [
    { label: "Gen Stars (White)", value: "genstars-white", image: GenStarsWhite },
    { label: "Gen Stars (Dark)", value: "genstars-dark", image: GenStarsDark },
    { label: "Bubble Logo", value: "bubble", image: BubbleLogo },
  ];

  const toggleLogo = (value: string) => {
    if (logoOption === value) {
      updateLogoOption("none");
    } else {
      updateLogoOption(value);
    }
  };

  const toggleDarkModeLogo = (value: string) => {
    if (darkModeLogoOption === value) {
      updateDarkModeLogoOption("none");
    } else {
      updateDarkModeLogoOption(value);
    }
  };

  const customColors = [
    { name: 'Purple', color: '#701471' },
    { name: 'Pink', color: '#b3425a' },
    { name: 'Violet', color: '#7c3aed' },
    { name: 'White', color: '#ffffff' },
    { name: 'Black', color: '#000000' },
    { name: 'Dark Gray', color: '#181a20' },
    { name: 'Light Gray', color: '#f5f5f7' },
    { name: 'Blue', color: '#2271b1' },
    { name: 'Cyan', color: '#06b6d4' },
    { name: 'Teal', color: '#14b8a6' },
  ];

  const getLogoImage = () => {
    if (logoOption.startsWith("custom-")) {
      const customLogoId = parseInt(logoOption.replace("custom-", ""));
      const customLogo = customLogos?.find(logo => logo.id === customLogoId);
      return customLogo?.url || null;
    }

    switch (logoOption) {
      case "bubble":
        return BubbleLogo;
      case "genstars-dark":
        return GenStarsDark;
      case "genstars-white":
        return GenStarsWhite;
      default:
        return null;
    }
  };

  const selectedLogo = getLogoImage();

  const getButtonStyle = () => {
    const baseStyle: React.CSSProperties = {
      "--scbc-radius": `${borderRadius}px`,
      "--scbc-height": `${buttonHeight}px`,
      color: textColor,
      fontSize: `${fontSize}px`,
      border: "none",
      marginTop: marginTop || "0px",
      marginRight: marginRight || "0px",
      marginBottom: marginBottom || "0px",
      marginLeft: marginLeft || "0px",
    } as React.CSSProperties;

    if (borderType !== "none") {
      if (borderType === "gradient") {
        baseStyle.border = `2px solid transparent`;

        if (buttonStyle === "animated") {
          baseStyle.backgroundImage = `linear-gradient(135deg, ${gradientColor1}, ${gradientColor2}, ${gradientColor1}), linear-gradient(135deg, ${borderGradientColor1}, ${borderGradientColor2})`;
        } else {
          baseStyle.backgroundImage = `linear-gradient(${backgroundColor}, ${backgroundColor}), linear-gradient(135deg, ${borderGradientColor1}, ${borderGradientColor2})`;
        }

        baseStyle.backgroundOrigin = "border-box";
        baseStyle.backgroundClip = "padding-box, border-box";
      } else if (borderType === "solid") {
        baseStyle.border = `2px solid ${borderColor}`;
      }
    }

    if (buttonStyle === "animated") {
      if (borderType === "gradient") {
        return {
          ...baseStyle,
          backgroundSize: "200% 200%, 100% 100%",
        };
      } else {
        return {
          ...baseStyle,
          background: `linear-gradient(135deg, ${gradientColor1}, ${gradientColor2}, ${gradientColor1})`,
          backgroundSize: "200% 200%",
        };
      }
    } else {
      if (borderType === "gradient") {
        return baseStyle;
      } else {
        return {
          ...baseStyle,
          backgroundColor: backgroundColor,
        };
      }
    }
  };

  const hasValidPrompts = () => {
    return interactiveTexts && interactiveTexts.length > 0 &&
           interactiveTexts.some(text => text && text.trim());
  };

  const getCurrentDisplayText = () => {
    if (!interactiveButton) return title;
    return displayedText;
  };

  return (
    <div {...blockProps}>
<InspectorControls>
  {/* SPOTLIGHT SETTINGS */}
  <PanelBody title="Spotlight Settings" initialOpen={true}>
    <div className="scbc-button-block__section">
      <TextControl
        label="Starting Message (Optional)"
        help="Custom message to send to Sideconvo when the button is clicked."
        value={getAttribute("data-sideconvo-message")}
        onChange={(val) =>
          handleAttrChange("data-sideconvo-message", val)
        }
      />
    </div>

    <div className="scbc-button-block-options">
      <label>Conversation Mode</label>
      <Segment
        options={[
          { label: "CHAT", value: "CHAT" },
          { label: "SPEAK", value: "SPEAK" },
        ]}
        value={getAttribute("data-sideconvo-mode")}
        onChange={(val) => handleAttrChange("data-sideconvo-mode", val)}
      />
    </div>

    <div className="scbc-button-block__section">
      <ToggleControl
        label="Start with a Fresh Conversation"
        help="Ensures a clean conversation state by clearing previous spotlights when the button is clicked."
        checked={forceInit}
        onChange={(value) => setAttributes({ forceInit: value })}
      />
    </div>
  </PanelBody>

  {/* BUTTON APPEARANCE */}
  <PanelBody title="Button Appearance" initialOpen={true}>
    <div className="scbc-button-block__section">
      <label className="components-base-control__label">
        Icon
      </label>
      <div className="scbc-logo-grid">
        {logoOptions.map((option) => (
          <button
            key={option.value}
            className={`scbc-logo-option ${
              logoOption === option.value ? "is-selected" : ""
            }`}
            onClick={() => toggleLogo(option.value)}
            title={option.label}
          >
            <img src={option.image} alt={option.label} />
            {logoOption === option.value && (
              <span className="scbc-logo-checkmark">✓</span>
            )}
          </button>
        ))}

        {/* Custom Logos & Upload */}
        <CustomLogoUpload
          customLogos={customLogos}
          logoOption={logoOption}
          setAttributes={setAttributes}
        />
      </div>
    </div>

    {/* BORDER STYLE */}
    <div className="scbc-button-block__section">
      <label className="components-base-control__label">
        Border Style
      </label>

      <div className="scbc-border-type-selector">
        <div className="scbc-border-type-grid">
          <button
            className={`scbc-border-type-option ${
              borderType === "none" ? "is-selected" : ""
            }`}
            onClick={() => setAttributes({ borderType: "none" })}
          >
            <div className="scbc-border-type-preview none-border">
              <span>None</span>
            </div>
          </button>

          <button
            className={`scbc-border-type-option ${
              borderType === "solid" ? "is-selected" : ""
            }`}
            onClick={() => setAttributes({ borderType: "solid" })}
          >
            <div className="scbc-border-type-preview solid-border">
              <span>Solid</span>
            </div>
          </button>

          <button
            className={`scbc-border-type-option ${
              borderType === "gradient" ? "is-selected" : ""
            }`}
            onClick={() => setAttributes({ borderType: "gradient" })}
          >
            <div className="scbc-border-type-preview gradient-border">
              <span>Gradient</span>
            </div>
          </button>
        </div>
      </div>

      {borderType === "solid" && (
        <div style={{ marginTop: '16px' }}>
          <PanelColorSettings
            title={__('Border Color')}
            colorSettings={[
              {
                value: borderColor,
                onChange: (value: string | undefined) => setAttributes({ borderColor: value || '#b3425a' }),
                label: __('Border Color'),
                colors: customColors,
              },
            ]}
          />
        </div>
      )}

      {borderType === "gradient" && (
        <div style={{ marginTop: '16px' }}>
          <PanelColorSettings
            title={__('Border Gradient Colors')}
            colorSettings={[
              {
                value: borderGradientColor1,
                onChange: (value: string | undefined) => setAttributes({ borderGradientColor1: value || '#b3425a' }),
                label: __('Gradient Color 1'),
                colors: customColors,
              },
              {
                value: borderGradientColor2,
                onChange: (value: string | undefined) => setAttributes({ borderGradientColor2: value || '#7c3aed' }),
                label: __('Gradient Color 2'),
                colors: customColors,
              },
            ]}
          />
        </div>
      )}
    </div>

    <div className="scbc-button-block__section">
      <RangeControl
        label="Border Radius"
        value={borderRadius}
        onChange={updateBorderRadius}
        min={0}
        max={20}
        help={`Rounded corners: ${borderRadius}px`}
      />
    </div>

    <div className="scbc-button-block__section">
      <FontSizeControl fontSize={fontSize} setAttributes={setAttributes} />
    </div>

    <div className="scbc-button-block__section">
      <ButtonSizeControls
        buttonHeight={buttonHeight}
        buttonHeightOption={buttonHeightOption}
        setAttributes={setAttributes}
      />
    </div>
  </PanelBody>

  {/* BUTTON STYLE */}
  <PanelBody title="Style" initialOpen={true}>
    <div className="scbc-button-block__section">
      <div className="scbc-style-grid" style={{ gridTemplateColumns: 'repeat(2, 1fr)' }}>
        <button
          className={`scbc-style-option ${
            buttonStyle === "animated" ? "is-selected" : ""
          }`}
          onClick={() => updateButtonStyle("animated")}
        >
          <div className="scbc-style-preview animated-style">
            <span>Animated</span>
          </div>
        </button>

        <button
          className={`scbc-style-option ${
            buttonStyle === "solid" ? "is-selected" : ""
          }`}
          onClick={() => updateButtonStyle("solid")}
        >
          <div className="scbc-style-preview solid-style">
            <span>Solid</span>
          </div>
        </button>
      </div>
    </div>

    {buttonStyle === "solid" && (
      <div className="scbc-button-block__section">
        <PanelColorSettings
          title={__('Background Color')}
          colorSettings={[
            {
              value: backgroundColor,
              onChange: (value: string | undefined) => setAttributes({ backgroundColor: value || '#ffffff' }),
              label: __('Background Color'),
              colors: customColors,
            },
          ]}
        />
      </div>
    )}

    {buttonStyle === "animated" && (
      <div className="scbc-button-block__section">
        <PanelColorSettings
          title={__('Gradient Colors')}
          colorSettings={[
            {
              value: gradientColor1,
              onChange: (value: string | undefined) => setAttributes({ gradientColor1: value || '#b3425a' }),
              label: __('Gradient Color 1'),
              colors: customColors,
            },
            {
              value: gradientColor2,
              onChange: (value: string | undefined) => setAttributes({ gradientColor2: value || '#7c3aed' }),
              label: __('Gradient Color 2'),
              colors: customColors,
            },
          ]}
        />
      </div>
    )}

    <div className="scbc-button-block__section">
      <PanelColorSettings
        title={__('Text Color')}
        colorSettings={[
          {
            value: textColor,
            onChange: (value: string | undefined) => setAttributes({ textColor: value || '#ffffff' }),
            label: __('Text Color'),
            colors: customColors,
          },
        ]}
      />
    </div>

    <div className="scbc-button-block__section">
      <ToggleControl
        label={__('Dark Mode customization')}
        help={
          themeCustomizable
            ? __('Button will adapt to light and dark modes.')
            : __('Enable to customize button for dark mode.')
        }
        checked={themeCustomizable}
        onChange={(value) => setAttributes({ themeCustomizable: value })}
      />
    </div>

    {themeCustomizable && (
      <>
        <div className="scbc-button-block__section">
          <label className="components-base-control__label">
            Dark Mode Background Type
          </label>
          <div className="scbc-style-grid" style={{ gridTemplateColumns: 'repeat(2, 1fr)' }}>
            <button
              className={`scbc-style-option ${
                darkModeBackgroundType === "solid" ? "is-selected" : ""
              }`}
              onClick={() => setAttributes({ darkModeBackgroundType: "solid" })}
            >
              <div className="scbc-style-preview" style={{
                background: darkModeBackgroundColor,
                color: darkModeTextColor
              }}>
                <span>Solid</span>
              </div>
            </button>

            <button
              className={`scbc-style-option ${
                darkModeBackgroundType === "gradient" ? "is-selected" : ""
              }`}
              onClick={() => setAttributes({ darkModeBackgroundType: "gradient" })}
            >
              <div className="scbc-style-preview" style={{
                background: `linear-gradient(135deg, ${darkModeGradientColor1}, ${darkModeGradientColor2})`,
                color: darkModeTextColor
              }}>
                <span>Gradient</span>
              </div>
            </button>
          </div>
        </div>

        {darkModeBackgroundType === "solid" && (
          <div className="scbc-button-block__section">
            <PanelColorSettings
              title={__('Dark Mode Solid Color')}
              colorSettings={[
                {
                  value: darkModeBackgroundColor,
                  onChange: (value: string | undefined) => setAttributes({ darkModeBackgroundColor: value || '#181a20' }),
                  label: __('Background Color'),
                  colors: customColors,
                },
              ]}
            />
          </div>
        )}

        {darkModeBackgroundType === "gradient" && (
          <div className="scbc-button-block__section">
            <PanelColorSettings
              title={__('Dark Mode Gradient Colors')}
              colorSettings={[
                {
                  value: darkModeGradientColor1,
                  onChange: (value: string | undefined) => setAttributes({ darkModeGradientColor1: value || '#b3425a' }),
                  label: __('Gradient Color 1'),
                  colors: customColors,
                },
                {
                  value: darkModeGradientColor2,
                  onChange: (value: string | undefined) => setAttributes({ darkModeGradientColor2: value || '#7c3aed' }),
                  label: __('Gradient Color 2'),
                  colors: customColors,
                },
              ]}
            />
          </div>
        )}

        <div className="scbc-button-block__section">
          <PanelColorSettings
            title={__('Dark Mode Text Color')}
            colorSettings={[
              {
                value: darkModeTextColor,
                onChange: (value: string | undefined) => setAttributes({ darkModeTextColor: value || '#ffffff' }),
                label: __('Text Color'),
                colors: customColors,
              },
            ]}
          />
        </div>

        <div className="scbc-button-block__section">
          <label className="components-base-control__label">
            Dark Mode Logo
          </label>
          <div className="scbc-logo-grid">
            {logoOptions.map((option) => (
              <button
                key={`dark-${option.value}`}
                className={`scbc-logo-option ${
                  darkModeLogoOption === option.value ? "is-selected" : ""
                }`}
                onClick={() => toggleDarkModeLogo(option.value)}
                title={option.label}
              >
                <img src={option.image} alt={option.label} />
                {darkModeLogoOption === option.value && (
                  <span className="scbc-logo-checkmark">✓</span>
                )}
              </button>
            ))}

            {customLogos && customLogos.map((customLogo) => (
              <button
                key={`dark-custom-${customLogo.id}`}
                className={`scbc-logo-option ${
                  darkModeLogoOption === `custom-${customLogo.id}` ? "is-selected" : ""
                }`}
                onClick={() => {
                  if (darkModeLogoOption === `custom-${customLogo.id}`) {
                    updateDarkModeLogoOption("none");
                  } else {
                    updateDarkModeLogoOption(`custom-${customLogo.id}`);
                  }
                }}
                title="Custom Logo"
              >
                <img src={customLogo.url} alt="Custom Logo" />
                {darkModeLogoOption === `custom-${customLogo.id}` && (
                  <span className="scbc-logo-checkmark">✓</span>
                )}
              </button>
            ))}

            <MediaUploadCheck>
              <MediaUpload
                onSelect={(media: any) => {
                  const newCustomLogos = customLogos || [];
                  const newLogo = { url: media.url, id: media.id };

                  const exists = newCustomLogos.find(logo => logo.id === media.id);

                  if (!exists) {
                    const updatedLogos = [...newCustomLogos, newLogo];
                    setAttributes({
                      customLogos: updatedLogos,
                      darkModeLogoOption: `custom-${media.id}`
                    });
                  } else {
                    setAttributes({
                      darkModeLogoOption: `custom-${media.id}`
                    });
                  }
                }}
                allowedTypes={["image"]}
                render={({ open }) => (
                  <button
                    className="scbc-logo-option scbc-logo-upload"
                    onClick={open}
                    title="Upload Custom Logo for Dark Mode"
                  >
                    <div className="scbc-logo-plus">
                      <span>+</span>
                    </div>
                  </button>
                )}
              />
            </MediaUploadCheck>
          </div>
        </div>
      </>
    )}
  </PanelBody>

  {/* SPACING (MARGIN) PANEL */}
  <PanelBody title="Spacing" initialOpen={false}>
    <div className="scbc-button-block__section">
      <MarginControls
        marginTop={marginTop}
        marginRight={marginRight}
        marginBottom={marginBottom}
        marginLeft={marginLeft}
        marginLinked={marginLinked}
        marginPreset={marginPreset}
        setAttributes={setAttributes}
      />
    </div>
  </PanelBody>

  {/* INTERACTIVE MODE FEATURE */}
  <PanelBody title="Interactive Mode" initialOpen={false}>
    <div className="scbc-button-block__section">
      <ToggleControl
        label={__('Enable Interactive Mode')}
        help={
          interactiveButton
            ? __('Button will cycle through custom texts.')
            : __('Enable to add rotating text prompts.')
        }
        checked={interactiveButton}
        onChange={(value) => {
          setAttributes({ interactiveButton: value });
          if (value && (!interactiveTexts || interactiveTexts.length === 0)) {
            setAttributes({ interactiveTexts: [""] });
          }
        }}
      />
    </div>

    {interactiveButton && (
      <>
        <div className="scbc-button-block__section">
          <ToggleControl
            label={__('Collapse at End')}
            help={
              collapseAtEnd
                ? __('Button will collapse after displaying all texts.')
                : __('Button will stay expanded after displaying all texts.')
            }
            checked={collapseAtEnd}
            onChange={(value) => setAttributes({ collapseAtEnd: value })}
          />
        </div>

        <div className="scbc-button-block__section">
          <ToggleControl
            label={__('Resize button when typing')}
            help={
              resizeMode === "dynamic"
                ? __('Button width adjusts dynamically to fit each text prompt.')
                : __('Button width stays fixed based on the longest text prompt.')
            }
            checked={resizeMode === "dynamic"}
            onChange={(value) => setAttributes({ resizeMode: value ? "dynamic" : "static" })}
          />
        </div>

        <div className="scbc-button-block__section">
          <label className="components-base-control__label">
            Rotating Text Prompts
          </label>
          <p className="components-base-control__help" style={{ marginTop: '-8px', marginBottom: '12px' }}>
            Add text prompts that will appear. The button shows only the logo first. The first prompt cannot be deleted but can be empty. Maximum 5 prompts allowed.
          </p>

          <div className="scbc-interactive-texts">
            {(interactiveTexts || []).map((text, index) => (
              <div key={index} className="scbc-interactive-text-item">
                <div className="scbc-interactive-text-number">
                  {index + 1}
                </div>
                <TextControl
                  value={text}
                  onChange={(value) => updateInteractiveText(index, value)}
                  placeholder={`Text prompt ${index + 1}...`}
                />
                <Button
                  isDestructive
                  icon="trash"
                  onClick={() => removeInteractiveText(index)}
                  className="scbc-interactive-text-remove"
                  disabled={index === 0}
                  title={index === 0 ? "First prompt cannot be deleted" : "Remove prompt"}
                  style={{
                    opacity: index === 0 ? 0.3 : 0.7,
                    cursor: index === 0 ? 'not-allowed' : 'pointer'
                  }}
                />
              </div>
            ))}
          </div>

          <Button
            isSecondary
            icon="plus"
            onClick={addInteractiveText}
            className="scbc-add-text-button"
            disabled={(interactiveTexts || []).length >= 5}
          >
            Add Text Prompt {(interactiveTexts || []).length >= 5 && "(Max 5)"}
          </Button>
        </div>
      </>
    )}
  </PanelBody>
</InspectorControls>

      {/* BUTTON PREVIEW IN EDITOR */}
      <button
        className={`scbc-button ${
          buttonStyle === "animated" ? "scbc-button-animated" : ""
        } ${interactiveButton ? "scbc-button-interactive" : ""} ${
          isAnimating ? "is-animating" : ""
        } ${isExpanding ? "is-expanding" : ""} ${
          isClosing ? "is-closing" : ""
        } ${interactiveButton && !hasValidPrompts() ? "editor-collapsed" : ""}`}
        style={getButtonStyle()}
      >
        {selectedLogo && (
          <img
            src={selectedLogo}
            alt="Button Logo"
            className={`scbc-button-logo ${
              interactiveButton && (currentTextIndex === -1 || !hasValidPrompts()) ? "logo-only" : ""
            } ${isLogoRotating ? "logo-rotating" : ""}`}
          />
        )}
        {interactiveButton ? (
          <span className={`scbc-button-text ${
            currentTextIndex === -1 || !hasValidPrompts() ? "text-hidden" : "text-visible"
          }`}>
            {getCurrentDisplayText()}
          </span>
        ) : (
          <RichText
            tagName="span"
            value={title}
            placeholder="Button Text ..."
            onChange={updateTitle}
          />
        )}
      </button>
    </div>
  );
};

export default Edit;
