<!DOCTYPE html>
<html lang="en">

{{> head pageTitle="Switch Account" ogUrl="/mbkauthe/accounts"}}

<body>
    {{> header}}
    {{> showmessage}}

    <section class="login-container account-switch">
        {{> backgroundElements}}

        <div class="login-box">
            <div class="login-box-inner">
                <!-- Left Column: Branding & Secondary Actions -->
                <div class="login-sidebar">
                    <div class="sidebar-content">
                        <div class="brand-section">
                            <div class="logo logo-centered">
                                <img src="/icon.svg" alt="Logo" class="logo-image">
                                <span class="logo-text">BK <span>Tech</span></span>
                            </div>
                            <h2 class="brand-title">Welcome to MBKAuthe</h2>
                            <p class="brand-description">Secure authentication for MBKTech.org services</p>
                        </div>

                        <div class="sidebar-actions">
                            <a href="/mbkauthe/login" id="useAnother" class="btn-social btn-switch-side">
                                <i class="fas fa-sign-in-alt"></i>
                                <span>Log in to another account</span>
                            </a>
                        </div>

                        <div class="sidebar-links">
                            <a href="https://portal.mbktech.org/forgot-password" class="sidebar-link">
                                <i class="fas fa-key"></i> Forgot Password?
                            </a>
                            <a href="https://mbktech.org/Support" target="_blank" class="sidebar-link">
                                <i class="fas fa-life-ring"></i> Need Help?
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Right Column: Account List -->
                <div class="login-main">
                    <h1 class="login-title">Choose an account</h1>
                    <p class="subtitle">to continue to <span class="highlight">{{appName}}</span></p>

                    <div id="accountList" class="account-list" aria-live="polite">
                        <!-- Loading state -->
                        <div class="loading-spinner">
                            <div class="spinner"></div>
                        </div>
                    </div>

                    <div id="emptyState" class="empty-state hidden-by-default">
                        <p>No signed-in accounts found.</p>
                        <a href="/mbkauthe/login" class="btn-login btn-login-inline">Go
                            to Login</a>
                    </div>

                    <div class="switch-footer">
                        <button class="btn-social btn-logout" id="logoutAll">
                            <i class="fas fa-sign-out-alt"></i>
                            <span>Sign out of all accounts</span>
                        </button>
                    </div>

                    <!-- Mobile/Tablet Only: Social & Secondary Actions -->
                    <div class="mobile-actions">
                        <a href="/mbkauthe/login" class="btn-social mobile-switch-btn">
                            <i class="fas fa-sign-in-alt"></i>
                            <span>Log in to another account</span>
                        </a>

                        <button class="btn-social btn-logout mobile-logout-btn">
                            <i class="fas fa-sign-out-alt"></i>
                            <span>Sign out of all accounts</span>
                        </button>

                        <div class="login-links">
                            <a href="https://portal.mbktech.org/forgot-password" class="login-link">Forgot Password?</a>
                            <a href="https://mbktech.org/Support" target="_blank" class="login-link">Need Help?</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <style>
        /* Specific styles for account switch list to match login theme */
        .subtitle {
            font-size: 15px;
            color: var(--text-light);
            margin: -20px 0 30px;
            text-align: center;
        }

        .highlight {
            color: var(--accent);
            font-weight: 600;
        }

        .account-list {
            display: flex;
            flex-direction: column;
            gap: 12px;
            margin-bottom: 20px;
            width: 100%;
            max-width: 420px;
            margin-left: auto;
            margin-right: auto;
        }

        .account-item {
            display: flex;
            align-items: center;
            gap: 16px;
            padding: 14px 20px;
            background: var(--input-bg);
            border: 2px solid color-mix(in srgb, var(--accent) 22%, transparent 78%);
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: var(--transition);
            text-align: left;
            width: 100%;
            position: relative;
            overflow: hidden;
        }

        .account-item:hover {
            background: var(--input-bg-focus);
            border-color: var(--accent);
            box-shadow: 0 4px 15px rgba(0, 184, 148, 0.15);
        }

        .avatar {
            width: 42px;
            height: 42px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 18px;
            flex-shrink: 0;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
            position: relative;
            overflow: hidden;
        }

        .avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            display: block;
            border-radius: 50%;
        }

        .avatar .initials {
            position: absolute;
            inset: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 18px;
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.02), rgba(255, 255, 255, 0));
        }

        .account-info {
            flex: 1;
            min-width: 0;
        }

        .account-name {
            font-weight: 600;
            color: var(--text);
            font-size: 16px;
            margin-bottom: 2px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .account-email {
            color: var(--text-light);
            font-size: 13px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .current-badge {
            font-size: 11px;
            font-weight: 700;
            color: var(--accent);
            background: rgba(0, 184, 148, 0.15);
            padding: 4px 10px;
            border-radius: 20px;
            border: 1px solid rgba(0, 184, 148, 0.3);
            white-space: nowrap;
        }

        .switch-footer {
            margin-top: auto;
            padding-top: 20px;
            text-align: center;
            width: 100%;
            display: flex;
            justify-content: center;
        }

        .btn-logout {
            background: var(--surface-soft);
            color: var(--text-light);
            border-color: var(--muted-border);
            width: 100%;
            max-width: 420px;
            cursor: pointer;
            font-family: inherit;
        }

        .btn-logout:hover {
            background: rgba(255, 118, 117, 0.1);
            border-color: var(--danger);
            color: var(--danger);
            box-shadow: 0 4px 15px rgba(255, 118, 117, 0.15);
        }

        [data-theme="light"] .account-item {
            background: rgba(255, 255, 255, 0.95);
            border-color: rgba(0, 184, 148, 0.18);
        }

        [data-theme="light"] .account-item:hover {
            background: rgba(255, 255, 255, 1);
        }

        [data-theme="light"] .btn-social.btn-logout {
            background: var(--accent);
            color: #ffffff;
            border-color: var(--accent);
        }

        [data-theme="light"] .btn-social.btn-logout:hover {
            background: rgba(255, 118, 117, 0.1);
            border-color: var(--danger);
            color: var(--danger);
            box-shadow: 0 4px 15px rgba(255, 118, 117, 0.15);
        }

        .loading-spinner {
            display: flex;
            justify-content: center;
            padding: 40px;
        }

        .spinner {
            width: 30px;
            height: 30px;
            border: 3px solid var(--muted-border);
            border-top-color: var(--accent);
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        .empty-state {
            text-align: center;
            padding: 30px;
            color: var(--text-light);
            background: var(--surface-muted);
            border-radius: var(--border-radius);
            border: 1px dashed var(--muted-border);
        }

        /* Mobile adjustments */
        @media (max-width: 992px) {
            .account-list {
                max-width: 100%;
            }

            .switch-footer {
                display: none;
            }

            .mobile-actions {
                display: flex;
                flex-direction: column;
                gap: 12px;
                margin-top: 30px;
                padding-top: 20px;
                border-top: 1px solid var(--muted-border);
            }

            .mobile-switch-btn,
            .mobile-logout-btn {
                width: 100%;
                justify-content: center;
                margin: 0;
                padding: 14px;
                font-size: 15px;
                border-radius: var(--border-radius);
                display: flex;
                align-items: center;
                gap: 10px;
                text-decoration: none;
                transition: var(--transition);
            }

            .mobile-switch-btn {
                background: var(--surface-soft);
                border: 1px solid var(--muted-border);
                color: var(--text);
            }

            .mobile-switch-btn:hover {
                background: color-mix(in srgb, var(--accent) 10%, var(--surface-soft) 90%);
                border-color: var(--accent);
                color: var(--accent);
                box-shadow: 0 4px 15px rgba(0, 184, 148, 0.15);
            }

            .login-links {
                justify-content: center;
                gap: 20px;
                margin-top: 10px;
            }
        }
    </style>

    <script>
        const redirectTarget = new URLSearchParams(window.location.search).get('redirect') || '{{customURL}}';

        // Ensure login anchors include ?redirect using the redirect query param (not the current page URL)
        (function setLoginHrefFromQuery() {
            try {
                const encoded = redirectTarget ? encodeURIComponent(redirectTarget) : '';

                const useAnotherLink = document.getElementById('useAnother');
                if (useAnotherLink) {
                    useAnotherLink.href = `/mbkauthe/login${encoded ? `?redirect=${encoded}` : ''}`;
                }

                const mobileLink = document.querySelector('.mobile-switch-btn');
                if (mobileLink) {
                    mobileLink.href = `/mbkauthe/login${encoded ? `?redirect=${encoded}` : ''}`;
                }

                const emptyStateLink = document.querySelector('#emptyState a.btn-login');
                if (emptyStateLink) {
                    emptyStateLink.href = `/mbkauthe/login${encoded ? `?redirect=${encoded}` : ''}`;
                }
            } catch (err) {
                console.error(`[mbkauthe] Failed to set login hrefs with redirect query param:`, err);
            }
        })();

        // Handle "Log in to another account" click
        const useAnotherBtn = document.getElementById('useAnother');
        if (useAnotherBtn) {
            useAnotherBtn.addEventListener('click', (e) => {
                e.preventDefault();
                window.location.href = `/mbkauthe/login?redirect=${encodeURIComponent(redirectTarget)}`;
            });
        }

        // Also handle mobile button
        const mobileSwitchBtn = document.querySelector('.mobile-switch-btn');
        if (mobileSwitchBtn) {
            mobileSwitchBtn.addEventListener('click', (e) => {
                e.preventDefault();
                window.location.href = `/mbkauthe/login?redirect=${encodeURIComponent(redirectTarget)}`;
            });
        }

        async function loadAccounts() {
            const list = document.getElementById('accountList');
            const empty = document.getElementById('emptyState');

            try {
                const res = await fetch('/mbkauthe/api/account-sessions', { credentials: 'include' });
                const data = await res.json();
                const accounts = Array.isArray(data.accounts) ? data.accounts : [];
                const currentId = data.currentSessionId || null;

                list.innerHTML = '';

                if (!accounts.length) {
                    empty.style.display = 'block';
                    return;
                }

                empty.style.display = 'none';

                accounts.slice(0, 5).forEach(acct => {
                    const isCurrent = acct.isCurrent || (currentId && acct.sessionId === currentId);
                    const initial = (acct.fullName || acct.username || '?').charAt(0).toUpperCase();

                    const item = document.createElement('div');
                    item.className = 'account-item';
                    item.role = 'button';
                    item.tabIndex = 0;

                    // Build avatar with image (if available) and initials fallback to avoid HTML injection
                    const avatar = document.createElement('div');
                    avatar.className = 'avatar';

                    const initials = document.createElement('div');
                    initials.className = 'initials';
                    initials.textContent = initial;
                    initials.style.display = acct.image ? 'none' : 'flex';

                    if (acct.image) {
                        const img = document.createElement('img');
                        img.className = 'avatar-img';
                        img.src = acct.image;
                        img.alt = `Avatar for ${acct.username}`;
                        img.loading = 'lazy';
                        img.decoding = 'async';
                        img.onerror = function () { img.style.display = 'none'; initials.style.display = 'flex'; };
                        avatar.appendChild(img);
                    }

                    avatar.appendChild(initials);

                    const info = document.createElement('div');
                    info.className = 'account-info';
                    info.innerHTML = `
                        <div class="account-name">${acct.fullName || acct.username}</div>
                        <div class="account-email">${acct.username}</div>
                    `;

                    item.appendChild(avatar);
                    item.appendChild(info);
                    if (isCurrent) {
                        const badge = document.createElement('div');
                        badge.className = 'current-badge';
                        badge.textContent = 'Current';
                        item.appendChild(badge);
                    };

                    item.addEventListener('click', () => {
                        if (!isCurrent) {
                            switchSession(acct.sessionId);
                        }
                    });

                    // Add keyboard support
                    item.addEventListener('keydown', (e) => {
                        if (e.key === 'Enter' || e.key === ' ') {
                            e.preventDefault();
                            if (!isCurrent) switchSession(acct.sessionId);
                        }
                    });

                    list.appendChild(item);
                });

            } catch (err) {
                console.error(`[mbkauthe] Failed to load accounts:`, err);
                list.innerHTML = '<div class="empty-state">Failed to load accounts.</div>';
            }
        }

        async function switchSession(sessionId) {
            try {
                const res = await fetch('/mbkauthe/api/switch-session', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include',
                    body: JSON.stringify({ sessionId, redirect: redirectTarget })
                });
                const data = await res.json();
                if (res.ok && data.success) {
                    // Prioritize explicit ?redirect if present and valid, else fall back to server-provided redirect or template
                    const params = new URLSearchParams(window.location.search);
                    let queryRedirect = null;
                    if (params.has('redirect')) {
                        try {
                            const raw = params.get('redirect');
                            if (raw) queryRedirect = decodeURIComponent(raw);
                        } catch (e) {
                            queryRedirect = null;
                        }
                    }
                    const finalRedirect = queryRedirect || data.redirect || redirectTarget;
                    if (finalRedirect) window.location.href = finalRedirect;
                } else {
                    showMessage(data.message || 'Could not switch account', 'Switch Account');
                    loadAccounts();
                }
            } catch (err) {
                console.error(`[mbkauthe] Switch failed:`, err);
                showMessage('Could not switch account right now. Please try again.', 'Switch Account');
            }
        }

        async function logoutAll() {
            if (!confirm('Are you sure you want to sign out of all accounts on this device?')) return;
            try {
                const res = await fetch('/mbkauthe/api/logout-all', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include'
                });
                const data = await res.json();
                if (res.ok && data.success) {
                    window.location.href = `/mbkauthe/login?redirect=${encodeURIComponent(redirectTarget)}`;
                } else {
                    showMessage(data.message || 'Could not sign out all accounts', 'Sign out');
                }
            } catch (err) {
                console.error(`[mbkauthe] Sign-out-all failed:`, err);
                showMessage('Could not sign out all accounts right now. Please try again.', 'Sign out');
            }
        }

        const logoutBtn = document.getElementById('logoutAll');
        if (logoutBtn) logoutBtn.addEventListener('click', logoutAll);

        const mobileLogoutBtn = document.querySelector('.mobile-logout-btn');
        if (mobileLogoutBtn) mobileLogoutBtn.addEventListener('click', logoutAll);

        document.addEventListener('DOMContentLoaded', loadAccounts);
    </script>
</body>

</html>