const targetAmount = 8000000;

function createChart(currentDonation, remainingAmount) {
    const formattedCollected = new Intl.NumberFormat('cs-CZ', {
        style: 'currency',
        currency: 'CZK',
        maximumFractionDigits: 0
    }).format(currentDonation);

    const ctx = document.getElementById('donationChart').getContext('2d');
    
    new Chart(ctx, {
        type: 'pie',
        data: {
            labels: ['Darováno', 'Zbývá'],
            datasets: [{
                data: [currentDonation, remainingAmount],
                backgroundColor: ['#D07F00', '#c8c9ca'],
            }]
        },
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: 'Vaše příspevky: '+formattedCollected,
                    font: {
                        size: 18
                    }
                },
                legend: {
                    position: 'bottom'
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            let label = context.label || '';
                            if (label) {
                                label += ': ';
                            }
                            const value = context.raw;
                            label += new Intl.NumberFormat('cs-CZ', {
                                style: 'currency',
                                currency: 'CZK'
                            }).format(value);
                            return label;
                        }
                    }
                }
            }
        }
    });
}

fetch('https://api.apify.com/v2/key-value-stores/LuY1gYzAyVyEApD3J/records/OUTPUT?token=apify_api_cZKe9WYmwzxlCLXZXy8XdtIePaQhzq3b1czw')
    .then(response => response.json())
    .then(data => {
        const currentDonation = data.collected;
        const remainingAmount = targetAmount - currentDonation;
        
        // Check if data.timestamp exists
        if (data.timestamp) {
            const timestamp = new Date(data.timestamp);
            const formattedTimestamp = timestamp.toLocaleString('cs-CZ', {
                day: '2-digit',
                month: '2-digit',
                year: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
            }).replace(',', '');
            document.getElementById('csob-transparent-timestamp').textContent = formattedTimestamp;
        } else {
            console.warn('Timestamp data is missing');
            document.getElementById('csob-transparent-timestamp').textContent = 'Datum není k dispozici';
        }
        
        createChart(currentDonation, remainingAmount);
    })
    .catch(error => console.error('Error fetching data:', error));