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

const AnimationPreviewSelector = ({ currentAnimation, onSelectAnimation }) => {
  const [animatingItems, setAnimatingItems] = useState({});
  const [autoPlay, setAutoPlay] = useState(false); // デフォルトはHover
  const buttonRefs = useRef({});
  const intervalRefs = useRef({});

  const animations = [
    { id: "01", label: __("Animation 01", "zenblocks"), description: __("Simple Switch", "zenblocks") },
    { id: "02", label: __("Animation 02", "zenblocks"), description: __("Vertical Slide (Standard)", "zenblocks") },
    { id: "03", label: __("Animation 03", "zenblocks"), description: __("Vertical Slide (Delayed)", "zenblocks") },
    { id: "04", label: __("Animation 04", "zenblocks"), description: __("Horizontal Slide (Left to Right)", "zenblocks") },
    { id: "05", label: __("Animation 05", "zenblocks"), description: __("Scale + Fade", "zenblocks") },
    { id: "06", label: __("Animation 06", "zenblocks"), description: __("Fade Only", "zenblocks") },
    { id: "07", label: __("Animation 07", "zenblocks"), description: __("Wave Vertical", "zenblocks") },
    { id: "08", label: __("Animation 08", "zenblocks"), description: __("Blur + Fade", "zenblocks") },
    { id: "09", label: __("Animation 09", "zenblocks"), description: __("Slight Float", "zenblocks") },
    { id: "10", label: __("Animation 10", "zenblocks"), description: __("Scale Up + Y Move", "zenblocks") },
  ];

  // "none"が選択されているかどうか
  const isNoneSelected = currentAnimation === "none";

  useEffect(() => {
    // 自動再生がOFFの場合はインターバルをクリアして終了
    if (!autoPlay) {
      Object.values(intervalRefs.current).forEach((interval) => clearInterval(interval));
      intervalRefs.current = {};
      setAnimatingItems({});
      return;
    }

    animations.forEach((animation, index) => {
      setTimeout(() => {
        intervalRefs.current[animation.id] = setInterval(() => {
          setAnimatingItems((prev) => ({
            ...prev,
            [animation.id]: true,
          }));

          setTimeout(() => {
            setAnimatingItems((prev) => ({
              ...prev,
              [animation.id]: false,
            }));
          }, 1500);
        }, 3000);
      }, index * 300);
    });

    return () => {
      Object.values(intervalRefs.current).forEach((interval) => clearInterval(interval));
    };
  }, [autoPlay]);

  const renderTextWithChars = (text) => {
    if (!text) return null;
    return Array.from(text).map((char, index) => (
      <span key={index} className="char" style={{ ["--char-index"]: index }}>
        {char === " " ? "\u00A0" : char}
      </span>
    ));
  };

  return (
    <div className="animation-preview-selector">
      <div className="zenblocks-custom-color-palette__tabs">
        <button
          type="button"
          className={`zenblocks-custom-color-palette__tab ${!autoPlay ? "is-active" : ""}`}
          onClick={() => setAutoPlay(false)}
        >
          {__("Hover", "zenblocks")}
        </button>
        <button
          type="button"
          className={`zenblocks-custom-color-palette__tab ${autoPlay ? "is-active" : ""}`}
          onClick={() => setAutoPlay(true)}
        >
          {__("Auto", "zenblocks")}
        </button>
      </div>
      <div className="animation-preview-grid">
        {animations.map((animation) => {
          const isActive = currentAnimation === animation.id;
          const isAnimating = animatingItems[animation.id];

          return (
            <div
              key={animation.id}
              className={`animation-preview-item ${isActive ? "is-active" : ""}`}
              onClick={() => {
                if (isActive) {
                  onSelectAnimation("none");
                } else {
                  onSelectAnimation(animation.id);
                }
              }}
            >
              <div
                className={`animation-preview-wrapper wp-block-zenblocks-button-basic zenblocks-button-hover-animation-text-${animation.id}${!autoPlay ? " is-hover-enabled" : ""}`}
              >
                <button 
                  type="button" 
                  className={`animation-preview-button ${isAnimating ? "is-force-hover" : ""}`}
                  ref={(el) => (buttonRefs.current[animation.id] = el)}
                >
                  <div className="wp-block-zenblocks-button-basic-content">
                    <span className="wp-block-zenblocks-button-basic-text">
                      <span className="default">{renderTextWithChars(__("Read More", "zenblocks"))}</span>
                      <span className="hover">{renderTextWithChars(__("Learn More", "zenblocks"))}</span>
                    </span>
                  </div>
                </button>
              </div>
              <div className="animation-preview-label">
                <span className="animation-number">{animation.id}</span>
                <span className="animation-description">{animation.description}</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default AnimationPreviewSelector;
