import { Text, TextProps } from "@mantine/core";
import { useEffect, useRef, useState } from "react";
import classes from "./animated-score.module.css";

interface AnimatedScoreProps extends TextProps {
  value: number;
}

const AnimatedScore = ({ value, ...textProps }: AnimatedScoreProps) => {
  const previousValueRef = useRef<number>(value);
  const [pulseKey, setPulseKey] = useState(0);

  useEffect(() => {
    if (previousValueRef.current !== value) {
      previousValueRef.current = value;
      setPulseKey((key) => key + 1);
    }
  }, [value]);

  return (
    <Text {...textProps}>
      <span
        key={pulseKey}
        className={
          pulseKey > 0 ? `${classes.value} ${classes.pulse}` : classes.value
        }
      >
        {value}
      </span>
    </Text>
  );
};

export default AnimatedScore;
