import React from "react";

class CountUp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 0,
    };
    this.start = 0;
    this.rafId = null;
  }

  componentDidMount() {
    this.animateCount();
  }

  componentDidUpdate(prevProps) {
    // 如果 end 改变了，就重新动画
    if (prevProps.end !== this.props.end) {
      this.start = this.state.value; // 从当前值开始动画
      cancelAnimationFrame(this.rafId);
      this.animateCount();
    }
  }

  componentWillUnmount() {
    cancelAnimationFrame(this.rafId);
  }

  animateCount() {
    const { end = 0, duration = 1000 } = this.props;
    const startTime = performance.now();

    const step = (now) => {
      const elapsed = now - startTime;
      const progress = Math.min(elapsed / duration, 1); // 限制在 0~1
      const currentValue = Math.floor(
        progress * (end - this.start) + this.start
      );
      this.setState({ value: currentValue });

      if (progress < 1) {
        this.rafId = requestAnimationFrame(step);
      }
    };

    this.rafId = requestAnimationFrame(step);
  }

  render() {
    return (
      <div className={this.props.className}>
        {this.state.value.toLocaleString()}
      </div>
    );
  }
}

export default CountUp;
