jQuery(document).ready(function ($) {

    /* ------------------------------------------------------------
     * Per-instance branding helpers (scoped to .wawp-otp-login-form)
     * ---------------------------------------------------------- */
    function hexToRgbA(hex, alpha = 1) {
        let c;
        if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
            c = hex.substring(1).split('');
            if (c.length === 3) {
                c = [c[0], c[0], c[1], c[1], c[2], c[2]];
            }
            c = '0x' + c.join('');
            return 'rgba(' + [(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') + ',' + alpha + ')';
        }
        return hex;
    }

    function updateBranding($wrapper, type, identifier, isMagicLink = false) {
        const $branding = $wrapper.find('.wawp-login-branding');
        if (!$branding.length) return;

        const l10n = window.wawpOtpL10n || {};

        if (!type) {
            // Restore original stored on the wrapper
            const orig = $wrapper.data('wawp-branding-orig');
            if (orig) {
                $branding.find('.wawp-logo-container').html(orig.logo);
                $branding.find('.wawp-login-title').text(orig.title);
                $branding.find('.wawp-login-description').html(orig.desc);
            }
            return;
        }

        let iconClass = '', titleText = '', descHtml = '', themeClass = '', customColor = '';

        if (type === 'whatsapp') {
            iconClass = 'ri-whatsapp-line'; titleText = l10n.checkWhatsApp || 'Check your WhatsApp';
            descHtml = (l10n.sentTo || 'We\u2019ve sent you a 6-digit code to') + ' <br><b>' + identifier + '</b>';
            themeClass = 'wawp-otp-theme-whatsapp';
            customColor = (window.wawpOtpAjax && window.wawpOtpAjax.button_colors) ? window.wawpOtpAjax.button_colors.whatsapp : '#25d366';
        } else if (type === 'firebase') {
            iconClass = 'ri-message-3-line'; titleText = l10n.checkSMS || 'Check your SMS';
            descHtml = (l10n.sentTo || 'We\u2019ve sent you a 6-digit code to') + ' <br><b>' + identifier + '</b>';
            themeClass = 'wawp-otp-theme-sms';
            customColor = (window.wawpOtpAjax && window.wawpOtpAjax.button_colors) ? window.wawpOtpAjax.button_colors.firebase : '#3b82f6';
        } else if (type === 'email') {
            iconClass = 'ri-mail-line'; titleText = l10n.checkEmail || 'Check your Email';
            descHtml = isMagicLink
                ? ((l10n.magicLinkSent || 'We\u2019ve sent you a secure login link to') + ' <br><b>' + identifier + '</b>')
                : ((l10n.sentTo || 'We\u2019ve sent you a 6-digit code to') + ' <br><b>' + identifier + '</b>');
            themeClass = 'wawp-otp-theme-email';
            customColor = (window.wawpOtpAjax && window.wawpOtpAjax.button_colors) ? window.wawpOtpAjax.button_colors.email_otp : '#ef4444';
        }

        $branding.find('.wawp-logo-container').html('<div class="wawp-icon-wrapper ' + themeClass + '"><i class="wawp-otp-icon ' + iconClass + '"></i></div>');
        if (customColor) {
            setTimeout(function () {
                const $ic = $branding.find('.wawp-otp-icon');
                if ($ic.length) {
                    $ic.css({ 'background-color': customColor, 'color': '#ffffff',
                        'box-shadow': '0 0 0 10px ' + hexToRgbA(customColor, 0.15),
                        'animation': 'wawp-pulse-scale 2s infinite ease-in-out' });
                }
            }, 50);
        }
        $branding.find('.wawp-login-title').text(titleText);
        $branding.find('.wawp-login-description').html(descHtml);
    }

    // Store original branding per wrapper on DOM ready
    $('.wawp-otp-login-form').each(function () {
        const $w = $(this);
        const $b = $w.find('.wawp-login-branding');
        $w.data('wawp-branding-orig', {
            logo: $b.find('.wawp-logo-container').html(),
            title: $b.find('.wawp-login-title').text(),
            desc: $b.find('.wawp-login-description').html()
        });
    });

    /* ------------------------------------------------------------
     * Email Autocomplete
     * ---------------------------------------------------------- */
    const emailDomains = wawpOtpAjax.email_domains || ['gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com', 'icloud.com'];

    function setupEmailAutocomplete($input) {
        const $wrapper = $('<div class="wawp-email-autocomplete-wrapper"></div>');
        $input.wrap($wrapper);
        const $list = $('<ul class="wawp-email-suggestions"></ul>');
        $input.after($list);

        $input.on('input', function () {
            const val = $(this).val();
            $list.empty().hide();
            if (!val || !val.includes('@')) return;

            const [user, domainPart] = val.split('@');
            if (!user) return;

            const matches = emailDomains.filter(d => d.startsWith(domainPart));
            if (matches.length > 0) {
                matches.forEach(m => {
                    const $li = $('<li>' + user + '@' + m + '</li>');
                    $li.on('click', function () {
                        $input.val($(this).text()).trigger('input');
                        $list.hide();
                    });
                    $list.append($li);
                });
                $list.show();
            }
        });

        $(document).on('click', function (e) {
            if (!$(e.target).closest('.wawp-email-autocomplete-wrapper').length) {
                $list.hide();
            }
        });
    }

    $('.js-wawp-email-input').each(function () { setupEmailAutocomplete($(this)); });

    /* ------------------------------------------------------------
     * Cooldown Guard (Persistent & Incremental)
     * ---------------------------------------------------------- */
    const STORAGE_KEY = 'wawp_otp_cooldown';
    let cooldownState = { phone: { attempts: 0, expires: 0 }, email: { attempts: 0, expires: 0 } };
    try {
        const stored = localStorage.getItem(STORAGE_KEY);
        if (stored) cooldownState = JSON.parse(stored);
    } catch (e) {
        console.error('AWP OTP: Corrupt storage reset', e);
        localStorage.removeItem(STORAGE_KEY);
    }

    function saveCooldownState() {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(cooldownState));
    }

    function runTimer(method, $btn, expiryTime) {
        const $container = $btn.closest('.wawp-action-buttons');
        let $timer = $container.find('.wawp-resend-timer');

        if (!$timer.length) {
            $timer = $('<div class="wawp-resend-timer" aria-live="polite" style="margin-top:10px;font-size:13px;opacity:0.9;text-align:center;width:100%;"></div>');
            $container.append($timer);
        }

        function label(sec) {
            return (window.wawpOtpL10n && wawpOtpL10n.resendIn) ? wawpOtpL10n.resendIn.replace('%s', sec) : 'Resend in ' + sec + 's';
        }

        $btn.prop('disabled', true);

        function update() {
            const now = Date.now();
            const remaining = Math.ceil((expiryTime - now) / 1000);

            if (remaining <= 0) {
                clearInterval($timer.data('interval'));
                $btn.prop('disabled', false);
                $timer.remove();
                cooldownState[method].expires = 0;
                saveCooldownState();
            } else {
                $timer.text(label(remaining));
            }
        }

        update(); // Run immediately

        // Clear any existing interval on this element
        if ($timer.data('interval')) clearInterval($timer.data('interval'));

        const interval = setInterval(update, 1000);
        $timer.data('interval', interval);
    }

    function checkCooldown(method, $btn) {
        const state = cooldownState[method];
        if (!state || !state.expires) return;

        // If no specific button passed, try to find the standard ones (for page load)
        if (!$btn || !$btn.length) {
            if (method === 'phone') {
                $btn = $('.wawp-request-btn[data-method="whatsapp"], .wawp-request-btn[data-method="firebase"], .wawp-resend-otp-phone');
            } else if (method === 'email') {
                $btn = $('.js-wawp-request-otp-email, .js-wawp-resend-otp-email');
            }
        }

        const now = Date.now();
        if (state.expires > now) {
            $btn.each(function () {
                runTimer(method, $(this), state.expires);
            });
        } else {
            // Reset attempts if expired long ago (e.g. 5 mins)
            if (now > state.expires + 300000) {
                state.attempts = 0;
                saveCooldownState();
            }
        }
    }

    function startCooldown(method, $btn) {
        const state = cooldownState[method];
        state.attempts = (state.attempts || 0) + 1;

        // Incremental: 30s, 60s, 120s, ... max 5 mins
        const initial = parseInt(wawpOtpAjax.initial_cooldown) || 30;
        const max = parseInt(wawpOtpAjax.max_cooldown) || 300;
        const seconds = Math.min(initial * Math.pow(2, state.attempts - 1), max);

        state.expires = Date.now() + (seconds * 1000);
        saveCooldownState();

        runTimer(method, $btn, state.expires);
    }


    /* ------------------------------------------------------------
     * Helpers
     * ---------------------------------------------------------- */
    function withSpinner($btn, fn) {
        const originalHtml = $btn.html();
        $btn.data('original-html', originalHtml).prop('disabled', true).addClass('is-loading').html('<i class="ri-loader-5-line"></i>');

        // Start progress timeline in the message box area
        const $form = $btn.closest('form');
        const $msgBox = $form.find('.wawp-login-message-phone, .js-wawp-msg-box-email');

        return fn(() => {
            $btn.prop('disabled', false).removeClass('is-loading').html($btn.data('original-html'));
        });
    }

    function setMessage($el, text, ok = true) {
        if (!$el || !$el.length) return;
        $el.html('<p class="' + (ok ? 'success' : 'error') + '">' + text + '</p>');
    }

    async function wawpRest(op, data = {}) {
        if (!wawpOtpAjax.rest_url) {
            // Fallback to legacy AJAX if rest_url is missing
            return $.post(wawpOtpAjax.ajax_url, {
                action: 'wawp_request_otp', // dummy action, logic will handle
                nonce: wawpOtpAjax.nonce,
                ...data,
                op: op
            }).promise();
        }

        const response = await fetch(wawpOtpAjax.rest_url + '/' + op, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': wawpOtpAjax.nonce
            },
            body: JSON.stringify(data)
        });

        const result = await response.json();
        if (!response.ok) {
            const err = new Error(result.message || 'REST Request Failed');
            err.data = result.data || result;
            throw err;
        }
        return result;
    }

    /* ------------------------------------------------------------
     * Firebase SDK Integration
     * ---------------------------------------------------------- */
    let firebaseLoading = false;
    let confirmationResult = null;

    async function resetFirebaseVerifier(force = false) {
        if (window.recaptchaVerifier) {
            try {
                window.recaptchaVerifier.clear();
            } catch (e) {
                console.warn('Error clearing verifier:', e);
            }
            window.recaptchaVerifier = null;
        }

        const container = document.getElementById('wawp-firebase-recaptcha-phone');
        if (container) {
            const parent = container.parentNode;
            if (parent) {
                const newContainer = document.createElement('div');
                newContainer.id = 'wawp-firebase-recaptcha-phone';
                newContainer.className = container.className;
                parent.replaceChild(newContainer, container);

                $(newContainer).removeClass('wawp-hide').css({
                    'position': 'absolute',
                    'width': '1px',
                    'height': '1px',
                    'padding': '0',
                    'margin': '-1px',
                    'overflow': 'hidden',
                    'clip': 'rect(0, 0, 0, 0)',
                    'border': '0',
                    'opacity': '0',
                    'pointer-events': 'none'
                });
            } else {
                container.innerHTML = '';
            }
        }

        await initFirebaseVerifier(force);
    }

    async function ensureFirebase(force = false) {
        if (typeof firebase !== 'undefined' && firebase.auth) {
            if (!window.recaptchaVerifier) {
                await resetFirebaseVerifier(force);
            }
            return true;
        }

        // Fallback: Dynamic loading if not enqueued (should happen rarely now)
        if (firebaseLoading) return new Promise((resolve, reject) => {
            const i = setInterval(() => {
                if (typeof firebase !== 'undefined' && firebase.auth) {
                    clearInterval(i);
                    resolve(true);
                }
            }, 100);
            setTimeout(() => {
                clearInterval(i);
                reject(new Error('Firebase SDK initialization timed out.'));
            }, 15000);
        });
        firebaseLoading = true;

        const scripts = [
            'https://www.gstatic.com/firebasejs/9.1.1/firebase-app-compat.js',
            'https://www.gstatic.com/firebasejs/9.1.1/firebase-auth-compat.js'
        ];

        for (const src of scripts) {
            await new Promise((resolve, reject) => {
                const s = document.createElement('script');
                s.src = src;
                s.onload = resolve;
                s.onerror = () => reject(new Error('Failed to load Firebase SDK from Google servers. Please check your network connection.'));
                document.head.appendChild(s);
            });
        }

        await resetFirebaseVerifier(force);
        return true;
    }

    async function initFirebaseVerifier(force = false) {
        // Guard: If the container doesn't exist (e.g. page without login form), skip init
        const container = document.getElementById('wawp-firebase-recaptcha-phone');
        if (!container) return;

        // Skip initialization if the parent element is hidden (e.g. inside an inactive tab) unless forced
        if (!force && $(container).parent().closest(':hidden').length > 0) {
            return;
        }

        const config = wawpOtpAjax.firebase_config;
        if (!config) { console.error('Firebase config missing'); return; }

        // Mobile fallback: map api_key to apiKey if missing
        if (!config.apiKey && config.api_key) {
            config.apiKey = config.api_key;
        }

        if (!config.apiKey && !config.api_key) {
            console.error('AWP OTP: Firebase API Key missing in localized config object. Please check your Firebase Sender settings and ensure a project is set as Active.');
            return;
        }

        // Clean the config object to only include valid Firebase parameters
        const firebaseConfig = {
            apiKey: config.apiKey || config.api_key,
            authDomain: config.authDomain,
            projectId: config.projectId,
            storageBucket: config.storageBucket,
            messagingSenderId: config.messagingSenderId,
            appId: config.appId,
            measurementId: config.measurementId
        };

        // Use a NAMED app to avoid conflicts with other plugins (like Google One Tap)
        let app = null;
        try {
            app = firebase.app('wawp_firebase_app');
        } catch (e) {
            // App not initialized yet
            app = firebase.initializeApp(firebaseConfig, 'wawp_firebase_app');
        }

        // Always ensure the container styles are properly set up (visible to DOM but screen-reader hidden)
        if (container) {
            $(container).removeClass('wawp-hide').css({
                'position': 'absolute',
                'width': '1px',
                'height': '1px',
                'padding': '0',
                'margin': '-1px',
                'overflow': 'hidden',
                'clip': 'rect(0, 0, 0, 0)',
                'border': '0',
                'opacity': '0',
                'pointer-events': 'none'
            });
        }

        if (!window.recaptchaVerifier) {
            try {
                // Pass the specific app instance
                window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('wawp-firebase-recaptcha-phone', {
                    'size': 'invisible',
                    'callback': (response) => { /* reCAPTCHA solved */ }
                }, app);

                // Render it immediately to warm up
                await window.recaptchaVerifier.render();
            } catch (e) { console.warn('Recaptcha init error', e); }
        }
    }

    // Highly-optimized async pre-loading: warm up and pre-load Firebase scripts and verifier immediately on page load in the background
    if (wawpOtpAjax.firebase_enabled) {
        ensureFirebase().catch(e => console.warn('Pre-loading Firebase failed asynchronously', e));
    }

    /* ------------------------------------------------------------
     * ReCAPTCHA (V2/V3)
     * ---------------------------------------------------------- */
    var recaptchaWidgets = {};
    let recaptchaInitAttempts = 0;
    function initRecaptcha(callback) {
        if (!wawpOtpAjax.recaptcha_enabled || wawpOtpAjax.recaptcha_enabled === '0') {
            if (typeof callback === 'function') callback();
            return;
        }

        if (typeof grecaptcha === 'undefined' || typeof grecaptcha.render !== 'function') {
            recaptchaInitAttempts++;
            if (recaptchaInitAttempts > 10) {
                console.warn('AWP OTP: Google ReCAPTCHA script not found. Proceeding without it.');
                if (typeof callback === 'function') callback();
                return;
            }
            setTimeout(() => initRecaptcha(callback), 300);
            return;
        }

        grecaptcha.ready(function () {
            $('.wawp-recaptcha-container').each(function () {
                var id = $(this).attr('id');
                if (id === 'wawp-recaptcha-signup') return; // Handled by wawp-signup.js

                if (id && recaptchaWidgets[id] === undefined) {
                    var isCheckbox = wawpOtpAjax.recaptcha_type === 'v2_checkbox';
                    var params = {
                        'sitekey': wawpOtpAjax.recaptcha_site_key,
                        'size': isCheckbox ? 'normal' : 'invisible',
                        'badge': wawpOtpAjax.is_rtl ? 'bottomleft' : 'bottomright',
                        'callback': function (token) {
                            var cb = $('#' + id).data('awp-recaptcha-cb');
                            if (cb) {
                                cb(token);
                                $('#' + id).data('awp-recaptcha-cb', null);
                            }
                        }
                    };
                    try {
                        recaptchaWidgets[id] = grecaptcha.render(id, params);
                    } catch (e) {
                        console.warn('AWP OTP: ReCAPTCHA render error for', id, e);
                    }
                }
            });
            if (typeof callback === 'function') callback();
        });
    }

    // Try init on ready and load
    initRecaptcha();
    $(window).on('load', function () { initRecaptcha(); });
    $(document).on('wawp_recaptcha_init', function () { initRecaptcha(); });

    function withRecaptcha(action, onSuccess, onError, $contextForm) {
        if (!wawpOtpAjax.recaptcha_enabled || !wawpOtpAjax.recaptcha_site_key || wawpOtpAjax.recaptcha_enabled === '0') return onSuccess(null);

        let called = false;
        const onceSuccess = (token) => {
            if (called) return;
            called = true;
            clearTimeout(safetyTimeout);
            onSuccess(token);
        };

        const safetyTimeout = setTimeout(() => {
            console.warn('AWP OTP: reCAPTCHA timed out for ' + action);
            onceSuccess(null);
        }, 6000);

        initRecaptcha(function () {
            // Try the new unified container first
            var containerId = 'wawp-recaptcha-login';
            var widgetId = recaptchaWidgets[containerId];

            // Fallback or override by context form
            if (widgetId === undefined && $contextForm && $contextForm.length) {
                var $c = $contextForm.find('.wawp-recaptcha-container');
                if ($c.length) {
                    var cid = $c.attr('id');
                    if (cid && recaptchaWidgets[cid] !== undefined) {
                        widgetId = recaptchaWidgets[cid];
                        containerId = cid;
                    }
                }
            }

            if (widgetId !== undefined) {
                var isCheckbox = wawpOtpAjax.recaptcha_type === 'v2_checkbox';
                var response = grecaptcha.getResponse(widgetId);

                try {
                    if (isCheckbox) {
                        if (response) {
                            onceSuccess(response);
                        } else {
                            setMessage($contextForm.find('.wawp-login-message-phone, .js-wawp-msg-box-email'), window.wawpOtpL10n.pleaseSolveRecaptcha || 'Please solve the reCAPTCHA.', false);
                            // We don't call onceSuccess(null) here yet, let user solve it and click again?
                            // Actually, withRecaptcha is called on button click.
                        }
                    } else {
                        // Invisible
                        if (response) {
                            grecaptcha.reset(widgetId);
                        }
                        $('#' + containerId).data('awp-recaptcha-cb', onceSuccess);
                        grecaptcha.execute(widgetId);
                    }
                } catch (e) {
                    console.error('AWP OTP: reCAPTCHA execute error', e);
                    onceSuccess(null);
                }
            } else {
                console.warn('AWP OTP: reCAPTCHA widget NOT rendered for', action);
                onceSuccess(null);
            }
        });
    }

    /* ------------------------------------------------------------
     * Tabs & UI Navigation (instance-scoped)
     * ---------------------------------------------------------- */
    $(document).on('click', '.wawp-tab', function () {
        const $tab = $(this);
        const tab = $tab.data('tab');
        const $wrapper = $tab.closest('.wawp-otp-login-form');
        $wrapper.find('.wawp-tab, .wawp-tab-pane').removeClass('active');
        $tab.addClass('active');
        $wrapper.find('#' + tab).addClass('active');

        if (tab.indexOf('phone_login') === 0 && wawpOtpAjax.firebase_enabled) {
            ensureFirebase().catch(e => console.warn('Pre-loading Firebase on tab switch failed', e));
        }
    });

    /* ------------------------------------------------------------
     * Phone Login Flow (instance-scoped)
     * ---------------------------------------------------------- */
    $(document).on('click', '.wawp-request-btn', function () {
        const $btn = $(this);
        const $form = $btn.closest('form');
        const $wrapper = $btn.closest('.wawp-otp-login-form');
        const method = $btn.data('method');
        const phone = $form.find('[name="phone"]').val().trim();
        const $msgBox = $form.find('.wawp-login-message-phone');

        if (!phone) return setMessage($msgBox, wawpOtpAjax.emptyFields, false);

        // Cooldown check
        const cooldownMethod = 'phone';
        const timerState = cooldownState[cooldownMethod];
        if (timerState && timerState.expires > Date.now()) {
            // Highlight the timer if active
            const $container = $btn.closest('.wawp-action-buttons');
            const $timer = $container.find('.wawp-resend-timer');
            if ($timer.length) {
                $timer.removeClass('wawp-timer-alert');
                void $timer[0].offsetWidth; // trigger reflow
                $timer.addClass('wawp-timer-alert');
            }
            return;
        }

        withSpinner($btn, async (finish) => {
            $msgBox.html('');

            if (method === 'firebase') {
                // Pre-check if user exists in WordPress before calling Firebase
                wawpRest('request', {
                    login_method: 'phone_firebase',
                    phone: phone
                }).then(async resp => {
                    if (resp.success) {
                        await ensureFirebase(true);
                        const $phoneInput = $form.find('[name="phone"]')[0];
                        const iti = ($phoneInput && window.intlTelInputGlobals && window.intlTelInputGlobals.getInstance) ? window.intlTelInputGlobals.getInstance($phoneInput) : null;
                        let fullPhone = '';
                        if (iti) {
                            const cd = iti.getSelectedCountryData() || {};
                            const dial = cd.dialCode ? String(cd.dialCode) : '';
                            const digits = phone.replace(/\D+/g, '');
                            const looksInternational = dial && digits.indexOf(dial) === 0;
                            let fullDigits = looksInternational ? digits : (dial + digits);

                            // Auto-Correction for Benin (+229) 10-digit upgrade (October 2024: adds "01" after dial)
                            if (dial === '229') {
                                const numPart = fullDigits.startsWith('229') ? fullDigits.substring(3) : fullDigits;
                                if (numPart.length === 8) {
                                    fullDigits = '22901' + numPart;
                                }
                            }

                            fullPhone = '+' + fullDigits;
                        } else {
                            fullPhone = phone.startsWith('+') ? phone : '+' + phone;
                        }

                        // Bulletproof Auto-Correction: If number is Benin (+229) and length is 12 (+229 + 8 digits), add "01"
                        if (fullPhone.startsWith('+229') && fullPhone.length === 12) {
                            const numberPart = fullPhone.substring(4); // Skip "+229"
                            fullPhone = '+22901' + numberPart;
                        }

                        // Use the NAMED app instance
                        const app = firebase.app('wawp_firebase_app');

                        app.auth().signInWithPhoneNumber(fullPhone, window.recaptchaVerifier)
                            .then((result) => {
                                confirmationResult = result;
                                // Log the request to history
                                wawpRest('log_firebase', { phone: phone });
                                finish();
                                updateBranding($wrapper, 'firebase', phone);
                                showOtpStep($wrapper, $form, 'phone', phone);
                                startCooldown('phone', $form.find('.wawp-resend-otp-phone'));
                            }).catch(async (error) => {
                                finish();
                                let userMsg = error.message;
                                if (error.code === 'auth/network-request-failed' || String(error).includes('network-request-failed')) {
                                    userMsg = (window.wawpOtpL10n && window.wawpOtpL10n.firebaseNetworkError)
                                        ? window.wawpOtpL10n.firebaseNetworkError
                                        : 'A network error occurred. If you are using Safari or Brave, please disable tracking protection (Shields) or try another browser.';
                                }
                                setMessage($msgBox, userMsg, false);
                                await resetFirebaseVerifier();
                                wawpRest('log_auth_failure', {
                                    phone: phone,
                                    method: 'firebase',
                                    error: error.message || String(error)
                                }).catch(e => console.warn('Logging failure error', e));
                            });
                    } else {
                        finish();
                        const errorMsg = (resp.data && resp.data.message) ? resp.data.message : (resp.data || (typeof resp === 'string' ? resp : 'Unknown error'));
                        if (resp.data && resp.data.redirect_to_signup) {
                            window.location.href = resp.data.redirect_to_signup;
                        } else {
                            setMessage($msgBox, errorMsg, false);
                        }
                    }
                }).catch((err) => {
                    finish();
                    if (err.data && err.data.redirect_to_signup) {
                        window.location.href = err.data.redirect_to_signup;
                        return;
                    }
                    setMessage($msgBox, err.message || 'Server error. Please try again later.', false);
                    wawpRest('log_auth_failure', {
                        phone: phone,
                        method: 'firebase',
                        error: err.message || String(err)
                    }).catch(e => console.warn('Logging failure error', e));
                });
            } else {
                // WhatsApp
                withRecaptcha('phone_' + method, (token) => {
                    wawpRest('request', {
                        login_method: 'phone_' + method,
                        phone: phone,
                        'g-recaptcha-response': token
                    }).then(resp => {
                        finish();
                        if (resp && resp.success) {
                            const authType = resp.data.whatsapp_auth_type || 'otp';

                            if (authType === 'list') {
                                // 1. Hide messy elements
                                $wrapper.find('.wawp-tabs').hide();
                                $wrapper.find('.wawp-remember-me').addClass('wawp-hide-force');
                                $wrapper.find('.wawp-login-branding').hide();
                                $form.find('.wawp-phone-group, .wawp-action-buttons, .wawp-otp-group-phone, .wawp-verify-row-phone, .wawp-separator, .wawp-switch-form').addClass('wawp-hide-force');
                                $msgBox.empty();

                                // 2. Inject Premium Waiting UI
                                const waitingHtml = `
                                    <div class="wawp-list-waiting-container">
                                        <div class="wawp-list-waiting-icon">
                                            <i class="ri-shield-check-line"></i>
                                        </div>
                                        <h4 class="wawp-list-waiting-title">${window.wawpOtpL10n.verifyYourIdentity || 'Verify Your Identity'}</h4>
                                        <p class="wawp-list-waiting-text">${window.wawpOtpL10n.weSentSecureRequest || 'We sent a secure verification request to'} <b>${phone}</b>.<br>${window.wawpOtpL10n.pleaseCheckDevice || 'Please check your device and approve it to continue.'}</p>
                                        <div style="margin-top: 20px; border-top: 1px solid #eee; padding-top: 15px;">
                                            <a href="#" class="js-wawp-back-to-input" style="font-size: 12px; color: #718096; text-decoration: underline;">${window.wawpOtpL10n.editNumberOrMethod || 'Edit number or use another method'}</a>
                                        </div>
                                    </div>
                                `;
                                $msgBox.after(waitingHtml);

                                // 3. Scroll to form if needed
                                $('html, body').animate({ scrollTop: $form.offset().top - 100 }, 500);

                                startListPolling(phone, resp.data.otp_transient, $msgBox);
                            } else {
                                setMessage($msgBox, resp.data.message || 'Verification code sent successfully.', true);
                                showOtpStep($wrapper, $form, 'phone', phone);
                                updateBranding($wrapper, 'whatsapp', phone);
                                $form.find('.wawp-verify-row-phone').removeClass('wawp-hide').css('display', 'flex').show();
                                $btn.hide();
                                $form.find('.wawp-remember-me').addClass('wawp-hide-force');
                                if (resp.data && resp.data.otp_transient) {
                                    $form.find('.wawp-resend-otp-phone').data('transient', resp.data.otp_transient);
                                    $form.find('.wawp-verify-otp-phone').data('transient', resp.data.otp_transient);
                                }
                                startCooldown('phone', $form.find('.wawp-resend-otp-phone'));
                            }
                        } else {
                            const errorMsg = (resp && resp.data && resp.data.message) ? resp.data.message : (resp && resp.data ? resp.data : (typeof resp === 'string' ? resp : 'Request failed.'));
                            if (resp && resp.data && resp.data.redirect_to_signup) {
                                window.location.href = resp.data.redirect_to_signup;
                            } else {
                                setMessage($msgBox, errorMsg, false);
                            }
                        }
                    }).catch((err) => {
                        finish();
                        if (err.data && err.data.redirect_to_signup) {
                            window.location.href = err.data.redirect_to_signup;
                            return;
                        }
                        setMessage($msgBox, 'Server error: ' + (err.message || 'unknown'), false);
                    });
                }, (err) => { finish(); setMessage($msgBox, err, false); }, $form);
            }
        });
    });

    // Resend Phone OTP (instance-scoped)
    $(document).on('click', '.wawp-resend-otp-phone', function () {
        const $btn = $(this);
        const $form = $btn.closest('form');
        const phone = $form.find('[name="phone"]').val().trim();
        const $msgBox = $form.find('.wawp-login-message-phone');
        setMessage($msgBox, window.wawpOtpL10n.sendingCode || 'Sending code...', true);

        wawpRest('request', {
            login_method: 'phone_whatsapp',
            phone: phone
        }).then(resp => {
            if (resp.success) {
                setMessage($msgBox, window.wawpOtpL10n.codeResent || 'Code resent!');
                startCooldown('phone', $btn);
            } else {
                const errorMsg = (resp.data && resp.data.message) ? resp.data.message : (resp.data || (typeof resp === 'string' ? resp : 'Unknown error'));
                setMessage($msgBox, errorMsg, false);
            }
        }).catch((err) => {
            setMessage($msgBox, err.message || 'Failed to resend. Server error.', false);
        });
    });

    function showOtpStep($wrapper, $form, tab, identifier) {
        $wrapper.find('.wawp-tabs').hide();
        $form.find('.wawp-remember-me').addClass('wawp-hide-force');
        if (tab === 'phone') {
            $form.find('.wawp-phone-group, .wawp-request-btn').hide();
            $form.find('.wawp-otp-group-phone, .wawp-otp-sent-message-phone').removeClass('wawp-hide').show();
            $form.find('.wawp-verify-row-phone').removeClass('wawp-hide').css('display', 'flex');

            // Focus 1st digit
            setTimeout(() => {
                const $otpInputs = $form.find('.wawp-otp-group-phone .wawp-otp-inputs input');
                $otpInputs.val('').removeClass('filled');
                $otpInputs.first().focus();
            }, 100);
            checkCooldown('phone', $form.find('.wawp-resend-otp-phone'));
        } else if (tab === 'email') {
            $form.find('.js-wawp-email-group').hide();
            $form.find('.js-wawp-request-otp-email, .js-wawp-show-password-btn').hide();
            $form.find('.js-wawp-otp-group-email, .js-wawp-email-back-link').removeClass('wawp-hide').show();
            $form.find('.js-wawp-verify-row-email').removeClass('wawp-hide').css('display', 'flex');

            // Focus 1st digit
            setTimeout(() => {
                const $otpInputs = $form.find('.js-wawp-otp-group-email .wawp-otp-inputs input');
                $otpInputs.val('').removeClass('filled');
                $otpInputs.first().focus();
            }, 100);
            checkCooldown('email', $form.find('.js-wawp-resend-otp-email'));
        }
    }

    // Edit phone (instance-scoped)
    $(document).on('click', '.wawp-edit-phone', function () {
        const $form = $(this).closest('form');
        const $wrapper = $(this).closest('.wawp-otp-login-form');
        $wrapper.find('.wawp-tabs').show();
        $form.find('.wawp-phone-group, .wawp-request-btn').show();
        $form.find('.wawp-remember-me').removeClass('wawp-hide-force');
        $form.find('.wawp-otp-group-phone, .wawp-otp-sent-message-phone').hide();
        $form.find('.wawp-verify-row-phone').hide();
        $form.find('.wawp-login-message-phone').html('');
        updateBranding($wrapper, null);
        if (typeof firebase !== 'undefined' && firebase.auth) {
            resetFirebaseVerifier();
        }
    });

    // Verify Phone OTP (instance-scoped)
    $(document).on('click', '.wawp-verify-otp-phone', function () {
        const $btn = $(this);
        const $form = $btn.closest('form');
        const $wrapper = $btn.closest('.wawp-otp-login-form');
        const otp = $form.find('[name="otp"]').val().trim();
        const phone = $form.find('[name="phone"]').val().trim();
        const $msgBox = $form.find('.wawp-login-message-phone');

        if (!otp) return setMessage($msgBox, window.wawpOtpL10n.pleaseEnterCode || 'Please enter the code.', false);

        withSpinner($btn, (finish) => {
            if (confirmationResult) {
                // Firebase Verification
                confirmationResult.confirm(otp).then((result) => {
                    result.user.getIdToken().then(idToken => {
                        wawpRest('verify_firebase', {
                            idToken: idToken,
                            remember: $form.find('.wawp-remember-phone-cb').is(':checked') ? 1 : 0
                        }).then(resp => {
                            finish();
                            if (resp && resp.success) window.location.href = resp.data.redirect_url;
                            else {
                                const errorMsg = (resp && resp.data && resp.data.message) ? resp.data.message : (resp && resp.data ? resp.data : (typeof resp === 'string' ? resp : 'Verification failed.'));
                                setMessage($msgBox, errorMsg, false);
                            }
                        }).catch((err) => {
                            finish();
                            setMessage($msgBox, 'Server error: ' + (err.message || 'unknown'), false);
                        });
                    });
                }).catch(error => { finish(); setMessage($msgBox, error.message, false); });
            } else {
                // WhatsApp Verification
                wawpRest('verify', {
                    login_method: 'whatsapp_otp',
                    phone: phone,
                    otp: otp,
                    otp_transient: $form.find('.wawp-verify-otp-phone').data('transient') || $form.find('.wawp-resend-otp-phone').data('transient') || '',
                    remember: $form.find('.wawp-remember-phone-cb').is(':checked') ? 1 : 0
                }).then(resp => {
                    finish();
                    if (resp && resp.success) window.location.href = resp.data.redirect_url;
                    else {
                        const errorMsg = (resp && resp.data && resp.data.message) ? resp.data.message : (resp && resp.data ? resp.data : (typeof resp === 'string' ? resp : 'Login failed. Please try again.'));
                        setMessage($msgBox, errorMsg, false);
                    }
                }).catch((err) => {
                    finish();
                    setMessage($msgBox, 'Server error: ' + (err.message || 'unknown'), false);
                });
            }
        });
    });

    /* ------------------------------------------------------------
     * Email Login Flow
     * ---------------------------------------------------------- */
    /* ------------------------------------------------------------
     * Email Login Flow (Scoped)
     * ---------------------------------------------------------- */
    $(document).on('click', '.js-wawp-show-password-btn', function () {
        const $form = $(this).closest('.wawp-merged-form');
        $form.find('.js-wawp-password-group, .js-wawp-login-submit-password, .js-wawp-email-back-link').removeClass('wawp-hide').show();
        $form.find('.js-wawp-show-password-btn, .js-wawp-request-otp-email').hide();
    });

    $(document).on('click', '.js-wawp-back-to-email-options', function (e) {
        e.preventDefault();
        const $form = $(this).closest('.wawp-merged-form');
        const $wrapper = $(this).closest('.wawp-otp-login-form');
        $form.find('.js-wawp-password-group, .js-wawp-login-submit-password, .js-wawp-otp-group-email, .js-wawp-email-back-link').hide();
        $form.find('.js-wawp-verify-row-email').hide();
        $form.find('.js-wawp-show-password-btn, .js-wawp-request-otp-email').show();
        $form.find('.js-wawp-email-group').show();
        $form.find('.wawp-remember-me').removeClass('wawp-hide-force');
        $wrapper.find('.wawp-tabs').show();
        updateBranding($wrapper, null);
    });

    // Email Resend Handler (instance-scoped)
    $(document).on('click', '.js-wawp-resend-otp-email', function () {
        const $btn = $(this);
        const $form = $btn.closest('.wawp-merged-form');
        const email = $form.find('.js-wawp-email-input').val();
        const $msgBox = $form.find('.js-wawp-msg-box-email');

        withSpinner($btn, (finish) => {
            wawpRest('request', {
                login_method: 'email_otp',
                email: email
            }).then(resp => {
                finish();
                if (resp.success) {
                    setMessage($msgBox, window.wawpOtpL10n.codeResent || 'Code resent!');
                    startCooldown('email', $btn);
                } else setMessage($msgBox, resp.data, false);
            }).catch((err) => {
                finish();
                setMessage($msgBox, err.message || 'Server error', false);
            });
        });
    });

    // Email Password Submission (instance-scoped)
    $(document).on('click', '.js-wawp-login-submit-password', function () {
        const $btn = $(this);
        const $form = $btn.closest('.wawp-merged-form');
        const login = $form.find('.js-wawp-email-input').val();
        const password = $form.find('.js-wawp-password-input').val();
        const $msgBox = $form.find('.js-wawp-msg-box-email');

        if (!login || !password) return setMessage($msgBox, wawpOtpAjax.emptyFields, false);

        withSpinner($btn, (finish) => {
            withRecaptcha('email_password', (token) => {
                wawpRest('login_password', {
                    login: login,
                    password: password,
                    remember: $form.find('.wawp-remember-email-cb').is(':checked') ? 1 : 0,
                    'g-recaptcha-response': token
                }).then(resp => {
                    finish();
                    if (resp && resp.success) window.location.href = resp.data.redirect_url;
                    else {
                        const errorMsg = (resp && resp.data && resp.data.message) ? resp.data.message : (resp && resp.data ? resp.data : (typeof resp === 'string' ? resp : 'Login failed. Please try again.'));
                        setMessage($msgBox, errorMsg, false);
                        const cId = 'wawp-recaptcha-email-merged';
                        if (recaptchaWidgets[cId] !== undefined) grecaptcha.reset(recaptchaWidgets[cId]);
                    }
                }).catch((err) => {
                    finish();
                    setMessage($msgBox, 'Server error: ' + (err.message || 'unknown'), false);
                });
            }, (err) => { finish(); setMessage($msgBox, err, false); }, $form);
        });
    });

    // Email OTP Submission (instance-scoped)
    $(document).on('click', '.js-wawp-request-otp-email', function () {
        const $btn = $(this);
        const $form = $btn.closest('.wawp-merged-form');
        const email = $form.find('.js-wawp-email-input').val();
        const $msgBox = $form.find('.js-wawp-msg-box-email');

        if (!email) return setMessage($msgBox, wawpOtpAjax.emptyFields, false);

        withSpinner($btn, (finish) => {
            withRecaptcha('email_otp', (token) => {
                wawpRest('request', {
                    login_method: 'email_otp',
                    email: email,
                    'g-recaptcha-response': token
                }).then(resp => {
                    finish();
                    if (resp && resp.success) {
                        setMessage($msgBox, resp.data.message || 'Magic link sent! Please check your inbox.', true);
                        const $wrapper2 = $btn.closest('.wawp-otp-login-form');
                        if (resp.data && resp.data.is_magic_link) {
                            $wrapper2.find('.wawp-tabs').hide();
                            $form.find('.wawp-remember-me').addClass('wawp-hide-force');
                            $wrapper2.find('.wawp-login-branding').hide();
                            $form.find('.js-wawp-email-group, .js-wawp-request-otp-email, .js-wawp-show-password-btn, .wawp-switch-form').hide();
                            $msgBox.empty();
                            const waitingHtml = `
                                <div class="wawp-list-waiting-container">
                                    <div class="wawp-list-waiting-icon">
                                        <i class="ri-shield-check-line"></i>
                                    </div>
                                    <h4 class="wawp-list-waiting-title">${window.wawpOtpL10n.verifyYourIdentity || 'Verify Your Identity'}</h4>
                                    <p class="wawp-list-waiting-text">${window.wawpOtpL10n.weSentSecureRequest || 'We sent a secure verification request to'} <b>${email}</b>.<br>${window.wawpOtpL10n.pleaseCheckInbox || 'Please check your inbox and click the link to continue.'}</p>
                                    <div style="margin-top: 20px; border-top: 1px solid #eee; padding-top: 15px;">
                                        <a href="#" onclick="window.location.reload();" class="js-wawp-back-to-input" style="font-size: 12px; color: #718096; text-decoration: underline;">${window.wawpOtpL10n.editEmailOrMethod || 'Edit email or use another method'}</a>
                                    </div>
                                </div>
                            `;
                            $msgBox.after(waitingHtml);
                            startListPolling(email, resp.data.otp_transient, $msgBox);
                        } else {
                            updateBranding($wrapper2, 'email', email, false);
                            showOtpStep($wrapper2, $form, 'email', email);
                            if (resp.data && resp.data.otp_transient) {
                                $form.find('.js-wawp-resend-otp-email').data('transient', resp.data.otp_transient);
                                $form.find('.js-wawp-verify-otp-email').data('transient', resp.data.otp_transient);
                            }
                            startCooldown('email', $form.find('.js-wawp-resend-otp-email'));
                        }
                    } else {
                        const errorMsg = (resp && resp.data && resp.data.message) ? resp.data.message : (resp && resp.data ? resp.data : (typeof resp === 'string' ? resp : 'Request failed.'));
                        setMessage($msgBox, errorMsg, false);
                        const cId = 'wawp-recaptcha-email-merged';
                        if (recaptchaWidgets[cId] !== undefined) grecaptcha.reset(recaptchaWidgets[cId]);
                    }
                }).catch((err) => {
                    finish();
                    if (err.data && err.data.redirect_to_signup) {
                        window.location.href = err.data.redirect_to_signup;
                        return;
                    }
                    setMessage($msgBox, 'Server error: ' + (err.message || 'unknown'), false);
                });
            }, (err) => { finish(); setMessage($msgBox, err, false); }, $form);
        });
    });

    $(document).on('click', '.js-wawp-verify-otp-email', function () {
        const $btn = $(this);
        const $form = $btn.closest('.wawp-merged-form');
        const email = $form.find('.js-wawp-email-input').val();
        const otp = $form.find('.js-wawp-otp-input-email').val();
        const $msgBox = $form.find('.js-wawp-msg-box-email');

        withSpinner($btn, (finish) => {
            wawpRest('verify', {
                login_method: 'email_otp',
                email: email,
                otp: otp,
                otp_transient: $btn.data('transient') || $form.find('.js-wawp-resend-otp-email').data('transient') || '',
                remember: $form.find('.wawp-remember-email-cb').is(':checked') ? 1 : 0
            }).then(resp => {
                finish();
                if (resp.success) window.location.href = resp.data.redirect_url;
                else {
                    const errorMsg = (resp.data && resp.data.message) ? resp.data.message : (resp.data || (typeof resp === 'string' ? resp : 'Unknown error'));
                    setMessage($msgBox, errorMsg, false);
                }
            }).catch(err => {
                finish();
                setMessage($msgBox, err.message || 'Error occurred.', false);
            });
        });
    });

    // Password Toggle (instance-scoped)
    $(document).on('click', '.js-wawp-password-toggle', function () {
        const $form = $(this).closest('.wawp-merged-form');
        const input = $form.find('.js-wawp-password-input');
        const type = input.attr('type') === 'password' ? 'text' : 'password';
        input.attr('type', type);
        $(this).toggleClass('ri-eye-line ri-eye-off-line');
    });

    // Check cooldowns on load
    checkCooldown('phone');
    checkCooldown('email');

    /* ------------------------------------------------------------
     * Enter Key Support
     * ---------------------------------------------------------- */
    function handleEnter(inputSel, btnSel) {
        $(document).on('keypress', inputSel, function (e) {
            if (e.which === 13) {
                e.preventDefault();
                $(btnSel).first().trigger('click');
            }
        });
    }

    // Phone Input -> Submit first visible request button (instance-scoped)
    $(document).on('keypress', '.wawp-phone-form [name="phone"]', function (e) {
        if (e.which === 13) {
            e.preventDefault();
            $(this).blur();
            $(this).closest('form').find('.wawp-request-btn:visible').first().trigger('click');
        }
    });

    // Phone OTP split inputs -> Verify on Enter
    $(document).on('keypress', '.wawp-otp-group-phone .wawp-otp-inputs input', function (e) {
        if (e.which === 13) {
            e.preventDefault();
            $(this).closest('form').find('.wawp-verify-otp-phone:visible').first().trigger('click');
        }
    });

    // Email Input -> Check context (Password login or OTP request) (instance-scoped)
    $(document).on('keypress', '.js-wawp-email-input', function (e) {
        if (e.which === 13) {
            e.preventDefault();
            $(this).blur();
            const $form = $(this).closest('.wawp-merged-form');
            const $passBtn = $form.find('.js-wawp-login-submit-password:visible');
            if ($passBtn.length) {
                $passBtn.trigger('click');
            } else {
                $form.find('.js-wawp-request-otp-email:visible').trigger('click');
            }
        }
    });

    // Password -> Login (instance-scoped)
    $(document).on('keypress', '.js-wawp-password-input', function (e) {
        if (e.which === 13) {
            e.preventDefault();
            $(this).closest('form').find('.js-wawp-login-submit-password:visible').trigger('click');
        }
    });

    // Email OTP split inputs -> Verify on Enter (instance-scoped)
    $(document).on('keypress', '.js-wawp-otp-group-email .wawp-otp-inputs input', function (e) {
        if (e.which === 13) {
            e.preventDefault();
            $(this).closest('form').find('.js-wawp-verify-otp-email:visible').first().trigger('click');
        }
    });

    // Fast Login Toggles (instance-scoped) - Re-init recaptcha just in case
    $(document).on('click', '.wawp-fast-login-signup-toggle, .wawp-fast-login-login-toggle', function () {
        setTimeout(function () {
            $(document).trigger('wawp_recaptcha_init');
        }, 100);
    });

    /* ------------------------------------------------------------
     * Legacy Client Fixes (Adapted for modern classes)
     * ---------------------------------------------------------- */
    // 1. Force enable buttons stuck in disabled state (e.g. from bfcache or browser bugs)
    $(document).on('mouseenter', '.wawp-btn, .wawp-request-btn', function () {
        var $btn = $(this);
        // Do not force enable if explicitly in a loading or active cooldown state
        if ($btn.hasClass('is-loading') || $btn.closest('.wawp-action-buttons').find('.wawp-resend-timer').length > 0) {
            return;
        }
        $btn.css('pointer-events', 'auto');
        $btn.removeAttr('disabled');
        $btn.removeClass('disabled loading blockUI');
    });

    // 2. Formatting Sync: Force focus to the request button 1 second after typing
    var typingTimer;
    var doneTypingInterval = 1000;
    $(document).on('keyup', '.wawp-phone-form [name="phone"]', function () {
        const $inp = $(this);
        clearTimeout(typingTimer);
        if ($inp.val()) {
            typingTimer = setTimeout(function () {
                var valLength = $inp.val().replace(/\D/g, '').length;
                if (valLength >= 7) {
                    var $whatsappBtn = $inp.closest('form').find('.wawp-request-btn[data-method="whatsapp"]:visible, .wawp-request-btn:visible').first();
                    if ($whatsappBtn.length) { $whatsappBtn.focus(); }
                }
            }, doneTypingInterval);
        }
    });
    $(document).on('keydown', '.wawp-phone-form [name="phone"]', function () {
        clearTimeout(typingTimer);
    });

    // 3. Modern Split OTP Input Logic
    $(document).on('input', '.wawp-otp-inputs input', function () {
        const $this = $(this);
        const $inputs = $this.parent().find('input');
        const targetId = $this.parent().data('target');
        const $hiddenInput = $(targetId);

        // Move forward if filled
        if ($this.val().length === 1) {
            $this.addClass('filled');
            const nextIdx = $inputs.index($this) + 1;
            if (nextIdx < $inputs.length) {
                $inputs.eq(nextIdx).focus();
            }
        } else {
            $this.removeClass('filled');
        }

        // Update hidden input
        let fullValue = '';
        $inputs.each(function () {
            fullValue += $(this).val();
        });
        $hiddenInput.val(fullValue);
    });

    $(document).on('keydown', '.wawp-otp-inputs input', function (e) {
        const $this = $(this);
        const $inputs = $this.parent().find('input');

        // Move backward on backspace if empty
        if (e.key === 'Backspace' && $this.val().length === 0) {
            const prevIdx = $inputs.index($this) - 1;
            if (prevIdx >= 0) {
                $inputs.eq(prevIdx).focus();
            }
        }
    });

    // Handle Paste for Split OTP
    $(document).on('paste', '.wawp-otp-inputs input', function (e) {
        e.preventDefault();
        const $this = $(this);
        const $inputs = $this.parent().find('input');
        const targetId = $this.parent().data('target');
        const $hiddenInput = $(targetId);

        const pasteData = (e.originalEvent || e).clipboardData.getData('text').slice(0, 6).split('');

        pasteData.forEach((char, i) => {
            if ($inputs.eq(i).length) {
                $inputs.eq(i).val(char).addClass('filled');
            }
        });

        $hiddenInput.val(pasteData.join(''));
        if ($inputs.eq(pasteData.length - 1).length) {
            $inputs.eq(pasteData.length - 1).focus();
        } else {
            $inputs.last().focus();
        }
    });

    $(document).on('click', '.js-wawp-back-to-input', function (e) {
        e.preventDefault();
        if (pollInterval) clearInterval(pollInterval);
        const $form = $(this).closest('form');
        const $wrapper = $(this).closest('.wawp-otp-login-form');
        $form.find('.wawp-list-waiting-container').remove();
        $wrapper.find('.wawp-tabs').show();
        $form.find('.wawp-remember-me').removeClass('wawp-hide-force');
        $wrapper.find('.wawp-login-branding').show();
        if ($form.hasClass('js-wawp-email-form')) {
            $form.find('.js-wawp-email-group, .js-wawp-request-otp-email, .js-wawp-show-password-btn, .wawp-switch-form').show();
        } else {
            $form.find('.wawp-phone-group, .wawp-action-buttons, .wawp-separator, .wawp-switch-form').removeClass('wawp-hide-force');
            $form.find('.wawp-login-message-phone').empty();
        }
        if (typeof firebase !== 'undefined' && firebase.auth) {
            resetFirebaseVerifier();
        }
    });

    let pollInterval = null;
    function startListPolling(phone, authId, $msgBox) {
        if (pollInterval) clearInterval(pollInterval);

        let attempts = 0;
        const maxAttempts = 60; // 3 minutes (3s * 60)
        const isEmail = $msgBox.hasClass('js-wawp-msg-box-email');
        const $form = $msgBox.closest('form');

        pollInterval = setInterval(() => {
            attempts++;
            if (attempts > maxAttempts) {
                clearInterval(pollInterval);
                const $wrapperP = $form.closest('.wawp-otp-login-form');
                $form.find('.wawp-list-waiting-container').remove();
                $wrapperP.find('.wawp-tabs').show();
                $form.find('.wawp-remember-me').removeClass('wawp-hide-force');
                $wrapperP.find('.wawp-login-branding').show();
                setMessage($msgBox, 'Authentication timeout. Please try again.', false);
                if (isEmail) {
                    $form.find('.js-wawp-email-group, .js-wawp-request-otp-email, .js-wawp-show-password-btn, .wawp-switch-form').show();
                } else {
                    $form.find('.wawp-phone-group, .wawp-action-buttons, .wawp-separator, .wawp-switch-form').removeClass('wawp-hide-force');
                }
                return;
            }

            wawpRest('status', {
                otp_transient: authId,
                whatsapp: phone,
                remember: isEmail ? ($form.find('.wawp-remember-email-cb').is(':checked') ? 1 : 0) : ($form.find('.wawp-remember-phone-cb').is(':checked') ? 1 : 0)
            }).then(resp => {
                if (resp.success && resp.data.verified) {
                    clearInterval(pollInterval);
                    $('.wawp-list-waiting-container').html('<div class="wawp-list-waiting-icon" style="background:#15803d"><i class="ri-check-line"></i></div><h4 class="wawp-list-waiting-title">' + (window.wawpOtpL10n.verified || 'Verified!') + '</h4><p class="wawp-list-waiting-text">' + (window.wawpOtpL10n.redirectingDashboard || 'Redirecting you to dashboard...') + '</p>');

                    setTimeout(() => {
                        if (resp.data.redirect_url) {
                            window.location.href = resp.data.redirect_url;
                        } else {
                            window.location.reload();
                        }
                    }, 1000);
                } else if (resp.success && resp.data.status === 'rejected') {
                    clearInterval(pollInterval);
                    const $wrapperR = $form.closest('.wawp-otp-login-form');
                    $form.find('.wawp-list-waiting-container').remove();
                    $wrapperR.find('.wawp-tabs').show();
                    $form.find('.wawp-remember-me').removeClass('wawp-hide-force');
                    $wrapperR.find('.wawp-login-branding').show();
                    setMessage($msgBox, isEmail ? (window.wawpOtpL10n.loginRejectedEmail || 'Login request was rejected.') : (window.wawpOtpL10n.loginRejectedPhone || 'Login request was rejected from your phone.'), false);
                    if (isEmail) {
                        $form.find('.js-wawp-email-group, .js-wawp-request-otp-email, .js-wawp-show-password-btn, .wawp-switch-form').show();
                    } else {
                        $form.find('.wawp-phone-group, .wawp-action-buttons, .wawp-separator, .wawp-switch-form').removeClass('wawp-hide-force');
                    }
                }
            }).catch(() => {
                // Silently ignore polling errors to keep trying
            });
        }, parseInt(wawpOtpAjax.polling_interval) || 1500);
    }
});
