window.$ = jQuery;

var _reportCharts = {};

function _destroyReportCharts() {
    Object.keys(_reportCharts).forEach(function (key) {
        if (_reportCharts[key]) {
            _reportCharts[key].dispose();
            delete _reportCharts[key];
        }
    });
}

function _isDarkMode() {
    return document.documentElement.classList.contains('dark');
}

function _getEchartsTheme() {
    var dark = _isDarkMode();
    return {
        color: ['#2ecc71', '#212f3d', '#3498db', '#FF5733', '#2e86c1', '#9b59b6', '#e67e22', '#1abc9c'],
        backgroundColor: 'transparent',
        textStyle: { color: dark ? '#e5e5e5' : '#333', fontFamily: 'Estedad' },
        title: {
            textStyle: { color: dark ? '#e5e5e5' : '#333', fontSize: 14, fontWeight: 'bold' },
            subtextStyle: { color: dark ? '#999' : '#666', fontSize: 12 }
        },
        legend: {
            textStyle: { color: dark ? '#ccc' : '#333' }
        },
        tooltip: {
            backgroundColor: dark ? '#262626' : '#fff',
            borderColor: dark ? '#333' : '#ccc',
            textStyle: { color: dark ? '#e5e5e5' : '#333' }
        },
        xAxis: {
            axisLine: { lineStyle: { color: dark ? '#2a2a2a' : '#ccc' } },
            axisLabel: { color: dark ? '#999' : '#666' },
            splitLine: { show: false },
            nameTextStyle: { color: dark ? '#999' : '#666' }
        },
        yAxis: {
            axisLine: { show: false },
            axisLabel: { color: dark ? '#999' : '#666' },
            splitLine: { lineStyle: { color: dark ? '#2a2a2a' : '#e6e6e6', type: 'dashed' } },
            nameTextStyle: { color: dark ? '#999' : '#666' }
        }
    };
}

function _formatNumber(val) {
    if (val == null) return '0';
    return Number(val).toLocaleString('en-US', { maximumFractionDigits: 0 });
}

function _formatAxisDate(value, isJalali) {
    if (isJalali) {
        return new persianDate(value).format('MMMM D');
    }
    var d = new Date(value);
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    return months[d.getMonth()] + ' ' + d.getDate();
}

window.renderReportCharts = function () {

    _destroyReportCharts();

    var isJalali = anbarak.is_jalali;

    function getData(id) {
        var el = document.getElementById('ajax-' + id) || document.getElementById(id);
        if (!el) return [];
        try { return JSON.parse(el.textContent); } catch (e) { return []; }
    }

    var month_sales_all = getData('month-sales-all');
    var month_sales_online = getData('month-sales-online');
    var month_sales_in_store = getData('month-sales-in-store');
    var month_expense = getData('month-expense');
    var month_share = getData('month-share');
    var month_profit = getData('month-profit');
    var month_name = getData('month-name');
    var last_six_month_sales = getData('last-six-month-sales-all');
    var last_six_month_profit = getData('last-six-month-profit');

    if (!month_sales_all.length && !last_six_month_sales.length) return;

    var theme = _getEchartsTheme();

    function calculateMonthlyTotals(data) {
        if (!isJalali) {
            var monthlyTotals = [];
            var timestamps = data.map(function (item) { return item[0]; });
            var orderAmounts = data.map(function (item) { return item[1]; });
            var startDate = new Date(timestamps[0]);
            var currentMonth = startDate.getFullYear() * 100 + startDate.getMonth();
            var currentTotal = 0;

            for (var i = 0; i < data.length; i++) {
                var timestamp = timestamps[i];
                var orderAmount = orderAmounts[i];
                var d = new Date(timestamp);
                var monthKey = d.getFullYear() * 100 + d.getMonth();

                if (monthKey === currentMonth) {
                    currentTotal += orderAmount;
                } else {
                    var prevDate = new Date(d);
                    prevDate.setDate(0);
                    prevDate.setHours(23, 59, 59);
                    monthlyTotals.push([prevDate.getTime(), currentTotal]);
                    currentMonth = monthKey;
                    currentTotal = orderAmount;
                }
            }

            var lastDate = new Date();
            lastDate.setHours(23, 59, 59);
            monthlyTotals.push([lastDate.getTime(), currentTotal]);
            monthlyTotals[monthlyTotals.length - 1][0] = Date.now();
            return monthlyTotals;
        }

        var monthlyTotals = [];
        var timestamps = data.map(function (item) { return item[0]; });
        var orderAmounts = data.map(function (item) { return item[1]; });
        var startDate = timestamps[0];

        var lastDayOfMonth = new persianDate(startDate).endOf('month');
        var currentMonth = lastDayOfMonth.format('YYYYMM');
        var currentTotal = 0;

        for (var i = 0; i < data.length; i++) {
            var timestamp = timestamps[i];
            var orderAmount = orderAmounts[i];
            var persianDateX = new persianDate(timestamp);

            if (persianDateX.format('YYYYMM') === currentMonth) {
                currentTotal += orderAmount;
            } else {
                monthlyTotals.push([persianDateX.valueOf(), currentTotal]);
                currentMonth = persianDateX.format('YYYYMM');
                currentTotal = orderAmount;
            }
        }

        monthlyTotals.push([lastDayOfMonth.add(1, 'day').valueOf(), currentTotal]);
        monthlyTotals[monthlyTotals.length - 1][0] = new persianDate().valueOf();
        return monthlyTotals;
    }

    function makeTimeAxisConfig(name, isJalali) {
        return {
            type: 'time',
            name: name,
            axisLabel: {
                color: _isDarkMode() ? '#999' : '#666',
                formatter: function (value) {
                    return _formatAxisDate(value, isJalali);
                }
            },
            axisTick: { show: false },
            axisLine: { lineStyle: { color: _isDarkMode() ? '#2a2a2a' : '#ccc' } },
            splitLine: { show: false }
        };
    }

    function makeTooltipConfig(isJalali) {
        return {
            trigger: 'axis',
            backgroundColor: _isDarkMode() ? '#262626' : '#fff',
            borderColor: _isDarkMode() ? '#333' : '#ccc',
            textStyle: { color: _isDarkMode() ? '#e5e5e5' : '#333', fontFamily: 'Estedad' },
            formatter: function (params) {
                if (!params || !params.length) return '';
                var dateStr = _formatAxisDate(params[0].value[0], isJalali);
                var s = '<div style="font-weight:bold;margin-bottom:4px;font-size:13px">' + dateStr + '</div>';
                params.forEach(function (p) {
                    s += '<div style="display:flex;align-items:center;gap:6px;margin:2px 0">'
                        + p.marker + ' <span style="flex:1">' + p.seriesName + '</span>'
                        + '<b>' + _formatNumber(p.value[1]) + '</b></div>';
                });
                return s;
            },
            axisPointer: {
                type: 'cross',
                crossStyle: { color: '#999' },
                lineStyle: { color: _isDarkMode() ? '#555' : '#ccc', type: 'dashed' }
            }
        };
    }

    if (last_six_month_sales.length) {
        var sixSales = calculateMonthlyTotals(last_six_month_sales);
        var sixProfit = calculateMonthlyTotals(last_six_month_profit);

        var el = document.getElementById('last-six-month-stat-chart');
        if (el) {
            var chart = echarts.init(el);
            _reportCharts.lastSixMonth = chart;

            chart.setOption(Object.assign({}, theme, {
                title: { text: anbarak.i18n.last_6_months_sales_stats, subtext: anbarak.i18n.zoom_chart_hint, left: 'center' },
                tooltip: makeTooltipConfig(isJalali),
                legend: { data: [anbarak.i18n.total_sales, anbarak.i18n.gross_profit], bottom: 0 },
                grid: { left: 60, right: 30, top: 60, bottom: 50 },
                dataZoom: [{ type: 'inside', start: 0, end: 100 }],
                xAxis: makeTimeAxisConfig(anbarak.i18n.months, isJalali),
                yAxis: {
                    type: 'value',
                    name: anbarak.i18n.price,
                    axisLabel: {
                        color: _isDarkMode() ? '#999' : '#666',
                        formatter: function (v) {
                            if (v >= 1000000) return (v / 1000000).toFixed(1) + 'M';
                            if (v >= 1000) return (v / 1000).toFixed(0) + 'K';
                            return v;
                        }
                    }
                },
                series: [
                    {
                        name: anbarak.i18n.total_sales,
                        type: 'line',
                        data: sixSales,
                        smooth: 0.3,
                        symbol: 'circle',
                        symbolSize: 6,
                        showSymbol: false,
                        lineStyle: { width: 2.5 },
                        itemStyle: { color: '#2ecc71' },
                        areaStyle: { opacity: 0 }
                    },
                    {
                        name: anbarak.i18n.gross_profit,
                        type: 'line',
                        data: sixProfit,
                        smooth: 0.3,
                        symbol: 'circle',
                        symbolSize: 6,
                        showSymbol: false,
                        lineStyle: { width: 2.5 },
                        itemStyle: { color: '#2ecc71' },
                        areaStyle: { opacity: 0.15 }
                    }
                ]
            }));

            window.addEventListener('resize', function () { chart.resize(); });
        }
    }

    if (month_sales_all.length) {
        var lbl = month_name || '';

        var el = document.getElementById('overall-stat-chart');
        if (el) {
            var chart = echarts.init(el);
            _reportCharts.overall = chart;

            chart.setOption(Object.assign({}, theme, {
                title: { text: anbarak.i18n.monthly_report + (lbl ? ' ( ' + lbl + ' )' : ''), subtext: anbarak.i18n.zoom_chart_hint, left: 'center' },
                tooltip: makeTooltipConfig(isJalali),
                legend: {
                    data: [
                        anbarak.i18n.total_sales,
                        anbarak.i18n.month_offline_sale_price,
                        anbarak.i18n.month_online_sale_price,
                        anbarak.i18n.month_total_expense_price
                    ],
                    bottom: 0
                },
                grid: { left: 60, right: 30, top: 60, bottom: 50 },
                dataZoom: [{ type: 'inside', start: 0, end: 100 }],
                xAxis: makeTimeAxisConfig(anbarak.i18n.day_of_month, isJalali),
                yAxis: {
                    type: 'value',
                    name: anbarak.i18n.price,
                    axisLabel: {
                        color: _isDarkMode() ? '#999' : '#666',
                        formatter: function (v) {
                            if (v >= 1000000) return (v / 1000000).toFixed(1) + 'M';
                            if (v >= 1000) return (v / 1000).toFixed(0) + 'K';
                            return v;
                        }
                    }
                },
                series: [
                    {
                        name: anbarak.i18n.total_sales,
                        type: 'line',
                        data: month_sales_all,
                        smooth: 0.3,
                        symbol: 'circle',
                        symbolSize: 6,
                        showSymbol: false,
                        lineStyle: { width: 3 },
                        itemStyle: { color: '#2ecc71' }
                    },
                    {
                        name: anbarak.i18n.month_offline_sale_price,
                        type: 'line',
                        data: month_sales_in_store,
                        smooth: 0.3,
                        symbol: 'circle',
                        symbolSize: 4,
                        showSymbol: false,
                        lineStyle: { width: 2 },
                        itemStyle: { color: '#212f3d' }
                    },
                    {
                        name: anbarak.i18n.month_online_sale_price,
                        type: 'line',
                        data: month_sales_online,
                        smooth: 0.3,
                        symbol: 'circle',
                        symbolSize: 4,
                        showSymbol: false,
                        lineStyle: { width: 2 },
                        itemStyle: { color: '#3498db' }
                    },
                    {
                        name: anbarak.i18n.month_total_expense_price,
                        type: 'line',
                        data: month_expense,
                        smooth: 0.3,
                        symbol: 'circle',
                        symbolSize: 4,
                        showSymbol: false,
                        lineStyle: { width: 2.5, type: 'dashed' },
                        itemStyle: { color: '#FF5733' }
                    }
                ]
            }));

            window.addEventListener('resize', function () { chart.resize(); });
        }

        var elProfit = document.getElementById('sell-profit-chart');
        if (elProfit) {
            var chartProfit = echarts.init(elProfit);
            _reportCharts.sellProfit = chartProfit;

            chartProfit.setOption(Object.assign({}, theme, {
                title: { text: anbarak.i18n.sales_gross_profit_chart + (lbl ? ' ( ' + lbl + ' )' : ''), subtext: anbarak.i18n.zoom_chart_hint, left: 'center' },
                tooltip: makeTooltipConfig(isJalali),
                legend: { data: [anbarak.i18n.total_sales, anbarak.i18n.gross_profit], bottom: 0 },
                grid: { left: 60, right: 30, top: 60, bottom: 50 },
                dataZoom: [{ type: 'inside', start: 0, end: 100 }],
                xAxis: makeTimeAxisConfig(anbarak.i18n.day_of_month, isJalali),
                yAxis: {
                    type: 'value',
                    name: anbarak.i18n.price,
                    axisLabel: {
                        color: _isDarkMode() ? '#999' : '#666',
                        formatter: function (v) {
                            if (v >= 1000000) return (v / 1000000).toFixed(1) + 'M';
                            if (v >= 1000) return (v / 1000).toFixed(0) + 'K';
                            return v;
                        }
                    }
                },
                series: [
                    {
                        name: anbarak.i18n.total_sales,
                        type: 'line',
                        data: month_sales_all,
                        smooth: 0.3,
                        symbol: 'circle',
                        symbolSize: 6,
                        showSymbol: false,
                        lineStyle: { width: 2.5 },
                        itemStyle: { color: '#2ecc71' }
                    },
                    {
                        name: anbarak.i18n.gross_profit,
                        type: 'line',
                        data: month_profit,
                        smooth: 0.3,
                        symbol: 'circle',
                        symbolSize: 6,
                        showSymbol: false,
                        lineStyle: { width: 2.5 },
                        itemStyle: { color: '#2ecc71' },
                        areaStyle: { opacity: 0.15 }
                    }
                ]
            }));

            window.addEventListener('resize', function () { chartProfit.resize(); });
        }
    }
};

jQuery(function ($) {
    if ($('.app-content.report').length < 1) return;

    window.renderReportCharts();

    var expensesStatsChart;
    var expensesStatsResizeBound = false;

    function renderExpensesStatsChart() {
        var dataEl = document.getElementById("expenses-share");
        var colorEl = document.getElementById("tags-color");
        var expense_share = [];
        var tag_color = [];

        try { expense_share = dataEl ? JSON.parse(dataEl.textContent) : []; } catch (e) { expense_share = []; }
        try { tag_color = colorEl ? JSON.parse(colorEl.textContent) : []; } catch (e) { tag_color = []; }

        var el = document.getElementById('overall-expense-pie-chart');
        if (!el) return;

        if (expensesStatsChart) expensesStatsChart.dispose();

        expensesStatsChart = echarts.init(el);

        var pieData = expense_share.map(function (item, i) {
            return {
                name: item.name || item[0],
                value: item.y != null ? item.y : (item.value || item[1] || 0),
                itemStyle: { color: tag_color[i] || undefined }
            };
        });

        var dark = _isDarkMode();
        var total = pieData.reduce(function (sum, item) {
            return sum + Number(item.value || 0);
        }, 0);
        var hasData = total > 0;

        expensesStatsChart.setOption({
            backgroundColor: 'transparent',
            textStyle: { fontFamily: 'Estedad' },
            color: tag_color.length ? tag_color : _getEchartsTheme().color,
            tooltip: {
                trigger: 'item',
                backgroundColor: dark ? '#262626' : '#fff',
                borderColor: dark ? '#333' : '#ccc',
                textStyle: { color: dark ? '#e5e5e5' : '#333', fontFamily: 'Estedad' },
                formatter: function (p) {
                    return '<b>' + p.name + '</b><br/>' + _formatNumber(p.value) + ' (' + p.percent + '%)';
                }
            },
            legend: {
                type: 'scroll',
                orient: 'horizontal',
                left: 16,
                right: 16,
                top: null,
                bottom: 8,
                itemWidth: 10,
                itemHeight: 10,
                icon: 'circle',
                textStyle: { fontFamily: 'Estedad', color: dark ? '#ccc' : '#333', fontSize: 12 }
            },
            graphic: hasData ? [] : [{
                type: 'group',
                left: 'center',
                top: 'middle',
                children: [
                    {
                        type: 'circle',
                        shape: { r: 38 },
                        style: { fill: dark ? '#262626' : '#f7f7f7', stroke: dark ? '#333' : '#e5e7eb', lineWidth: 1 }
                    },
                    {
                        type: 'text',
                        left: 'center',
                        top: 54,
                        style: {
                            text: anbarak.i18n.nothing_found,
                            fill: dark ? '#a3a3a3' : '#6b7280',
                            font: '13px Estedad',
                            textAlign: 'center'
                        }
                    }
                ]
            }],
            series: [{
                name: anbarak.i18n.share,
                type: 'pie',
                radius: hasData ? ['36%', '64%'] : ['0%', '0%'],
                center: ['50%', '43%'],
                avoidLabelOverlap: true,
                padAngle: 1,
                minAngle: 3,
                itemStyle: { borderRadius: 7, borderColor: dark ? '#1a1a1a' : '#fff', borderWidth: 3 },
                label: {
                    show: hasData,
                    formatter: function (p) {
                        return p.percent + '%';
                    },
                    fontFamily: 'Estedad',
                    color: dark ? '#d4d4d4' : '#374151',
                    fontWeight: 'bold'
                },
                labelLine: {
                    show: hasData,
                    length: 10,
                    length2: 8,
                    lineStyle: { color: dark ? '#555' : '#d1d5db' }
                },
                emphasis: {
                    label: { show: true, fontSize: 14, fontWeight: 'bold' },
                    itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0, 0, 0, 0.2)' }
                },
                data: pieData
            }],
            media: [
                {
                    query: { maxWidth: 640 },
                    option: {
                        legend: { orient: 'horizontal', left: 16, right: 16, top: null, bottom: 8 },
                        series: [{ center: ['50%', '42%'], radius: hasData ? ['34%', '58%'] : ['0%', '0%'] }]
                    }
                }
            ]
        });

        if (!expensesStatsResizeBound) {
            window.addEventListener('resize', function () {
                if (expensesStatsChart) expensesStatsChart.resize();
            });
            expensesStatsResizeBound = true;
        }

        setTimeout(function () {
            if (expensesStatsChart) expensesStatsChart.resize();
        }, 50);
    }

    window.renderExpensesStatsChart = renderExpensesStatsChart;
    renderExpensesStatsChart();

    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function () {
        if (typeof window.renderReportCharts === 'function') window.renderReportCharts();
        if (typeof window.renderExpensesStatsChart === 'function') window.renderExpensesStatsChart();
    });
});
