// graficos.js - Inicialização e Atualização de Gráficos (Chart.js)

const Graficos = {
    composicaoChart: null,
    evolucaoChart: null,

    // Inicializar Gráfico de Composição (Doughnut)
    initComposicao(canvasId, labels = [], data = [], colors = []) {
        const ctx = document.getElementById(canvasId);
        if (!ctx) return;

        // Destruir gráfico anterior se existir
        if (this.composicaoChart) {
            this.composicaoChart.destroy();
        }

        // Cores padrão caso não sejam passadas
        const defaultColors = [
            '#3B82F6', // Blue
            '#10B981', // Emerald
            '#F59E0B', // Amber
            '#8B5CF6', // Purple
            '#EC4899', // Pink
            '#6366F1', // Violet
            '#14B8A6', // Teal
            '#F43F5E'  // Rose
        ];

        const backgroundColors = colors.length > 0 ? colors : defaultColors;

        this.composicaoChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: data,
                    backgroundColor: backgroundColors,
                    borderWidth: 2,
                    borderColor: '#ffffff',
                    hoverOffset: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'right',
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                family: "'Inter', sans-serif",
                                size: 12
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const value = context.raw;
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = ((value * 100) / total).toFixed(1) + '%';
                                
                                // Formatar como moeda
                                const formattedValue = new Intl.NumberFormat('pt-BR', {
                                    style: 'currency',
                                    currency: 'BRL'
                                }).format(value);
                                
                                return ` ${context.label}: ${formattedValue} (${percentage})`;
                            }
                        },
                        backgroundColor: 'rgba(15, 23, 42, 0.9)',
                        titleFont: { size: 14, family: "'Inter', sans-serif" },
                        bodyFont: { size: 13, family: "'Inter', sans-serif" },
                        padding: 12,
                        cornerRadius: 8,
                        displayColors: true
                    }
                },
                cutout: '65%',
                animation: {
                    animateScale: true,
                    animateRotate: true
                }
            }
        });
    },

    // Inicializar Gráfico de Evolução (Line)
    initEvolucao(canvasId, labels = [], dataCarteira = [], dataIBOV = []) {
        const ctx = document.getElementById(canvasId);
        if (!ctx) return;

        // Destruir gráfico anterior se existir
        if (this.evolucaoChart) {
            this.evolucaoChart.destroy();
        }

        this.evolucaoChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'Sua Carteira',
                        data: dataCarteira,
                        borderColor: '#3B82F6', // Blue
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        borderWidth: 3,
                        pointBackgroundColor: '#3B82F6',
                        pointBorderColor: '#ffffff',
                        pointBorderWidth: 2,
                        pointRadius: 4,
                        pointHoverRadius: 6,
                        fill: true,
                        tension: 0.4 // Curvas suaves
                    },
                    {
                        label: 'IBOV (Referência)',
                        data: dataIBOV,
                        borderColor: '#9CA3AF', // Gray
                        backgroundColor: 'transparent',
                        borderWidth: 2,
                        borderDash: [5, 5], // Linha tracejada
                        pointRadius: 0,
                        pointHoverRadius: 4,
                        fill: false,
                        tension: 0.4
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false,
                },
                plugins: {
                    legend: {
                        position: 'top',
                        labels: {
                            usePointStyle: true,
                            font: { family: "'Inter', sans-serif" }
                        }
                    },
                    tooltip: {
                        backgroundColor: 'rgba(15, 23, 42, 0.9)',
                        titleFont: { size: 14, family: "'Inter', sans-serif" },
                        bodyFont: { size: 13, family: "'Inter', sans-serif" },
                        padding: 12,
                        cornerRadius: 8,
                        callbacks: {
                            label: function(context) {
                                let label = context.dataset.label || '';
                                if (label) {
                                    label += ': ';
                                }
                                if (context.parsed.y !== null) {
                                    label += new Intl.NumberFormat('pt-BR', {
                                        style: 'percent',
                                        minimumFractionDigits: 2
                                    }).format(context.parsed.y / 100);
                                }
                                return label;
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: {
                            display: false,
                            drawBorder: false
                        },
                        ticks: {
                            font: { family: "'Inter', sans-serif", size: 11 },
                            color: '#6B7280'
                        }
                    },
                    y: {
                        grid: {
                            color: 'rgba(243, 244, 246, 1)',
                            drawBorder: false
                        },
                        ticks: {
                            font: { family: "'Inter', sans-serif", size: 11 },
                            color: '#6B7280',
                            callback: function(value) {
                                return value + '%';
                            }
                        }
                    }
                }
            }
        });
    }
};
