/**
 * Analytics Dashboard — Chart.js initialization & AJAX period switching.
 *
 * Depends on: Chart.js (loaded as strp-sub-chartjs), jQuery, strp_sub_dashboard_ajax.
 *
 * Global vars injected by PHP:
 *  - strpDashboardChartData    { labels: [], values: [] }
 *  - strpDashboardPlanData     { monthly: n, annual: n, lifetime: n }
 *  - strpDashboardKpis         { mrr, active, new, churn_rate, ... }
 *  - strpRetentionReasonsData  [{ label, count }]              (Professional only)
 *  - strpRetentionOffersData   [{ type, accepted, rejected }]  (Professional only)
 */
(function ($) {
    'use strict';

    var ajaxParams = (typeof strp_sub_dashboard_ajax !== 'undefined') ? strp_sub_dashboard_ajax : {};

    // Chart instances retained to prevent garbage collection and enable destroy/recreate on data updates.
    var revenueChart          = null;
    var planChart             = null;
    var retentionReasonsChart = null;
    var retentionOffersChart  = null;

    // ------------------------------------------------------------------
    //  Initialization
    // ------------------------------------------------------------------

    $(document).ready(function () {
        initRevenueChart();
        initPlanChart();
        initRetentionReasonsChart();
        initRetentionOffersChart();
        initPeriodSelector();
        animateKpiValues();
    });

    // ------------------------------------------------------------------
    //  Revenue Line Chart
    // ------------------------------------------------------------------

    function initRevenueChart() {
        var ctx = document.getElementById('strp-revenue-chart');
        if (!ctx) {
            return;
        }

        var context  = ctx.getContext('2d');
        var gradient = context.createLinearGradient(0, 0, 0, 300);
        gradient.addColorStop(0, 'rgba(132, 68, 249, 0.3)');
        gradient.addColorStop(1, 'rgba(132, 68, 249, 0.02)');

        var data    = (typeof strpDashboardChartData !== 'undefined') ? strpDashboardChartData : { labels: [], values: [] };
        var labels  = data.labels || [];
        var values  = data.values || [];

        revenueChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: (ajaxParams.i18n_revenue) || 'Revenue',
                    data: values,
                    borderColor: '#8444F9',
                    backgroundColor: gradient,
                    borderWidth: 2.5,
                    pointBackgroundColor: '#8444F9',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 3,
                    pointHoverRadius: 6,
                    fill: true,
                    tension: 0.35
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    intersect: false,
                    mode: 'index'
                },
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: '#1e293b',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        padding: 12,
                        cornerRadius: 8,
                        callbacks: {
                            label: function (context) {
                                return (ajaxParams.currency_symbol || '$') + context.parsed.y.toFixed(2);
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: {
                            color: '#94a3b8',
                            font: { size: 12 },
                            maxTicksLimit: 12
                        }
                    },
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(226, 232, 240, 0.5)',
                            drawBorder: false
                        },
                        ticks: {
                            color: '#94a3b8',
                            font: { size: 12 },
                            callback: function (value) {
                                return (ajaxParams.currency_symbol || '$') + value;
                            }
                        }
                    }
                }
            }
        });
    }

    // ------------------------------------------------------------------
    //  Plan Distribution Doughnut
    // ------------------------------------------------------------------

    function initPlanChart() {
        var ctx = document.getElementById('strp-plan-chart');
        if (!ctx) {
            return;
        }

        var data     = (typeof strpDashboardPlanData !== 'undefined') ? strpDashboardPlanData : {};
        var monthly  = data.monthly  || 0;
        var annual   = data.annual   || 0;
        var lifetime = data.lifetime || 0;

        planChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: [
                    (ajaxParams.i18n_monthly) || 'Monthly',
                    (ajaxParams.i18n_annual) || 'Annual',
                    (ajaxParams.i18n_lifetime) || 'Lifetime'
                ],
                datasets: [{
                    data: [monthly, annual, lifetime],
                    backgroundColor: ['#8444F9', '#00d4aa', '#6C63FF'],
                    borderColor: '#fff',
                    borderWidth: 3,
                    hoverBorderWidth: 0,
                    hoverOffset: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '65%',
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 20,
                            usePointStyle: true,
                            pointStyleWidth: 12,
                            font: { size: 13, weight: '500' },
                            color: '#64748b'
                        }
                    },
                    tooltip: {
                        backgroundColor: '#1e293b',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        padding: 12,
                        cornerRadius: 8
                    }
                }
            }
        });
    }

    // ------------------------------------------------------------------
    //  Retention: Cancellation Reasons Horizontal Bar Chart
    // ------------------------------------------------------------------

    function initRetentionReasonsChart() {
        var ctx = document.getElementById('strp-retention-reasons-chart');
        if (!ctx) {
            return;
        }

        var data   = (typeof strpRetentionReasonsData !== 'undefined') ? strpRetentionReasonsData : [];
        var labels = [];
        var values = [];

        for (var i = 0; i < data.length; i++) {
            labels.push(data[i].label || '');
            values.push(data[i].count || 0);
        }

        retentionReasonsChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: (ajaxParams.i18n_count) || 'Count',
                    data: values,
                    backgroundColor: '#8444F9',
                    borderColor: '#8444F9',
                    borderWidth: 1,
                    borderRadius: 4,
                    barThickness: 24
                }]
            },
            options: {
                indexAxis: 'y',
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: '#1e293b',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        padding: 12,
                        cornerRadius: 8
                    }
                },
                scales: {
                    x: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(226, 232, 240, 0.5)',
                            drawBorder: false
                        },
                        ticks: {
                            color: '#94a3b8',
                            font: { size: 12 },
                            precision: 0
                        }
                    },
                    y: {
                        grid: { display: false },
                        ticks: {
                            color: '#94a3b8',
                            font: { size: 12 }
                        }
                    }
                }
            }
        });
    }

    // ------------------------------------------------------------------
    //  Retention: Offer Performance Stacked Bar Chart
    // ------------------------------------------------------------------

    function initRetentionOffersChart() {
        var ctx = document.getElementById('strp-retention-offers-chart');
        if (!ctx) {
            return;
        }

        var data   = (typeof strpRetentionOffersData !== 'undefined') ? strpRetentionOffersData : [];
        var labels   = [];
        var accepted = [];
        var rejected = [];

        for (var i = 0; i < data.length; i++) {
            labels.push(data[i].type || '');
            accepted.push(data[i].accepted || 0);
            rejected.push(data[i].rejected || 0);
        }

        retentionOffersChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: (ajaxParams.i18n_accepted) || 'Accepted',
                        data: accepted,
                        backgroundColor: '#00d4aa',
                        borderColor: '#00d4aa',
                        borderWidth: 1,
                        borderRadius: 4
                    },
                    {
                        label: (ajaxParams.i18n_rejected) || 'Rejected',
                        data: rejected,
                        backgroundColor: '#8444F9',
                        borderColor: '#8444F9',
                        borderWidth: 1,
                        borderRadius: 4
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 20,
                            usePointStyle: true,
                            pointStyleWidth: 12,
                            font: { size: 13, weight: '500' },
                            color: '#64748b'
                        }
                    },
                    tooltip: {
                        backgroundColor: '#1e293b',
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        padding: 12,
                        cornerRadius: 8
                    }
                },
                scales: {
                    x: {
                        stacked: true,
                        grid: { display: false },
                        ticks: {
                            color: '#94a3b8',
                            font: { size: 12 }
                        }
                    },
                    y: {
                        stacked: true,
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(226, 232, 240, 0.5)',
                            drawBorder: false
                        },
                        ticks: {
                            color: '#94a3b8',
                            font: { size: 12 },
                            precision: 0
                        }
                    }
                }
            }
        });
    }

    // ------------------------------------------------------------------
    //  Period Selector
    // ------------------------------------------------------------------

    function initPeriodSelector() {
        $(document).on('click', '.strp-period-selector__btn', function (e) {
            e.preventDefault();

            var $btn   = $(this);
            var period = $btn.data('period');

            if ($btn.hasClass('strp-period-selector__btn--active')) {
                return;
            }

            // Update active state.
            $('.strp-period-selector__btn').removeClass('strp-period-selector__btn--active');
            $btn.addClass('strp-period-selector__btn--active');

            // Mark KPI values as loading.
            $('.strp-kpi-card__value').addClass('strp-kpi-card__value--loading');

            $.ajax({
                url: ajaxParams.ajax_url || ajaxurl,
                type: 'POST',
                data: {
                    action: 'strp_sub_dashboard_switch_period',
                    nonce: ajaxParams.nonce || '',
                    period: period
                },
                success: function (response) {
                    if (response.success && response.data) {
                        updateKpis(response.data.kpis);
                        updateRevenueChart(response.data.chart_data);
                        if (response.data.retention_kpis) {
                            updateRetentionKpis(response.data.retention_kpis);
                        }
                    } else {
                        // Server returned an error or unexpected payload — leave current data intact.
                    }
                },
                error: function () {
                    // Network or server error — leave current data intact so the UI is not blank.
                },
                complete: function () {
                    $('.strp-kpi-card__value').removeClass('strp-kpi-card__value--loading');
                }
            });
        });
    }

    // ------------------------------------------------------------------
    //  Update KPIs After AJAX
    // ------------------------------------------------------------------

    function updateKpis(kpis) {
        if (!kpis) {
            return;
        }

        var $cards = $('.strp-kpi-card');
        if ($cards.length < 4) {
            return;
        }

        // MRR.
        var mrrFormatted = (ajaxParams.currency_symbol || '$') + (parseFloat(kpis.mrr) || 0).toFixed(2);
        $cards.eq(0).find('.strp-kpi-card__value').text(mrrFormatted);
        updateTrend($cards.eq(0), kpis.mrr_change);

        // Active.
        $cards.eq(1).find('.strp-kpi-card__value').text(kpis.active);
        updateTrend($cards.eq(1), kpis.active_change);

        // New.
        $cards.eq(2).find('.strp-kpi-card__value').text(kpis.new);
        updateTrend($cards.eq(2), kpis.new_change);

        // Churn.
        $cards.eq(3).find('.strp-kpi-card__value').text((parseFloat(kpis.churn_rate) || 0).toFixed(1) + '%');
        updateTrend($cards.eq(3), kpis.churn_change);

        animateKpiValues();
    }

    function updateTrend($card, change) {
        var $trend = $card.find('.strp-kpi-card__trend');
        var isUp   = change >= 0;
        var arrow  = isUp ? '\u25B2' : '\u25BC';

        $trend
            .removeClass('strp-kpi-card__trend--up strp-kpi-card__trend--down')
            .addClass(isUp ? 'strp-kpi-card__trend--up' : 'strp-kpi-card__trend--down')
            .empty()
            .append(document.createTextNode(arrow + ' ' + Math.abs(Math.round(change * 10) / 10) + '% ' + (ajaxParams.i18n_vs_prior || 'vs prior period')));
    }

    // ------------------------------------------------------------------
    //  Update Revenue Chart After AJAX
    // ------------------------------------------------------------------

    function updateRevenueChart(chartData) {
        if (!revenueChart || !chartData) {
            return;
        }

        revenueChart.data.labels              = chartData.labels || [];
        revenueChart.data.datasets[0].data    = chartData.values || [];
        revenueChart.update('active');
    }

    // ------------------------------------------------------------------
    //  Update Retention KPIs After AJAX
    // ------------------------------------------------------------------

    function updateRetentionKpis(kpis) {
        if (!kpis) {
            return;
        }

        var $section = $('.strp-analytics-section');
        if (!$section.length) {
            return;
        }

        var $cards = $section.find('.strp-kpi-card');
        if ($cards.length < 3) {
            return;
        }

        // Save Rate.
        $cards.eq(0).find('.strp-kpi-card__value').text((parseFloat(kpis.save_rate) || 0).toFixed(1) + '%');

        // Revenue Saved.
        var revSaved = (ajaxParams.currency_symbol || '$') + (parseFloat(kpis.estimated_revenue_saved) || 0).toFixed(2);
        $cards.eq(1).find('.strp-kpi-card__value').text(revSaved);

        // Top Reason.
        $cards.eq(2).find('.strp-kpi-card__value').text(kpis.top_reason || '\u2014');
    }

    // ------------------------------------------------------------------
    //  KPI Count-Up Animation
    // ------------------------------------------------------------------

    function animateKpiValues() {
        $('.strp-kpi-card__value').each(function () {
            var $el  = $(this);
            var text = $el.text();

            // Extract numeric portion.
            var numeric = text.replace(/[^0-9.]/g, '');
            var num     = parseFloat(numeric);
            if (isNaN(num) || num === 0) {
                return;
            }

            var prefix  = text.replace(/[\d.,]+.*$/, '');
            var suffix  = text.replace(/^[^0-9]*[\d.,]+/, '');
            var decimals = (text.indexOf('.') !== -1) ? (text.split('.')[1] || '').replace(/[^0-9]/g, '').length : 0;

            var startVal  = 0;
            var duration  = 800;
            var startTime = null;

            function step(timestamp) {
                if (!startTime) {
                    startTime = timestamp;
                }
                var progress = Math.min((timestamp - startTime) / duration, 1);
                // Ease-out cubic.
                var eased = 1 - Math.pow(1 - progress, 3);
                var current = startVal + (num - startVal) * eased;

                if (decimals > 0) {
                    $el.text(prefix + current.toFixed(decimals) + suffix);
                } else {
                    $el.text(prefix + Math.round(current).toLocaleString() + suffix);
                }

                if (progress < 1) {
                    requestAnimationFrame(step);
                } else {
                    // Restore the original text to avoid formatting drift.
                    $el.text(text);
                }
            }

            requestAnimationFrame(step);
        });
    }

})(jQuery);
