(function () {
    function fmt(n, locale) {
        return new Intl.NumberFormat(locale || document.documentElement.lang || 'en-US', {
            maximumFractionDigits: 0
        }).format(Number(n || 0));
    }

    window.renderBarCompareChart = function (canvasId, payload) {
        var canvas = document.getElementById(canvasId);
        if (!canvas || !payload || !Array.isArray(payload.labels)) return;

        var locale = payload.locale || (document.documentElement.lang === 'ar' ? 'ar-SA' : 'en-US');
        var rtl = (payload.dir || document.documentElement.dir) === 'rtl';
        var dpr = window.devicePixelRatio || 1;
        var rect = canvas.getBoundingClientRect();
        var width = Math.max(rect.width, 760);
        var height = Number(canvas.getAttribute('height') || 188) * 2.12;
        canvas.width = width * dpr;
        canvas.height = 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 = payload.series || [];
        var values = [];
        series.forEach(function (s) { (s.values || []).forEach(function (v) { values.push(Number(v || 0)); }); });
        var max = Math.max.apply(null, values.concat([1]));
        var min = Math.min.apply(null, values.concat([0]));
        if (min > 0) min = 0;
        if (max === min) max = min + 1;

        var pad = { top: 62, right: rtl ? 96 : 30, bottom: 62, left: rtl ? 30 : 96 };
        var plotX = pad.left;
        var plotY = pad.top;
        var plotW = width - pad.left - pad.right;
        var plotH = height - pad.top - pad.bottom;
        var zeroY = plotY + plotH - ((0 - min) / (max - min)) * 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();

        ctx.font = '12px Segoe UI, Tahoma, Arial';
        ctx.textBaseline = 'middle';
        ctx.strokeStyle = '#e3eaf5';
        ctx.lineWidth = 1;
        ctx.fillStyle = '#60708b';
        ctx.textAlign = rtl ? 'left' : 'right';

        for (var i = 0; i <= 5; i++) {
            var y = plotY + (plotH / 5) * i;
            var value = max - ((max - min) / 5) * i;
            ctx.beginPath();
            ctx.moveTo(plotX, y);
            ctx.lineTo(plotX + plotW, y);
            ctx.stroke();
            ctx.fillText(fmt(value, locale), rtl ? width - pad.right + 12 : pad.left - 12, y);
        }

        ctx.strokeStyle = '#95a3b8';
        ctx.beginPath();
        ctx.moveTo(plotX, zeroY);
        ctx.lineTo(plotX + plotW, zeroY);
        ctx.stroke();

        var groupW = plotW / Math.max(labels.length, 1);
        var barW = Math.max(9, Math.min(24, groupW / 5.3));
        var gap = 6;
        var palettes = [
            ['#1455d9', '#70a5ff'],
            ['#0ea5e9', '#7dd3fc'],
            ['#059669', '#6ee7b7']
        ];

        labels.forEach(function (label, idx) {
            var visualIdx = rtl ? (labels.length - 1 - idx) : idx;
            var center = plotX + groupW * visualIdx + groupW / 2;
            ctx.fillStyle = '#60708b';
            ctx.save();
            ctx.translate(center, height - 31);
            ctx.rotate(rtl ? Math.PI / 7 : -Math.PI / 7);
            ctx.textAlign = rtl ? 'left' : 'right';
            ctx.fillText(String(label).trim(), 0, 0);
            ctx.restore();

            series.forEach(function (s, sIdx) {
                var value = Number((s.values || [])[idx] || 0);
                var scaledY = plotY + plotH - ((value - min) / (max - min)) * plotH;
                var x = center - ((series.length * barW + (series.length - 1) * gap) / 2) + sIdx * (barW + gap);
                var y = Math.min(scaledY, zeroY);
                var h = Math.max(3, Math.abs(zeroY - scaledY));
                var grad = ctx.createLinearGradient(0, y, 0, y + h);
                grad.addColorStop(0, palettes[sIdx % palettes.length][1]);
                grad.addColorStop(1, palettes[sIdx % palettes.length][0]);
                ctx.fillStyle = grad;
                roundRect(ctx, x, y, barW, h, 8);
                ctx.fill();
            });
        });

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

        ctx.font = '12px Segoe UI, Tahoma, Arial';
        series.forEach(function (s, idx) {
            var blockW = 136;
            var x = rtl ? width - 26 - (idx + 1) * blockW : 26 + idx * blockW;
            var y = 43;
            ctx.fillStyle = palettes[idx % palettes.length][0];
            roundRect(ctx, x, y, 13, 13, 4);
            ctx.fill();
            ctx.fillStyle = '#334155';
            ctx.textAlign = 'left';
            ctx.fillText(s.label || '', x + 20, y + 7);
        });
    };

    function renderChartsByPrefix(dataPrefix, canvasPrefix) {
        document.querySelectorAll('script[type="application/json"][id^="' + dataPrefix + '"]').forEach(function (node) {
            var key = node.id.replace(dataPrefix, '');
            try {
                var payload = JSON.parse(node.textContent || '{}');
                window.renderBarCompareChart(canvasPrefix + key, payload);
            } catch (e) {}
        });
    }

    window.refreshOracleCharts = function () {
        renderChartsByPrefix('chart_data_', 'chart_');
        renderChartsByPrefix('visits_chart_data_', 'visits_chart_');
        renderChartsByPrefix('doctors_chart_data_', 'doctors_chart_');
    };

    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();
    }
})();

// Phase 4: branch switcher modal. No API calls; the form posts back to PHP.
(function () {
    const modal = document.querySelector('[data-branch-modal]');
    if (!modal) return;

    const openers = document.querySelectorAll('[data-branch-open]');
    const closers = modal.querySelectorAll('[data-branch-close]');

    function openModal() {
        modal.classList.add('open');
        modal.setAttribute('aria-hidden', 'false');
        document.body.classList.add('modal-lock');
    }

    function closeModal() {
        modal.classList.remove('open');
        modal.setAttribute('aria-hidden', 'true');
        document.body.classList.remove('modal-lock');
    }

    openers.forEach(btn => btn.addEventListener('click', openModal));
    closers.forEach(btn => btn.addEventListener('click', closeModal));
    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape') closeModal();
    });

    modal.querySelectorAll('.branch-option input').forEach(function (input) {
        input.addEventListener('change', function () {
            modal.querySelectorAll('.branch-option').forEach(label => label.classList.remove('selected'));
            input.closest('.branch-option').classList.add('selected');
        });
    });
})();

// Phase 5: mobile sidebar toggle, keeps the workspace usable on tablets and phones.
(function () {
    const toggle = document.querySelector('[data-sidebar-toggle]');
    const close = document.querySelector('[data-sidebar-close]');
    if (!toggle) return;

    toggle.addEventListener('click', function () {
        document.body.classList.toggle('sidebar-open');
    });
    if (close) {
        close.addEventListener('click', function () {
            document.body.classList.remove('sidebar-open');
        });
    }
})();
