<!-- Cost Over Time Trend Chart -->
<div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
    <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold text-gray-900">Cost Over Time</h3>
        <a href="/tokens" class="text-sm text-[#0770E3] hover:underline flex items-center gap-1">
            View breakdown
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg>
        </a>
    </div>
    <div style="height: 250px;">
        <canvas id="costTrendChart"></canvas>
    </div>
</div>

<!-- Cost Breakdown Pie Chart -->
<div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
    <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold text-gray-900">Cost Breakdown</h3>
        <a href="/tokens" class="text-sm text-[#0770E3] hover:underline flex items-center gap-1">
            View breakdown
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg>
        </a>
    </div>
    <div class="flex justify-center" style="height: 250px;">
        <canvas id="costPieChart"></canvas>
    </div>
</div>

<script>
(function() {
    // Use requestAnimationFrame to wait for DOM layout before creating charts
    // This fixes rendering issues when HTMX swaps in new content
    requestAnimationFrame(function() {
        requestAnimationFrame(function() {
            initCharts();
        });
    });

    function initCharts() {
        // Destroy existing charts if they exist (for HTMX reloads)
        // Must be done right before creating new charts to avoid race conditions
        const existingTokenChart = Chart.getChart('costTrendChart');
        if (existingTokenChart) existingTokenChart.destroy();
        const existingPieChart = Chart.getChart('costPieChart');
        if (existingPieChart) existingPieChart.destroy();

        // Cost Trend Chart (top-left panel)
        const tokenCtx = document.getElementById('costTrendChart');
        if (tokenCtx) {
            const costLabels = {{ cost_trend.labels|default([])|tojson }};
            const costDatasets = {{ cost_trend.datasets|default({})|tojson }};

            if (costLabels && costLabels.length > 0) {
                new Chart(tokenCtx, {
                    type: 'line',
                    data: {
                        labels: costLabels,
                        datasets: [
                            {
                                label: 'Total Cost',
                                data: costDatasets.total || [],
                                borderColor: '#0770E3',
                                backgroundColor: 'rgba(7, 112, 227, 0.1)',
                                tension: 0.4,
                                fill: true,
                                borderWidth: 2
                            },
                            {
                                label: 'Input',
                                data: costDatasets.input || [],
                                borderColor: '#34D399',
                                backgroundColor: 'transparent',
                                tension: 0.4,
                                fill: false,
                                borderWidth: 1.5,
                                borderDash: [5, 5]
                            },
                            {
                                label: 'Output',
                                data: costDatasets.output || [],
                                borderColor: '#F59E0B',
                                backgroundColor: 'transparent',
                                tension: 0.4,
                                fill: false,
                                borderWidth: 1.5,
                                borderDash: [5, 5]
                            },
                            {
                                label: 'Cache',
                                data: costDatasets.cache || [],
                                borderColor: '#8B5CF6',
                                backgroundColor: 'transparent',
                                tension: 0.4,
                                fill: false,
                                borderWidth: 1.5,
                                borderDash: [5, 5]
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        interaction: { mode: 'index', intersect: false },
                        plugins: {
                            legend: {
                                display: true,
                                position: 'bottom',
                                labels: { padding: 12, usePointStyle: true, font: { size: 11 } }
                            },
                            tooltip: {
                                mode: 'index',
                                intersect: false,
                                callbacks: {
                                    label: function(context) {
                                        let label = context.dataset.label || '';
                                        if (label) label += ': ';
                                        let value = context.parsed.y;
                                        return value > 0 ? label + '$' + value.toFixed(4) : null;
                                    }
                                }
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: { callback: function(value) { return '$' + value.toFixed(2); } }
                            }
                        }
                    }
                });
            }
        }

        // Cost Pie Chart
        const pieCtx = document.getElementById('costPieChart');
        if (pieCtx) {
            const inputCost = {{ tokens.input_cost|default(0.0)|float }};
            const outputCost = {{ tokens.output_cost|default(0.0)|float }};
            const cacheCost = {{ tokens.cache_creation_cost|default(0.0)|float }};
            const cacheReadCost = {{ tokens.cache_read_cost|default(0.0)|float }};

            new Chart(pieCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Input Tokens', 'Output Tokens', 'Cache Creation', 'Cache Reads'],
                    datasets: [{
                        data: [inputCost, outputCost, cacheCost, cacheReadCost],
                        backgroundColor: [
                            '#0770E3',
                            '#34D399',
                            '#F59E0B',
                            '#8B5CF6'
                        ],
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true,
                                font: {
                                    size: 12
                                }
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    let label = context.label || '';
                                    if (label) {
                                        label += ': ';
                                    }
                                    label += '$' + context.parsed.toFixed(2);
                                    return label;
                                }
                            }
                        }
                    }
                }
            });
        }
    }
})();
</script>
