import { __ } from "@wordpress/i18n";
import { useState, useEffect, useRef } from "@wordpress/element";

const ButtonAnimationPreviewSelector = ({
  currentAnimation,
  onSelectAnimation,
  transitionDuration = 2000,
  transitionEasing = "ease-in-out",
  interval = 1000,
}) => {
  const [animatingItems, setAnimatingItems] = useState({});
  const intervalRefs = useRef({});
  const timeoutRefs = useRef({});

  const animations = [
    {
      id: "shake-01",
      label: __("Shake", "zenblocks"),
      description: __("Swaying left and right", "zenblocks")
    },
    {
      id: "bounce-01",
      label: __("Bounce", "zenblocks"),
      description: __("Bouncing up and down", "zenblocks")
    },
    {
      id: "heartbeat-01",
      label: __("Heartbeat", "zenblocks"),
      description: __("Pulsing like a heartbeat", "zenblocks")
    },
    {
      id: "wobble-01",
      label: __("Wobble", "zenblocks"),
      description: __("Wobbling", "zenblocks")
    },
    {
      id: "swing-01",
      label: __("Swing", "zenblocks"),
      description: __("Swinging like a pendulum", "zenblocks")
    },
    {
      id: "rubberband-01",
      label: __("Rubber Band", "zenblocks"),
      description: __("Stretching like rubber", "zenblocks")
    },
    {
      id: "tada-01",
      label: __("Tada", "zenblocks"),
      description: __("Attention-grabbing motion", "zenblocks")
    },
    {
      id: "pulse-01",
      label: __("Pulse", "zenblocks"),
      description: __("Repeated scaling", "zenblocks")
    },
    {
      id: "flash-01",
      label: __("Flash", "zenblocks"),
      description: __("Flashing", "zenblocks")
    },
    {
      id: "headshake-01",
      label: __("Head Shake", "zenblocks"),
      description: __("Shaking head", "zenblocks")
    },
    {
      id: "pop-01",
      label: __("Pop", "zenblocks"),
      description: __("Popping out", "zenblocks")
    },
    {
      id: "vibrate-01",
      label: __("Vibrate", "zenblocks"),
      description: __("Vibrating rapidly", "zenblocks")
    },
  ];

  // アニメーションの総時間（duration + interval）
  const totalCycle = transitionDuration + interval;

  useEffect(() => {
    // 既存のインターバルとタイムアウトをクリア
    Object.values(intervalRefs.current).forEach((id) => clearInterval(id));
    Object.values(timeoutRefs.current).forEach((id) => clearTimeout(id));
    intervalRefs.current = {};
    timeoutRefs.current = {};
    setAnimatingItems({});

    // 初回再生を即座に開始（staggered）
    animations.forEach((animation, index) => {
      const startDelay = index * 300;

      timeoutRefs.current[`start-${animation.id}`] = setTimeout(() => {
        // 初回アニメーション実行
        setAnimatingItems((prev) => ({
          ...prev,
          [animation.id]: true,
        }));

        timeoutRefs.current[`end-${animation.id}`] = setTimeout(() => {
          setAnimatingItems((prev) => ({
            ...prev,
            [animation.id]: false,
          }));
        }, transitionDuration);

        // 以降はインターバルで繰り返し
        intervalRefs.current[animation.id] = setInterval(() => {
          setAnimatingItems((prev) => ({
            ...prev,
            [animation.id]: true,
          }));

          setTimeout(() => {
            setAnimatingItems((prev) => ({
              ...prev,
              [animation.id]: false,
            }));
          }, transitionDuration);
        }, totalCycle);
      }, startDelay);
    });

    return () => {
      Object.values(intervalRefs.current).forEach((id) => clearInterval(id));
      Object.values(timeoutRefs.current).forEach((id) => clearTimeout(id));
    };
  }, [transitionDuration, interval]);

  return (
    <div className="button-animation-preview-selector">
      <div className="button-animation-preview-grid">
        {animations.map((animation) => {
          const isActive = currentAnimation === animation.id;
          const isAnimating = animatingItems[animation.id];

          return (
            <div
              key={animation.id}
              className={`button-animation-preview-item ${isActive ? "is-active" : ""}`}
              onClick={() => {
                if (isActive) {
                  onSelectAnimation("none");
                } else {
                  onSelectAnimation(animation.id);
                }
              }}
            >
              <div
                className={`button-animation-preview-wrapper button-animation-preview-${animation.id}`}
              >
                <button
                  type="button"
                  className={`button-animation-preview-button ${isAnimating ? "is-force-animation" : ""}`}
                  style={{
                    "--button-animation-duration": `${transitionDuration}ms`,
                    "--button-animation-easing": transitionEasing,
                  }}
                >
                  <div className="wp-block-zenblocks-button-basic-content">
                    <span className="wp-block-zenblocks-button-basic-text">
                      <span className="default">VIEW MORE</span>
                    </span>
                  </div>
                  <span className="wp-block-zenblocks-button-basic-bg">
                    <span className="wp-block-zenblocks-button-basic-bg-color"></span>
                  </span>
                </button>
              </div>
              <div className="button-animation-preview-label">
                <span className="button-animation-name">{animation.label}</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default ButtonAnimationPreviewSelector;
