// Projections Page
let projectionsChart = null;
let cashFlowChart = null;
let futureBillsChart = null;

async function renderProjections() {
    const content = document.getElementById('main-content');
    content.innerHTML = '<div class="flex justify-center items-center h-64"><div class="spinner"></div></div>';
    
    try {
        await loadProjections('monthly');
    } catch (error) {
        content.innerHTML = `<div class="empty-state"><p>Erro ao carregar projeções: ${error.message}</p></div>`;
    }
}

async function loadProjections(periodType) {
    const content = document.getElementById('main-content');
    
    try {
        const data = await apiRequest(`projections.php?periodType=${periodType}`);
        
        content.innerHTML = `
            <div class="flex flex-wrap gap-2 mb-6">
                <button class="date-filter-btn ${periodType === 'weekly' ? 'active' : ''}" onclick="loadProjections('weekly')">Semanal</button>
                <button class="date-filter-btn ${periodType === 'biweekly' ? 'active' : ''}" onclick="loadProjections('biweekly')">Quinzenal</button>
                <button class="date-filter-btn ${periodType === 'monthly' ? 'active' : ''}" onclick="loadProjections('monthly')">Mensal</button>
            </div>
            
            <!-- Projection Cards -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                <div class="card" data-testid="card-projected-income">
                    <div class="text-sm text-gray-500 dark:text-gray-400 mb-2">Receita Projetada (${data.periodLabel})</div>
                    <div class="text-2xl font-bold text-income">${formatMoney(data.projectedIncome)}</div>
                </div>
                
                <div class="card" data-testid="card-projected-expenses">
                    <div class="text-sm text-gray-500 dark:text-gray-400 mb-2">Despesa Projetada (${data.periodLabel})</div>
                    <div class="text-2xl font-bold text-expense">${formatMoney(data.projectedExpenses)}</div>
                </div>
                
                <div class="card" data-testid="card-projected-balance">
                    <div class="text-sm text-gray-500 dark:text-gray-400 mb-2">Saldo Projetado (${data.periodLabel})</div>
                    <div class="text-2xl font-bold ${data.projectedBalance >= 0 ? 'text-income' : 'text-expense'}">${formatMoney(data.projectedBalance)}</div>
                </div>
                
                <div class="card" data-testid="card-confidence">
                    <div class="text-sm text-gray-500 dark:text-gray-400 mb-2">Confiança da Projeção</div>
                    <div class="text-2xl font-bold text-blue-500">${data.confidenceScore || 0}%</div>
                    <div class="w-full bg-gray-200 dark:bg-zinc-700 rounded-full h-2 mt-2">
                        <div class="bg-blue-500 h-2 rounded-full" style="width: ${data.confidenceScore || 0}%"></div>
                    </div>
                </div>
            </div>
            
            <!-- Bills Summary -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                <div class="card">
                    <h3 class="text-lg font-semibold mb-2 text-gray-800 dark:text-white">Boletos Pendentes</h3>
                    <div class="text-2xl font-bold text-expense">${formatMoney(data.pendingBillsTotal)}</div>
                    <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">Total de boletos a vencer no período</p>
                </div>
                <div class="card">
                    <h3 class="text-lg font-semibold mb-2 text-gray-800 dark:text-white">Boletos Recorrentes</h3>
                    <div class="text-2xl font-bold text-orange-500">${formatMoney(data.recurringBills)}</div>
                    <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">Despesas fixas recorrentes</p>
                </div>
            </div>
            
            <!-- Cash Flow Chart -->
            <div class="card mb-6">
                <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">Fluxo de Caixa (Histórico + Projeção)</h3>
                <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">* Meses com asterisco são projeções baseadas na média histórica</p>
                <div class="chart-container" style="height: 300px;">
                    <canvas id="cash-flow-chart"></canvas>
                </div>
            </div>
            
            <!-- Two Charts Side by Side -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                <!-- Future Bills Chart -->
                <div class="card">
                    <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">Despesas Futuras (Boletos)</h3>
                    <div class="chart-container" style="height: 250px;">
                        <canvas id="future-bills-chart"></canvas>
                    </div>
                </div>
                
                <!-- Category Breakdown -->
                <div class="card">
                    <h3 class="text-lg font-semibold mb-4 text-gray-800 dark:text-white">Projeções por Categoria</h3>
                    <div class="chart-container" style="height: 250px;">
                        <canvas id="projections-chart"></canvas>
                    </div>
                </div>
            </div>
        `;
        
        // Render all charts
        renderCashFlowChart(data.cashFlowData);
        renderFutureBillsChart(data.futureBillsData);
        renderProjectionsChart(data.projectionsByCategory);
        
    } catch (error) {
        content.innerHTML = `<div class="empty-state"><p>Erro ao carregar projeções: ${error.message}</p></div>`;
    }
}

function renderCashFlowChart(cashFlowData) {
    const ctx = document.getElementById('cash-flow-chart');
    if (!ctx) return;
    
    if (cashFlowChart) {
        cashFlowChart.destroy();
    }
    
    if (!cashFlowData || cashFlowData.length === 0) {
        ctx.parentElement.innerHTML = '<div class="empty-state"><p>Sem dados de fluxo de caixa</p></div>';
        return;
    }
    
    const labels = cashFlowData.map(d => d.month);
    const incomeData = cashFlowData.map(d => d.income);
    const expenseData = cashFlowData.map(d => d.expense);
    const balanceData = cashFlowData.map(d => d.balance);
    
    // Different styling for projected months
    const incomeColors = cashFlowData.map(d => d.type === 'projected' ? 'rgba(34, 197, 94, 0.5)' : '#22c55e');
    const expenseColors = cashFlowData.map(d => d.type === 'projected' ? 'rgba(239, 68, 68, 0.5)' : '#ef4444');
    
    cashFlowChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [
                {
                    label: 'Receita',
                    data: incomeData,
                    backgroundColor: incomeColors,
                    borderRadius: 4
                },
                {
                    label: 'Despesa',
                    data: expenseData,
                    backgroundColor: expenseColors,
                    borderRadius: 4
                },
                {
                    label: 'Saldo',
                    data: balanceData,
                    type: 'line',
                    borderColor: '#3b82f6',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    fill: true,
                    tension: 0.4,
                    pointRadius: 4,
                    pointBackgroundColor: '#3b82f6'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        padding: 15
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return context.dataset.label + ': ' + formatMoney(context.parsed.y);
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: value => formatMoney(value)
                    }
                }
            }
        }
    });
}

function renderFutureBillsChart(futureBillsData) {
    const ctx = document.getElementById('future-bills-chart');
    if (!ctx) return;
    
    if (futureBillsChart) {
        futureBillsChart.destroy();
    }
    
    if (!futureBillsData || futureBillsData.length === 0) {
        ctx.parentElement.innerHTML = '<div class="empty-state"><p>Sem boletos futuros cadastrados</p></div>';
        return;
    }
    
    futureBillsChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: futureBillsData.map(d => d.month),
            datasets: [{
                label: 'Boletos a Vencer',
                data: futureBillsData.map(d => d.total),
                backgroundColor: '#f97316',
                borderRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return formatMoney(context.parsed.y);
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: value => formatMoney(value)
                    }
                }
            }
        }
    });
}

function renderProjectionsChart(categoryData) {
    const ctx = document.getElementById('projections-chart');
    if (!ctx) return;
    
    if (projectionsChart) {
        projectionsChart.destroy();
    }
    
    if (!categoryData || categoryData.length === 0) {
        ctx.parentElement.innerHTML = '<div class="empty-state"><p>Sem dados de categoria</p></div>';
        return;
    }
    
    projectionsChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: categoryData.map(c => c.name),
            datasets: [{
                label: 'Valor Projetado',
                data: categoryData.map(c => parseFloat(c.projected_amount)),
                backgroundColor: categoryData.map(c => c.type === 'income' ? '#22c55e' : '#ef4444'),
                borderRadius: 4
            }]
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return formatMoney(context.parsed.x);
                        }
                    }
                }
            },
            scales: {
                x: {
                    beginAtZero: true,
                    ticks: {
                        callback: value => formatMoney(value)
                    }
                }
            }
        }
    });
}
