/**
 * Chart.js rendering for maca Restu admin dashboard.
 */
(function () {
    'use strict';

    var instances = {};
    var containerEl = null;

    function getConfig() {
        return window.macaMenulistDashboard || {};
    }

    function formatCurrency(value) {
        var cfg = getConfig();
        var currency = cfg.currency || 'SEK';
        var amount = Number(value) || 0;
        var decimals = Math.floor(amount) === amount ? 0 : 2;
        var formatted = amount.toLocaleString(undefined, {
            minimumFractionDigits: decimals,
            maximumFractionDigits: decimals,
        });
        return formatted + ' ' + currency;
    }

    function hexToRgba(hex, alpha) {
        var normalized = String(hex || '#2271b1').replace('#', '');
        if (normalized.length === 3) {
            normalized = normalized
                .split('')
                .map(function (c) {
                    return c + c;
                })
                .join('');
        }
        var int = parseInt(normalized, 16);
        var r = (int >> 16) & 255;
        var g = (int >> 8) & 255;
        var b = int & 255;
        return 'rgba(' + r + ',' + g + ',' + b + ',' + alpha + ')';
    }

    function destroyCharts() {
        Object.keys(instances).forEach(function (key) {
            if (instances[key]) {
                instances[key].destroy();
            }
        });
        instances = {};
        if (containerEl) {
            containerEl.innerHTML = '';
        }
    }

    function buildDataset(ds) {
        var color = ds.color || '#2271b1';
        var dataset = {
            label: ds.label || '',
            data: ds.data || [],
            backgroundColor: ds.type === 'line' ? hexToRgba(color, 0.15) : color,
            borderColor: color,
            borderWidth: ds.type === 'line' ? 2 : 1,
            borderRadius: ds.type === 'bar' ? 4 : 0,
            tension: 0.3,
            fill: !!ds.fill,
            yAxisID: ds.yAxisID || 'y',
        };

        if (ds.type === 'line') {
            dataset.type = 'line';
            dataset.pointRadius = 3;
            dataset.pointHoverRadius = 5;
        } else {
            dataset.type = 'bar';
        }

        return dataset;
    }

    function createMixedChart(canvas, chartConfig) {
        var datasets = (chartConfig.datasets || []).map(buildDataset);
        var hasCurrency = (chartConfig.datasets || []).some(function (ds) {
            return ds.format === 'currency';
        });

        return new window.Chart(canvas, {
            type: 'bar',
            data: {
                labels: chartConfig.labels || [],
                datasets: datasets,
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false,
                },
                plugins: {
                    legend: {
                        position: 'bottom',
                    },
                    tooltip: {
                        callbacks: {
                            label: function (context) {
                                var ds = chartConfig.datasets[context.datasetIndex] || {};
                                var prefix = context.dataset.label ? context.dataset.label + ': ' : '';
                                if (ds.format === 'currency') {
                                    return prefix + formatCurrency(context.parsed.y);
                                }
                                return prefix + context.parsed.y;
                            },
                        },
                    },
                },
                scales: {
                    x: {
                        grid: {
                            display: false,
                        },
                    },
                    y: {
                        beginAtZero: true,
                        position: 'left',
                        ticks: {
                            precision: 0,
                        },
                    },
                    y1: hasCurrency
                        ? {
                              beginAtZero: true,
                              position: 'right',
                              grid: {
                                  drawOnChartArea: false,
                              },
                              ticks: {
                                  callback: function (value) {
                                      return formatCurrency(value);
                                  },
                              },
                          }
                        : undefined,
                },
            },
        });
    }

    function createLineChart(canvas, chartConfig) {
        var ds = (chartConfig.datasets && chartConfig.datasets[0]) || {};
        return new window.Chart(canvas, {
            type: 'line',
            data: {
                labels: chartConfig.labels || [],
                datasets: [buildDataset(ds)],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false,
                    },
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            precision: 0,
                        },
                    },
                },
            },
        });
    }

    function createBarChart(canvas, chartConfig, horizontal) {
        var ds = (chartConfig.datasets && chartConfig.datasets[0]) || {};
        var dataset = buildDataset(ds);

        return new window.Chart(canvas, {
            type: 'bar',
            data: {
                labels: chartConfig.labels || [],
                datasets: [dataset],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                indexAxis: horizontal ? 'y' : 'x',
                plugins: {
                    legend: {
                        display: false,
                    },
                },
                scales: {
                    x: {
                        beginAtZero: true,
                        ticks: {
                            precision: 0,
                        },
                    },
                    y: {
                        beginAtZero: horizontal,
                    },
                },
            },
        });
    }

    function createDoughnutChart(canvas, chartConfig) {
        var colors = chartConfig.colors || ['#00a32a', '#dba617', '#d63638'];

        return new window.Chart(canvas, {
            type: 'doughnut',
            data: {
                labels: chartConfig.labels || [],
                datasets: [
                    {
                        data: chartConfig.data || [],
                        backgroundColor: colors,
                        borderWidth: 0,
                    },
                ],
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                    },
                },
            },
        });
    }

    function renderCharts(charts) {
        destroyCharts();

        if (!containerEl) {
            containerEl = document.getElementById('maca-dashboard-charts');
        }
        if (!containerEl || typeof window.Chart === 'undefined') {
            return;
        }

        if (!charts || !charts.length) {
            var cfg = getConfig();
            var emptyLabel = (cfg.labels && cfg.labels.noCharts) || '';
            containerEl.innerHTML =
                '<p class="maca-dashboard-charts-empty">' + emptyLabel + '</p>';
            return;
        }

        charts.forEach(function (chartConfig) {
            var card = document.createElement('div');
            card.className = 'maca-dashboard-chart-card';
            card.setAttribute('data-chart-id', chartConfig.id || '');

            var title = document.createElement('h3');
            title.className = 'maca-dashboard-chart-title';
            title.textContent = chartConfig.title || '';
            card.appendChild(title);

            var canvasWrap = document.createElement('div');
            canvasWrap.className = 'maca-dashboard-chart-canvas-wrap';
            var canvas = document.createElement('canvas');
            canvas.setAttribute('role', 'img');
            canvas.setAttribute('aria-label', chartConfig.title || '');
            canvasWrap.appendChild(canvas);
            card.appendChild(canvasWrap);

            containerEl.appendChild(card);

            var chartInstance;
            if (chartConfig.kind === 'doughnut') {
                chartInstance = createDoughnutChart(canvas, chartConfig);
            } else if (chartConfig.kind === 'mixed') {
                chartInstance = createMixedChart(canvas, chartConfig);
            } else if (chartConfig.kind === 'line') {
                chartInstance = createLineChart(canvas, chartConfig);
            } else {
                var horizontal =
                    chartConfig.datasets &&
                    chartConfig.datasets[0] &&
                    chartConfig.datasets[0].horizontal;
                chartInstance = createBarChart(canvas, chartConfig, horizontal);
            }

            instances[chartConfig.id || String(Math.random())] = chartInstance;
        });
    }

    window.MacaMenulistDashboardCharts = {
        render: renderCharts,
        destroy: destroyCharts,
    };
})();
