(function () {
    'use strict';

    function localeOf(payload) {
        return (payload && payload.locale) || (document.documentElement.lang === 'ar' ? 'ar-SA' : 'en-US');
    }

    function formatFull(value, locale, decimals) {
        return new Intl.NumberFormat(locale || 'en-US', {
            minimumFractionDigits: 0,
            maximumFractionDigits: typeof decimals === 'number' ? decimals : 2
        }).format(Number(value || 0));
    }

    function formatCompact(value, locale) {
        var n = Number(value || 0);
        var abs = Math.abs(n);
        if (abs >= 1000000) return formatFull(n / 1000000, locale, 2) + 'M';
        if (abs >= 1000) return formatFull(n / 1000, locale, 1) + 'K';
        return formatFull(n, locale, 0);
    }

    function ensureTooltip() {
        var node = document.getElementById('ddb-chart-tooltip');
        if (node) return node;
        var style = document.createElement('style');
        style.id = 'ddb-chart-tooltip-style';
        style.textContent = [
            '#ddb-chart-tooltip{position:fixed;z-index:99999;pointer-events:none;min-width:176px;max-width:min(340px,calc(100vw - 24px));padding:12px 14px;border:1px solid rgba(148,163,184,.28);border-radius:12px;background:rgba(7,17,31,.96);box-shadow:0 12px 32px rgba(15,23,42,.22);color:#fff;font:650 14px/1.45 "Segoe UI",Tahoma,Arial,sans-serif;opacity:0;transform:translateY(4px);transition:opacity .1s ease,transform .1s ease;backdrop-filter:blur(8px)}',
            '#ddb-chart-tooltip.is-visible{opacity:1;transform:translateY(0)}',
            '#ddb-chart-tooltip strong{display:block;margin-bottom:5px;color:#fff;font-size:14px;font-weight:950}',
            '#ddb-chart-tooltip span{display:block;color:#d8e3f2}',
            '#ddb-chart-tooltip b{color:#fff;font-weight:950}',
            'canvas[data-chart-rendered="true"]{cursor:crosshair}',
            '[data-ddb-chart-segments]{cursor:crosshair}'
        ].join('');
        document.head.appendChild(style);
        node = document.createElement('div');
        node.id = 'ddb-chart-tooltip';
        node.setAttribute('role', 'status');
        node.setAttribute('aria-live', 'polite');
        document.body.appendChild(node);
        return node;
    }

    function tooltipHtml(item, locale) {
        var prefix = item.prefix || '';
        var suffix = item.suffix || '';
        var decimals = typeof item.decimals === 'number' ? item.decimals : 2;
        var value = prefix + formatFull(item.value, locale, decimals) + suffix;
        var percentage = typeof item.percentage === 'number' ? ' · ' + formatFull(item.percentage, locale, 1) + '%' : '';
        return '<strong>' + escapeHtml(item.label || '') + '</strong>' +
            (item.series ? '<span>' + escapeHtml(item.series) + '</span>' : '') +
            '<span><b>' + escapeHtml(value) + '</b>' + escapeHtml(percentage) + '</span>';
    }

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

    function placeTooltip(clientX, clientY, html) {
        var tip = ensureTooltip();
        tip.innerHTML = html;
        tip.classList.add('is-visible');
        var rect = tip.getBoundingClientRect();
        var left = clientX + 16;
        var top = clientY + 16;
        if (left + rect.width > window.innerWidth - 10) left = clientX - rect.width - 16;
        if (top + rect.height > window.innerHeight - 10) top = clientY - rect.height - 16;
        tip.style.left = Math.max(8, left) + 'px';
        tip.style.top = Math.max(8, top) + 'px';
    }

    function hideTooltip() {
        var tip = document.getElementById('ddb-chart-tooltip');
        if (tip) tip.classList.remove('is-visible');
    }

    function bindCanvas(canvas, regions, meta) {
        if (!canvas) return;
        canvas.__ddbTooltipRegions = regions || [];
        canvas.__ddbTooltipMeta = meta || {};
        if (canvas.getAttribute('data-ddb-tooltip-bound') === 'true') return;
        canvas.setAttribute('data-ddb-tooltip-bound', 'true');

        function locate(event) {
            var rect = canvas.getBoundingClientRect();
            var scaleX = (canvas.__ddbTooltipMeta.width || rect.width) / Math.max(rect.width, 1);
            var scaleY = (canvas.__ddbTooltipMeta.height || rect.height) / Math.max(rect.height, 1);
            var x = (event.clientX - rect.left) * scaleX;
            var y = (event.clientY - rect.top) * scaleY;
            var found = null;
            (canvas.__ddbTooltipRegions || []).some(function (r) {
                if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
                    found = r;
                    return true;
                }
                return false;
            });
            if (found) {
                placeTooltip(event.clientX, event.clientY, tooltipHtml(found, canvas.__ddbTooltipMeta.locale || 'en-US'));
                canvas.setAttribute('data-ddb-tooltip-active', 'true');
            } else {
                hideTooltip();
                canvas.setAttribute('data-ddb-tooltip-active', 'false');
            }
        }

        canvas.addEventListener('pointermove', locate, { passive: true });
        canvas.addEventListener('pointerdown', locate, { passive: true });
        canvas.addEventListener('pointerleave', hideTooltip, { passive: true });
        canvas.addEventListener('blur', hideTooltip, { passive: true });
    }

    function bindSegmentChart(element) {
        if (window.DDBECharts && typeof window.DDBECharts.renderDonutElement === 'function' && window.DDBECharts.hasEngine()) {
            var upgraded = window.DDBECharts.renderDonutElement(element);
            if (upgraded && upgraded.rendered) return;
        }
        if (!element || element.getAttribute('data-ddb-segment-tooltip-bound') === 'true') return;
        var raw = element.getAttribute('data-ddb-chart-segments') || '[]';
        var segments;
        try { segments = JSON.parse(raw); } catch (e) { return; }
        if (!Array.isArray(segments) || !segments.length) return;
        element.setAttribute('data-ddb-segment-tooltip-bound', 'true');
        var locale = element.getAttribute('data-ddb-chart-locale') || (document.documentElement.lang === 'ar' ? 'ar-SA' : 'en-US');
        var innerRatio = Number(element.getAttribute('data-ddb-chart-inner-ratio') || 0.54);

        function locate(event) {
            var rect = element.getBoundingClientRect();
            var cx = rect.left + rect.width / 2;
            var cy = rect.top + rect.height / 2;
            var dx = event.clientX - cx;
            var dy = event.clientY - cy;
            var radius = Math.min(rect.width, rect.height) / 2;
            var distance = Math.sqrt(dx * dx + dy * dy);
            if (distance > radius || distance < radius * innerRatio) {
                hideTooltip();
                return;
            }
            var angle = (Math.atan2(dy, dx) * 180 / Math.PI + 90 + 360) % 360;
            var pct = angle / 360 * 100;
            var cursor = 0;
            var item = null;
            segments.some(function (segment) {
                var share = Math.max(0, Number(segment.percentage || 0));
                var end = cursor + share;
                if (pct >= cursor && pct < end) {
                    item = segment;
                    return true;
                }
                cursor = end;
                return false;
            });
            if (item) placeTooltip(event.clientX, event.clientY, tooltipHtml(item, locale));
            else hideTooltip();
        }
        element.addEventListener('pointermove', locate, { passive: true });
        element.addEventListener('pointerdown', locate, { passive: true });
        element.addEventListener('pointerleave', hideTooltip, { passive: true });
    }

    function bindSegmentCharts(root) {
        Array.prototype.slice.call((root || document).querySelectorAll('[data-ddb-chart-segments]')).forEach(bindSegmentChart);
    }

    window.DDBChartTooltip = {
        bindCanvas: bindCanvas,
        bindSegmentCharts: bindSegmentCharts,
        hide: hideTooltip,
        showCustom: placeTooltip,
        formatFull: formatFull,
        formatCompact: formatCompact
    };


function niceStep(value) {
    var n = Math.abs(Number(value || 1));
    if (!isFinite(n) || n <= 0) return 1;
    var exp = Math.pow(10, Math.floor(Math.log10(n)));
    var f = n / exp;
    var factors = [1, 1.5, 2, 2.5, 3, 4, 5, 7.5, 10];
    var nice = 10;
    for (var i = 0; i < factors.length; i++) {
        if (f <= factors[i]) { nice = factors[i]; break; }
    }
    return nice * exp;
}

function formatAxisValue(value, locale) {
    var n = Number(value || 0);
    var abs = Math.abs(n);
    if (abs >= 1000000) return formatFull(n / 1000000, locale, 0) + 'M';
    if (abs >= 1000) return formatFull(n / 1000, locale, 0) + 'K';
    return formatFull(n, locale, 0);
}

function drawValueLabel(ctx, cx, cy, text, color) {
    ctx.save();
    ctx.font = '900 10.5px Segoe UI, Tahoma, Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.lineWidth = 3.5;
    ctx.strokeStyle = 'rgba(255,255,255,0.96)';
    ctx.strokeText(text, cx, cy);
    ctx.fillStyle = color || '#172033';
    ctx.fillText(text, cx, cy);
    ctx.restore();
}

window.renderBarCompareChart = function (canvasId, payload) {
    if (window.DDBECharts && typeof window.DDBECharts.renderCompareBar === 'function' && window.DDBECharts.hasEngine()) {
        try {
            var professionalResult = window.DDBECharts.renderCompareBar(canvasId, payload || {});
            if (professionalResult && professionalResult.rendered) return professionalResult;
        } catch (professionalError) {
            if (window.console && typeof window.console.error === 'function') {
                window.console.error('Professional chart engine failed; using preserved fallback.', professionalError);
            }
        }
    }
    var canvas = document.getElementById(canvasId);
    if (!canvas || !payload || !Array.isArray(payload.labels)) {
        return { rendered: false, reason: 'invalid-input' };
    }
    canvas.setAttribute('data-chart-rendered', 'false');

    var locale = localeOf(payload);
    var rtl = (payload.dir || document.documentElement.dir) === 'rtl';
    var dpr = window.devicePixelRatio || 1;
    var rect = canvas.getBoundingClientRect();
    var width = Math.max(rect.width, 620);
    var requestedHeight = Number(canvas.getAttribute('height') || 188) * 2.32;
    var height = Math.max(390, requestedHeight);
    canvas.width = Math.round(width * dpr);
    canvas.height = Math.round(height * dpr);

    var ctx = canvas.getContext('2d');
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.clearRect(0, 0, width, height);

    var labels = payload.labels || [];
    var series = Array.isArray(payload.series) ? payload.series : [];
    if (!series.length) {
        return { rendered: false, reason: 'series-missing' };
    }

    var values = [];
    series.forEach(function (s) {
        (s.values || []).forEach(function (v) { values.push(Number(v || 0)); });
    });
    var maxValue = Math.max.apply(null, values.concat([1]));
    var minValue = Math.min.apply(null, values.concat([0]));
    if (minValue > 0) minValue = 0;
    if (maxValue === minValue) maxValue = minValue + 1;
    var positiveMax = Math.max(maxValue, 0);
    var negativeMin = Math.min(minValue, 0);
    var targetIntervals = 5;
    var step = niceStep((positiveMax - negativeMin) / targetIntervals || 1);
    var chartTop = step * targetIntervals;
    while (chartTop < positiveMax) chartTop += step;
    var chartBottom = negativeMin < 0 ? -Math.ceil(Math.abs(negativeMin) / step) * step : 0;
    var span = Math.max(1, chartTop - chartBottom);

    var showHeader = payload.showHeader !== false;
    var pad = {
        top: showHeader ? 78 : 38,
        right: rtl ? 86 : 22,
        bottom: 60,
        left: rtl ? 22 : 90
    };
    var plotX = pad.left;
    var plotY = pad.top;
    var plotW = Math.max(100, width - pad.left - pad.right);
    var plotH = Math.max(120, height - pad.top - pad.bottom);
    var zeroY = plotY + plotH - ((0 - chartBottom) / span) * plotH;

    var bg = ctx.createLinearGradient(0, 0, 0, height);
    bg.addColorStop(0, '#ffffff');
    bg.addColorStop(1, '#f8fbff');
    ctx.fillStyle = bg;
    roundRect(ctx, 0, 0, width, height, 24);
    ctx.fill();

    // grid and y-axis labels
    ctx.textBaseline = 'middle';
    ctx.strokeStyle = '#e4ebf5';
    ctx.lineWidth = 1;
    ctx.font = '700 12px Segoe UI, Tahoma, Arial';
    ctx.fillStyle = '#64748b';
    ctx.textAlign = rtl ? 'left' : 'right';
    for (var gv = chartBottom; gv <= chartTop + 0.0001; gv += step) {
        var y = plotY + plotH - ((gv - chartBottom) / span) * plotH;
        ctx.beginPath();
        ctx.moveTo(plotX, y);
        ctx.lineTo(plotX + plotW, y);
        ctx.stroke();
        ctx.fillText(formatAxisValue(gv, locale), rtl ? width - pad.right + 12 : pad.left - 12, y);
    }

    // zero baseline
    ctx.strokeStyle = '#94a3b8';
    ctx.lineWidth = 1.3;
    ctx.beginPath();
    ctx.moveTo(plotX, zeroY);
    ctx.lineTo(plotX + plotW, zeroY);
    ctx.stroke();

    var groupW = plotW / Math.max(labels.length, 1);
    var totalGroupWidth = Math.min(groupW * 0.86, Math.max(54, groupW - 6));
    var gap = Math.max(5, Math.min(9, totalGroupWidth * 0.07));
    var barW = Math.max(14, Math.min(38, (totalGroupWidth - Math.max(0, series.length - 1) * gap) / Math.max(series.length, 1)));
    totalGroupWidth = series.length * barW + Math.max(0, series.length - 1) * gap;
    var palettes = [
        { top: '#818cf8', bottom: '#4f46e5', label: '#3730a3' },
        { top: '#67e8f9', bottom: '#06b6d4', label: '#0e7490' },
        { top: '#86efac', bottom: '#10b981', label: '#065f46' },
        { top: '#fdba74', bottom: '#f59e0b', label: '#92400e' }
    ];
    var hitRegions = [];
    var prefix = payload.valuePrefix || '';
    var suffix = payload.valueSuffix || '';
    var decimals = typeof payload.valueDecimals === 'number' ? payload.valueDecimals : 2;
    var canShowDataLabels = payload.showDataLabels !== false && plotW >= 560;

    labels.forEach(function (label, idx) {
        var visualIdx = rtl ? (labels.length - 1 - idx) : idx;
        var center = plotX + groupW * visualIdx + groupW / 2;
        ctx.fillStyle = '#334155';
        ctx.font = '800 12px Segoe UI, Tahoma, Arial';
        ctx.textAlign = 'center';
        var labelText = String(label || '').trim();
        if (labelText.length > 11) labelText = labelText.slice(0, 10) + '…';
        ctx.fillText(labelText, center, height - 28);

        series.forEach(function (s, sIdx) {
            var value = Number((s.values || [])[idx] || 0);
            var scaledY = plotY + plotH - ((value - chartBottom) / span) * plotH;
            var x = center - totalGroupWidth / 2 + sIdx * (barW + gap);
            var y = Math.min(scaledY, zeroY);
            var h = Math.abs(zeroY - scaledY);
            if (h < 1 && value === 0) {
                hitRegions.push({
                    x: x, y: zeroY - 6, w: barW, h: 12,
                    label: String(label), series: String(s.label || ''), value: value,
                    prefix: prefix, suffix: suffix, decimals: decimals
                });
                return;
            }
            h = Math.max(h, value === 0 ? 1 : 6);
            var palette = palettes[sIdx % palettes.length];
            var grad = ctx.createLinearGradient(0, y, 0, y + h);
            grad.addColorStop(0, palette.top);
            grad.addColorStop(1, palette.bottom);
            ctx.fillStyle = grad;
            ctx.shadowColor = 'rgba(37, 99, 235, 0.10)';
            ctx.shadowBlur = 10;
            ctx.shadowOffsetY = 4;
            roundRect(ctx, x, y, barW, h, Math.min(10, barW / 2.2));
            ctx.fill();
            ctx.shadowColor = 'transparent';
            ctx.shadowBlur = 0;
            ctx.shadowOffsetY = 0;

            hitRegions.push({
                x: x, y: y, w: barW, h: h,
                label: String(label), series: String(s.label || ''), value: value,
                prefix: prefix, suffix: suffix, decimals: decimals,
                color: palette.bottom
            });

            if (canShowDataLabels && value !== 0) {
                var labelY = value >= 0 ? Math.max(plotY + 10, y - 10) : Math.min(plotY + plotH - 10, y + h + 13);
                if (series.length > 1) {
                    var siblingIndex = sIdx === 0 ? 1 : 0;
                    var siblingValue = Number(((series[siblingIndex] || {}).values || [])[idx] || 0);
                    var siblingY = plotY + plotH - ((siblingValue - chartBottom) / span) * plotH;
                    if (siblingValue !== 0 && Math.abs(siblingY - scaledY) < 18) {
                        labelY += sIdx === 0 ? -7 : 7;
                    }
                }
                drawValueLabel(ctx, x + barW / 2, labelY, formatCompact(value, locale), palette.label);
            }
        });
    });

    if (showHeader) {
        ctx.fillStyle = '#07111f';
        ctx.font = '900 16px Segoe UI, Tahoma, Arial';
        ctx.textAlign = rtl ? 'right' : 'left';
        ctx.fillText(payload.title || '', rtl ? width - 26 : 26, 25);

        ctx.font = '700 12px Segoe UI, Tahoma, Arial';
        series.forEach(function (s, idx) {
            var blockW = 138;
            var x = rtl ? width - 26 - (idx + 1) * blockW : 26 + idx * blockW;
            var y = 46;
            var palette = palettes[idx % palettes.length];
            ctx.fillStyle = palette.bottom;
            roundRect(ctx, x, y, 14, 14, 4);
            ctx.fill();
            ctx.fillStyle = '#334155';
            ctx.textAlign = 'left';
            ctx.fillText(s.label || '', x + 22, y + 8);
        });
    }

    canvas.setAttribute('data-chart-rendered', 'true');
    canvas.setAttribute('data-chart-label-count', String(labels.length));
    canvas.setAttribute('data-chart-series-count', String(series.length));
    canvas.setAttribute('data-ddb-tooltip-enabled', 'true');
    bindCanvas(canvas, hitRegions, { width: width, height: height, locale: locale });
    return {
        rendered: true,
        canvasId: canvasId,
        labels: labels.length,
        series: series.length,
        width: width,
        height: height,
        tooltipRegions: hitRegions.length
    };
};

function renderChartsByPrefix(dataPrefix, canvasPrefix) {
        var result = { expected: 0, rendered: 0, failed: 0 };
        document.querySelectorAll('script[type="application/json"][id^="' + dataPrefix + '"]').forEach(function (node) {
            var key = node.id.replace(dataPrefix, '');
            result.expected += 1;
            try {
                var payload = JSON.parse(node.textContent || '{}');
                var renderResult = window.renderBarCompareChart(canvasPrefix + key, payload);
                if (renderResult && renderResult.rendered) result.rendered += 1;
                else result.failed += 1;
            } catch (e) {
                result.failed += 1;
                if (window.console && typeof window.console.error === 'function') {
                    window.console.error('Chart rendering failed for ' + key, e);
                }
            }
        });
        return result;
    }

    window.refreshOracleCharts = function () {
        var summary = {
            revenue: renderChartsByPrefix('chart_data_', 'chart_'),
            visits: renderChartsByPrefix('visits_chart_data_', 'visits_chart_'),
            doctors: renderChartsByPrefix('doctors_chart_data_', 'doctors_chart_')
        };
        bindSegmentCharts(document);
        window.__DDB_CHART_RUNTIME__ = summary;
        return summary;
    };

    window.addEventListener('resize', debounce(function () {
        window.refreshOracleCharts();
    }, 180));

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

    function roundRect(ctx, x, y, w, h, r) {
        var rr = Math.min(r, Math.abs(w) / 2, Math.abs(h) / 2);
        ctx.beginPath();
        ctx.moveTo(x + rr, y);
        ctx.arcTo(x + w, y, x + w, y + h, rr);
        ctx.arcTo(x + w, y + h, x, y + h, rr);
        ctx.arcTo(x, y + h, x, y, rr);
        ctx.arcTo(x, y, x + w, y, rr);
        ctx.closePath();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () { bindSegmentCharts(document); }, { once: true });
    } else {
        bindSegmentCharts(document);
    }
}());

/* H11.0-P11.1-R22 — Shared Apache ECharts delegation active for all canvas comparison charts and segment donuts. */
