/**
 * Affiliate Reports — Chart.js Initialization
 *
 * Renders four charts using data injected by the PHP render method
 * via the global affpReportsData object.
 *
 * Brand colors:
 *   Primary purple:  #8444F9
 *   Teal:            #00d4aa
 *   Light purple:    #6C63FF
 */

(function () {
    'use strict';

    if (typeof Chart === 'undefined' || typeof affpReportsData === 'undefined') {
        return;
    }

    var chartCommissionTrend = null;
    var chartReferralFunnel  = null;
    var chartTopAffiliates   = null;
    var chartPlanDistribution = null;

    var PURPLE      = '#8444F9';
    var TEAL        = '#00d4aa';
    var LIGHT_PURPLE = '#6C63FF';

    var currency = affpReportsData.currencySymbol || '$';
    var i18n     = affpReportsData.i18n || {};

    // Shared defaults.
    Chart.defaults.font.family = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, sans-serif';
    Chart.defaults.font.size   = 13;
    Chart.defaults.color       = '#64748b';

    // ---------------------------------------------------------------
    // 1. Commission Trend — Line chart (dual lines: earned & paid)
    // ---------------------------------------------------------------
    (function () {
        var ctx = document.getElementById('affp-chart-commission-trend');
        if (!ctx) return;

        var data = affpReportsData.commissionTrend;

        if (chartCommissionTrend) { chartCommissionTrend.destroy(); }
        chartCommissionTrend = new Chart(ctx.getContext('2d'), {
            type: 'line',
            data: {
                labels: data.labels,
                datasets: [
                    {
                        label: i18n.earned || 'Earned',
                        data: data.earned,
                        borderColor: PURPLE,
                        backgroundColor: 'rgba(132, 68, 249, 0.1)',
                        borderWidth: 2,
                        fill: true,
                        tension: 0.3,
                        pointRadius: 3,
                        pointBackgroundColor: PURPLE
                    },
                    {
                        label: i18n.paid || 'Paid',
                        data: data.paid,
                        borderColor: TEAL,
                        backgroundColor: 'rgba(0, 212, 170, 0.1)',
                        borderWidth: 2,
                        fill: true,
                        tension: 0.3,
                        pointRadius: 3,
                        pointBackgroundColor: TEAL
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false
                },
                plugins: {
                    legend: {
                        position: 'top',
                        labels: {
                            usePointStyle: true,
                            padding: 16
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function (context) {
                                return context.dataset.label + ': ' + currency + parseFloat(context.raw).toFixed(2);
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function (value) {
                                return currency + value;
                            }
                        },
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    })();

    // ---------------------------------------------------------------
    // 2. Referral Funnel — Horizontal bar chart
    // ---------------------------------------------------------------
    (function () {
        var ctx = document.getElementById('affp-chart-referral-funnel');
        if (!ctx) return;

        var data = affpReportsData.referralFunnel;

        var barColors = [PURPLE, LIGHT_PURPLE, TEAL, '#00b894'];

        if (chartReferralFunnel) { chartReferralFunnel.destroy(); }
        chartReferralFunnel = new Chart(ctx.getContext('2d'), {
            type: 'bar',
            data: {
                labels: data.labels,
                datasets: [{
                    label: i18n.count || 'Count',
                    data: data.values,
                    backgroundColor: barColors,
                    borderColor: barColors,
                    borderWidth: 1,
                    borderRadius: 4,
                    barPercentage: 0.6
                }]
            },
            options: {
                indexAxis: 'y',
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function (context) {
                                return context.raw.toLocaleString();
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        beginAtZero: true,
                        ticks: {
                            precision: 0
                        },
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    y: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    })();

    // ---------------------------------------------------------------
    // 3. Top Affiliates — Horizontal bar chart (purple bars)
    // ---------------------------------------------------------------
    (function () {
        var ctx = document.getElementById('affp-chart-top-affiliates');
        if (!ctx) return;

        var data = affpReportsData.topAffiliates;

        if (!data.labels.length) {
            var p = document.createElement('p');
            p.className = 'affp-chart-empty-state';
            p.textContent = i18n.noAffData || 'No affiliate data available yet.';
            ctx.parentNode.appendChild(p);
            ctx.style.display = 'none';
            return;
        }

        if (chartTopAffiliates) { chartTopAffiliates.destroy(); }
        chartTopAffiliates = new Chart(ctx.getContext('2d'), {
            type: 'bar',
            data: {
                labels: data.labels,
                datasets: [{
                    label: i18n.totalEarned || 'Total Earned',
                    data: data.values,
                    backgroundColor: PURPLE,
                    borderColor: PURPLE,
                    borderWidth: 1,
                    borderRadius: 4,
                    barPercentage: 0.6
                }]
            },
            options: {
                indexAxis: 'y',
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function (context) {
                                return currency + parseFloat(context.raw).toFixed(2);
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        beginAtZero: true,
                        ticks: {
                            callback: function (value) {
                                return currency + value;
                            }
                        },
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    y: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    })();

    // ---------------------------------------------------------------
    // 4. Plan Distribution — Doughnut chart
    // ---------------------------------------------------------------
    (function () {
        var ctx = document.getElementById('affp-chart-plan-distribution');
        if (!ctx) return;

        var data = affpReportsData.planDistribution;

        var total = data.values.reduce(function (sum, v) { return sum + v; }, 0);

        if (total === 0) {
            var p = document.createElement('p');
            p.className = 'affp-chart-empty-state';
            p.textContent = i18n.noPlanData || 'No plan data available yet.';
            ctx.parentNode.appendChild(p);
            ctx.style.display = 'none';
            return;
        }

        if (chartPlanDistribution) { chartPlanDistribution.destroy(); }
        chartPlanDistribution = new Chart(ctx.getContext('2d'), {
            type: 'doughnut',
            data: {
                labels: data.labels,
                datasets: [{
                    data: data.values,
                    backgroundColor: [PURPLE, TEAL, LIGHT_PURPLE],
                    borderColor: '#ffffff',
                    borderWidth: 3,
                    hoverOffset: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '60%',
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            usePointStyle: true,
                            padding: 16
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function (context) {
                                var pct = total > 0 ? ((context.raw / total) * 100).toFixed(1) : 0;
                                return context.label + ': ' + context.raw + ' (' + pct + '%)';
                            }
                        }
                    }
                }
            }
        });
    })();

})();
