---
const { value } = Astro.props;
---

<p class="text-3xl font-bold text-amber-400">
    <span class="animated-counter" data-value={value}>0</span>
</p>

<script>
    function setupAnimatedCounters() {
        const counters = document.querySelectorAll('.animated-counter');
        if (!counters.length) return;

        const observer = new IntersectionObserver((entries, obs) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    animateCounter(entry.target);
                    obs.unobserve(entry.target);
                }
            });
        }, { threshold: 0.1 });

        counters.forEach(c => observer.observe(c));
    }

    function animateCounter(counter) {
        const rawValue = counter.getAttribute('data-value') || '';
        const match = rawValue.match(/^(\d+)/);

        if (!match) {
            counter.textContent = rawValue;
            return;
        }

        const target = parseInt(match[0], 10);
        const suffix = rawValue.slice(match[0].length);

        let start = 0;
        const duration = 2000;
        const step = 20;
        const increment = target / (duration / step);

        const timer = setInterval(() => {
            start += increment;
            if (start >= target) {
                counter.textContent = target.toLocaleString('de-DE') + suffix;
                clearInterval(timer);
            } else {
                counter.textContent = Math.round(start).toLocaleString('de-DE') + suffix;
            }
        }, step);
    }

    document.addEventListener('DOMContentLoaded', setupAnimatedCounters);
</script>