(function () {
    'use strict';

    function parseConfig() {
        var node = document.getElementById('diagnostics110_chart_config');
        if (!node) return null;
        try {
            return JSON.parse(node.textContent || '{}');
        } catch (error) {
            return null;
        }
    }

    function payloadHasData(payload) {
        var values = [];
        (payload.series || []).forEach(function (series) {
            (series.values || []).forEach(function (value) {
                values.push(Number(value || 0));
            });
        });
        return values.some(function (value) { return value !== 0; });
    }

    function renderMetric(key, config) {
        var metric = config.metrics && config.metrics[key];
        var card = document.querySelector('.diagnostics110-chart-card');
        var heading = document.querySelector('[data-diagnostics110-chart-heading]');
        var canvas = document.getElementById('diagnostics110_chart');
        if (!metric || !card || !canvas) return false;

        if (heading) heading.textContent = metric.title || '';
        card.setAttribute('data-diagnostics110-chart-state', 'pending');
        canvas.hidden = false;
        canvas.style.display = '';

        var payload = metric.payload || {};
        if (!payloadHasData(payload)) {
            card.setAttribute('data-diagnostics110-chart-state', 'empty');
            return true;
        }

        try {
            var result = window.renderBarCompareChart('diagnostics110_chart', payload);
            if (!result || !result.rendered) throw new Error('Chart renderer did not confirm success.');
            card.setAttribute('data-diagnostics110-chart-state', 'rendered');
            return true;
        } catch (error) {
            card.setAttribute('data-diagnostics110-chart-state', 'error');
            return false;
        }
    }

    window.addEventListener('DOMContentLoaded', function () {
        var mode = document.querySelector('[data-diagnostics110-mode]');
        var form = document.querySelector('[data-diagnostics110-filter]');
        var rangeFields = Array.prototype.slice.call(document.querySelectorAll('[data-diagnostics110-range-field]'));
        var yearField = document.querySelector('[data-diagnostics110-year-field]');

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

        if (mode) mode.addEventListener('change', syncMode);
        syncMode();

        var config = parseConfig();
        if (!config) return;

        var active = config.defaultMetric || 'combined';
        var buttons = Array.prototype.slice.call(document.querySelectorAll('[data-diagnostics110-metric]'));
        buttons.forEach(function (button) {
            button.addEventListener('click', function () {
                active = button.getAttribute('data-diagnostics110-metric') || 'combined';
                buttons.forEach(function (item) {
                    item.classList.toggle('is-active', item === button);
                });
                window.setTimeout(function () {
                    renderMetric(active, config);
                    window.dispatchEvent(new Event('resize'));
                }, 20);
            });
        });

        var chartPass = renderMetric(active, config);
        var topbar = document.querySelector('.elite-topbar--flow-safe');
        var topbarPosition = topbar ? window.getComputedStyle(topbar).position : 'missing';
        var headerPass = topbarPosition !== 'sticky' && topbarPosition !== 'fixed';

        window.__DDB_DIAGNOSTICS_R45_P10_BROWSER_GATE__ = {
            chart: {
                expected: 1,
                rendered: chartPass ? 1 : 0,
                failed: chartPass ? 0 : 1,
                status: chartPass ? 'PASS' : 'FAIL'
            },
            header: {
                found: !!topbar,
                computedPosition: topbarPosition,
                noOverlay: headerPass,
                status: headerPass ? 'PASS' : 'FAIL'
            },
            status: chartPass && headerPass ? 'PASS' : 'FAIL'
        };

        document.documentElement.setAttribute(
            'data-diagnostics-r45-p10-browser-gate',
            chartPass && headerPass ? 'PASS' : 'FAIL'
        );
    });
})();
