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

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

  const animations = [
    {
      id: "shine-01",
      label: __("Shine 01", "zenblocks"),
      description: __("Light sweeps left to right", "zenblocks")
    },
    {
      id: "shine-02",
      label: __("Shine 02", "zenblocks"),
      description: __("Light sweeps diagonally", "zenblocks")
    },
    {
      id: "sparkle-01",
      label: __("Sparkle", "zenblocks"),
      description: __("Stars twinkling", "zenblocks")
    },
    {
      id: "border-run-01",
      label: __("Border Run", "zenblocks"),
      description: __("Light runs along border", "zenblocks")
    },
    {
      id: "neon-01",
      label: __("Neon", "zenblocks"),
      description: __("Glowing like neon sign", "zenblocks")
    },
    {
      id: "laser-01",
      label: __("Laser", "zenblocks"),
      description: __("Vertical laser beams", "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="frame-animation-preview-selector">
      <div className="frame-animation-preview-grid">
        {animations.map((animation) => {
          const isActive = currentAnimation === animation.id;
          const isAnimating = animatingItems[animation.id];

          return (
            <div
              key={animation.id}
              className={`frame-animation-preview-item ${isActive ? "is-active" : ""}`}
              onClick={() => {
                if (isActive) {
                  onSelectAnimation("none");
                } else {
                  onSelectAnimation(animation.id);
                }
              }}
            >
              <div
                className={`frame-animation-preview-wrapper frame-animation-preview-${animation.id}`}
              >
                <button
                  type="button"
                  className={`frame-animation-preview-button ${isAnimating ? "is-force-animation" : ""}`}
                  style={{
                    "--frame-animation-duration": `${transitionDuration}ms`,
                    "--frame-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>
                  <span className="wp-block-zenblocks-button-basic-frame"></span>
                </button>
              </div>
              <div className="frame-animation-preview-label">
                <span className="frame-animation-name">{animation.label}</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default FrameAnimationPreviewSelector;
