// Live Stats Counter
document.addEventListener('DOMContentLoaded', () => {
    fetchStats();
});

async function fetchStats() {
    try {
        const response = await fetch('/api/public-stats');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        
        updateStat('Total Players', data.totalPlayers);
        updateStat('Active Players', data.activePlayers);
        updateStat('Games Played', data.gamesPlayed);
        updateStat('Hours Played', data.hoursPlayed);
        
    } catch (error) {
        console.error('Error fetching stats:', error);
    }
}

function updateStat(label, value) {
    const cards = document.querySelectorAll('.stat-card');
    cards.forEach(card => {
        if (card.querySelector('.stat-label').textContent === label) {
            const numberEl = card.querySelector('.stat-number');
            animateValue(numberEl, 0, value, 2000);
        }
    });
}

function animateValue(obj, start, end, duration) {
    let startTimestamp = null;
    const step = (timestamp) => {
        if (!startTimestamp) startTimestamp = timestamp;
        const progress = Math.min((timestamp - startTimestamp) / duration, 1);
        
        // Ease out quart
        const easeProgress = 1 - Math.pow(1 - progress, 4);
        
        const current = Math.floor(progress * (end - start) + start);
        obj.innerHTML = current.toLocaleString();
        
        if (progress < 1) {
            window.requestAnimationFrame(step);
        } else {
            obj.innerHTML = end.toLocaleString();
        }
    };
    window.requestAnimationFrame(step);
}
