(function () {
    'use strict';

    var serviceConfigs = {};
    var activeService = '';

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

    function syncMode() {
        var mode = document.querySelector('[data-branch113-mode]');
        var form = document.querySelector('[data-branch113-filter]');
        var rangeFields = Array.prototype.slice.call(document.querySelectorAll('[data-branch113-range-field]'));
        var yearField = document.querySelector('[data-branch113-year-field]');
        var isRange = !!(mode && mode.value === 'range');

        rangeFields.forEach(function (field) {
            field.hidden = !isRange;
            Array.prototype.forEach.call(field.querySelectorAll('input,select'), function (input) {
                input.disabled = !isRange;
            });
        });

        if (yearField) {
            yearField.hidden = isRange;
            Array.prototype.forEach.call(yearField.querySelectorAll('input,select'), function (input) {
                input.disabled = isRange;
            });
        }

        if (form) {
            form.classList.toggle('is-range', isRange);
            form.classList.toggle('is-year', !isRange);
        }
    }

    function buildConfigIndex() {
        serviceConfigs = {};
        var configs = parseJson('branch113_service_chart_config', []);
        if (!Array.isArray(configs)) return;

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

    function renderService(key) {
        key = String(key || '');
        var config = serviceConfigs[key];
        var wrap = document.querySelector('.branch113-chart-wrap');
        var title = document.getElementById('branch113_trend_title');
        var rendered = false;

        if (!config) {
            if (wrap) wrap.setAttribute('data-branch113-chart-state', 'error');
            return false;
        }

        try {
            var result = window.renderBarCompareChart('branch113_service_chart', config.payload || {});
            rendered = !!(result && result.rendered);
        } catch (error) {
            rendered = false;
        }

        if (wrap) {
            wrap.setAttribute('data-branch113-chart-state', rendered ? 'rendered' : 'error');
        }
        if (title) {
            title.textContent = document.documentElement.lang === 'ar'
                ? String(config.label_ar || config.label_en || key)
                : String(config.label_en || key);
        }

        return rendered;
    }

    function activateService(key) {
        key = String(key || '');
        if (!serviceConfigs[key]) return false;
        activeService = key;

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

        Array.prototype.forEach.call(
            document.querySelectorAll('[data-branch113-service-panel]'),
            function (panel) {
                panel.classList.toggle(
                    'is-active',
                    panel.getAttribute('data-branch113-service-panel') === key
                );
            }
        );

        return renderService(key);
    }

    function publishBrowserGate(chartRendered) {
        window.setTimeout(function () {
            var root = document.documentElement;
            var topbar = document.querySelector('.elite-topbar--flow-safe');
            var topbarPosition = topbar ? window.getComputedStyle(topbar).position : 'missing';
            var headerPass = topbarPosition !== 'sticky' && topbarPosition !== 'fixed';
            var overflowPass = root.scrollWidth <= root.clientWidth + 2;
            var branchCards = document.querySelectorAll('.branch113-branch-card').length;
            var serviceCards = document.querySelectorAll('.branch113-service-card').length;
            var latestCards = document.querySelectorAll('.branch113-latest-grid > article').length;
            var serviceTabs = document.querySelectorAll('[data-branch113-service-tab]').length;
            var priorityRows = document.querySelectorAll('.branch113-priority-list > article').length;
            var structurePass = branchCards === 2
                && serviceCards === 6
                && latestCards === 2
                && serviceTabs === 6
                && priorityRows <= 4;
            var status = chartRendered && headerPass && overflowPass && structurePass
                ? 'PASS'
                : 'FAIL';

            window.__DDB_BRANCH_COMPARISON_R45_P11_3_BROWSER_GATE__ = {
                serviceChart: {
                    activeService: activeService,
                    rendered: chartRendered,
                    status: chartRendered ? 'PASS' : 'FAIL'
                },
                executiveStructure: {
                    branchCards: branchCards,
                    serviceCards: serviceCards,
                    latestMonthCards: latestCards,
                    serviceTabs: serviceTabs,
                    priorityRows: priorityRows,
                    status: structurePass ? 'PASS' : 'FAIL'
                },
                header: {
                    found: !!topbar,
                    computedPosition: topbarPosition,
                    noOverlay: headerPass,
                    status: headerPass ? 'PASS' : 'FAIL'
                },
                responsive: {
                    viewportWidth: root.clientWidth,
                    scrollWidth: root.scrollWidth,
                    horizontalOverflow: !overflowPass,
                    status: overflowPass ? 'PASS' : 'FAIL'
                },
                status: status
            };

            root.setAttribute('data-branch-comparison-r45-p11-3-browser-gate', status);
        }, 180);
    }

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

    window.addEventListener('DOMContentLoaded', function () {
        var mode = document.querySelector('[data-branch113-mode]');
        if (mode) mode.addEventListener('change', syncMode);
        syncMode();

        buildConfigIndex();

        Array.prototype.forEach.call(
            document.querySelectorAll('[data-branch113-service-tab]'),
            function (tab) {
                tab.addEventListener('click', function () {
                    var rendered = activateService(
                        tab.getAttribute('data-branch113-service-tab') || ''
                    );
                    publishBrowserGate(rendered);
                });
            }
        );

        var defaultInput = document.getElementById('branch113_default_service');
        var defaultService = defaultInput ? String(defaultInput.value || '') : '';
        if (!serviceConfigs[defaultService]) {
            defaultService = Object.keys(serviceConfigs)[0] || '';
        }

        var rendered = defaultService ? activateService(defaultService) : false;
        publishBrowserGate(rendered);

        window.addEventListener('resize', debounce(function () {
            var resized = activeService ? renderService(activeService) : false;
            publishBrowserGate(resized);
        }, 180));
    });
})();
