<template>
  <div class="flip-number">{{ display }}</div>
</template>

<script>
export default {
  props: {
    value: { type: Number, default: 0 },
    duration: { type: Number, default: 1200 }
  },
  data() {
    return {
      display: 0,
      timer: null
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        this.animate(newVal)
      }
    }
  },
  methods: {
    animate(target) {
      cancelAnimationFrame(this.timer)
      const start = this.display
      const startTime = performance.now()

      const step = now => {
        const progress = Math.min((now - startTime) / this.duration, 1)
        this.display = Math.floor(start + (target - start) * progress)
        if (progress < 1) {
          this.timer = requestAnimationFrame(step)
        }
      }
      this.timer = requestAnimationFrame(step)
    }
  }
}
</script>

<style scoped>
.flip-number {
  font-size: 26px;
  font-weight: bold;
  color: #00eaff;
  text-shadow: 0 0 12px rgba(0,234,255,.6);
}
</style>
