import React, { useEffect, useState } from 'react';
import classNames from 'classnames';
import styles from './index.less';
import numberBoardBg from '@/assets/images/V-2504/running-board-bg.png';

interface NumberBoardProps {
  number: number;
  totalDigits?: number;
}

const NumberBoard: React.FC<NumberBoardProps> = ({ 
  number, 
  totalDigits = 6 
}) => {
  // 前一个数字值，用于动画效果
  const [prevNumber, setPrevNumber] = useState<number>(number);
  // 是否正在动画中
  const [animating, setAnimating] = useState<boolean[]>(Array(totalDigits).fill(false));
  
  // 将数字转为字符串并左侧补0
  const numberStr = number.toString().padStart(totalDigits, '0');
  const prevNumberStr = prevNumber.toString().padStart(totalDigits, '0');
  
  // 计算左侧有多少个补位的0
  const leadingZeros = numberStr.length - numberStr.replace(/^0+/, '').length;
  
  // 检测数字变化并触发动画
  useEffect(() => {
    if (number !== prevNumber) {
      // 找出哪些位置的数字发生了变化
      const newAnimating = [...animating];
      
      for (let i = 0; i < totalDigits; i++) {
        if (numberStr[i] !== prevNumberStr[i]) {
          newAnimating[i] = true;
        }
      }
      
      setAnimating(newAnimating);
      
      // 动画结束后重置状态
      setTimeout(() => {
        setAnimating(Array(totalDigits).fill(false));
        setPrevNumber(number);
      }, 500); // 动画持续时间
    }
  }, [number]);

  return (
    <div className={styles.boardContainer}>
      {numberStr.split('').map((digit, index) => (
        <div key={index} className={styles.digitContainer}>
          <img src={numberBoardBg} className={styles.boardBg} alt="背景" />
          <div className={styles.boardShadow}></div>
          
          <div className={styles.digitFlipContainer}>
            {/* 当前数字 */}
            <div 
              className={classNames(
                styles.digit, 
                { 
                  [styles.leadingZero]: index < leadingZeros,
                  [styles.flipIn]: animating[index]
                }
              )}
            >
              {digit}
            </div>
            
            {/* 前一个数字（仅在动画时显示） */}
            {animating[index] && (
              <div 
                className={classNames(
                  styles.digit, 
                  styles.prevDigit,
                  { [styles.leadingZero]: index < leadingZeros }
                )}
              >
                {prevNumberStr[index]}
              </div>
            )}
          </div>
        </div>
      ))}
    </div>
  );
};

export default NumberBoard; 