<div class="mbkauthe-header-actions">
    {{#if userLoggedIn}}
    <div class="mbkauthe-profile-menu">
        <button class="mbkauthe-profile-trigger" type="button" aria-expanded="false" aria-haspopup="true">
            <img src="/mbkauthe/user/profilepic?u={{username}}" alt="Profile" class="mbkauthe-profile-avatar">
        </button>
        <div class="mbkauthe-profile-dropdown" role="menu" hidden>
            <a class="mbkauthe-profile-item" role="menuitem" title="{{username}}">
                <span>@{{username}}</span>
            </a>
            <a class="mbkauthe-profile-item" href="https://portal.mbktech.org/user/settings" role="menuitem"
                title="Settings">
                <i class="fas fa-cog"></i>
                <span>Settings</span>
            </a>
            <a class="mbkauthe-profile-item" href="/mbkauthe/accounts" role="menuitem"
                title="Switch or Add another Account">
                <i class="fa fa-user-group"></i>
                <span>Switch account</span>
            </a>
            <button class="mbkauthe-profile-item" type="button" data-theme-toggle role="menuitem" title="Switch theme">
                <i class="fas fa-circle-half-stroke"></i>
                <span data-theme-label>Switch to light theme</span>
            </button>
            <button class="mbkauthe-profile-item" type="button" data-action="logout" role="menuitem" title="Logout">
                <i class="fas fa-sign-out-alt"></i>
                <span>Logout</span>
            </button>
        </div>
    </div>
    {{else}}
    <a class="mbkauthe-btn-login link-no-decoration" href="/mbkauthe/login"><i
            class="fas fa-sign-in-alt"></i>
        Login</a>
    {{/if}}
</div>
<style>
    .mbkauthe-btn-login {
        width: 100%;
        color: var(--accent);
        font-weight: 700;
        font-size: 1.5rem;
        cursor: pointer;
        transition: all 0.4s cubic-bezier(.4, 0, .2, 1);
    }

    .mbkauthe-btn-login:hover {
        color: var(--light);
    }

    .mbkauthe-btn-login:disabled {
        background: var(--dark);
        color: var(--accent);
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
    }

    .mbkauthe-header-actions {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        margin-left: auto;
    }

    .mbkauthe-profile-menu {
        position: relative;
    }

    .mbkauthe-profile-trigger {
        width: 45px;
        height: 45px;
        border-radius: 999px;
        border: 1px solid var(--muted-border);
        background: var(--surface-soft);
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: var(--transition);
    }

    .mbkauthe-profile-trigger:hover {
        border-color: var(--accent);
        box-shadow: 0 10px 30px rgba(0, 184, 148, 0.2);
    }

    .mbkauthe-profile-trigger:focus-visible {
        outline: 2px solid var(--accent);
        outline-offset: 2px;
    }

    .mbkauthe-profile-avatar {
        width: 40px;
        height: 40px;
        border-radius: 999px;
        object-fit: cover;
        background: var(--surface-1);
    }

    .mbkauthe-profile-dropdown {
        position: absolute;
        right: 0;
        top: calc(100% + 0.5rem);
        background: var(--surface-1);
        border: 1px solid var(--muted-border);
        border-radius: var(--border-radius);
        min-width: 190px;
        box-shadow: var(--box-shadow);
        padding: 0;
        opacity: 0;
        visibility: hidden;
        transform: translateY(-6px);
        transition: var(--transition);
        z-index: 1000;
        backdrop-filter: blur(6px);
        -webkit-backdrop-filter: blur(6px);
        color: var(--text);
        overflow: hidden;
    }

    .mbkauthe-profile-dropdown.open {
        display: block;
        opacity: 1;
        visibility: visible;
        transform: translateY(0);
        border-radius: 3%;
    }

    .mbkauthe-profile-item {
        width: 100%;
        display: flex;
        align-items: center;
        gap: 0.6rem;
        padding: 0.85rem 1rem;
        color: var(--text);
        background: transparent;
        border: none;
        text-decoration: none;
        text-align: left;
        font-weight: 600;
        letter-spacing: 0.01em;
        cursor: pointer;
        transition: background 0.12s ease, color 0.12s ease, transform 0.12s ease;
    }

    .mbkauthe-profile-item:hover {
        background: color-mix(in srgb, var(--accent) 10%, transparent 90%);
        color: var(--accent);
    }

    .mbkauthe-profile-item:focus-visible {
        outline: 2px solid color-mix(in srgb, var(--accent) 40%, transparent 60%);
        outline-offset: 2px;
    }

    .mbkauthe-profile-item:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }

    .mbkauthe-profile-item i {
        width: 18px;
        text-align: center;
    }
</style>
<script>
    (() => {
        const html = document.documentElement;
        const themeToggles = document.querySelectorAll('[data-theme-toggle]');

        const getTheme = () => html.getAttribute('data-theme') === 'light' ? 'light' : 'dark';

        const applyTheme = (theme) => {
            html.setAttribute('data-theme', theme);
            localStorage.setItem('mbkauthe-theme', theme);

            const isLight = theme === 'light';
            themeToggles.forEach((btn) => {
                const labelEl = btn.querySelector('[data-theme-label]');
                btn.setAttribute('aria-label', isLight ? 'Switch to dark theme' : 'Switch to light theme');
                btn.setAttribute('title', isLight ? 'Switch to dark theme' : 'Switch to light theme');
                if (labelEl) {
                    labelEl.textContent = isLight ? 'Switch to dark theme' : 'Switch to light theme';
                }
            });
        };

        themeToggles.forEach((btn) => {
            btn.addEventListener('click', () => {
                const currentTheme = getTheme();
                const nextTheme = currentTheme === 'dark' ? 'light' : 'dark';
                applyTheme(nextTheme);
            });
        });

        applyTheme(getTheme());

        const mbkTrigger = document.querySelector('.mbkauthe-profile-trigger');
        const mbkDropdown = document.querySelector('.mbkauthe-profile-dropdown');

        if (!mbkTrigger || !mbkDropdown) {
            return;
        }

        const closeMenu = () => {
            if (!mbkDropdown.classList.contains('open')) return;
            mbkDropdown.classList.remove('open');
            mbkTrigger.setAttribute('aria-expanded', 'false');
            // After transition, hide to prevent FOUC on next paint
            const onTransition = (e) => {
                if (e.propertyName === 'opacity') {
                    mbkDropdown.setAttribute('hidden', '');
                    mbkDropdown.removeEventListener('transitionend', onTransition);
                }
            };

            mbkDropdown.addEventListener('transitionend', onTransition);
            // Fallback in case transitionend doesn't fire
            setTimeout(() => {
                if (!mbkDropdown.classList.contains('open')) {
                    mbkDropdown.setAttribute('hidden', '');
                }
            }, 350);
        };

        mbkTrigger.addEventListener('click', (event) => {
            event.stopPropagation();
            const isOpening = !mbkDropdown.classList.contains('open');
            if (isOpening) {
                // Reveal then start transition to open state
                mbkDropdown.removeAttribute('hidden');
                // Ensure the class add happens on next frame for transition to work
                requestAnimationFrame(() => {
                    mbkDropdown.classList.add('open');
                    mbkTrigger.setAttribute('aria-expanded', 'true');
                });
            } else {
                // Close the menu
                closeMenu();
            }
        });

        document.addEventListener('click', (event) => {
            if (!mbkDropdown.contains(event.target) && !mbkTrigger.contains(event.target)) {
                closeMenu();
            }
        });

        document.addEventListener('keydown', (event) => {
            if (event.key === 'Escape') {
                closeMenu();
            }
        });

        const logoutButton = mbkDropdown.querySelector('[data-action="logout"]');
        if (logoutButton) {
            logoutButton.addEventListener('click', async () => {
                const originalLabel = logoutButton.textContent;
                logoutButton.disabled = true;
                logoutButton.textContent = 'Logging out...';

                try {
                    const response = await fetch('/mbkauthe/api/logout', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        credentials: 'include'
                    });

                    const result = await response.json().catch(() => ({}));

                    if (response.ok) {
                        window.location.reload();
                    } else {
                        alert(result.message || 'Logout failed. Please try again.');
                    }
                } catch (error) {
                    console.error(`[mbkauthe] Error during logout:`, error);
                    alert('Logout failed. Please try again.');
                } finally {
                    logoutButton.disabled = false;
                    logoutButton.textContent = originalLabel;
                    closeMenu();
                }
            });
        }

        // Populate the "Switch account" link with encoded current page URL in its `redirect` param
        (function setSwitchAccountRedirect() {
            const switchAccountLink = mbkDropdown.querySelector('a[href^="/mbkauthe/accounts"]');
            if (!switchAccountLink) return;

            try {
                const currentUrl = window.location.href;
                // Ensure the href uses the base path up to ?redirect= and append the encoded current URL
                const baseHref = switchAccountLink.href.split('?redirect=')[0] + '?redirect=';
                switchAccountLink.href = baseHref + encodeURIComponent(currentUrl);
            } catch (err) {
                // non-fatal, but log for debugging
                console.error(`[mbkauthe] Failed to set redirect URL for switch account link`, err);
            }
        })();
    })();
</script>