(function () {
    'use strict';

    var params;
    try {
        params = new URLSearchParams(window.location.search || '');
    } catch (error) {
        return;
    }

    var routePage = String(params.get('page') || '').toLowerCase();
    if (routePage !== 'revenue') {
        return;
    }

    var body = document.body;
    if (!body) {
        return;
    }

    function all(selector, context) {
        return Array.prototype.slice.call((context || document).querySelectorAll(selector));
    }

    function setChartState(shell, state) {
        if (!shell) {
            return;
        }
        shell.setAttribute('data-chart-render-state', state);
        var canvas = shell.querySelector('[data-revenue-chart-canvas]');
        var error = shell.querySelector('[data-revenue-chart-error]');
        if (canvas) {
            canvas.hidden = state === 'error';
        }
        if (error) {
            error.hidden = state !== 'error';
        }
    }

    function renderPanelChart(panel) {
        if (!panel) {
            return { rendered: false, reason: 'panel-missing' };
        }
        if (panel.getAttribute('data-chart-data-state') === 'empty') {
            setChartState(panel, 'empty');
            return { rendered: true, empty: true };
        }
        var key = panel.getAttribute('data-chart-key') || '';
        var payloadNode = document.getElementById('chart_data_' + key);
        var canvas = document.getElementById('chart_' + key);
        try {
            if (typeof window.renderBarCompareChart !== 'function') {
                throw new Error('Chart runtime unavailable');
            }
            if (!payloadNode || !canvas) {
                throw new Error('Chart payload or canvas unavailable');
            }
            var payload = JSON.parse(payloadNode.textContent || '{}');
            var result = window.renderBarCompareChart('chart_' + key, payload);
            var rendered = !!(result && result.rendered && canvas.getAttribute('data-chart-rendered') === 'true');
            if (!rendered) {
                throw new Error('Chart renderer did not confirm completion');
            }
            setChartState(panel, 'rendered');
            return { rendered: true, empty: false };
        } catch (error) {
            setChartState(panel, 'error');
            if (window.console && typeof window.console.error === 'function') {
                window.console.error('Revenue chart render failed for ' + key, error);
            }
            return { rendered: false, error: String(error && error.message ? error.message : error) };
        }
    }

    function renderAllCharts() {
        var panels = all('[data-eri-trend-panel]');
        var summary = { expected: 0, rendered: 0, empty: 0, failed: 0 };
        panels.forEach(function (panel) {
            if (panel.getAttribute('data-chart-data-state') === 'empty') {
                summary.empty += 1;
                setChartState(panel, 'empty');
                return;
            }
            summary.expected += 1;
            var wasHidden = panel.hidden;
            var previousAria = panel.getAttribute('aria-hidden');
            if (wasHidden) {
                panel.hidden = false;
                panel.setAttribute('aria-hidden', 'false');
                panel.classList.add('eri-v2-measuring');
            }
            var result = renderPanelChart(panel);
            if (result.rendered) {
                summary.rendered += 1;
            } else {
                summary.failed += 1;
            }
            if (wasHidden) {
                panel.hidden = true;
                panel.classList.remove('eri-v2-measuring');
                panel.setAttribute('aria-hidden', previousAria || 'true');
            }
        });
        document.documentElement.setAttribute('data-revenue-charts-expected', String(summary.expected));
        document.documentElement.setAttribute('data-revenue-charts-rendered', String(summary.rendered));
        document.documentElement.setAttribute('data-revenue-charts-failed', String(summary.failed));
        document.documentElement.setAttribute('data-revenue-chart-gate', summary.failed === 0 && summary.rendered === summary.expected ? 'PASS' : 'FAIL');
        window.__DDB_REVENUE_CHART_GATE__ = summary;
        return summary;
    }

    function syncModeFields() {
        var modeSelect = document.querySelector('[data-revenue-mode-select]');
        var form = document.querySelector('[data-revenue-filter-form]');
        if (!modeSelect || !form) {
            return false;
        }
        var isRange = modeSelect.value === 'range';
        all('[data-revenue-range-field]', form).forEach(function (field) {
            field.hidden = !isRange;
            field.setAttribute('aria-hidden', isRange ? 'false' : 'true');
        });
        all('[data-revenue-year-field]', form).forEach(function (field) {
            field.hidden = isRange;
            field.setAttribute('aria-hidden', isRange ? 'true' : 'false');
        });
        body.setAttribute('data-eri-year-fields-hidden', !isRange && all('[data-revenue-range-field]', form).every(function (field) { return field.hidden; }) ? 'true' : 'false');
        return true;
    }

    function updateTrendSummary(panel) {
        var host = document.querySelector('[data-eri-trend-summary]');
        if (!host || !panel) {
            return;
        }
        var map = [
            ['[data-eri-summary-current]', 'data-summary-current'],
            ['[data-eri-summary-comparison]', 'data-summary-comparison'],
            ['[data-eri-summary-change]', 'data-summary-change'],
            ['[data-eri-summary-best]', 'data-summary-best'],
            ['[data-eri-summary-weakest]', 'data-summary-weakest']
        ];
        map.forEach(function (entry) {
            var node = host.querySelector(entry[0]);
            if (node) {
                node.textContent = panel.getAttribute(entry[1]) || 'N/A';
            }
        });
        var changeCard = host.querySelector('.eri-v2-summary-change');
        if (changeCard) {
            changeCard.classList.remove('eri-v2-summary-change--positive', 'eri-v2-summary-change--negative', 'eri-v2-summary-change--neutral');
            changeCard.classList.add('eri-v2-summary-change--' + (panel.getAttribute('data-summary-change-class') || 'neutral'));
        }
    }

    function activateTrend(key, moveFocus) {
        var panels = all('[data-eri-trend-panel]');
        var tabs = all('[data-eri-trend-tab]');
        var activePanel = null;
        panels.forEach(function (panel) {
            var active = panel.getAttribute('data-eri-trend-panel') === key;
            panel.hidden = !active;
            panel.setAttribute('aria-hidden', active ? 'false' : 'true');
            if (active) {
                activePanel = panel;
            }
        });
        tabs.forEach(function (tab) {
            var active = tab.getAttribute('data-eri-trend-tab') === key;
            tab.setAttribute('aria-selected', active ? 'true' : 'false');
            tab.tabIndex = active ? 0 : -1;
            if (active && moveFocus) {
                tab.focus();
            }
        });
        if (activePanel) {
            updateTrendSummary(activePanel);
            window.setTimeout(function () {
                renderPanelChart(activePanel);
                updateDiagnostics();
            }, 40);
        }
    }

    function bindTrendTabs() {
        var tabs = all('[data-eri-trend-tab]');
        if (!tabs.length) {
            return false;
        }
        tabs.forEach(function (tab, index) {
            tab.addEventListener('click', function () {
                activateTrend(tab.getAttribute('data-eri-trend-tab') || '', false);
            });
            tab.addEventListener('keydown', function (event) {
                if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') {
                    return;
                }
                event.preventDefault();
                var direction = event.key === 'ArrowRight' ? 1 : -1;
                if (document.documentElement.getAttribute('dir') === 'rtl') {
                    direction *= -1;
                }
                var next = (index + direction + tabs.length) % tabs.length;
                activateTrend(tabs[next].getAttribute('data-eri-trend-tab') || '', true);
            });
        });
        var selected = tabs.filter(function (tab) { return tab.getAttribute('aria-selected') === 'true'; })[0] || tabs[0];
        activateTrend(selected.getAttribute('data-eri-trend-tab') || '', false);
        return true;
    }

    function updateDiagnostics() {
        var root = document.documentElement;
        var overflow = root.scrollWidth > root.clientWidth + 1;
        var stickyBottom = 0;
        all('header, [role="banner"], .topbar, .top-bar, .app-header, .elite-topbar').forEach(function (element) {
            var style = window.getComputedStyle(element);
            var rect = element.getBoundingClientRect();
            var isSticky = (style.position === 'sticky' || style.position === 'fixed') && rect.top <= 12 && rect.height > 0 && rect.height < 240 && rect.width >= window.innerWidth * 0.45;
            if (isSticky) {
                stickyBottom = Math.max(stickyBottom, rect.bottom);
            }
        });
        var firstSection = document.querySelector('.eri-v2-summary');
        var stickyOverlap = !!(firstSection && stickyBottom > 0 && firstSection.getBoundingClientRect().top < stickyBottom - 1);
        var priorities = all('[data-eri-priority-grid] .eri-v2-priority-card');
        var statusCard = document.querySelector('[data-eri-leadership-status]');
        var statusReady = !!statusCard && !/N\/A|غير متاح/i.test(statusCard.textContent || '');
        var trendTabs = all('[data-eri-trend-tab]');
        var trendWorkspace = document.querySelector('[data-eri-trend-workspace]');
        var decisionGrid = document.querySelector('[data-eri-decision-grid]');
        var rangeFields = all('[data-revenue-range-field]');
        var yearMode = (document.querySelector('[data-revenue-mode-select]') || {}).value === 'year';
        var yearFieldsHidden = !yearMode || rangeFields.every(function (field) { return field.hidden; });
        var totalPanel = document.querySelector('[data-eri-trend-panel="total"]');
        var monthExtremesReady = !!totalPanel && !/N\/A|غير متاح/i.test((totalPanel.getAttribute('data-summary-best') || '') + ' ' + (totalPanel.getAttribute('data-summary-weakest') || ''));
        var activeStage = document.querySelector('[data-eri-trend-panel]:not([hidden]) .eri-v2-chart-stage');
        var chartHeightBounded = true;
        if (activeStage) {
            var stageHeight = activeStage.getBoundingClientRect().height;
            chartHeightBounded = stageHeight >= 320 && stageHeight <= 540;
            body.setAttribute('data-eri-active-chart-height', String(Math.round(stageHeight)));
        }

        body.setAttribute('data-executive-revenue-v1', 'true');
        body.setAttribute('data-executive-revenue-v2', 'true');
        body.setAttribute('data-eri-summary-ready', priorities.length === 4 ? 'true' : 'false');
        body.setAttribute('data-eri-decision-ready', decisionGrid ? 'true' : 'false');
        body.setAttribute('data-eri-trend-ready', trendWorkspace && trendTabs.length === 5 ? 'true' : 'false');
        body.setAttribute('data-eri-leadership-status-ready', statusReady ? 'true' : 'false');
        body.setAttribute('data-eri-year-fields-hidden', yearFieldsHidden ? 'true' : 'false');
        body.setAttribute('data-eri-month-extremes-ready', monthExtremesReady ? 'true' : 'false');
        body.setAttribute('data-eri-chart-height-bounded', chartHeightBounded ? 'true' : 'false');
        body.setAttribute('data-eri-no-kpi-duplication', all('.revenue109-kpis').length === 1 ? 'true' : 'false');
        body.setAttribute('data-eri-direct-view', document.querySelector('[data-executive-revenue-v2]') ? 'true' : 'false');
        body.setAttribute('data-eri-overflow-x', overflow ? '1' : '0');
        body.setAttribute('data-eri-sticky-overlap', stickyOverlap ? '1' : '0');
        body.setAttribute('data-eri-ready', priorities.length === 4 && decisionGrid && trendWorkspace && trendTabs.length === 5 && statusReady && yearFieldsHidden && monthExtremesReady && chartHeightBounded && !overflow && !stickyOverlap ? 'true' : 'false');
        body.setAttribute('data-eri-viewport-width', String(root.clientWidth || window.innerWidth || 0));
    }

    function initialize() {
        if (!document.querySelector('[data-executive-revenue-v2]')) {
            return;
        }
        body.classList.add('eri-page-active', 'eri-v2-active');
        if (document.documentElement.getAttribute('dir') === 'rtl') {
            body.classList.add('eri-page-active--rtl');
        }

        var modeSelect = document.querySelector('[data-revenue-mode-select]');
        if (modeSelect) {
            modeSelect.addEventListener('change', function () {
                syncModeFields();
                updateDiagnostics();
            });
        }
        syncModeFields();
        bindTrendTabs();
        renderAllCharts();

        window.requestAnimationFrame(function () {
            window.requestAnimationFrame(updateDiagnostics);
        });
        window.addEventListener('resize', function () {
            window.requestAnimationFrame(function () {
                var activePanel = document.querySelector('[data-eri-trend-panel]:not([hidden])');
                if (activePanel) {
                    renderPanelChart(activePanel);
                }
                updateDiagnostics();
            });
        }, { passive: true });
    }

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