import React, { useEffect, useState, useRef } from 'react'
import styles from './index.module.scss'

const FlipPic = ({ activeIndex }: { activeIndex: number }) => {
  const [prevIndex, setPrevIndex] = useState(activeIndex);
  const [isAnimating, setIsAnimating] = useState(true);
  const [displayIndex, setDisplayIndex] = useState(activeIndex);
  const [isForward, setIsForward] = useState<boolean>(false);
  const containerRef = useRef<HTMLDivElement>(null);

  // 添加图片预加载逻辑
  useEffect(() => {
    const caroIndexes = [
      activeIndex + 1,
      (activeIndex + 1) % 3 + 1,
      (activeIndex + 3) % 3 + 1
    ];

    caroIndexes.forEach(caro => {
      [1, 2, 3].forEach(i => {
        const img = new Image();
        img.src = require(`../../image/caro${caro}/pic${i}.png`);
      });
    });
  }, [activeIndex]);

  useEffect(() => {
    const diff = (activeIndex - prevIndex + 3) % 3;
    if (diff !== 0) {
      setIsForward(diff === 1);
      setIsAnimating(false);
      requestAnimationFrame(() => {
        setIsAnimating(true);
        const timer = setTimeout(() => {
          setPrevIndex(activeIndex);
          setDisplayIndex(activeIndex);
        }, 300);
        return () => clearTimeout(timer);
      });
    }
  }, [activeIndex, prevIndex]);

  const title: Record<string, string[]> = {
    pic1: ['元青花四爱图梅瓶', '“太阳人”石刻', '铜钺'],
    pic2: ['《甘绩熙自述》', '起义军占领武昌后制发的出入城门证', '王汉烈士画像'],
    pic3: ['战争年代李先念使用过的怀表', `郭天民1955年荣获的八一、解放、独立一级勋章`, '123']
  }

  return (
    <div
      ref={containerRef}
      className={`${styles.flipPic} ${isAnimating ? 'active' : ''}`}
    >
      {[1, 2, 3].map((i) => (
        <div className={`picBox picBox${i}`} key={`bg${i}-${activeIndex}`}>
          <div className="title">●{title[`pic${displayIndex + 1}`][i - 1] as any}</div>
          <div className='pic'>
            <img
              className='front'
              src={require(`../../image/caro${isForward // 使用存储的方向状态
                ? (activeIndex + 2) % 3 + 1       // 向前切换：下一张
                : (activeIndex + 1) % 3 + 1       // 向后切换：上一张
                }/pic${i}.png`)}
              alt=''
              draggable='false'
            />
            <img
              className='back'
              src={require(`../../image/caro${(activeIndex) % 3 + 1}/pic${i}.png`)}
              alt=''
              draggable='false'
            />
          </div>
        </div>
      ))}
    </div>
  )
}
export default FlipPic
