// public/assets/js/header.js
document.addEventListener('DOMContentLoaded', function () {
    const supportedLangs = ['de', 'en', 'it', 'fr'];

    // Globale Config aus PHP-Partial (app_config.php)
    const cfg     = window.usbConfig || {};
    const cfgLang = (cfg.lang || '').toLowerCase();

    function resolveCurrentLang() {
        const url        = new URL(window.location.href);
        const urlLang    = (url.searchParams.get('lang') || '').toLowerCase();
        const docLang    = (document.documentElement.getAttribute('lang') || '').toLowerCase();

        if (supportedLangs.includes(urlLang)) return urlLang;
        if (supportedLangs.includes(cfgLang)) return cfgLang;
        if (supportedLangs.includes(docLang)) return docLang;
        return 'de';
    }

    // --------------------------------------------------
    // LOGIN-BUTTON → /login mit redirect + lang
    // --------------------------------------------------
    const loginBtn = document.getElementById('loginButton');

    if (loginBtn) {
        loginBtn.addEventListener('click', function (event) {
            event.preventDefault();

            const currentPath  = window.location.pathname || '/';
            const currentQuery = window.location.search || '';
            const redirect     = currentPath + currentQuery;

            const lang = resolveCurrentLang();

            // Wenn wir bereits auf /login sind → nur zum #auth scrollen
            if (currentPath === '/login' || currentPath === '/login/') {
                const authEl = document.getElementById('auth');
                if (authEl) {
                    authEl.scrollIntoView({ behavior: 'smooth', block: 'start' });
                }
                return;
            }

            // Sonst: auf Login-Seite mit lang + redirect-Parameter
            const url = '/login/?lang=' + encodeURIComponent(lang) +
                '&redirect=' + encodeURIComponent(redirect) +
                '#auth';

            window.location.href = url;
        });
    }

    // --------------------------------------------------
    // AVATAR-MENÜ (userAvatar / userMenu)
    // --------------------------------------------------
    const avatarBtn = document.getElementById('userAvatar');
    const userMenu  = document.getElementById('userMenu');

    if (avatarBtn && userMenu) {
        avatarBtn.addEventListener('click', function (event) {
            event.stopPropagation();
            userMenu.classList.toggle('hidden');

            const expanded = avatarBtn.getAttribute('aria-expanded') === 'true';
            avatarBtn.setAttribute('aria-expanded', expanded ? 'false' : 'true');
        });

        // Klick außerhalb schließt Menü
        document.addEventListener('click', function (event) {
            if (userMenu.classList.contains('hidden')) {
                return;
            }

            const clickedInsideMenu   = userMenu.contains(event.target);
            const clickedAvatarButton = avatarBtn.contains(event.target);

            if (!clickedInsideMenu && !clickedAvatarButton) {
                userMenu.classList.add('hidden');
                avatarBtn.setAttribute('aria-expanded', 'false');
            }
        });
    }

    // --------------------------------------------------
    // LOGOUT-MODAL
    // --------------------------------------------------
    const logoutButtons = document.querySelectorAll('[data-logout-link="true"]');
    const backdrop      = document.getElementById('logoutModalBackdrop');
    const btnConfirm    = document.getElementById('logoutConfirm');
    const btnCancel     = document.getElementById('logoutCancel');

    let logoutTarget = null;

    function showLogoutModal(targetHref) {
        logoutTarget = targetHref || null;
        if (!backdrop) return;

        backdrop.classList.remove('hidden');
        document.body.classList.add('overflow-hidden');
    }

    function hideLogoutModal() {
        if (!backdrop) return;
        backdrop.classList.add('hidden');
        document.body.classList.remove('overflow-hidden');
        logoutTarget = null;
    }

    if (logoutButtons.length && backdrop && btnConfirm && btnCancel) {
        logoutButtons.forEach(function (btn) {
            btn.addEventListener('click', function (event) {
                event.preventDefault();
                event.stopPropagation();

                const href = btn.getAttribute('data-logout-href')
                    || btn.getAttribute('href')
                    || '/auth/logout';

                showLogoutModal(href);

                // Avatar-Menü beim Öffnen des Modals schließen
                if (userMenu && !userMenu.classList.contains('hidden')) {
                    userMenu.classList.add('hidden');
                    if (avatarBtn) {
                        avatarBtn.setAttribute('aria-expanded', 'false');
                    }
                }
            });
        });

        // Bestätigen → weiter zur Logout-URL
        btnConfirm.addEventListener('click', function () {
            if (logoutTarget) {
                window.location.href = logoutTarget;
            } else {
                window.location.href = '/auth/logout';
            }
        });

        // Abbrechen → Modal schließen
        btnCancel.addEventListener('click', function () {
            hideLogoutModal();
        });

        // Klick auf Hintergrund schließt Modal (außer man klickt auf die Card)
        backdrop.addEventListener('click', function (event) {
            const card = backdrop.querySelector('.max-w-sm');
            if (card && !card.contains(event.target)) {
                hideLogoutModal();
            }
        });

        // ESC-Taste schließt Modal
        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape' && !backdrop.classList.contains('hidden')) {
                hideLogoutModal();
            }
        });
    }
});
