(function () {
    'use strict';

    function parseConfig() {
        var node = document.getElementById('beds82_comparison_config');
        if (!node) return null;
        try {
            return JSON.parse(node.textContent || '{}');
        } catch (error) {
            return null;
        }
    }

    function setState(key, state) {
        var shell = document.querySelector('[data-beds82-chart-shell="' + key + '"]');
        if (shell) shell.setAttribute('data-chart-state', state);
    }

    function number(value) {
        var parsed = Number(value);
        return Number.isFinite(parsed) ? parsed : null;
    }

    function format(value) {
        var parsed = number(value);
        return parsed === null ? '—' : parsed.toFixed(1) + '%';
    }

    function movement(value) {
        var parsed = number(value);
        if (parsed === null) return '—';
        if (Math.abs(parsed) < 0.05) return 'No material change';
        return (parsed > 0 ? '↑ +' : '↓ ') + parsed.toFixed(1) + ' pp';
    }

    function maxValue(rows) {
        var max = 100;
        rows.forEach(function (row) {
            ['current', 'compare'].forEach(function (key) {
                var value = number(row[key]);
                if (value !== null) max = Math.max(max, value);
            });
        });
        return Math.ceil(max / 10) * 10;
    }

    function renderFallback(target, config, rows) {
        target.innerHTML = '';
        target.classList.add('beds82-chart-fallback');

        rows.forEach(function (row) {
            var current = number(row.current);
            var compare = number(row.compare);
            var item = document.createElement('div');
            item.className = 'beds82-fallback-row';
            item.innerHTML =
                '<strong title="' + String(row.label || '').replace(/"/g, '&quot;') + '">' +
                    String(row.label || '') +
                '</strong>' +
                '<div class="beds82-fallback-series">' +
                    '<span>' + config.currentLabel + '</span>' +
                    '<i><b style="width:' + Math.max(0, Math.min(100, current || 0)) + '%"></b></i>' +
                    '<em>' + format(current) + '</em>' +
                '</div>' +
                '<div class="beds82-fallback-series is-compare">' +
                    '<span>' + config.compareLabel + '</span>' +
                    '<i><b style="width:' + Math.max(0, Math.min(100, compare || 0)) + '%"></b></i>' +
                    '<em>' + format(compare) + '</em>' +
                '</div>' +
                '<small>' + movement(row.movement) + '</small>';
            target.appendChild(item);
        });

        return rows.length > 0;
    }

    function renderChart(section, config) {
        var rows = Array.isArray(section.rows) ? section.rows : [];
        var target = document.getElementById(section.targetId);
        if (!target || !rows.length) {
            setState(section.shellKey, 'empty');
            return;
        }

        if (!window.echarts || typeof window.echarts.init !== 'function') {
            setState(section.shellKey, renderFallback(target, config, rows) ? 'rendered' : 'error');
            return;
        }

        try {
            var existing = window.echarts.getInstanceByDom(target);
            if (existing) existing.dispose();

            target.innerHTML = '';
            target.style.height = Math.max(320, rows.length * 58 + 95) + 'px';

            var chart = window.echarts.init(target);
            var labels = rows.map(function (row) { return String(row.label || ''); });
            var currentValues = rows.map(function (row) { return number(row.current); });
            var compareValues = rows.map(function (row) { return number(row.compare); });

            chart.setOption({
                animationDuration: 420,
                aria: { enabled: true },
                color: ['#5146e5', '#14a89a'],
                legend: {
                    top: 4,
                    left: 18,
                    itemWidth: 14,
                    itemHeight: 10,
                    textStyle: { color: '#334155', fontSize: 12, fontWeight: 700 },
                    data: [config.currentLabel, config.compareLabel]
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { type: 'shadow' },
                    confine: true,
                    backgroundColor: '#0f172a',
                    borderWidth: 0,
                    textStyle: { color: '#fff', fontSize: 12 },
                    formatter: function (params) {
                        var index = params && params.length ? params[0].dataIndex : 0;
                        var row = rows[index] || {};
                        return '<strong>' + String(row.label || '') + '</strong><br>' +
                            config.currentLabel + ': ' + format(row.current) + '<br>' +
                            config.compareLabel + ': ' + format(row.compare) + '<br>' +
                            'Movement: ' + movement(row.movement);
                    }
                },
                grid: {
                    left: 18,
                    right: 62,
                    top: 48,
                    bottom: 10,
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    min: 0,
                    max: maxValue(rows),
                    axisLine: { show: false },
                    axisTick: { show: false },
                    axisLabel: {
                        color: '#64748b',
                        fontSize: 11,
                        formatter: '{value}%'
                    },
                    splitLine: { lineStyle: { color: '#e8edf5' } }
                },
                yAxis: {
                    type: 'category',
                    inverse: true,
                    data: labels,
                    axisLine: { show: false },
                    axisTick: { show: false },
                    axisLabel: {
                        color: '#334155',
                        fontSize: 12,
                        fontWeight: 700,
                        width: 165,
                        overflow: 'truncate',
                        formatter: function (value) {
                            var text = String(value || '');
                            return text.length > 24 ? text.slice(0, 23) + '…' : text;
                        }
                    }
                },
                series: [
                    {
                        name: config.currentLabel,
                        type: 'bar',
                        data: currentValues,
                        barMaxWidth: 14,
                        barGap: '35%',
                        itemStyle: { borderRadius: [0, 8, 8, 0] },
                        label: {
                            show: true,
                            position: 'right',
                            color: '#312e81',
                            fontWeight: 800,
                            formatter: function (params) { return format(params.value); }
                        },
                        emphasis: { focus: 'series' }
                    },
                    {
                        name: config.compareLabel,
                        type: 'bar',
                        data: compareValues,
                        barMaxWidth: 14,
                        itemStyle: { borderRadius: [0, 8, 8, 0] },
                        label: {
                            show: true,
                            position: 'right',
                            color: '#0f766e',
                            fontWeight: 800,
                            formatter: function (params) { return format(params.value); }
                        },
                        emphasis: { focus: 'series' }
                    }
                ]
            }, true);

            var resize = function () {
                if (!chart.isDisposed()) chart.resize();
            };
            window.addEventListener('resize', resize, { passive: true });
            setState(section.shellKey, 'rendered');
        } catch (error) {
            setState(section.shellKey, renderFallback(target, config, rows) ? 'rendered' : 'error');
        }
    }

    window.addEventListener('DOMContentLoaded', function () {
        var config = parseConfig();
        if (!config) return;
        renderChart(config.unit || {}, config);
        renderChart(config.bed || {}, config);
    });
})();
