jQuery(document).ready(function ($) {
    var resendDelay = 0;
    var emailDomains = WAWP_Signup_Params.email_domains || ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com', 'aol.com'];
    var otpMethod = WAWP_Signup_Params.otp_method || 'whatsapp';
    if (otpMethod === 'wa') {
        otpMethod = 'whatsapp';
    }
    var passwordStrong = WAWP_Signup_Params.password_strong || 0;

    // Firebase SMS Integration
    let confirmationResult = null;
    let firebaseLoading = false;

    async function ensureFirebase() {
        if (typeof firebase !== 'undefined' && firebase.auth) {
            if (!window.recaptchaVerifierSignup) await initFirebaseVerifierSignup();
            return true;
        }

        if (firebaseLoading) return new Promise(resolve => {
            const i = setInterval(() => { if (typeof firebase !== 'undefined' && firebase.auth) { clearInterval(i); resolve(true); } }, 100);
        });
        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 => {
                const s = document.createElement('script');
                s.src = src; s.onload = resolve; document.head.appendChild(s);
            });
        }

        await initFirebaseVerifierSignup();
        return true;
    }

    async function initFirebaseVerifierSignup() {
        if (!document.getElementById('wawp-firebase-recaptcha-signup')) return;

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

        if (!config.apiKey && config.api_key) config.apiKey = config.api_key;
        if (!config.apiKey) { console.error('Firebase API Key missing'); 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
        };

        let app = null;
        try {
            app = firebase.app('wawp_signup_app');
        } catch (e) {
            app = firebase.initializeApp(firebaseConfig, 'wawp_signup_app');
        }

        if (!window.recaptchaVerifierSignup) {
            try {
                window.recaptchaVerifierSignup = new firebase.auth.RecaptchaVerifier('wawp-firebase-recaptcha-signup', {
                    'size': 'invisible',
                    'callback': (response) => { }
                }, app);
                window.recaptchaVerifierSignup.render();
            } catch (e) { console.warn('Recaptcha init error', e); }
        }
    }

    if (WAWP_Signup_Params.firebase_config && otpMethod === 'firebase') {
        ensureFirebase();
    }

    // Prefill phone from OTP login redirect (?pre_phone=)
    (function prefillPhoneFromQuery() {
        try {
            var params = new URLSearchParams(window.location.search);
            var p = params.get('pre_phone');
            if (p) {
                p = decodeURIComponent(p);
                $('#wawp_phone').val(p).trigger('input');
            }
        } catch (e) { }
    })();

    var recaptchaWidgetId = null;

    function initRecaptcha(callback, attempt) {
        if (!WAWP_Signup_Params.recaptcha_enabled || WAWP_Signup_Params.recaptcha_enabled === '0') {
            if (typeof callback === 'function') callback();
            return;
        }

        attempt = typeof attempt === 'number' ? attempt : 1;

        if (typeof grecaptcha === 'undefined' || typeof grecaptcha.render !== 'function') {
            if (attempt <= 20) {
                setTimeout(function () { initRecaptcha(callback, attempt + 1); }, 300);
            } else if (typeof callback === 'function') {
                callback();
            }
            return;
        }

        grecaptcha.ready(function () {
            var id = 'wawp-recaptcha-signup';
            var $container = $('#' + id);
            if ($container.length && recaptchaWidgetId === null) {
                try {
                    var isCheckbox = WAWP_Signup_Params.recaptcha_type === 'v2_checkbox';
                    var params = {
                        'sitekey': WAWP_Signup_Params.recaptcha_site_key,
                        'size': isCheckbox ? 'normal' : 'invisible',
                        'badge': WAWP_Signup_Params.is_rtl ? 'bottomleft' : 'bottomright',
                        'callback': function (token) {
                            var cb = $container.data('wawp-recaptcha-cb');
                            if (cb) {
                                cb(token);
                                $container.data('wawp-recaptcha-cb', null);
                            }
                        }
                    };
                    recaptchaWidgetId = grecaptcha.render(id, params);
                } catch (e) {
                    console.warn('WAWP Signup: ReCAPTCHA render error', e);
                }
            }
            if (typeof callback === 'function') callback();
        });
    }

    function triggerFirebaseFallback(originalError) {
        if (!parseInt(WAWP_Signup_Params.fallback_enabled)) {
            displayMessage(originalError, 'error');
            return;
        }

        const canWhatsApp = parseInt(WAWP_Signup_Params.whatsapp_configured) && $('#wawp_phone').val();
        const canEmail = parseInt(WAWP_Signup_Params.email_configured) && parseInt(WAWP_Signup_Params.email_enabled) && $('#wawp_email').val();

        if (canWhatsApp) {
            displayMessage('فشل إرسال SMS. جاري الإرسال عبر واتساب...');
            setTimeout(() => { triggerResend('whatsapp'); }, 1500);
        } else if (canEmail) {
            displayMessage('فشل إرسال SMS. جاري الإرسال عبر البريد الإلكتروني...');
            setTimeout(() => { triggerResend('email'); }, 1500);
        } else {
            displayMessage(originalError, 'error');
        }
    }

    $(window).on('load', function () { initRecaptcha(); });
    $(document).on('wawp_recaptcha_init', function () { setTimeout(initRecaptcha, 100); });

    function withRecaptcha(onSuccess, onError) {
        if (!WAWP_Signup_Params.recaptcha_enabled || !WAWP_Signup_Params.recaptcha_site_key || otpMethod === 'firebase') {
            onSuccess(null);
            return;
        }

        initRecaptcha(function () {
            if (recaptchaWidgetId !== null) {
                var isCheckbox = WAWP_Signup_Params.recaptcha_type === 'v2_checkbox';
                var response = grecaptcha.getResponse(recaptchaWidgetId);

                if (isCheckbox) {
                    if (response) {
                        onSuccess(response);
                    } else {
                        displayMessage(WAWP_Signup_L10n.pleaseSolveRecaptcha || 'Please solve the reCAPTCHA.', 'error');
                    }
                } else {
                    // Invisible mode
                    if (response) {
                        grecaptcha.reset(recaptchaWidgetId);
                    }
                    $('#wawp-recaptcha-signup').data('wawp-recaptcha-cb', onSuccess);
                    grecaptcha.execute(recaptchaWidgetId);
                }
            } else {
                console.warn('WAWP Signup: ReCAPTCHA widget not found');
                onSuccess(null);
            }
        });
    }

    async function wawpRest(op, data = {}) {
        if (!WAWP_Signup_Params.rest_url) {
            return $.post(WAWP_Signup_Params.ajax_url, {
                action: 'wawp_signup_op',
                nonce: WAWP_Signup_Params.nonce,
                ...data,
                op: op
            });
        }

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

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

        // Normalize response data structure for signup
        let normalized = {
            success: false,
            data: {}
        };

        if (result && typeof result === 'object') {
            if ('success' in result && result.data && typeof result.data === 'object') {
                const inner = result.data;
                normalized.success = 'success' in inner ? !!inner.success : !!result.success;

                for (const key in inner) {
                    if (key !== 'data' && key !== 'success') {
                        normalized.data[key] = inner[key];
                    }
                }

                if (inner.data && typeof inner.data === 'object') {
                    for (const key in inner.data) {
                        normalized.data[key] = inner.data[key];
                    }
                }
            } else {
                normalized.success = !!result.success;
                normalized.data = result.data || result;
            }
        }

        return normalized;
    }

    function displayMessage(message, type = 'success') {
        var color = (type === 'success') ? '#15803d' : '#b91c1c';
        var background = (type === 'success') ? '#e0faec' : '#fecaca';
        var border = (type === 'success') ? '1px solid rgba(21, 128, 61, 0.15)' : '1px solid rgba(185, 28, 28, 0.15)';
        $('.wawp-success-message').text(message).css({
            'color': color,
            'padding': '12px 20px',
            'border-radius': '10px',
            'margin-top': '24px',
            'text-align': 'center',
            'font-size': '14px',
            'font-weight': '600',
            'background-color': background,
            'border': border,
            'box-sizing': 'border-box',
            'width': '100%',
            'display': 'inline-block'
        }).removeClass('wawp-hide').show();
    }

    function clearMessages() {
        $('.wawp-success-message').hide().text('');
        $('.wawp-error-message').hide().text('');
    }

    function showFieldError($input, errorText) {
        $input.closest('.wawp-form-group')
            .find('.wawp-error-message')
            .text(errorText)
            .show();
    }


    if ($('#wawp_email').length > 0) {
        $('#wawp_email').autocomplete({
            source: function (request, response) {
                var term = request.term;
                var atIndex = term.indexOf('@');
                if (atIndex === -1) {
                    if (term.trim() === '') {
                        response([]);
                        return;
                    }
                    var suggestions = [];
                    for (var i = 0; i < emailDomains.length && suggestions.length < 5; i++) {
                        suggestions.push(term + '@' + emailDomains[i]);
                    }
                    response(suggestions);
                } else {
                    var prefix = term.substring(0, atIndex + 1);
                    var suffix = term.substring(atIndex + 1);
                    var suggestions = [];
                    for (var i = 0; i < emailDomains.length && suggestions.length < 5; i++) {
                        if (emailDomains[i].startsWith(suffix)) {
                            suggestions.push(prefix + emailDomains[i]);
                        }
                    }
                    response(suggestions);
                }
            },
            minLength: 1,
            select: function (event, ui) {
                $('#wawp_email').val(ui.item.value);
                return false;
            }
        }).autocomplete("instance")._renderItem = function (ul, item) {
            var atIndex = item.label.indexOf('@');
            var username = item.label.substring(0, atIndex);
            var domain = item.label.substring(atIndex);
            var formatted = '<span>' + username + '<span style="color: green;">' + domain + '</span></span>';
            return $('<li></li>')
                .data("item.autocomplete", item)
                .append(formatted)
                .appendTo(ul);
        };
    }

    $(document).on('blur', '#wawp_email, #wawp_phone', function () {
        const $input = $(this);
        const value = $.trim($input.val());
        const field = $input.attr('id').replace('wawp_', '');

        if (!value || value.length < 3) return;

        // Don't check if already showing a basic required error
        const $group = $input.closest('.wawp-form-group');
        const $errorMsg = $group.find('.wawp-error-message');

        if ($input.hasClass('wawp-field-error') && $errorMsg.text() === WAWP_Signup_L10n.fieldRequired) {
            return;
        }

        $input.addClass('wawp-checking');
        $errorMsg.hide().text('');

        wawpRest('check_availability', { [field]: value }).then(response => {
            $input.removeClass('wawp-checking wawp-field-error wawp-field-success');

            if (!response.success) {
                $input.addClass('wawp-field-error');
                showFieldError($input, response.data.message);
            } else {
                $input.addClass('wawp-field-success');
            }
        }).catch(() => { $input.removeClass('wawp-checking'); });
    });

    $('#wawp-signup-form').on('submit', function (e) {
        e.preventDefault();
        clearMessages();
        var form = $(this);
        var data = form.serializeArray();
        var obj = {};
        data.forEach(item => obj[item.name] = item.value);
        obj['otp_method'] = otpMethod;

        form.find('.wawp-form-control').removeClass('wawp-field-error wawp-field-success');
        var hasError = false;
        form.find('.wawp-form-control[required]').each(function () {
            if ($.trim($(this).val()) === '') {
                $(this).addClass('wawp-field-error');
                showFieldError($(this), WAWP_Signup_L10n.fieldRequired);
                hasError = true;
            }
        });
        if (hasError) return;
        var submitButton = form.find('.wawp-submit-button');
        var originalBtnHtml = submitButton.html();

        withRecaptcha(async function (token) {
            submitButton.prop('disabled', true).html('<i class="ri-loader-5-line"></i>');
            const $msgBox = form.next('.wawp-success-message');

            if (token) obj['g-recaptcha-response'] = token;

            try {
                const response = await wawpRest('signup', obj);
                submitButton.prop('disabled', false).html(originalBtnHtml);
                if (response.success) {
                    if (response.data.redirect_url) {
                        displayMessage(response.data.message);
                        setTimeout(function () { window.location.href = response.data.redirect_url; }, 2000);
                        return;
                    }
                    if (response.data.otp_transient) {
                        form.hide();
                        $('#wawp-signup-branding').hide();
                        $('#wawp-otp-section').removeClass('wawp-hide').show();

                        const otpMethod = response.data.method || response.data.otp_method;
                        const phone = response.data.phone || '';
                        let fullPhone = phone.startsWith('+') ? phone : '+' + phone;

                        if (fullPhone.startsWith('+229') && fullPhone.length === 12) {
                            fullPhone = '+22901' + fullPhone.substring(4);
                        }

                        $('#wawp-otp-form').data('phone', phone);
                        $('#wawp-otp-form').data('method', otpMethod);

                        if (otpMethod === 'email' || response.data.is_magic_link || response.data.whatsapp_auth_type === 'list') {
                            $('#wawp-otp-section').addClass('wawp-hide').hide();
                            $('#wawp-otp-branding, #wawp-otp-form').hide();

                            const waitingHtml = `
                                <div class="wawp-list-waiting-container" style="background: white; padding: 40px 20px; border-radius: 12px; text-align: center; box-shadow: 0 10px 25px -5px rgba(0,0,0,0.1);">
                                    <div class="wawp-list-waiting-icon" style="width: 80px; height: 80px; background: #e0faec; color: #15803d; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 24px; font-size: 40px;">
                                        <i class="ri-shield-check-line"></i>
                                    </div>
                                    <h4 class="wawp-list-waiting-title" style="font-size: 20px; font-weight: 800; color: #1a202c; margin-bottom: 12px;">${WAWP_Signup_L10n.verifyYourIdentity || 'Verify Your Identity'}</h4>
                                    <p class="wawp-list-waiting-text" style="font-size: 14px; color: #4a5568; line-height: 1.6; margin-bottom: 24px;">
                                        ${otpMethod === 'email' ? (WAWP_Signup_L10n.weSentLink || 'We sent a secure verification link to your email') + ' <b>' + response.data.email + '</b>.<br>' + (WAWP_Signup_L10n.pleaseClickLink || 'Please check your inbox and click the link to verify.') : (WAWP_Signup_L10n.weSentSecureRequest || 'We sent a secure verification request to') + ' <b>' + fullPhone + '</b>.<br>' + (WAWP_Signup_L10n.pleaseCheckDevice || 'Please check your device and approve it to continue.')}
                                    </p>
                                    <div style="margin-top: 20px; border-top: 1px solid #edf2f7; padding-top: 20px;">
                                        <a href="#" class="js-wawp-back-to-signup" style="font-size: 13px; color: #718096; font-weight: 600; text-decoration: underline;">${WAWP_Signup_L10n.changeDetailsOrRetry || 'Change details or retry'}</a>
                                    </div>
                                </div>
                            `;
                            $('#wawp-otp-section').after(waitingHtml);
                            startListPolling(otpMethod === 'email' ? response.data.email : phone, response.data.otp_transient);
                        } else {
                            $('#otp-icon').attr('class', otpMethod === 'firebase' ? 'ri-message-3-line' : 'ri-whatsapp-line');
                            $('#wawp-otp-sent-heading').text(WAWP_Signup_L10n.checkYourPhone);
                            $('#wawp-otp-sent-message').html(WAWP_Signup_L10n.weSentCode.replace('%s', fullPhone));
                            $('#wawp-resend-message').text(WAWP_Signup_L10n.wrongNumber);
                            $('#wawp-edit-contact-btn').text(WAWP_Signup_L10n.reEnterNumber);
                        }

                        $('#wawp_otp_transient').val(response.data.otp_transient);

                        function setupVerificationUI(method) {
                            $('#wawp-otp-form').data('method', method);
                            startResendCooldown(parseInt(WAWP_Signup_Params.initial_cooldown) || 30);
                            setupFallbacks(method);
                        }

                        function setupFallbacks(method) {
                            $('#wawp-firebase-fallback, #wawp-whatsapp-fallback').remove();
                            if (!parseInt(WAWP_Signup_Params.fallback_enabled)) return;
                            if (method === 'firebase' && parseInt(WAWP_Signup_Params.whatsapp_configured)) {
                                createFallbackLink('whatsapp', 10);
                            } else if (method === 'whatsapp' && parseInt(WAWP_Signup_Params.firebase_configured)) {
                                createFallbackLink('firebase', 15);
                            }
                        }

                        function createFallbackLink(targetMethod, delay) {
                            const isWhatsApp = targetMethod === 'whatsapp';
                            const linkId = isWhatsApp ? 'wawp-whatsapp-fallback-link' : 'wawp-firebase-fallback-link';
                            const containerId = isWhatsApp ? 'wawp-firebase-fallback' : 'wawp-whatsapp-fallback';
                            const color = isWhatsApp ? '#25d366' : '#f57c00';
                            const icon = isWhatsApp ? 'ri-whatsapp-line' : 'ri-fire-line';
                            const text = isWhatsApp ? WAWP_Signup_L10n.sendOTPWhatsApp : WAWP_Signup_L10n.sendOTPSMS;
                            const $fallbackContainer = $('<div id="' + containerId + '" style="margin-top: 10px; font-size: 14px; text-align: center;"></div>');
                            const $fallbackLink = $('<a href="#" id="' + linkId + '" style="color: ' + color + '; text-decoration: none; cursor: not-allowed; opacity: 0.6; display: flex; align-items: center; justify-content: center; gap: 5px;"><i class="' + icon + '"></i> <span>' + text + ' (' + delay + 's)</span></a>');
                            $fallbackContainer.append($fallbackLink);
                            $('.wawp-success-message').append($fallbackContainer);

                            let remaining = delay;
                            let interval = setInterval(() => {
                                remaining--;
                                if (remaining > 0) { $fallbackLink.find('span').text(text + ' (' + remaining + 's)'); } else {
                                    clearInterval(interval);
                                    $fallbackLink.css({ 'cursor': 'pointer', 'opacity': '1' }).find('span').text(text);
                                    $fallbackLink.on('click', function (e) { e.preventDefault(); triggerResend(targetMethod); });
                                }
                            }, 1000);
                        }

                        if (otpMethod === 'firebase') {
                            displayMessage(WAWP_Signup_L10n.sendingCode);
                            ensureFirebase().then(() => {
                                const app = firebase.app('wawp_signup_app');
                                app.auth().signInWithPhoneNumber(fullPhone, window.recaptchaVerifierSignup)
                                    .then((result) => {
                                        confirmationResult = result;
                                        clearMessages();
                                        displayMessage(WAWP_Signup_L10n.codeSentSuccess || 'Code sent successfully!');
                                        setupVerificationUI('firebase');
                                        submitButton.prop('disabled', false).html(originalBtnHtml);
                                    }).catch((error) => {
                                        clearMessages();
                                        submitButton.prop('disabled', false).html(originalBtnHtml);
                                        triggerFirebaseFallback(error.message);
                                    });
                            }).catch((err) => {
                                clearMessages();
                                submitButton.prop('disabled', false).html(originalBtnHtml);
                                triggerFirebaseFallback('Firebase initialization failed.');
                            });
                        } else {
                            clearMessages();
                            displayMessage(WAWP_Signup_L10n.codeSentSuccess || 'Code sent successfully!');
                            setupVerificationUI(otpMethod);
                            submitButton.prop('disabled', false).html(originalBtnHtml);
                        }
                    } else {
                        displayMessage(response.data.message);
                        form.find('.wawp-form-control').addClass('wawp-field-success');
                        form[0].reset();
                        if (recaptchaWidgetId !== null) grecaptcha.reset(recaptchaWidgetId);
                    }
                } else {
                    submitButton.prop('disabled', false).html(originalBtnHtml);
                    if (response.data.errors) {
                        $.each(response.data.errors, function (field, message) {
                            var $input = $('#' + field);
                            if ($input.length) { $input.addClass('wawp-field-error'); showFieldError($input, message); }
                        });
                    }
                    if (response.data.message) displayMessage(response.data.message, 'error');
                    if (recaptchaWidgetId !== null) grecaptcha.reset(recaptchaWidgetId);
                }
            } catch (err) {
                submitButton.prop('disabled', false).html(originalBtnHtml);
                displayMessage(WAWP_Signup_L10n.unexpectedError, 'error');
            }
        }, function (errMsg) {
            displayMessage(errMsg, 'error');
        });
    });

    function startResendCooldown(seconds = 30) {
        let remaining = seconds;
        $('#wawp-resend-otp-btn').prop('disabled', true).text(WAWP_Signup_L10n.waitSeconds.replace('%s', remaining));
        if (window.wawpSignupResendInterval) clearInterval(window.wawpSignupResendInterval);

        window.wawpSignupResendInterval = setInterval(() => {
            remaining--;
            if (remaining > 0) {
                $('#wawp-resend-otp-btn').text(WAWP_Signup_L10n.waitSeconds.replace('%s', remaining));
            } else {
                clearInterval(window.wawpSignupResendInterval);
                $('#wawp-resend-otp-btn').prop('disabled', false).text(WAWP_Signup_L10n.resendCode);
            }
        }, 1000);
    }

    function triggerResend(forceMethod = null) {
        const transientKey = $('#wawp_otp_transient').val();
        const currentMethod = forceMethod || $('#wawp-otp-form').data('method');
        const phone = $('#wawp-otp-form').data('phone');
        let fullPhone = phone.startsWith('+') ? phone : '+' + phone;

        if (fullPhone.startsWith('+229') && fullPhone.length === 12) fullPhone = '+22901' + fullPhone.substring(4);

        const $btn = $('#wawp-resend-otp-btn');
        const $msgBox = $('.wawp-success-message');

        $btn.prop('disabled', true).html('<i class="ri-loader-5-line"></i>');

        if (currentMethod === 'firebase') {
            ensureFirebase().then(() => {
                const app = firebase.app('wawp_signup_app');
                app.auth().signInWithPhoneNumber(fullPhone, window.recaptchaVerifierSignup)
                    .then((result) => {
                        confirmationResult = result;
                        displayMessage(WAWP_Signup_L10n.codeResentSMS || 'Code resent via SMS!');
                        $btn.prop('disabled', false).text(WAWP_Signup_L10n.resendCode);
                        startResendCooldown(parseInt(WAWP_Signup_Params.initial_cooldown) || 30);
                    }).catch((error) => {
                        $btn.prop('disabled', false).text(WAWP_Signup_L10n.resendCode);
                        triggerFirebaseFallback(error.message);
                    });
            });
        } else {
            wawpRest('resend', {
                otp_transient: transientKey,
                nonce_field: $('#wawp-otp-form input[name="wawp_signup_nonce_field"]').val(),
                force_otp_method: currentMethod
            }).then(response => {
                $btn.prop('disabled', false).text(WAWP_Signup_L10n.resendCode);
                if (response.success) {
                    displayMessage(response.data.message);
                    $('#wawp_otp_transient').val(response.data.otp_transient);
                    startResendCooldown(parseInt(WAWP_Signup_Params.initial_cooldown) || 30);
                } else {
                    displayMessage(response.data.message, 'error');
                }
            }).catch(() => {
                $btn.prop('disabled', false).text(WAWP_Signup_L10n.resendCode);
            });
        }
    }

    $('#wawp-otp-form').on('submit', function (e) {
        e.preventDefault();
        clearMessages();
        var form = $(this);
        var verifyButton = form.find('.wawp-submit-button');
        var originalBtnHtml = verifyButton.html();
        verifyButton.prop('disabled', true).html('<i class="ri-loader-5-line"></i>');

        if (confirmationResult) {
            const otpCode = $('#wawp_otp_code').val().trim();
            confirmationResult.confirm(otpCode).then((result) => {
                result.user.getIdToken().then(idToken => {
                    wawpRest('verify', { idToken: idToken, otp_transient: $('#wawp_otp_transient').val() }).then(response => {
                        verifyButton.prop('disabled', false).html(originalBtnHtml);
                        if (response.success) {
                            displayMessage(response.data.message);
                            if (response.data.redirect_url) setTimeout(function () { window.location.href = response.data.redirect_url; }, 2000);
                        } else { displayMessage(response.data.message, 'error'); }
                    });
                });
            }).catch(error => {
                verifyButton.prop('disabled', false).html(originalBtnHtml);
                displayMessage(error.message, 'error');
            });
        } else {
            var data = form.serializeArray();
            var obj = {};
            data.forEach(item => obj[item.name] = item.value);
            wawpRest('verify', obj).then(response => {
                verifyButton.prop('disabled', false).html(originalBtnHtml);
                if (response.success) {
                    displayMessage(response.data.message);
                    if (response.data.redirect_url) setTimeout(function () { window.location.href = response.data.redirect_url; }, 2000);
                    else $('#wawp-signup-container').hide();
                } else {
                    if (response.data.message) displayMessage(response.data.message, 'error');
                }
            }).catch(() => { verifyButton.prop('disabled', false).html(originalBtnHtml); });
        }
    });

    $(document).on('click', '#wawp-edit-contact-btn', function () {
        $('#wawp-otp-section').hide();
        clearMessages();
        $('#wawp-otp-form')[0].reset();
        $('#wawp_otp_transient').val('');
        $('#wawp-signup-branding').show();
        $('#wawp-signup-form').show();
        if (window.wawpSignupResendInterval) clearInterval(window.wawpSignupResendInterval);
        $('#wawp-resend-otp-btn').prop('disabled', false).html(WAWP_Signup_L10n.resendCode);
    });

    $(document).on('click', '#wawp-resend-otp-btn', function () { triggerResend(); });

    function getPasswordStrength(password) {
        var strength = { percent: 0, color: 'red', text: 'Weak' };
        var rules = [
            { regex: /[A-Z]/, increment: 20 },
            { regex: /[a-z]/, increment: 20 },
            { regex: /[0-9]/, increment: 20 },
            { regex: /.{8,}/, increment: 20 },
            { regex: /[^A-Za-z0-9]/, increment: 20 }
        ];
        rules.forEach(function (rule) {
            if (rule.regex.test(password)) strength.percent += rule.increment;
        });
        if (strength.percent >= 90) { strength.color = '#22c55e'; strength.text = 'excellent'; }
        else if (strength.percent >= 70) { strength.color = '#22c55e'; strength.text = 'Strong'; }
        else if (strength.percent >= 50) { strength.color = '#f59e0b'; strength.text = 'Average'; }
        else { strength.color = '#ef4444'; strength.text = 'Weak'; }
        return strength;
    }

    if ($('#wawp_password').length > 0 && passwordStrong) {
        $('#wawp_password').on('input', function () {
            var password = $(this).val();
            $('#password-requirements li').each(function (index) {
                var regex;
                switch (index) {
                    case 0: regex = /[A-Z]/; break;
                    case 1: regex = /[a-z]/; break;
                    case 2: regex = /[0-9]/; break;
                    case 3: regex = /.{8,}/; break;
                    case 4: regex = /[^A-Za-z0-9]/; break;
                    default: regex = /.*/; break;
                }
                if (regex.test(password)) $(this).find('.wawp-check').html('<i class="ri-check-line text-success"></i>');
                else $(this).find('.wawp-check').html('<i class="ri-close-line text-danger"></i>');
            });
            var strength = getPasswordStrength(password);
            $('#password-strength-meter').css({ width: strength.percent + '%', backgroundColor: strength.color });
            $('#password-strength-text').text(strength.text).css('color', strength.color);
        });
    }

    $('.wawp-toggle-password').click(function () {
        var passwordInput = $(this).siblings('input[type="password"], input[type="text"]');
        var type = (passwordInput.attr('type') === 'password') ? 'text' : 'password';
        passwordInput.attr('type', type);
        $(this).find('i').toggleClass('ri-eye-off-line');
    });

    $(document).on('click', '.wawp-fast-login-signup-toggle', function (e) {
        e.preventDefault();
        const $wrapper = $(this).closest('.wawp-fast-login-wrapper');
        const $loginView = $wrapper.find('.wawp-fast-login-view-login');
        const $signupView = $wrapper.find('.wawp-fast-login-view-signup');
        if ($loginView.length) {
            $loginView.fadeOut(200, function () {
                if ($signupView.length) {
                    $signupView.fadeIn(200, function () { $(window).trigger('resize'); $(document).trigger('wawp_recaptcha_init'); });
                }
            });
        } else if ($signupView.length) { $signupView.fadeIn(200); }
    });

    $(document).on('click', '.wawp-fast-login-login-toggle', function (e) {
        e.preventDefault();
        const $wrapper = $(this).closest('.wawp-fast-login-wrapper');
        const $loginView = $wrapper.find('.wawp-fast-login-view-login');
        const $signupView = $wrapper.find('.wawp-fast-login-view-signup');
        if ($signupView.length) {
            $signupView.fadeOut(200, function () {
                if ($loginView.length) {
                    $loginView.fadeIn(200, function () { $(window).trigger('resize'); $(document).trigger('wawp_recaptcha_init'); });
                }
            });
        } else if ($loginView.length) { $loginView.fadeIn(200); }
    });

    $(document).on('click', '.js-wawp-back-to-signup', function (e) {
        e.preventDefault();
        if (pollInterval) clearInterval(pollInterval);
        $('.wawp-list-waiting-container').remove();
        $('#wawp-signup-branding').show();
        $('#wawp-signup-form').show();
        $('#wawp-otp-section').addClass('wawp-hide').hide();
    });

    let pollInterval = null;
    function startListPolling(phone, authId) {
        if (pollInterval) clearInterval(pollInterval);
        let attempts = 0;
        const maxAttempts = 60;
        pollInterval = setInterval(async () => {
            attempts++;
            if (attempts > maxAttempts) {
                clearInterval(pollInterval);
                $('.wawp-list-waiting-container').remove();
                displayMessage(WAWP_Signup_L10n.authTimeout || 'Authentication timeout. Please try again.', 'error');
                $('#wawp-signup-branding, #wawp-signup-form').show();
                return;
            }
            try {
                const resp = await wawpRest('status', { otp_transient: authId, whatsapp: phone });
                if (resp.success && resp.data.verified) {
                    clearInterval(pollInterval);
                    $('.wawp-list-waiting-container').html('<div class="wawp-list-waiting-icon" style="background:#15803d; color:white;"><i class="ri-check-line"></i></div><h4 class="wawp-list-waiting-title">' + (WAWP_Signup_L10n.verified || 'Verified!') + '</h4><p class="wawp-list-waiting-text">' + (WAWP_Signup_L10n.accountCreated || 'Your account has been created successfully.') + '</p>');
                    setTimeout(() => { if (resp.data.redirect_url) window.location.href = resp.data.redirect_url; else window.location.reload(); }, 1500);
                } else if (resp.success && resp.data.status === 'rejected') {
                    clearInterval(pollInterval);
                    $('.wawp-list-waiting-container').remove();
                    displayMessage(WAWP_Signup_L10n.registrationRejected || 'Registration rejected from your phone.', 'error');
                    $('#wawp-signup-branding, #wawp-signup-form').show();
                }
            } catch (e) { }
        }, parseInt(WAWP_Signup_Params.polling_interval) || 1500);
    }
});