<script setup lang="ts">
const props = defineProps({
  endValue: {
    type: Number,
    default: 0,
  },
  duration: {
    type: Number,
    default: 2000,
  },
});

const displayValue = ref(props.endValue);
const hasAnimated = ref(false);
const el = ref(null);

const animateCount = () => {
  const start = 0;
  const end = props.endValue;
  const startTime = performance.now();

  const animate = (currentTime: number) => {
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / props.duration, 1);
    displayValue.value = Math.floor(progress * (end - start));

    if (progress < 1) {
      requestAnimationFrame(animate);
    } else {
      displayValue.value = end;
    }
  };

  requestAnimationFrame(animate);
};

onMounted(() => {
  const observer = new IntersectionObserver(
    ([entry]) => {
      if (entry.isIntersecting && !hasAnimated.value) {
        hasAnimated.value = true;
        animateCount();
        observer.disconnect();
      }
    },
    { threshold: 0.5 },
  );

  if (el.value) {
    observer.observe(el.value);
  }
});
</script>
<template>
  <span ref="el" class="text-accent text-[1.75rem]">
    {{ displayValue.toLocaleString() }}
  </span>
</template>

<style scoped></style>
