(function () {
    'use strict';

    var VERSION = 'H11.0-P11.1-R33';
    var ENGINE = 'Apache ECharts 6.1.0';
    var instances = [];
    var autoUpgradeStarted = false;
    var palette = ['#4f46e5', '#06b6d4', '#10b981', '#f59e0b', '#e11d48', '#8b5cf6', '#0f766e', '#f97316'];
    var gradientPalette = [
        ['#818cf8', '#4f46e5'],
        ['#67e8f9', '#06b6d4'],
        ['#6ee7b7', '#10b981'],
        ['#fcd34d', '#f59e0b'],
        ['#fb7185', '#e11d48'],
        ['#c4b5fd', '#8b5cf6'],
        ['#5eead4', '#0f766e'],
        ['#fdba74', '#f97316']
    ];

    function hasEngine() {
        return !!(window.echarts && typeof window.echarts.init === 'function');
    }

    function lang() {
        return document.documentElement.lang === 'ar' ? 'ar' : 'en';
    }

    function locale() {
        return lang() === 'ar' ? 'ar-SA' : 'en-US';
    }

    function rtl() {
        return document.documentElement.dir === 'rtl' || lang() === 'ar';
    }

    function all(selector, root) {
        return Array.prototype.slice.call((root || document).querySelectorAll(selector));
    }

    function num(value) {
        var n = Number(value == null ? 0 : value);
        return isFinite(n) ? n : 0;
    }

    function compact(value, loc, digits) {
        var n = num(value);
        var abs = Math.abs(n);
        var maxDigits = typeof digits === 'number' ? digits : 2;
        if (abs >= 1000000000) return formatNumber(n / 1000000000, loc, maxDigits) + 'B';
        if (abs >= 1000000) return formatNumber(n / 1000000, loc, maxDigits) + 'M';
        if (abs >= 1000) return formatNumber(n / 1000, loc, Math.min(1, maxDigits)) + 'K';
        return formatNumber(n, loc, maxDigits > 0 ? Math.min(1, maxDigits) : 0);
    }

    function formatNumber(value, loc, digits) {
        try {
            return new Intl.NumberFormat(loc || locale(), {
                minimumFractionDigits: 0,
                maximumFractionDigits: typeof digits === 'number' ? digits : 2
            }).format(num(value));
        } catch (error) {
            return String(Math.round(num(value) * 100) / 100);
        }
    }

    function formatExact(value, prefix, suffix, loc, digits) {
        return String(prefix || '') + formatNumber(value, loc || locale(), typeof digits === 'number' ? digits : 2) + String(suffix || '');
    }

    function escapeHtml(value) {
        return String(value == null ? '' : value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function ensureHost(target, className, preferredHeight) {
        if (!target) return null;
        if (target.classList && target.classList.contains('ddb-echart-host')) return target;
        var existing = target.__ddbEChartHost;
        if (existing && existing.parentNode) return existing;

        var host = document.createElement('div');
        host.className = 'ddb-echart-host ' + (className || '');
        host.setAttribute('data-ddb-echart-host', 'true');
        host.setAttribute('data-ddb-echart-source-id', target.id || 'anonymous');
        host.setAttribute('role', 'img');
        var aria = target.getAttribute ? (target.getAttribute('aria-label') || '') : '';
        if (aria) host.setAttribute('aria-label', aria);
        var h = Math.max(120, Number(preferredHeight || 0));
        if (h) host.style.minHeight = h + 'px';

        if (target.tagName === 'CANVAS') {
            target.parentNode.insertBefore(host, target.nextSibling);
        } else {
            target.appendChild(host);
        }
        target.__ddbEChartHost = host;
        return host;
    }

    function disposeHost(host) {
        if (!host || !hasEngine()) return;
        var instance = window.echarts.getInstanceByDom(host);
        if (instance) instance.dispose();
    }

    function initHost(host) {
        if (!hasEngine() || !host) return null;
        disposeHost(host);
        var chart = window.echarts.init(host, null, {
            renderer: 'canvas',
            devicePixelRatio: window.devicePixelRatio || 1,
            useDirtyRect: true
        });
        instances.push(chart);
        return chart;
    }

    function markSuccess(source, host, chart, type) {
        if (source) {
            source.setAttribute('data-ddb-echarts-rendered', 'true');
            source.setAttribute('data-chart-rendered', 'true');
            source.setAttribute('data-ddb-chart-engine', ENGINE);
            if (source.tagName === 'CANVAS') source.style.display = 'none';
        }
        if (host) {
            host.setAttribute('data-ddb-echarts-rendered', 'true');
            host.setAttribute('data-ddb-chart-type', type || 'chart');
            host.setAttribute('data-ddb-chart-engine', ENGINE);
        }
        if (chart && typeof chart.resize === 'function') {
            window.setTimeout(function () { try { chart.resize(); } catch (e) {} }, 0);
        }
    }

    function tooltipBox(title, subtitle, value, extra) {
        var html = '<div class="ddb-echarts-tooltip">';
        if (title) html += '<strong>' + escapeHtml(title) + '</strong>';
        if (subtitle) html += '<span>' + escapeHtml(subtitle) + '</span>';
        if (value) html += '<b>' + escapeHtml(value) + '</b>';
        if (extra) html += '<em>' + escapeHtml(extra) + '</em>';
        return html + '</div>';
    }

    function gradient(index, horizontal) {
        if (!hasEngine()) return palette[index % palette.length];
        var colors = gradientPalette[index % gradientPalette.length];
        return new window.echarts.graphic.LinearGradient(
            0,
            0,
            horizontal ? 1 : 0,
            horizontal ? 0 : 1,
            [
                { offset: 0, color: colors[0] },
                { offset: 1, color: colors[1] }
            ]
        );
    }

    function niceStep(value) {
        var n = Math.abs(num(value));
        if (!n) return 1;
        var exp = Math.pow(10, Math.floor(Math.log(n) / Math.LN10));
        var f = n / exp;
        var nice = f <= 1 ? 1 : (f <= 2 ? 2 : (f <= 2.5 ? 2.5 : (f <= 5 ? 5 : 10)));
        return nice * exp;
    }


function normalizeCategoryLabel(value, loc) {
    var text = String(value == null ? '' : value).trim();
    if (!text) return '';
    if ((loc || locale()).indexOf('ar') === 0) return text;
    var monthMap = {
        jan: 'JAN', january: 'JAN',
        feb: 'FEB', february: 'FEB',
        mar: 'MAR', march: 'MAR',
        apr: 'APR', april: 'APR',
        may: 'MAY',
        jun: 'JUN', june: 'JUN',
        jul: 'JUL', july: 'JUL',
        aug: 'AUG', august: 'AUG',
        sep: 'SEP', sept: 'SEP', september: 'SEP',
        oct: 'OCT', october: 'OCT',
        nov: 'NOV', november: 'NOV',
        dec: 'DEC', december: 'DEC'
    };
    var key = text.toLowerCase().replace(/\./g, '');
    return monthMap[key] || text;
}

function donutCenterParts(title, subtitle) {
    var main = String(title || '').trim();
    var sub = String(subtitle || '').trim();
    var match = main.match(/^([A-Z]{2,5})\s+(.+)$/i);
    if (match) {
        main = match[2];
        sub = match[1].toUpperCase();
    }
    return { main: main, sub: sub };
}

function compactTooltipCss() {
    return 'max-width:230px;border-radius:12px;box-shadow:0 12px 30px rgba(15,23,42,.22);';
}

function axisExtent(values) {
    var arr = (values || []).map(num);
    var max = Math.max.apply(null, arr.concat([0]));
    var min = Math.min.apply(null, arr.concat([0]));
    if (max === 0 && min === 0) {
        return { min: 0, max: 1, interval: 0.2 };
    }

    if (min >= 0) {
        var positiveTarget = Math.max(1, max * 1.09);
        var positiveStep = niceStep(positiveTarget / 7);
        return {
            min: 0,
            max: Math.max(positiveStep, Math.ceil(positiveTarget / positiveStep) * positiveStep),
            interval: positiveStep
        };
    }

    var paddedMax = max > 0 ? max * 1.12 : 0;
    var paddedMin = min < 0 ? min * 1.08 : 0;
    var span = Math.max(1, paddedMax - paddedMin);
    var mixedStep = niceStep(span / 6);
    return {
        min: Math.floor(paddedMin / mixedStep) * mixedStep,
        max: Math.ceil(paddedMax / mixedStep) * mixedStep,
        interval: mixedStep
    };
}

var smartMeasureCanvas = null;
var smartMeasureContext = null;

function smartMeasureText(text, font) {
    if (!smartMeasureCanvas) {
        smartMeasureCanvas = document.createElement('canvas');
        smartMeasureContext = smartMeasureCanvas.getContext('2d');
    }
    if (!smartMeasureContext) return Math.max(28, String(text || '').length * 7);
    smartMeasureContext.font = font || '900 12px Segoe UI, Tahoma, Arial';
    return Math.ceil(smartMeasureContext.measureText(String(text || '')).width);
}

function smartRect(cx, cy, width, height) {
    return {
        x: cx - width / 2,
        y: cy - height / 2,
        w: width,
        h: height,
        cx: cx,
        cy: cy
    };
}

function smartOverlap(a, b, padding) {
    var p = typeof padding === 'number' ? padding : 4;
    return !(
        a.x + a.w + p <= b.x ||
        b.x + b.w + p <= a.x ||
        a.y + a.h + p <= b.y ||
        b.y + b.h + p <= a.y
    );
}

function smartInside(rect, bounds, padding) {
    var p = typeof padding === 'number' ? padding : 2;
    return rect.x >= bounds.left + p &&
        rect.x + rect.w <= bounds.right - p &&
        rect.y >= bounds.top + p &&
        rect.y + rect.h <= bounds.bottom - p;
}

function smartCollides(rect, placed) {
    return placed.some(function (item) { return smartOverlap(rect, item.rect, 4); });
}

function smartSeriesColor(index) {
    return index === 0 ? '#3730a3' : (index === 1 ? '#0f5d7a' : palette[index % palette.length]);
}


function smartLabelTextGraphic(id, text, x, y, color, fontSize, backgroundMode) {
    var inside = backgroundMode === 'inside';
    var card = backgroundMode === true || backgroundMode === 'card';
    var fill = inside ? '#ffffff' : (color || '#172033');
    var backgroundColor = inside ? 'rgba(15, 23, 42, 0.84)' : (card ? 'rgba(255,255,255,.98)' : 'transparent');
    var borderColor = inside ? 'rgba(255,255,255,.32)' : (card ? 'rgba(148,163,184,.48)' : 'transparent');
    var stroke = inside ? 'rgba(15,23,42,.92)' : (card ? 'transparent' : 'rgba(255,255,255,.99)');
    var lineWidth = inside ? 2 : (card ? 0 : 4);

    return {
        id: id,
        type: 'text',
        silent: true,
        z: 120,
        x: x,
        y: y,
        style: {
            text: text,
            fill: fill,
            font: '900 ' + String(fontSize || 12) + 'px Segoe UI, Tahoma, Arial',
            align: 'center',
            verticalAlign: 'middle',
            stroke: stroke,
            lineWidth: lineWidth,
            paintOrder: 'stroke',
            backgroundColor: backgroundColor,
            borderColor: borderColor,
            borderWidth: inside || card ? 1 : 0,
            borderRadius: inside || card ? 6 : 0,
            padding: inside ? [3, 5] : (card ? [4, 6] : 0)
        }
    };
}

function smartBuildBarGeometry(chart, payload, extent) {
    var labels = Array.isArray(payload.labels) ? payload.labels : [];
    var rawSeries = Array.isArray(payload.series) ? payload.series : [];
    var centers = labels.map(function (_, idx) {
        return num(chart.convertToPixel({ xAxisIndex: 0 }, idx));
    });
    var categoryBand = centers.length > 1 ? Math.abs(centers[1] - centers[0]) : Math.max(70, chart.getWidth() - 80);
    var groupSpan = Math.min(categoryBand * 0.72, Math.max(38, categoryBand - 10));
    var seriesCount = Math.max(rawSeries.length, 1);
    var centerStep = seriesCount > 1 ? Math.min(40, groupSpan / seriesCount) : 0;
    var first = centers.length ? Math.min.apply(null, centers) : 40;
    var last = centers.length ? Math.max.apply(null, centers) : chart.getWidth() - 40;
    var top = num(chart.convertToPixel({ yAxisIndex: 0 }, extent.max));
    var bottom = num(chart.convertToPixel({ yAxisIndex: 0 }, extent.min));
    return {
        centers: centers,
        categoryBand: categoryBand,
        centerStep: centerStep,
        bounds: {
            left: Math.max(2, first - categoryBand / 2),
            right: Math.min(chart.getWidth() - 2, last + categoryBand / 2),
            top: Math.min(top, bottom),
            bottom: Math.max(top, bottom)
        },
        zeroY: num(chart.convertToPixel({ yAxisIndex: 0 }, 0))
    };
}

function smartBuildCandidates(item, group, geometry, fontSize, labelWidth, labelHeight) {
    var positive = item.value >= 0;
    var outward = item.seriesIndex % 2 === 0 ? -1 : 1;
    var xShift = Math.min(12, geometry.categoryBand * 0.08) * outward;
    var barHeight = Math.abs(geometry.zeroY - item.y);
    var sameSign = group.filter(function (other) {
        return other !== item && ((other.value >= 0) === positive) && other.value !== 0;
    });
    var close = sameSign.some(function (other) {
        var verticalClose = Math.abs(other.y - item.y) < labelHeight + 10;
        var horizontalDistance = Math.abs(other.x - item.x);
        return verticalClose && horizontalDistance < (labelWidth + other.labelWidth) / 2 + 10;
    });

    var positions = [];
    function add(cx, cy, inside, priority) {
        positions.push({ cx: cx, cy: cy, inside: !!inside, priority: priority || 0 });
    }

    if (positive) {
        if (close) {
            add(item.x + xShift, item.groupTop - 18 - item.seriesIndex * (labelHeight + 3), false, 100);
            add(item.x + xShift * 1.45, item.groupTop - 20 - (item.seriesIndex + 1) * (labelHeight + 4), false, 95);
        }
        add(item.x, item.y - 14, false, 90);
        add(item.x + xShift, item.y - 18, false, 85);
        add(item.x, item.y - labelHeight - 18, false, 80);
        if (barHeight >= labelHeight + 24) {
            add(item.x, item.y + labelHeight / 2 + 10, true, 70);
        }
        add(item.x + xShift, Math.max(geometry.bounds.top + labelHeight / 2 + 2, item.groupTop - 40), false, 60);
    } else {
        if (close) {
            add(item.x + xShift, item.groupBottom + 18 + item.seriesIndex * (labelHeight + 3), false, 100);
            add(item.x + xShift * 1.45, item.groupBottom + 20 + (item.seriesIndex + 1) * (labelHeight + 4), false, 95);
        }
        add(item.x, item.y + 14, false, 90);
        add(item.x + xShift, item.y + 18, false, 85);
        add(item.x, item.y + labelHeight + 18, false, 80);
        if (barHeight >= labelHeight + 24) {
            add(item.x, item.y - labelHeight / 2 - 10, true, 70);
        }
        add(item.x + xShift, Math.min(geometry.bounds.bottom - labelHeight / 2 - 2, item.groupBottom + 40), false, 60);
    }

    return positions.sort(function (a, b) { return b.priority - a.priority; });
}

function smartCombinedFallback(group, geometry, placed, graphics, payload, loc, fontSize) {
    var unplaced = group.filter(function (item) { return !item.placed && item.value !== 0; });
    if (!unplaced.length) return;

    var rawSeries = Array.isArray(payload.series) ? payload.series : [];
    var lines = unplaced.map(function (item) {
        var seriesName = String((rawSeries[item.seriesIndex] || {}).label || ('Series ' + (item.seriesIndex + 1)));
        return seriesName + '  ' + item.text;
    });
    var maxWidth = Math.max.apply(null, lines.map(function (line) {
        return smartMeasureText(line, '900 ' + fontSize + 'px Segoe UI, Tahoma, Arial');
    }).concat([40]));
    var width = maxWidth + 16;
    var height = lines.length * (fontSize + 7) + 10;
    var centerX = group[0].categoryX;
    var positiveItems = unplaced.filter(function (item) { return item.value >= 0; });
    var anchorY = positiveItems.length ? Math.min.apply(null, positiveItems.map(function (item) { return item.y; })) - height / 2 - 12 : geometry.zeroY - height / 2 - 12;
    var attempts = [0, -height - 6, height + 6, -2 * height - 12];
    var chosen = null;

    attempts.some(function (shift) {
        var cy = Math.max(geometry.bounds.top + height / 2 + 3, Math.min(geometry.bounds.bottom - height / 2 - 3, anchorY + shift));
        var rect = smartRect(centerX, cy, width, height);
        if (smartInside(rect, geometry.bounds, 2) && !smartCollides(rect, placed)) {
            chosen = { cx: centerX, cy: cy, rect: rect };
            return true;
        }
        return false;
    });

    if (!chosen) {
        chosen = {
            cx: centerX,
            cy: Math.max(geometry.bounds.top + height / 2 + 3, Math.min(geometry.bounds.bottom - height / 2 - 3, anchorY)),
            rect: smartRect(centerX, anchorY, width, height)
        };
    }

    graphics.push(smartLabelTextGraphic(
        'ddb-smart-combined-' + String(group[0].dataIndex),
        lines.join('\n'),
        chosen.cx,
        chosen.cy,
        '#172033',
        fontSize,
        true
    ));
    placed.push({ rect: chosen.rect, combined: true });
    unplaced.forEach(function (item) { item.placed = true; });
}

function applySmartBarLabels(chart, payload) {
    if (!chart || !payload || payload.showDataLabels === false) return { rendered: false, reason: 'disabled' };
    var labels = Array.isArray(payload.labels) ? payload.labels : [];
    var rawSeries = Array.isArray(payload.series) ? payload.series : [];
    if (!labels.length || !rawSeries.length) return { rendered: false, reason: 'empty' };

    var allValues = [];
    rawSeries.forEach(function (s) {
        (s.values || []).forEach(function (v) { allValues.push(num(v)); });
    });
    var extent = axisExtent(allValues);
    var geometry = smartBuildBarGeometry(chart, payload, extent);
    var width = chart.getWidth();
    var fontSize = width < 680 ? 10 : (width < 900 ? 11 : 12);
    var labelHeight = fontSize + 8;
    var loc = payload.locale || locale();
    var groups = [];

    labels.forEach(function (label, dataIndex) {
        var categoryX = geometry.centers[dataIndex];
        var group = [];
        rawSeries.forEach(function (series, seriesIndex) {
            var value = num((series.values || [])[dataIndex]);
            if (value === 0) return;
            var offset = (seriesIndex - (rawSeries.length - 1) / 2) * geometry.centerStep;
            var x = categoryX + offset;
            var y = num(chart.convertToPixel({ yAxisIndex: 0 }, value));
            var text = compact(value, loc, 2);
            var labelWidth = smartMeasureText(text, '900 ' + fontSize + 'px Segoe UI, Tahoma, Arial') + 8;
            group.push({
                dataIndex: dataIndex,
                seriesIndex: seriesIndex,
                value: value,
                x: x,
                y: y,
                text: text,
                labelWidth: labelWidth,
                labelHeight: labelHeight,
                categoryX: categoryX,
                categoryLabel: String(label || ''),
                placed: false
            });
        });
        if (group.length) {
            group.forEach(function (item) {
                item.groupTop = Math.min.apply(null, group.filter(function (g) { return g.value >= 0; }).map(function (g) { return g.y; }).concat([item.y]));
                item.groupBottom = Math.max.apply(null, group.filter(function (g) { return g.value < 0; }).map(function (g) { return g.y; }).concat([item.y]));
            });
            groups.push(group);
        }
    });

    var placed = [];
    var graphics = [];
    groups.forEach(function (group) {
        group.slice().sort(function (a, b) {
            return Math.abs(b.value) - Math.abs(a.value);
        }).forEach(function (item) {
            var candidates = smartBuildCandidates(item, group, geometry, fontSize, item.labelWidth, labelHeight);
            var chosen = null;
            candidates.some(function (candidate) {
                var rect = smartRect(candidate.cx, candidate.cy, item.labelWidth, labelHeight);
                if (!smartInside(rect, geometry.bounds, 2)) return false;
                if (smartCollides(rect, placed)) return false;
                chosen = { candidate: candidate, rect: rect };
                return true;
            });

            if (chosen) {
                graphics.push(smartLabelTextGraphic(
                    'ddb-smart-label-' + item.seriesIndex + '-' + item.dataIndex,
                    item.text,
                    chosen.candidate.cx,
                    chosen.candidate.cy,
                    chosen.candidate.inside ? '#ffffff' : smartSeriesColor(item.seriesIndex),
                    fontSize,
                    chosen.candidate.inside ? 'inside' : false
                ));
                placed.push({ rect: chosen.rect, seriesIndex: item.seriesIndex, dataIndex: item.dataIndex });
                item.placed = true;
            }
        });

        smartCombinedFallback(group, geometry, placed, graphics, payload, loc, fontSize);
    });

    try {
        chart.setOption({ graphic: graphics }, { replaceMerge: ['graphic'], lazyUpdate: false });
    } catch (error) {
        chart.setOption({ graphic: graphics }, false);
    }
    return {
        rendered: true,
        labels: graphics.length,
        values: allValues.filter(function (v) { return v !== 0; }).length,
        collisionsResolved: true
    };
}

function compareOption(payload) {
    var loc = payload.locale || locale();
    var isRtl = (payload.dir || '') === 'rtl' || rtl();
    var labels = Array.isArray(payload.labels) ? payload.labels.map(function (v) { return normalizeCategoryLabel(v, loc); }) : [];
    var rawSeries = Array.isArray(payload.series) ? payload.series : [];
    var allValues = [];
    rawSeries.forEach(function (s) {
        (s.values || []).forEach(function (v) { allValues.push(num(v)); });
    });
    var extent = axisExtent(allValues);
    var hostWidth = num(payload.__hostWidth || 0);
    var showValues = payload.showDataLabels !== false && labels.length <= 14 && (hostWidth === 0 || hostWidth >= 520);
    var prefix = payload.valuePrefix || '';
    var suffix = payload.valueSuffix || '';
    var decimals = typeof payload.valueDecimals === 'number' ? payload.valueDecimals : 2;
    var showInternalLegend = rawSeries.length > 1 && payload.showLegend !== false && payload.showHeader !== false;
    var stableHover = payload.stableHover === true;

    var series = rawSeries.map(function (s, sIdx) {
        var values = (s.values || []).map(num);
        return {
            name: String(s.label || ''),
            type: 'bar',
            data: values,
            barMaxWidth: labels.length <= 12 ? 46 : 32,
            barMinWidth: labels.length <= 12 ? 18 : 11,
            barGap: '16%',
            barCategoryGap: labels.length <= 12 ? '20%' : '30%',
            itemStyle: {
                color: gradient(sIdx, false),
                borderRadius: [9, 9, 2, 2],
                shadowColor: 'rgba(15,23,42,0.09)',
                shadowBlur: 8,
                shadowOffsetY: 3
            },
            emphasis: stableHover ? {
                disabled: true,
                focus: 'none',
                blurScope: 'none',
                itemStyle: { opacity: 1 }
            } : {
                focus: 'none',
                blurScope: 'none',
                itemStyle: {
                    opacity: 1,
                    shadowColor: 'rgba(79,70,229,0.22)',
                    shadowBlur: 14,
                    shadowOffsetY: 4
                }
            },
            blur: {
                itemStyle: { opacity: 1 }
            },
            select: {
                disabled: true,
                itemStyle: { opacity: 1 }
            },
            label: { show: false }
        };
    });

    return {
        animationDuration: 520,
        animationDurationUpdate: 0,
        animationEasing: 'cubicOut',
        hoverLayerThreshold: stableHover ? Infinity : 3000,
        stateAnimation: { duration: 0 },
        color: palette,
        aria: { enabled: true, label: { enabled: true } },
        tooltip: {
            trigger: 'item',
            confine: false,
            appendToBody: true,
            transitionDuration: stableHover ? 0 : 0.2,
            enterable: false,
            backgroundColor: '#0b1627',
            borderWidth: 0,
            padding: [9, 11],
            textStyle: { color: '#ffffff', fontSize: 12, fontWeight: 600 },
            extraCssText: compactTooltipCss(),
            formatter: function (params) {
                var title = labels[params.dataIndex] || params.name || '';
                var exact = formatExact(params.value, prefix, suffix, loc, decimals);
                return tooltipBox(title, params.seriesName || '', exact, '');
            }
        },
        legend: {
            show: showInternalLegend,
            top: 4,
            right: isRtl ? 'auto' : 10,
            left: isRtl ? 10 : 'auto',
            icon: 'roundRect',
            itemWidth: 12,
            itemHeight: 8,
            itemGap: 18,
            textStyle: { color: '#334155', fontSize: 12, fontWeight: 700 }
        },
        grid: {
            left: 16,
            right: 18,
            top: showInternalLegend ? 64 : (showValues ? 54 : 28),
            bottom: 12,
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: labels,
            axisLine: { lineStyle: { color: '#aebbd0' } },
            axisTick: { show: false },
            axisLabel: {
                color: '#334155',
                fontSize: 12,
                fontWeight: 850,
                interval: 0,
                hideOverlap: true,
                rotate: labels.length > 12 ? 28 : 0,
                margin: 12,
                formatter: function (value) {
                    var text = String(value == null ? '' : value);
                    return text.length > 14 ? text.slice(0, 13) + '…' : text;
                }
            }
        },
        yAxis: {
            type: 'value',
            min: extent.min,
            max: extent.max,
            interval: extent.interval,
            splitNumber: 6,
            axisLine: { show: false },
            axisTick: { show: false },
            axisLabel: {
                color: '#64748b',
                fontSize: 12,
                fontWeight: 700,
                margin: 12,
                formatter: function (value) { return compact(value, loc, 1); }
            },
            splitLine: { lineStyle: { color: '#e5ecf5', width: 1 } }
        },
        series: series
    };
}


function renderCompareBar(targetId, payload) {
        if (!hasEngine()) return { rendered: false, reason: 'echarts-unavailable' };
        var target = document.getElementById(targetId);
        if (!target) return { rendered: false, reason: 'target-missing' };
        var rect = target.parentElement ? target.parentElement.getBoundingClientRect() : target.getBoundingClientRect();
        var attrHeight = Number(target.getAttribute('height') || 0);
        var preferredHeight = Math.max(260, rect.height || 0, attrHeight ? attrHeight * 2.2 : 0);
        var host = ensureHost(target, 'ddb-echart-host--compare', preferredHeight);
        if (!host) return { rendered: false, reason: 'host-failed' };
        host.style.height = preferredHeight + 'px';
        var chart = initHost(host);
        if (!chart) return { rendered: false, reason: 'init-failed' };
        payload = payload || {};
        payload.__hostWidth = host.getBoundingClientRect().width || rect.width || 0;
        chart.setOption(compareOption(payload), true);
        chart.__ddbSmartLabelPayload = payload;
        var smartLabels = applySmartBarLabels(chart, payload);
        markSuccess(target, host, chart, 'bar-compare');
        host.setAttribute('data-ddb-smart-labels', smartLabels && smartLabels.rendered ? 'true' : 'false');
        host.setAttribute('data-ddb-smart-label-values', String(smartLabels && smartLabels.values ? smartLabels.values : 0));
        return {
            rendered: true,
            engine: ENGINE,
            labels: Array.isArray(payload.labels) ? payload.labels.length : 0,
            series: Array.isArray(payload.series) ? payload.series.length : 0,
            tooltip: true,
            smartLabels: smartLabels
        };
    }

    function horizontalOption(config, rows) {
        var loc = config.locale || locale();
        var isRtl = rtl();
        var seriesName = String(config.seriesLabel || config.title || '');
        var prefix = config.valuePrefix || '';
        var suffix = config.valueSuffix || '';
        var decimals = typeof config.valueDecimals === 'number' ? config.valueDecimals : 2;
        var stableHover = config.stableHover === true;
        var labels = rows.map(function (r) { return String(r.label || ''); });
        var values = rows.map(function (r) { return num(r.value); });
        return {
            animationDuration: 450,
            animationDurationUpdate: stableHover ? 0 : 300,
            stateAnimation: { duration: 0 },
            aria: { enabled: true, label: { enabled: true } },
            tooltip: {
                trigger: 'item',
                confine: false,
                appendToBody: true,
                backgroundColor: '#0b1627',
                borderWidth: 0,
                padding: [9, 11],
                textStyle: { color: '#fff', fontSize: 12 },
                extraCssText: compactTooltipCss(),
                formatter: function (params) {
                    return tooltipBox(params.name || '', seriesName, formatExact(params.value, prefix, suffix, loc, decimals), '');
                }
            },
            grid: { left: 14, right: 18, top: 8, bottom: 8, containLabel: true },
            xAxis: {
                type: 'value',
                axisLine: { show: false },
                axisTick: { show: false },
                axisLabel: { color: '#64748b', fontSize: 11, formatter: function (v) { return compact(v, loc, 1); } },
                splitLine: { lineStyle: { color: '#eef2f7' } }
            },
            yAxis: {
                type: 'category',
                data: labels,
                inverse: true,
                axisLine: { show: false },
                axisTick: { show: false },
                axisLabel: {
                    color: '#334155',
                    fontWeight: 700,
                    fontSize: 12,
                    width: 160,
                    overflow: 'truncate',
                    align: isRtl ? 'left' : 'right'
                }
            },
            series: [{
                name: seriesName,
                type: 'bar',
                data: values,
                barMaxWidth: 20,
                itemStyle: {
                    color: gradient(Number(config.colorIndex || 0), true),
                    borderRadius: [0, 10, 10, 0]
                },
                emphasis: stableHover ? {
                    disabled: true,
                    focus: 'none',
                    blurScope: 'none',
                    itemStyle: { opacity: 1 }
                } : {
                    focus: 'none',
                    blurScope: 'none',
                    itemStyle: { opacity: 1 }
                },
                blur: { itemStyle: { opacity: 1 } },
                select: { disabled: true, itemStyle: { opacity: 1 } },
                label: {
                    show: true,
                    position: 'right',
                    color: '#172033',
                    fontWeight: 800,
                    formatter: function (p) { return compact(p.value, loc, 2); }
                },
                labelLayout: { hideOverlap: true }
            }]
        };
    }

    function renderHorizontalBar(targetId, config) {
        if (!hasEngine()) return { rendered: false, reason: 'echarts-unavailable' };
        var target = document.getElementById(targetId);
        if (!target) return { rendered: false, reason: 'target-missing' };
        config = config || {};
        var rows = (config.rows || []).slice().filter(function (r) { return num(r.value) !== 0; })
            .sort(function (a, b) { return num(b.value) - num(a.value); })
            .slice(0, Number(config.limit || 10));
        if (!rows.length) return { rendered: false, empty: true };
        var requestedHeight = Number(config.preferredHeight || config.height || 0);
        var parentHeight = 0;
        if (config.fitParent && target.parentElement && typeof target.parentElement.getBoundingClientRect === 'function') {
            parentHeight = Math.round(target.parentElement.getBoundingClientRect().height || 0);
        }
        var preferredHeight = parentHeight >= 220
            ? parentHeight
            : (requestedHeight > 0
                ? Math.max(220, Math.min(560, requestedHeight))
                : Math.max(320, Math.min(560, rows.length * 46 + 48)));
        var host = ensureHost(target, 'ddb-echart-host--horizontal', preferredHeight);
        host.style.height = preferredHeight + 'px';
        if (config.fitParent) {
            host.style.minHeight = '0';
            host.style.maxHeight = preferredHeight + 'px';
        }
        var chart = initHost(host);
        if (!chart) return { rendered: false, reason: 'init-failed' };
        chart.setOption(horizontalOption(config, rows), true);
        markSuccess(target, host, chart, 'bar-horizontal');
        return { rendered: true, rows: rows.length, tooltip: true, engine: ENGINE };
    }

    function segmentData(element) {
        var raw = element.getAttribute('data-ddb-chart-segments') || '[]';
        try {
            var segments = JSON.parse(raw);
            return Array.isArray(segments) ? segments : [];
        } catch (error) {
            return [];
        }
    }


function renderDonutElement(element) {
    if (!hasEngine() || !element) return { rendered: false, reason: 'invalid' };
    if (element.getAttribute('data-ddb-echarts-rendered') === 'true' && element.__ddbEChartHost) {
        return { rendered: true, reused: true, engine: ENGINE };
    }
    var segments = segmentData(element);
    if (!segments.length) return { rendered: false, empty: true };

    var loc = element.getAttribute('data-ddb-chart-locale') || locale();
    var isDailyRevenue = element.classList && element.classList.contains('idr-v11-donut');
    var ratio = Math.max(0.2, Math.min(0.8, num(element.getAttribute('data-ddb-chart-inner-ratio') || (isDailyRevenue ? 0.64 : 0.54))));
    var elementHeight = Math.max(isDailyRevenue ? 196 : 150, element.getBoundingClientRect().height || 0);
    var host = ensureHost(element, 'ddb-echart-host--donut' + (isDailyRevenue ? ' ddb-echart-host--daily-revenue-donut' : ''), elementHeight);
    host.classList.add('ddb-echart-overlay');
    host.style.position = 'absolute';
    host.style.inset = '0';
    host.style.width = '100%';
    host.style.height = '100%';
    host.style.minHeight = '0';

    var center = element.firstElementChild;
    var centerTitle = String(element.getAttribute('data-ddb-center-value') || '').trim();
    var centerSubtitle = String(element.getAttribute('data-ddb-center-currency') || '').trim();
    if (!centerTitle && center) {
        var strongNode = center.querySelector('strong');
        var subNode = center.querySelector('span');
        centerTitle = strongNode ? String(strongNode.textContent || '').trim() : '';
        centerSubtitle = subNode ? String(subNode.textContent || '').trim() : '';
        var centerParts = donutCenterParts(centerTitle, centerSubtitle);
        centerTitle = centerParts.main;
        centerSubtitle = centerParts.sub;
    }
    if (center) {
        center.style.display = 'none';
        center.setAttribute('aria-hidden', 'true');
    }

    var chart = initHost(host);
    if (!chart) return { rendered: false, reason: 'init-failed' };
    var data = segments.map(function (s, idx) {
        return {
            name: String(s.label || ''),
            value: num(s.value),
            itemStyle: { color: s.color || palette[idx % palette.length] },
            __ddbPrefix: s.prefix || '',
            __ddbSuffix: s.suffix || '',
            __ddbPercentage: typeof s.percentage === 'number' ? s.percentage : null,
            __ddbDecimals: typeof s.decimals === 'number' ? s.decimals : 2
        };
    });

    var centerMainSize = isDailyRevenue ? 22 : 19;
    var centerSubSize = isDailyRevenue ? 12 : 11;
    var centerWidth = isDailyRevenue ? 118 : 108;
    var innerPct = Math.max(Math.round(ratio * 100), isDailyRevenue ? 64 : 60);
    var outerPct = isDailyRevenue ? 90 : 95;

    chart.setOption({
        animationDuration: 520,
        aria: { enabled: true, label: { enabled: true } },
        tooltip: {
            trigger: 'item',
            confine: false,
            appendToBody: true,
            backgroundColor: '#0b1627',
            borderWidth: 0,
            padding: [9, 11],
            textStyle: { color: '#fff', fontSize: 12 },
            extraCssText: compactTooltipCss(),
            formatter: function (params) {
                var d = params.data || {};
                var exact = formatExact(d.value, d.__ddbPrefix, d.__ddbSuffix, loc, d.__ddbDecimals);
                var pct = d.__ddbPercentage !== null ? formatNumber(d.__ddbPercentage, loc, 1) + '%' : formatNumber(params.percent, loc, 1) + '%';
                return tooltipBox(d.name || '', '', exact, pct);
            }
        },
        graphic: centerTitle ? [{
            type: 'group',
            left: 'center',
            top: 'center',
            bounding: 'raw',
            silent: true,
            children: [
                {
                    type: 'text',
                    style: {
                        text: centerTitle,
                        fill: '#0f2747',
                        font: '900 ' + centerMainSize + 'px Segoe UI, Tahoma, Arial',
                        textAlign: 'center',
                        textVerticalAlign: 'middle',
                        width: centerWidth,
                        overflow: 'break',
                        lineHeight: centerMainSize + 3
                    },
                    x: 0,
                    y: centerSubtitle ? -8 : 0
                },
                {
                    type: 'text',
                    invisible: !centerSubtitle,
                    style: {
                        text: centerSubtitle,
                        fill: '#64748b',
                        font: '800 ' + centerSubSize + 'px Segoe UI, Tahoma, Arial',
                        textAlign: 'center',
                        textVerticalAlign: 'middle',
                        width: centerWidth,
                        overflow: 'break'
                    },
                    x: 0,
                    y: 20
                }
            ]
        }] : [],
        series: [{
            type: 'pie',
            radius: [innerPct + '%', outerPct + '%'],
            center: ['50%', '50%'],
            clockwise: true,
            avoidLabelOverlap: true,
            label: { show: false },
            labelLine: { show: false },
            itemStyle: { borderColor: '#ffffff', borderWidth: 2 },
            emphasis: {
                focus: 'none',
                blurScope: 'none',
                scale: true,
                scaleSize: isDailyRevenue ? 5 : 7,
                itemStyle: { opacity: 1 }
            },
            blur: { itemStyle: { opacity: 1 } },
            select: { disabled: true, itemStyle: { opacity: 1 } },
            data: data
        }]
    }, true);

    element.style.background = 'transparent';
    element.style.position = element.style.position || 'relative';
    markSuccess(element, host, chart, 'donut');
    return { rendered: true, segments: data.length, tooltip: true, engine: ENGINE, dailyRevenueOptimized: isDailyRevenue };
}

    function renderSimpleDonut(element, segments, centerText, centerSubtext, options) {
        if (!hasEngine() || !element || !segments || !segments.length) return { rendered: false, reason: 'invalid' };
        options = options || {};
        var host = ensureHost(element, 'ddb-echart-host--donut', options.height || Math.max(140, element.getBoundingClientRect().height || 0));
        host.classList.add('ddb-echart-overlay');
        host.style.position = 'absolute';
        host.style.inset = '0';
        host.style.minHeight = '0';
        all(':scope > *:not(.ddb-echart-host)', element).forEach(function (node) {
            node.style.position = 'relative';
            node.style.zIndex = '2';
            node.style.pointerEvents = 'none';
        });
        var chart = initHost(host);
        var loc = options.locale || locale();
        chart.setOption({
            animationDuration: 480,
            aria: { enabled: true, label: { enabled: true } },
            tooltip: {
                trigger: 'item',
                confine: true,
                backgroundColor: '#0b1627',
                borderWidth: 0,
                padding: [12, 14],
                textStyle: { color: '#fff', fontSize: 13 },
                formatter: function (params) {
                    var d = params.data || {};
                    var exact = d.displayValue || formatNumber(d.value, loc, 1);
                    return tooltipBox(d.name || '', '', exact, typeof params.percent === 'number' ? formatNumber(params.percent, loc, 1) + '%' : '');
                }
            },
            series: [{
                type: 'pie',
                radius: [options.inner || '68%', options.outer || '94%'],
                center: ['50%', '50%'],
                label: { show: false },
                labelLine: { show: false },
                itemStyle: { borderColor: '#fff', borderWidth: 2 },
                emphasis: { scale: true, scaleSize: 6 },
                data: segments
            }]
        }, true);
        element.style.background = 'transparent';
        element.style.position = element.style.position || 'relative';
        markSuccess(element, host, chart, 'donut');
        return { rendered: true };
    }

    function renderDomHorizontalBars(container, rows, options) {
        if (!hasEngine() || !container || !rows || !rows.length) return { rendered: false, empty: true };
        options = options || {};
        var host = document.createElement('div');
        host.className = 'ddb-echart-host ddb-echart-dom-upgrade ' + (options.className || '');
        host.setAttribute('data-ddb-echart-host', 'true');
        var height = Math.max(options.minHeight || 150, Math.min(options.maxHeight || 520, rows.length * (options.rowHeight || 44) + 36));
        host.style.height = height + 'px';
        container.parentNode.insertBefore(host, container);
        var chart = initHost(host);
        if (!chart) {
            host.remove();
            return { rendered: false, reason: 'init-failed' };
        }
        var labels = rows.map(function (r) { return String(r.label || ''); });
        var values = rows.map(function (r) { return num(r.value); });
        var display = rows.map(function (r) { return String(r.displayValue == null ? '' : r.displayValue); });
        var chartDisplay = rows.map(function (r) { return String(r.chartDisplayValue == null ? '' : r.chartDisplayValue); });
        var loc = options.locale || locale();
        chart.setOption({
            animationDuration: 420,
            aria: { enabled: true, label: { enabled: true } },
            tooltip: {
                trigger: 'item',
                confine: true,
                backgroundColor: '#0b1627',
                borderWidth: 0,
                padding: [12, 14],
                textStyle: { color: '#fff', fontSize: 13 },
                formatter: function (params) {
                    return tooltipBox(params.name || '', options.seriesName || '', display[params.dataIndex] || formatNumber(params.value, loc, 2), rows[params.dataIndex] && rows[params.dataIndex].extra ? rows[params.dataIndex].extra : '');
                }
            },
            grid: { left: 14, right: 24, top: 8, bottom: 8, containLabel: true },
            xAxis: {
                type: 'value',
                max: options.max || null,
                axisLine: { show: false },
                axisTick: { show: false },
                axisLabel: { show: options.showAxis !== false, color: '#64748b', formatter: function (v) { return options.axisFormatter ? options.axisFormatter(v) : compact(v, loc, 1); } },
                splitLine: { show: options.showGrid !== false, lineStyle: { color: '#eef2f7' } }
            },
            yAxis: {
                type: 'category',
                inverse: true,
                data: labels,
                axisLine: { show: false },
                axisTick: { show: false },
                axisLabel: {
                    color: '#334155',
                    fontSize: 12,
                    fontWeight: 700,
                    width: options.labelWidth || 150,
                    overflow: 'truncate'
                }
            },
            series: [{
                name: options.seriesName || '',
                type: 'bar',
                data: values,
                barMaxWidth: options.barMaxWidth || 18,
                itemStyle: { color: gradient(options.colorIndex || 0, true), borderRadius: [0, 9, 9, 0] },
                label: {
                    show: options.showLabels !== false,
                    position: 'right',
                    color: '#172033',
                    fontSize: 11,
                    fontWeight: 800,
                    formatter: function (p) { return chartDisplay[p.dataIndex] || display[p.dataIndex] || compact(p.value, loc, 1); }
                },
                labelLayout: { hideOverlap: true }
            }]
        }, true);
        container.setAttribute('data-ddb-original-chart-hidden', 'true');
        container.style.display = 'none';
        markSuccess(container, host, chart, options.type || 'bar-horizontal');
        return { rendered: true, rows: rows.length };
    }

    function renderDomVerticalBars(container, rows, options) {
        if (!hasEngine() || !container || !rows || !rows.length) return { rendered: false, empty: true };
        options = options || {};
        var host = document.createElement('div');
        host.className = 'ddb-echart-host ddb-echart-dom-upgrade ' + (options.className || '');
        host.setAttribute('data-ddb-echart-host', 'true');
        host.style.height = Math.max(options.height || 260, 220) + 'px';
        container.parentNode.insertBefore(host, container);
        var chart = initHost(host);
        if (!chart) { host.remove(); return { rendered: false, reason: 'init-failed' }; }
        var labels = rows.map(function (r) { return String(r.label || ''); });
        var values = rows.map(function (r) { return num(r.value); });
        var display = rows.map(function (r) { return String(r.displayValue == null ? '' : r.displayValue); });
        var loc = options.locale || locale();
        chart.setOption({
            animationDuration: 420,
            aria: { enabled: true, label: { enabled: true } },
            tooltip: {
                trigger: 'item',
                confine: true,
                backgroundColor: '#0b1627',
                borderWidth: 0,
                padding: [12, 14],
                textStyle: { color: '#fff', fontSize: 13 },
                formatter: function (params) {
                    return tooltipBox(params.name || '', options.seriesName || '', display[params.dataIndex] || formatNumber(params.value, loc, 2), rows[params.dataIndex] && rows[params.dataIndex].extra ? rows[params.dataIndex].extra : '');
                }
            },
            grid: { left: 14, right: 12, top: 18, bottom: 12, containLabel: true },
            xAxis: {
                type: 'category',
                data: labels,
                axisLine: { lineStyle: { color: '#b7c4d6' } },
                axisTick: { show: false },
                axisLabel: { color: '#475569', fontSize: 11, fontWeight: 700, interval: 0, hideOverlap: true }
            },
            yAxis: {
                type: 'value',
                axisLine: { show: false },
                axisTick: { show: false },
                axisLabel: { color: '#64748b', formatter: function (v) { return compact(v, loc, 1); } },
                splitLine: { lineStyle: { color: '#eef2f7' } }
            },
            series: [{
                name: options.seriesName || '',
                type: 'bar',
                data: values,
                barMaxWidth: options.barMaxWidth || 34,
                itemStyle: { color: gradient(options.colorIndex || 0, false), borderRadius: [8, 8, 2, 2] },
                label: {
                    show: options.showLabels !== false,
                    position: 'top',
                    color: '#172033',
                    fontSize: 11,
                    fontWeight: 800,
                    formatter: function (p) { return display[p.dataIndex] || compact(p.value, loc, 1); }
                },
                labelLayout: { hideOverlap: true }
            }]
        }, true);
        container.setAttribute('data-ddb-original-chart-hidden', 'true');
        container.style.display = 'none';
        markSuccess(container, host, chart, options.type || 'bar-vertical');
        return { rendered: true, rows: rows.length };
    }

    function parsePercentText(text) {
        var m = String(text || '').replace(',', '.').match(/(-?\d+(?:\.\d+)?)\s*%/);
        return m ? num(m[1]) : 0;
    }

    function parseFlexibleNumber(text) {
        var source = String(text || '').replace(/,/g, '').trim();
        var m = source.match(/(-?\d+(?:\.\d+)?)\s*([KMB])?/i);
        if (!m) return 0;
        var value = num(m[1]);
        var unit = String(m[2] || '').toUpperCase();
        if (unit === 'K') value *= 1000;
        if (unit === 'M') value *= 1000000;
        if (unit === 'B') value *= 1000000000;
        return value;
    }

    function upgradeDashboard(root) {
        var count = 0;
        all('.exec-leadership-donut', root).forEach(function (element) {
            if (element.getAttribute('data-ddb-echarts-rendered') === 'true') return;
            var pct = parsePercentText((element.querySelector('strong') || {}).textContent || '');
            var segments = [
                { name: lang() === 'ar' ? 'الإشغال' : 'Occupied', value: pct, displayValue: formatNumber(pct, locale(), 1) + '%', itemStyle: { color: '#6d28d9' } },
                { name: lang() === 'ar' ? 'المتاح' : 'Available', value: Math.max(0, 100 - pct), displayValue: formatNumber(Math.max(0, 100 - pct), locale(), 1) + '%', itemStyle: { color: '#e5edf6' } }
            ];
            if (renderSimpleDonut(element, segments, '', '', { inner: '70%', outer: '96%' }).rendered) count++;
        });

        all('.exec-leadership-units', root).forEach(function (container) {
            if (container.getAttribute('data-ddb-original-chart-hidden') === 'true') return;
            var rows = all('.exec-leadership-unit-row', container).map(function (row) {
                var label = (row.querySelector('span') || {}).textContent || '';
                var display = (row.querySelector('em') || {}).textContent || '';
                return { label: label.trim(), value: parsePercentText(display), displayValue: display.trim() };
            }).filter(function (r) { return r.label; });
            if (rows.length && renderDomHorizontalBars(container, rows, { max: 100, showAxis: false, showGrid: false, seriesName: lang() === 'ar' ? 'الإشغال' : 'Occupancy', type: 'dashboard-occupancy-bars', minHeight: 140, rowHeight: 42, labelWidth: 120, colorIndex: 0 }).rendered) count++;
        });

        all('.exec-leadership-ranking', root).forEach(function (container) {
            if (container.getAttribute('data-ddb-original-chart-hidden') === 'true') return;
            var rows = all('li:not(.is-empty)', container).map(function (row) {
                var label = (row.querySelector('b') || {}).textContent || '';
                var display = (row.querySelector('em') || {}).textContent || '';
                return { label: label.trim(), value: parseFlexibleNumber(display), displayValue: display.trim() };
            }).filter(function (r) { return r.label; });
            if (rows.length && renderDomHorizontalBars(container, rows, { showAxis: false, showGrid: false, seriesName: lang() === 'ar' ? 'الإيراد' : 'Revenue', type: 'dashboard-specialty-ranking', minHeight: 150, rowHeight: 46, labelWidth: 130, colorIndex: 1 }).rendered) count++;
        });
        return count;
    }

    function upgradeDailyInpatient(root) {
        var count = 0;
        all('.idr-v11-care-list', root).forEach(function (container) {
            if (container.getAttribute('data-ddb-original-chart-hidden') === 'true') return;
            var rows = all('.idr-v11-care-row', container).map(function (row) {
                var label = ((row.querySelector('div > strong') || {}).textContent || '').trim();
                var valueNode = row.querySelector('.idr-r15-care-value > strong');
                var display = String(row.getAttribute('data-ddb-chart-exact-value') || (valueNode ? valueNode.textContent.trim() : '')).trim();
                var chartDisplay = String(row.getAttribute('data-ddb-chart-display-value') || '').trim();
                var extraNode = row.querySelector('.idr-r15-care-value > small');
                return { label: label, value: parseFlexibleNumber(display), displayValue: display, chartDisplayValue: chartDisplay, extra: extraNode ? extraNode.textContent.trim() : '' };
            }).filter(function (r) { return r.label; });
            if (rows.length && renderDomHorizontalBars(container, rows, { showAxis: true, seriesName: lang() === 'ar' ? 'الإيراد اليومي' : 'Daily revenue', type: 'inpatient-care-area-revenue', minHeight: 260, rowHeight: 52, labelWidth: 170, colorIndex: 1 }).rendered) count++;
        });
        return count;
    }

    function upgradeActionCenter(root) {
        var count = 0;
        all('.review-trend-chart', root).forEach(function (container) {
            if (container.getAttribute('data-ddb-original-chart-hidden') === 'true') return;
            var rows = all('.review-trend-day', container).map(function (row) {
                var label = (row.querySelector('small') || {}).textContent || '';
                var valueText = (row.querySelector('.review-trend-count') || {}).textContent || '0';
                return { label: label.trim(), value: parseFlexibleNumber(valueText), displayValue: valueText.trim() };
            }).filter(function (r) { return r.label; });
            if (rows.length && renderDomVerticalBars(container, rows, { seriesName: lang() === 'ar' ? 'نشاط المراجعة' : 'Review activity', type: 'action-center-trend', height: 270, colorIndex: 0 }).rendered) count++;
        });

        all('.review-status-donut', root).forEach(function (element) {
            if (element.getAttribute('data-ddb-echarts-rendered') === 'true') return;
            var wrap = element.closest('.review-status-donut-wrap');
            var segments = [];
            if (wrap) {
                all('.review-status-breakdown > span', wrap).forEach(function (item, idx) {
                    var labelNodes = Array.prototype.slice.call(item.childNodes).filter(function (n) { return n.nodeType === 3 && String(n.textContent || '').trim(); });
                    var label = labelNodes.length ? String(labelNodes[labelNodes.length - 1].textContent || '').trim() : item.className;
                    var value = parseFlexibleNumber((item.querySelector('b') || {}).textContent || '0');
                    segments.push({ name: label, value: value, displayValue: formatNumber(value, locale(), 0), itemStyle: { color: palette[idx % palette.length] } });
                });
            }
            if (segments.length && renderSimpleDonut(element, segments, '', '', { inner: '62%', outer: '95%' }).rendered) count++;
        });

        all('.review-ranking-list', root).forEach(function (container) {
            if (container.getAttribute('data-ddb-original-chart-hidden') === 'true') return;
            var rows = all('.review-ranking-row', container).map(function (row) {
                var label = (row.querySelector('.review-rank-main strong') || {}).textContent || '';
                var small = (row.querySelector('.review-rank-main small') || {}).textContent || '';
                return { label: label.trim(), value: parseFlexibleNumber(small), displayValue: small.trim() };
            }).filter(function (r) { return r.label; });
            if (rows.length && renderDomHorizontalBars(container, rows, { showAxis: false, showGrid: false, showLabels: false, seriesName: lang() === 'ar' ? 'نشاط التدقيق' : 'Audit activity', type: 'action-center-ranking', minHeight: 180, rowHeight: 48, labelWidth: 180, colorIndex: 4 }).rendered) count++;
        });
        return count;
    }

    function upgradeCommonDomCharts(root) {
        var count = 0;
        all('.daily-bars', root).forEach(function (container) {
            if (container.getAttribute('data-ddb-original-chart-hidden') === 'true') return;
            var rows = all(':scope > div', container).map(function (row) {
                var label = (row.querySelector('small') || {}).textContent || '';
                var display = (row.querySelector('b') || {}).textContent || '';
                return { label: label.trim(), value: parseFlexibleNumber(display), displayValue: display.trim() };
            }).filter(function (r) { return r.label; });
            if (rows.length && renderDomVerticalBars(container, rows, { seriesName: lang() === 'ar' ? 'النشاط اليومي' : 'Daily activity', type: 'daily-bars', height: 260, colorIndex: 1 }).rendered) count++;
        });

        all('.rank-list', root).forEach(function (container) {
            if (container.getAttribute('data-ddb-original-chart-hidden') === 'true') return;
            if (container.closest('.exec-leadership-ranking') || container.closest('.review-ranking-list')) return;
            var rows = all('.rank-row', container).map(function (row) {
                var label = (row.querySelector('strong') || {}).textContent || '';
                var display = (row.querySelector(':scope > b') || {}).textContent || '';
                return { label: label.trim(), value: parseFlexibleNumber(display), displayValue: display.trim() };
            }).filter(function (r) { return r.label; });
            if (rows.length >= 2 && rows.length <= 15 && renderDomHorizontalBars(container, rows, { showAxis: false, showGrid: false, seriesName: lang() === 'ar' ? 'القيمة' : 'Value', type: 'rank-list', minHeight: 150, rowHeight: 44, labelWidth: 170, colorIndex: 2 }).rendered) count++;
        });
        return count;
    }

    function bindMicroIndicatorTooltips(root) {
        var count = 0;
        var selectors = [
            '.mix-meter',
            '.beds1014-capacity-bar',
            '.doctors1013-mix-list i',
            '[data-outpatient-payer-mix] .rank-row span',
            '[data-admission-category-mix] .rank-row span'
        ];
        selectors.forEach(function (selector) {
            all(selector, root).forEach(function (element) {
                if (element.getAttribute('data-ddb-micro-tooltip-bound') === 'true') return;
                element.setAttribute('data-ddb-micro-tooltip-bound', 'true');
                element.addEventListener('pointermove', function (event) {
                    var owner = element.closest('.rank-row, .mix-meter, .beds1014-capacity, .doctors1013-mix-list') || element.parentElement;
                    var text = owner ? String(owner.textContent || '').replace(/\s+/g, ' ').trim() : '';
                    if (window.DDBChartTooltip && typeof window.DDBChartTooltip.showCustom === 'function') {
                        window.DDBChartTooltip.showCustom(event.clientX, event.clientY, tooltipBox('', '', text, ''));
                    }
                }, { passive: true });
                element.addEventListener('pointerleave', function () {
                    if (window.DDBChartTooltip && typeof window.DDBChartTooltip.hide === 'function') window.DDBChartTooltip.hide();
                }, { passive: true });
                count++;
            });
        });
        return count;
    }

    function safeUpgrade(label, fn) {
        try {
            return Number(fn() || 0);
        } catch (error) {
            if (window.console && typeof window.console.error === 'function') {
                window.console.error('Professional chart auto-upgrade failed for ' + label + '; original fallback remains available.', error);
            }
            return 0;
        }
    }

    function upgradePageCharts(root) {
        root = root || document;
        var summary = {
            engine: ENGINE,
            segmentDonuts: 0,
            dashboard: 0,
            inpatient: 0,
            actionCenter: 0,
            domCharts: 0,
            microIndicators: 0
        };
        summary.segmentDonuts = safeUpgrade('segment-donuts', function () {
            var count = 0;
            all('[data-ddb-chart-segments]', root).forEach(function (element) {
                if (element.getAttribute('data-ddb-echarts-rendered') === 'true') return;
                var result = renderDonutElement(element);
                if (result && result.rendered) count++;
            });
            return count;
        });
        summary.dashboard = safeUpgrade('dashboard', function () { return upgradeDashboard(root); });
        summary.inpatient = safeUpgrade('daily-inpatient-revenue', function () { return upgradeDailyInpatient(root); });
        summary.actionCenter = safeUpgrade('action-center', function () { return upgradeActionCenter(root); });
        summary.domCharts = safeUpgrade('common-dom-charts', function () { return upgradeCommonDomCharts(root); });
        summary.microIndicators = safeUpgrade('micro-indicators', function () { return bindMicroIndicatorTooltips(root); });
        var cumulative = window.__DDB_ECHARTS_AUTO_UPGRADE_TOTAL__ || {
            engine: ENGINE,
            segmentDonuts: 0,
            dashboard: 0,
            inpatient: 0,
            actionCenter: 0,
            domCharts: 0,
            microIndicators: 0
        };
        ['segmentDonuts', 'dashboard', 'inpatient', 'actionCenter', 'domCharts', 'microIndicators'].forEach(function (key) {
            cumulative[key] += Number(summary[key] || 0);
        });
        window.__DDB_ECHARTS_AUTO_UPGRADE__ = summary;
        window.__DDB_ECHARTS_AUTO_UPGRADE_TOTAL__ = cumulative;
        document.documentElement.setAttribute('data-ddb-chart-engine', ENGINE);
        document.documentElement.setAttribute('data-ddb-echarts-auto-upgrade', 'PASS');
        return summary;
    }

    function resizeAll() {
        instances = instances.filter(function (chart) {
            try {
                if (chart && !chart.isDisposed()) {
                    chart.resize();
                    if (chart.__ddbSmartLabelPayload) {
                        applySmartBarLabels(chart, chart.__ddbSmartLabelPayload);
                    }
                    return true;
                }
            } catch (error) {}
            return false;
        });
    }

    function debounce(fn, wait) {
        var timer = null;
        return function () {
            clearTimeout(timer);
            timer = setTimeout(fn, wait);
        };
    }

    function startAutoUpgrade() {
        if (autoUpgradeStarted) return;
        autoUpgradeStarted = true;
        if (!hasEngine()) {
            document.documentElement.setAttribute('data-ddb-echarts-auto-upgrade', 'ENGINE_MISSING');
            return;
        }
        upgradePageCharts(document);
        window.setTimeout(function () { upgradePageCharts(document); resizeAll(); }, 80);
        window.setTimeout(function () { upgradePageCharts(document); resizeAll(); }, 350);
    }


function chartInteractionStabilityContract() {
    return {
        phase: 'H11.0-P11.1-R27',
        hoverFocus: 'none',
        blurOpacity: 1,
        selectionDisabled: true,
        smartLabelInsideContrast: 'white-on-dark-badge',
        smartLabelOutsideContrast: 'series-color-with-white-halo'
    };
}

    window.DDBECharts = {
        version: VERSION,
        engine: ENGINE,
        renderCompareBar: renderCompareBar,
        renderHorizontalBar: renderHorizontalBar,
        renderDonutElement: renderDonutElement,
        renderSimpleDonut: renderSimpleDonut,
        renderDomHorizontalBars: renderDomHorizontalBars,
        renderDomVerticalBars: renderDomVerticalBars,
        upgradePageCharts: upgradePageCharts,
        resizeAll: resizeAll,
        interactionStabilityContract: chartInteractionStabilityContract,
        hasEngine: hasEngine,
        formatCompact: compact,
        formatExact: formatExact,
        applySmartBarLabels: applySmartBarLabels
    };

    window.DDBEChartsSmartLabels = {
        version: 'R27',
        apply: applySmartBarLabels,
        collisionPolicy: 'ADAPTIVE_LANES_WITH_COMBINED_FALLBACK',
        valuesRemainAvailableInTooltip: true
    };

    window.addEventListener('resize', debounce(resizeAll, 120), { passive: true });
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', startAutoUpgrade, { once: true });
    } else {
        startAutoUpgrade();
    }
}());
