(function () {
    'use strict';

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

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

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

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

        var payload = metric.payload || {};
        var values = valuesOf(payload);
        if (!values.some(function (value) { return value !== 0; })) {
            card.setAttribute('data-operations91-chart-state', 'empty');
            return true;
        }

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

    window.addEventListener('DOMContentLoaded', function () {
        var mode = document.querySelector('[data-operations91-mode]');
        var form = document.querySelector('[data-operations91-filter]');
        var rangeFields = Array.prototype.slice.call(document.querySelectorAll('[data-operations91-range-field]'));
        var yearField = document.querySelector('[data-operations91-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 || 'performed';
        var buttons = Array.prototype.slice.call(document.querySelectorAll('[data-operations91-metric]'));
        buttons.forEach(function (button) {
            button.addEventListener('click', function () {
                active = button.getAttribute('data-operations91-metric') || 'performed';
                buttons.forEach(function (item) {
                    item.classList.toggle('is-active', item === button);
                });
                window.setTimeout(function () {
                    renderMetric(active, config);
                    window.dispatchEvent(new Event('resize'));
                }, 20);
            });
        });

        var pass = 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_OPERATIONS_R45_P9_1_BROWSER_GATE__ = {
            chart: {
                expected: 1,
                rendered: pass ? 1 : 0,
                failed: pass ? 0 : 1,
                status: pass ? 'PASS' : 'FAIL'
            },
            header: {
                found: !!topbar,
                computedPosition: topbarPosition,
                noOverlay: headerPass,
                status: headerPass ? 'PASS' : 'FAIL'
            },
            status: pass && headerPass ? 'PASS' : 'FAIL'
        };
        document.documentElement.setAttribute(
            'data-operations-r45-p9-1-browser-gate',
            pass && headerPass ? 'PASS' : 'FAIL'
        );
    });
})();
