(function () {
    'use strict';

    var configs = {};
    var activeSpecialty = '';
    var activeMetric = 'outpatient';

    function parseJson(id, fallback) {
        var node = document.getElementById(id);
        if (!node) return fallback;
        try {
            return JSON.parse(node.textContent || '');
        } catch (error) {
            return fallback;
        }
    }

    function buildIndex() {
        configs = {};
        var list = parseJson('sf121_activity_chart_config', []);
        if (!Array.isArray(list)) return;

        list.forEach(function (item) {
            var id = String(item.id || '');
            if (!id) return;
            configs[id] = item;
        });
    }

    function metricLabel(metric) {
        var isArabic = document.documentElement.lang === 'ar';
        if (metric === 'admissions') {
            return isArabic ? 'حالات الدخول' : 'Admissions';
        }
        return isArabic ? 'زيارات العيادات الخارجية' : 'Outpatient Visits';
    }

    function renderChart() {
        var config = configs[activeSpecialty];
        var stage = document.querySelector('[data-sf121-chart-state]');
        var title = document.getElementById('sf121_activity_chart_title');

        if (!config || !config[activeMetric]) {
            if (stage) stage.setAttribute('data-sf121-chart-state', 'error');
            return false;
        }

        if (title) {
            title.textContent = String(config.label || activeSpecialty)
                + ' · '
                + metricLabel(activeMetric);
        }

        try {
            var result = window.renderBarCompareChart(
                'sf121_activity_chart',
                config[activeMetric]
            );
            var rendered = !!(result && result.rendered);
            if (stage) {
                stage.setAttribute(
                    'data-sf121-chart-state',
                    rendered ? 'rendered' : 'error'
                );
            }
            return rendered;
        } catch (error) {
            if (stage) stage.setAttribute('data-sf121-chart-state', 'error');
            return false;
        }
    }

    function activateMetric(metric) {
        metric = metric === 'admissions' ? 'admissions' : 'outpatient';
        activeMetric = metric;

        var root = document.querySelector('[data-sf121-root]');
        var tableTitle = document.getElementById('sf121_activity_table_title');
        var viewTitle = document.getElementById('sf121_activity_view_title');
        var label = metricLabel(metric);
        var isArabic = document.documentElement.lang === 'ar';

        if (root) {
            root.setAttribute('data-sf121-active-metric', metric);
        }
        if (tableTitle) {
            tableTitle.textContent = isArabic
                ? label + ' حسب التخصص'
                : label + ' by Specialty';
        }
        if (viewTitle) {
            viewTitle.textContent = label;
        }

        Array.prototype.forEach.call(
            document.querySelectorAll('[data-sf121-metric]'),
            function (button) {
                var selected = button.getAttribute('data-sf121-metric') === metric;
                button.classList.toggle('is-active', selected);
                button.setAttribute('aria-selected', selected ? 'true' : 'false');
            }
        );

        return renderChart();
    }

    function initViewAll() {
        var root = document.querySelector('[data-sf121-root]');
        var button = document.querySelector('[data-sf121-view-all]');
        if (!root || !button) return;

        button.addEventListener('click', function () {
            var expanded = button.getAttribute('aria-expanded') === 'true';
            var nextExpanded = !expanded;

            Array.prototype.forEach.call(
                document.querySelectorAll('[data-sf121-extra-row]'),
                function (row) {
                    row.hidden = !nextExpanded;
                }
            );

            button.setAttribute('aria-expanded', nextExpanded ? 'true' : 'false');
            button.textContent = nextExpanded
                ? String(root.getAttribute('data-view-top-label') || '')
                : String(root.getAttribute('data-view-all-label') || '');
        });
    }

    function publishGate(chartRendered) {
        window.setTimeout(function () {
            var root = document.documentElement;
            var activityKpis = document.querySelectorAll('.sf121-kpi').length;
            var activityRows = document.querySelectorAll(
                '[data-sf121-activity-row]'
            ).length;
            var metricTabs = document.querySelectorAll(
                '[data-sf121-metric]'
            ).length;
            var selector = document.querySelector(
                '[data-sf121-specialty-select]'
            );
            var visibleSignals = document.querySelectorAll(
                '[data-sf121-signal-metric="' + activeMetric + '"]'
            ).length;
            var visibleMetricCells = document.querySelectorAll(
                '[data-sf121-metric-cell="' + activeMetric + '"]'
            ).length;
            var overflowPass = root.scrollWidth <= root.clientWidth + 2;
            var allSpecialtiesReady = !!configs.__all__;
            var structurePass = activityKpis === 2
                && activityRows > 0
                && metricTabs === 2
                && visibleSignals === 2
                && visibleMetricCells === activityRows * 3
                && allSpecialtiesReady
                && !!selector;
            var status = chartRendered && structurePass && overflowPass
                ? 'PASS'
                : 'FAIL';

            window.__DDB_SPECIALTY_FINANCE_P12_1_BROWSER_GATE__ = {
                activity: {
                    kpis: activityKpis,
                    specialtyRows: activityRows,
                    metricTabs: metricTabs,
                    visibleSignals: visibleSignals,
                    visibleMetricCells: visibleMetricCells,
                    selector: !!selector,
                    allSpecialtiesReady: allSpecialtiesReady,
                    activeSpecialty: activeSpecialty,
                    activeMetric: activeMetric,
                    chartRendered: chartRendered,
                    status: chartRendered && structurePass ? 'PASS' : 'FAIL'
                },
                responsive: {
                    viewportWidth: root.clientWidth,
                    scrollWidth: root.scrollWidth,
                    horizontalOverflow: !overflowPass,
                    status: overflowPass ? 'PASS' : 'FAIL'
                },
                financialCharts: window.__DDB_SPECIALTY_FINANCE_CHART_GATE__ || null,
                status: status
            };

            root.setAttribute(
                'data-specialty-finance-p12-1-browser-gate',
                status
            );
        }, 220);
    }

    function debounce(fn, delay) {
        var timer = null;
        return function () {
            var args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                fn.apply(null, args);
            }, delay);
        };
    }

    function initialize() {
        if (!document.querySelector('[data-sf121-root]')) return;

        buildIndex();
        initViewAll();

        var defaultSpecialtyInput = document.getElementById(
            'sf121_default_specialty'
        );
        var defaultMetricInput = document.getElementById(
            'sf121_default_metric'
        );
        var selector = document.querySelector(
            '[data-sf121-specialty-select]'
        );

        activeSpecialty = defaultSpecialtyInput
            ? String(defaultSpecialtyInput.value || '')
            : '';
        if (!configs[activeSpecialty]) {
            activeSpecialty = Object.keys(configs)[0] || '';
        }

        activeMetric = defaultMetricInput
            && defaultMetricInput.value === 'admissions'
            ? 'admissions'
            : 'outpatient';

        if (selector) {
            selector.value = activeSpecialty;
            selector.addEventListener('change', function () {
                activeSpecialty = String(selector.value || '');
                var rendered = renderChart();
                publishGate(rendered);
            });
        }

        Array.prototype.forEach.call(
            document.querySelectorAll('[data-sf121-metric]'),
            function (button) {
                button.addEventListener('click', function () {
                    var rendered = activateMetric(
                        button.getAttribute('data-sf121-metric') || ''
                    );
                    publishGate(rendered);
                });
            }
        );

        var rendered = activateMetric(activeMetric);
        publishGate(rendered);

        window.addEventListener('resize', debounce(function () {
            var resized = renderChart();
            publishGate(resized);
        }, 180));
    }

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