document.addEventListener('DOMContentLoaded', () => {
    const ctx = document.getElementById('kazPriceChart');
    if (!ctx) return;

    let kazChart = null;

    const initChart = (labels, values) => {
        const chartData = {
            labels: labels,
            datasets: [{
                label: 'Cena (1g)',
                data: values,
                borderColor: '#0075FF',
                borderWidth: 3,
                pointRadius: 0,
                pointHoverRadius: 5,
                fill: true,
                tension: 0.4,
                backgroundColor: (context) => {
                    const chartCtx = context.chart.ctx;
                    const gradient = chartCtx.createLinearGradient(0, 0, 0, context.chart.height || 300);
                    gradient.addColorStop(0, 'rgba(0, 117, 255, 0.3)');
                    gradient.addColorStop(1, 'rgba(0, 117, 255, 0)');
                    return gradient;
                }
            }]
        };

        const config = {
            type: 'line',
            data: chartData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        intersect: false,
                        mode: 'index',
                        backgroundColor: '#051229',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: '#0075FF',
                        borderWidth: 1
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: { color: 'rgba(255, 255, 255, 0.5)' }
                    },
                    y: {
                        grid: { color: 'rgba(255, 255, 255, 0.05)' },
                        ticks: { color: 'rgba(255, 255, 255, 0.5)' },
                        min: 12000,
                        max: 24000
                    }
                }
            }
        };

        kazChart = new Chart(ctx, config);
    };

    const updateChartData = (days) => {
        const baseUrl = typeof kaz_live_prices_data !== 'undefined' 
            ? kaz_live_prices_data.rest_url.replace('live-prices', 'chart-data') 
            : '/wp-json/kaz/v1/chart-data';
            
        fetch(`${baseUrl}?days=${days}`)
            .then(res => res.json())
            .then(data => {
                if (data && data.labels && data.values) {
                    if (!kazChart) {
                        initChart(data.labels, data.values);
                    } else {
                        kazChart.data.labels = data.labels;
                        kazChart.data.datasets[0].data = data.values;
                        kazChart.update();
                    }
                }
            })
            .catch(err => console.error('Error fetching chart data', err));
    };

    // Initialize with 7 days
    updateChartData(7);

    // Tab logic
    const tabs = document.querySelectorAll('.kaz-chart-tab');
    tabs.forEach(tab => {
        tab.addEventListener('click', () => {
            tabs.forEach(t => t.classList.remove('active'));
            tab.classList.add('active');
            const days = tab.getAttribute('data-days');
            updateChartData(days);
        });
    });
});
