/**
 * Global connectivity: offline banner, back-online notice, AJAX hint when network is down.
 * Expects window.BV_CONNECTIVITY { offline, offlineDetail, online } from common/js.php (optional).
 * Each value may be a string (legacy) or { en: string, ar: string } for bilingual admin messages.
 */
(function () {
    'use strict';

    var cfg = window.BV_CONNECTIVITY || {};

    function pickEnAr(val, legacyFallback) {
        if (val && typeof val === 'object' && (val.en !== undefined || val.ar !== undefined)) {
            return {
                en: String(val.en !== undefined && val.en !== null ? val.en : ''),
                ar: String(val.ar !== undefined && val.ar !== null ? val.ar : ''),
            };
        }
        var s = val !== undefined && val !== null && val !== '' ? String(val) : legacyFallback;
        return { en: s, ar: '' };
    }

    var offlineTitle = pickEnAr(cfg.offline, 'No internet connection');
    var offlineDetail = pickEnAr(
        cfg.offlineDetail,
        'You appear to be offline. Check your connection and try again.'
    );
    var onlinePair = pickEnAr(cfg.online, 'You are back online.');

    function escapeHtml(text) {
        var d = document.createElement('div');
        d.textContent = text;
        return d.innerHTML;
    }

    function formatBilingualBlock(pair) {
        var en = pair.en;
        var ar = pair.ar;
        if (!ar || ar === en) {
            return escapeHtml(en);
        }
        return (
            '<div class="bv-bilingual-stack">' +
            '<div dir="ltr" lang="en" class="bv-bilingual-en">' +
            escapeHtml(en) +
            '</div>' +
            '<div dir="rtl" lang="ar" class="bv-bilingual-ar">' +
            escapeHtml(ar) +
            '</div>' +
            '</div>'
        );
    }

    function ensureBanner() {
        var el = document.getElementById('bv-offline-banner');
        if (el) {
            return el;
        }
        el = document.createElement('div');
        el.id = 'bv-offline-banner';
        el.className = 'bv-offline-banner';
        el.setAttribute('role', 'alert');
        el.setAttribute('aria-live', 'assertive');
        el.innerHTML =
            '<div class="bv-offline-banner__inner">' +
            '<span class="bv-offline-banner__icon" aria-hidden="true">\u26A0</span>' +
            '<div class="bv-offline-banner__text">' +
            '<div class="bv-offline-banner__title">' +
            formatBilingualBlock(offlineTitle) +
            '</div>' +
            '<div class="bv-offline-banner__detail">' +
            formatBilingualBlock(offlineDetail) +
            '</div>' +
            '</div></div>';
        document.body.appendChild(el);
        return el;
    }

    function setVisible(show) {
        var el = document.getElementById('bv-offline-banner');
        if (!show) {
            if (el) {
                el.classList.remove('bv-offline-banner--visible');
            }
            return;
        }
        ensureBanner();
        document.getElementById('bv-offline-banner').classList.add('bv-offline-banner--visible');
    }

    var onlineToastHideTimer;
    var onlineToastVisibleMs = 10000;

    function showOnlineToast() {
        var t = document.getElementById('bv-online-toast');
        if (!t) {
            t = document.createElement('div');
            t.id = 'bv-online-toast';
            t.className = 'bv-online-toast';
            t.setAttribute('role', 'status');
            t.setAttribute('aria-live', 'polite');
            document.body.appendChild(t);
        }
        t.innerHTML = formatBilingualBlock(onlinePair);
        t.classList.add('bv-online-toast--visible');
        if (onlineToastHideTimer) {
            clearTimeout(onlineToastHideTimer);
        }
        onlineToastHideTimer = setTimeout(function () {
            t.classList.remove('bv-online-toast--visible');
        }, onlineToastVisibleMs);
    }

    function syncState() {
        if (typeof navigator !== 'undefined' && navigator.onLine === false) {
            ensureBanner();
            setVisible(true);
        } else {
            setVisible(false);
        }
    }

    window.addEventListener('offline', function () {
        ensureBanner();
        setVisible(true);
    });

    window.addEventListener('online', function () {
        setVisible(false);
        showOnlineToast();
    });

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', syncState);
    } else {
        syncState();
    }

    function bindJqAjax() {
        if (!window.jQuery) {
            return;
        }
        jQuery(document).ajaxError(function (_event, jqXHR, settings) {
            if (!settings || settings.crossDomain) {
                return;
            }
            if (jqXHR.status !== 0) {
                return;
            }
            if (typeof navigator !== 'undefined' && navigator.onLine === false) {
                ensureBanner();
                setVisible(true);
            }
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', bindJqAjax);
    } else {
        bindJqAjax();
    }
})();
