(function ($) {
    'use strict';

    function formatEuro(value) {
        return Number(value || 0).toLocaleString('fr-FR', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        }) + ' €';
    }

    function parseJsonAttribute(element, attributeName) {
        let payload = element.getAttribute(attributeName);
        if (!payload) {
            return null;
        }

        try {
            return JSON.parse(payload);
        } catch (error) {
            return null;
        }
    }

    function initRevenueChart() {
        let chartElement = document.getElementById('order-stats-chart');

        if (!chartElement || typeof echarts === 'undefined') {
            return;
        }

        let chartData = parseJsonAttribute(chartElement, 'data-chart');
        if (!chartData) {
            return;
        }

        let chart = echarts.init(chartElement);

        chart.setOption({
            color: ['#274c77', '#d97706', '#6b7280'],
            animationDuration: 250,
            grid: {
                top: 40,
                right: 24,
                bottom: 70,
                left: 70
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function (params) {
                    let lines = [params[0] ? params[0].axisValue : ''];

                    params.forEach(function (item) {
                        if (item.seriesName === 'Commandes') {
                            lines.push(item.marker + ' ' + item.seriesName + ' : ' + item.value);
                            return;
                        }

                        lines.push(item.marker + ' ' + item.seriesName + ' : ' + formatEuro(item.value));
                    });

                    return lines.join('<br>');
                }
            },
            legend: {
                top: 0,
                selected: {
                    'Panier moyen': false
                }
            },
            dataZoom: [
                {
                    type: 'inside'
                },
                {
                    type: 'slider',
                    height: 20,
                    bottom: 16
                }
            ],
            xAxis: {
                type: 'category',
                data: chartData.categories || [],
                axisLabel: {
                    rotate: 35
                }
            },
            yAxis: [
                {
                    type: 'value',
                    name: 'Commandes',
                    minInterval: 1
                },
                {
                    type: 'value',
                    name: 'CA / panier',
                    axisLabel: {
                        formatter: function (value) {
                            return formatEuro(value);
                        }
                    }
                }
            ],
            series: [
                {
                    name: 'Commandes',
                    type: 'bar',
                    yAxisIndex: 0,
                    barMaxWidth: 38,
                    data: chartData.orders || []
                },
                {
                    name: 'Chiffre d\'affaire',
                    type: 'line',
                    yAxisIndex: 1,
                    smooth: true,
                    symbolSize: 8,
                    data: chartData.revenue || []
                },
                {
                    name: 'Panier moyen',
                    type: 'line',
                    yAxisIndex: 1,
                    smooth: true,
                    lineStyle: {
                        type: 'dashed'
                    },
                    symbolSize: 6,
                    data: chartData.average_basket || []
                }
            ]
        });

        return chart;
    }

    function initRadarChart() {
        let radarElement = document.getElementById('order-stats-radar');

        if (!radarElement || typeof echarts === 'undefined') {
            return;
        }

        let radarData = parseJsonAttribute(radarElement, 'data-radar');
        if (!radarData || !radarData.indicators || radarData.indicators.length === 0) {
            return;
        }

        let radarChart = echarts.init(radarElement);

        radarChart.setOption({
            color: ['#1d4ed8', '#d97706'],
            animationDuration: 250,
            legend: {
                bottom: 0
            },
            tooltip: {
                trigger: 'item',
                formatter: function (params) {
                    let lines = ['<strong>' + params.seriesName + '</strong>'];

                    params.value.forEach(function (value, index) {
                        let label = radarData.indicators[index] ? radarData.indicators[index].name : 'Produit';
                        lines.push(label + ' : ' + Number(value || 0).toLocaleString('fr-FR', {
                            minimumFractionDigits: 1,
                            maximumFractionDigits: 1
                        }) + ' %');
                    });

                    return lines.join('<br>');
                }
            },
            radar: {
                indicator: radarData.indicators,
                radius: '65%',
                splitNumber: 5,
                axisName: {
                    color: '#334155',
                    fontSize: 11
                },
                splitArea: {
                    areaStyle: {
                        color: ['rgba(148, 163, 184, 0.08)', 'rgba(148, 163, 184, 0.03)']
                    }
                }
            },
            series: [
                {
                    name: 'Produits',
                    type: 'radar',
                    data: [
                        {
                            value: radarData.revenue_share || [],
                            name: 'Part du CA'
                        },
                        {
                            value: radarData.quantity_share || [],
                            name: 'Part des quantites'
                        }
                    ]
                }
            ]
        });

        return radarChart;
    }

    function normalizeSortValue(value, type) {
        if (type === 'number') {
            let normalized = String(value || '')
                .replace(/\s/g, '')
                .replace('%', '')
                .replace('€', '')
                .replace(',', '.');

            let parsed = Number(normalized);

            return isNaN(parsed) ? 0 : parsed;
        }

        return String(value || '').toLocaleLowerCase('fr-FR');
    }

    function getCellSortValue(cell, type) {
        let customValue = cell.getAttribute('data-sort-value');
        let value = customValue !== null ? customValue : cell.textContent;

        return normalizeSortValue(value, type);
    }

    function updateSortIndicators(table, activeHeader, direction) {
        $(table).find('th[data-sortable]').each(function () {
            let header = $(this);

            if (this === activeHeader) {
                header.attr('data-sort-direction', direction);
                header.find('.order-stats-sort-indicator').text(direction === 'asc' ? '▲' : '▼');
                return;
            }

            header.removeAttr('data-sort-direction');
            header.find('.order-stats-sort-indicator').text('');
        });
    }

    function sortTable(table, columnIndex, direction, type, activeHeader) {
        let tbody = table.tBodies[0];
        if (!tbody) {
            return;
        }

        let rows = Array.prototype.slice.call(tbody.querySelectorAll('tr'));
        let emptyRows = rows.filter(function (row) {
            return row.getAttribute('data-empty-row') === 'true';
        });
        let sortableRows = rows.filter(function (row) {
            return row.getAttribute('data-empty-row') !== 'true';
        });

        sortableRows.sort(function (leftRow, rightRow) {
            let leftCell = leftRow.cells[columnIndex];
            let rightCell = rightRow.cells[columnIndex];

            let leftValue = getCellSortValue(leftCell, type);
            let rightValue = getCellSortValue(rightCell, type);

            if (leftValue < rightValue) {
                return direction === 'asc' ? -1 : 1;
            }

            if (leftValue > rightValue) {
                return direction === 'asc' ? 1 : -1;
            }

            return 0;
        });

        sortableRows.concat(emptyRows).forEach(function (row) {
            tbody.appendChild(row);
        });

        updateSortIndicators(table, activeHeader, direction);
    }

    function initSortableTables() {
        $('[data-sortable-table]').each(function () {
            let table = this;
            let defaultSortIndex = Number(table.getAttribute('data-default-sort'));
            let defaultOrder = table.getAttribute('data-default-order') || 'asc';

            $(table).find('th[data-sortable]').each(function (index) {
                $(this).on('click', function () {
                    let currentDirection = this.getAttribute('data-sort-direction');
                    let nextDirection = currentDirection === 'asc' ? 'desc' : 'asc';
                    let sortType = this.getAttribute('data-sort-type') || 'text';

                    sortTable(table, index, nextDirection, sortType, this);
                });
            });

            if (!isNaN(defaultSortIndex)) {
                let defaultHeader = $(table).find('th[data-sortable]').get(defaultSortIndex);
                if (defaultHeader) {
                    sortTable(
                        table,
                        defaultSortIndex,
                        defaultOrder === 'asc' ? 'asc' : 'desc',
                        defaultHeader.getAttribute('data-sort-type') || 'text',
                        defaultHeader
                    );
                }
            }
        });
    }

    $(function () {
        let charts = [];
        let revenueChart = initRevenueChart();
        let radarChart = initRadarChart();

        if (revenueChart) {
            charts.push(revenueChart);
        }

        if (radarChart) {
            charts.push(radarChart);
        }

        initSortableTables();

        $(window).on('resize', function () {
            charts.forEach(function (chart) {
                chart.resize();
            });
        });
    });
})(jQuery);
