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

{{> head pageTitle="Login" ogUrl="/mbkauthe/login"}}

<body>
    {{> header}}

    <style>
        .last-used-parent {
            position: relative;
        }

        .last-used-badge {
            position: absolute;
            top: -8px;
            right: -8px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 26px;
            height: 20px;
            padding: 0 6px;
            font-size: 11px;
            font-weight: 700;
            background: var(--accent);
            color: #fff;
            border-radius: 999px;
            border: 2px solid var(--muted-border);
            z-index: 30;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25);
            line-height: 1;
            text-transform: none;
        }

        /* Ensure login button has reasonable space for badge */
        #loginButton {
            position: relative;
            overflow: visible;
        }

        .mobile-github-btn,
        .mobile-google-btn,
        .btn-social {
            position: relative;
            overflow: visible;
        }

        .form-row-split {
            align-items: center;
        }

        @media (max-width: 1000px) {
            .login-box {
                position: relative;
                background: var(--glass-bg);
                overflow: hidden;
            }

            .login-box::before {
                content: "";
                position: absolute;
                inset: 0;
                background: linear-gradient(135deg,
                        color-mix(in srgb, var(--primary) 16%, transparent 84%),
                        color-mix(in srgb, var(--accent) 16%, transparent 84%));
                pointer-events: none;
                z-index: 0;
            }

            .login-box>* {
                position: relative;
                z-index: 1;
            }
        }
    </style>

    {{> showmessage}}

    <section class="login-container">

        {{> 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">
                            {{#if githubLoginEnabled }}
                            <a type="button" id="githubLoginBtn" class="btn-social btn-switch-side last-used-parent">
                                <i class="fab fa-github"></i>
                                <span>Login with GitHub</span>
                                {{#if lastLoginGithub}}<span class="last-used-badge" aria-hidden="true"
                                    title="Last used">Last</span>{{/if}}
                            </a>
                            {{/if}}
                            {{#if googleLoginEnabled }}
                            <a type="button" id="googleLoginBtn" class="btn-social btn-google-side last-used-parent">
                                <i class="fab fa-google"></i>
                                <span>Login with Google</span>
                                {{#if lastLoginGoogle}}<span class="last-used-badge" aria-hidden="true"
                                    title="Last used">Last</span>{{/if}}
                            </a>
                            {{/if}}
                            <a href="/mbkauthe/accounts" id="switchacc" class="btn-social btn-switch-side">
                                <i class="fa fa-user-group"></i>
                                <span>Switch 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: Main Login Form -->
                <div class="login-main">
                    <h1 class="login-title">Login</h1>

                    <form id="loginForm" method="POST" class="login-form">
                        <input type="hidden" name="_csrf" value="{{csrfToken}}">
                        <div class="form-group">
                            <input id="loginUsername" class="form-input" type="text" name="username" placeholder=" "
                                required pattern="^[a-z0-9.]+$"
                                title="Username must contain lowercase letters, numbers, and periods only, no spaces, no special characters."
                                oninput="this.value = this.value.toLowerCase().replace(/[^a-z0-9.]/g, '')" />
                            <label class="form-label">Username</label>
                            <i class="fas fa-info-circle input-icon" onclick="usernameinfo()"></i>
                        </div>

                        <div class="form-group">
                            <input id="loginPassword" class="form-input" type="password" name="Password" placeholder=""
                                required minlength="8" title="Password must be at least 8 characters long" />
                            <label class="form-label">Password</label>
                            <i class="fas fa-eye input-icon" id="togglePassword"></i>
                        </div>

                        <div class="form-row-split">
                            <div class="remember-me remember-me-inline">
                                <input type="checkbox" id="rememberMe" name="rememberMe">
                                <label for="rememberMe">Remember me</label>
                            </div>

                            <a href="https://portal.mbktech.org/forgot-password" class="login-link login-link-nowrap">Forgot Password?</a>
                        </div>

                        <button type="submit" class="btn-login last-used-parent" id="loginButton">
                            <span id="loginButtonText">Login</span>
                            {{#if lastLoginPassword}}<span class="last-used-badge" aria-hidden="true"
                                title="Last used">Last</span>{{/if}}
                        </button>
                        {{#if userLoggedIn }}
                        <div class="WarningboxInfo already-logged-info">
                            <strong>You are already logged in as</strong>
                            <span class="username">"<span id="headerProfileUserName">{{username}}</span>"</span>.
                            <div>
                                <a class="terms-link" href="{{customURL}}">Go to dashboard</a>
                                or
                                <a class="terms-link" href="/mbkauthe/accounts">switch account</a>.
                            </div>
                        </div>
                        {{/if}}
                        <!-- Mobile/Tablet Only: Social & Secondary Actions -->
                        <div class="mobile-actions">
                            {{#if githubLoginEnabled }}
                            {{#if googleLoginEnabled }}
                            <div class="social-login">
                                <div class="divider">
                                    <span>or</span>
                                </div>
                                <div class="social-icons-row">
                                    <a type="button" class="swi s mobile-github-btn last-used-parent"
                                        title="Login with GitHub">
                                        <i class="fab fa-github"></i>
                                        {{#if lastLoginGithub}}<span class="last-used-badge" aria-hidden="true"
                                            title="Last used">Last</span>{{/if}}
                                    </a>
                                    <a type="button" class="swi s mobile-google-btn last-used-parent"
                                        title="Login with Google">
                                        <i class="fab fa-google"></i>
                                        {{#if lastLoginGoogle}}<span class="last-used-badge" aria-hidden="true"
                                            title="Last used">Last</span>{{/if}}
                                    </a>
                                </div>
                            </div>
                            {{/if}}
                            {{/if}}

                            {{#if githubLoginEnabled }}
                            {{#if googleLoginEnabled }}
                            <div class="divider">
                                <span>or</span>
                            </div>
                            {{/if}}
                            {{/if}}

                            <a href="/mbkauthe/accounts" class="swi btn-social btn-switch-side">
                                <i class="fa fa-user-group"></i>
                                <span>Switch Account</span>
                            </a>

                        </div>

                        <p class="terms-info">
                            By logging in, you agree to our
                            <a href="https://mbktech.org/PrivacyPolicy" target="_blank" class="terms-link">Terms &
                                Conditions</a>
                            and
                            <a href="https://mbktech.org/PrivacyPolicy" target="_blank" class="terms-link">Privacy
                                Policy</a>.
                        </p>
                    </form>
                </div>
            </div>
        </div>
        </div>
    </section>

    {{> versionInfo}}

    <script>
        // Toggle password visibility
        const togglePassword = document.getElementById('togglePassword');
        const passwordInput = document.getElementById('loginPassword');

        togglePassword.addEventListener('click', function () {
            const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
            passwordInput.setAttribute('type', type);
            togglePassword.classList.toggle('fa-eye');
            togglePassword.classList.toggle('fa-eye-slash');
        });

        function fpass() {
            showMessage(`If you have forgotten your password, please contact support at <a href="https://mbktech.org/Support" target="_blank">https://mbktech.org/Support</a> to reset it.`, `Forgot Password`);
        }

        // Info dialogs
        function usernameinfo() {
            showMessage(`Your username is the part of your MBKTech.org email before the @ (e.g., abc.xyz@mbktech.org → abc.xyz). For guests or if you’ve forgotten your credentials, contact <a href="https://mbktech.org/Support">Support</a>.`, `What is my username?`);
        }

        function tokeninfo() {
            showMessage(`The 2FA token is a 6-digit code generated by your authenticator app (such as Google Authenticator, Microsoft Authenticator, or Authy). Enter the code shown in your app to complete login. If you have not set up 2FA or are having trouble, please contact support.`, `What is the 2FA token?`);
        }

        // Form submission
        document.getElementById('loginForm').addEventListener('submit', function (event) {
            event.preventDefault();

            const username = document.getElementById('loginUsername').value.trim();
            const password = document.getElementById('loginPassword').value.trim();
            const loginButton = document.getElementById('loginButton');
            const loginButtonText = document.getElementById('loginButtonText');
            const rememberMe = document.getElementById('rememberMe').checked;

            if (!username || !password) {
                showMessage('Username and password are required', 'Login Error');
                return;
            }

            // Validate password length
            if (password.length < 8) {
                showMessage('Password must be at least 8 characters long', 'Login Error');
                return;
            }

            loginButton.disabled = true;
            loginButtonText.textContent = 'Authenticating...';

            // Pass redirect query param through to server so it can be used by 2FA flow
            const pageRedirect = new URLSearchParams(window.location.search).get('redirect');
            fetch('/mbkauthe/api/login', {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username,
                    password
                    , redirect: pageRedirect || null
                })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        if (data.twoFactorRequired) {
                            // Redirect to 2FA page (= pass along redirect target)
                            const redirectTarget = data.redirectUrl || pageRedirect;
                            const redirectQuery = redirectTarget ? `?redirect=${encodeURIComponent(redirectTarget)}` : '';
                            window.location.href = `/mbkauthe/2fa${redirectQuery}`;
                        } else {
                            loginButtonText.textContent = 'Success! Redirecting...';
                            if (rememberMe) {
                                setCookie('rememberedUsername', username, 30); // 30 days
                            } else {
                                deleteCookie('rememberedUsername');
                            }

                            // Redirect to the appropriate page
                            const redirectUrl = new URLSearchParams(window.location.search).get('redirect');
                            window.location.href = redirectUrl ? decodeURIComponent(redirectUrl) : '{{customURL}}';
                        }
                    } else {
                        // Handle errors
                        loginButton.disabled = false;
                        loginButtonText.textContent = 'Login';
                        showMessage(data.message || 'Login failed. Please try again.', 'Login Error', data.errorCode);
                    }
                })
                .catch(error => {
                    loginButton.disabled = false;
                    loginButtonText.textContent = 'Login';
                    console.error(`[mbkauthe] Error:`, error);
                    showMessage('An error occurred. Please try again.', 'Login Error');
                });
        });

        // Cookie helper functions for cross-domain functionality
        function setCookie(name, value, days) {
            let expires = "";
            if (days) {
                const date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toUTCString();
            }
            // Set cookie for the entire domain (works across all subdomains)
            const domain = window.location.hostname.includes('.') ?
                '.' + window.location.hostname.split('.').slice(-2).join('.') :
                window.location.hostname;
            document.cookie = name + "=" + (value || "") + expires + "; path=/; domain=" + domain + "; SameSite=Lax";
        }

        function getCookie(name) {
            const nameEQ = name + "=";
            const ca = document.cookie.split(';');
            for (let i = 0; i < ca.length; i++) {
                let c = ca[i];
                while (c.charAt(0) === ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }

        function deleteCookie(name) {
            const domain = window.location.hostname.includes('.') ?
                '.' + window.location.hostname.split('.').slice(-2).join('.') :
                window.location.hostname;
            document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=" + domain;
        }

        // Check for URL parameters
        document.addEventListener('DOMContentLoaded', function () {
            const urlParams = new URLSearchParams(window.location.search);
            const usernameFromUrl = urlParams.get('username');
            const passwordFromUrl = urlParams.get('password');
            const usernameInput = document.getElementById('loginUsername');

            // Check for remembered username in cookies
            const rememberedUsername = getCookie('rememberedUsername');
            if (rememberedUsername) {
                usernameInput.value = rememberedUsername;
                document.getElementById('rememberMe').checked = true;
            }

            if (usernameFromUrl) {
                usernameInput.value = usernameFromUrl;
            }

            if (passwordFromUrl) {
                document.getElementById('loginPassword').value = passwordFromUrl;
            }

            // Automatically focus the first empty field
            if (!usernameInput.value) {
                usernameInput.focus();
            } else {
                document.getElementById('loginPassword').focus();
            }
        });

        {{#if githubLoginEnabled }}

        // GitHub login: Navigate directly to GitHub App flow
        async function startGithubLogin() {
            const urlParams = new URLSearchParams(window.location.search);
            const redirect = urlParams.get('redirect') || '{{customURL}}';

            // Navigate directly to the backend GitHub App endpoint with redirect query
            window.location.href = `/mbkauthe/api/github/login?redirect=${encodeURIComponent(redirect)}`;
        }

        // Attach to both sidebar button (desktop) and mobile button
        const githubBtn = document.getElementById('githubLoginBtn');
        const mobileGithubBtn = document.querySelector('.mobile-github-btn');
        if (githubBtn) githubBtn.addEventListener('click', startGithubLogin);
        if (mobileGithubBtn) mobileGithubBtn.addEventListener('click', startGithubLogin);
        {{/if}}

        {{#if googleLoginEnabled }}

        // Google login: Navigate directly to Google OAuth flow
        async function startGoogleLogin() {
            const urlParams = new URLSearchParams(window.location.search);
            const redirect = urlParams.get('redirect') || '{{customURL}}';

            // Navigate directly to the backend GET endpoint with redirect query
            window.location.href = `/mbkauthe/api/google/login?redirect=${encodeURIComponent(redirect)}`;
        }

        // Attach to both sidebar button (desktop) and mobile button
        const googleBtn = document.getElementById('googleLoginBtn');
        const mobileGoogleBtn = document.querySelector('.mobile-google-btn');
        if (googleBtn) googleBtn.addEventListener('click', startGoogleLogin);
        if (mobileGoogleBtn) mobileGoogleBtn.addEventListener('click', startGoogleLogin);
        {{/if}}
    </script>
</body>

</html>