jQuery.migrateMute = true;
jQuery(document).ready(function ($) {
    var otpSent = false;
    var resendInterval;
    var baseHoldTime = parseInt(wawpCheckoutOtpAjax.initial_cooldown) || 5;
    var resendCount = 0;
    var currentHoldTime = 5;
    var $wawpOtpPopup = $('#wawp_otp_popup');
    var $userPhoneNumber = $('#user_phone_number');
    var $wawpResendOtpBtn = $('#wawp_resend_otp_btn');
    var $wawpResendTimer = $('#wawp_resend_timer');
    var $wawpVerifyOtpBtn = $('#wawp_verify_otp_btn');
    var $wawpOtpInput = $('#wawp_otp_input');
    var $popupMessage = $wawpOtpPopup.find('.wawp-popup-message');
    var $checkoutForm = $('form.woocommerce-checkout');

    const data = {
        // required for WordPress AJAX
        action: 'send_otp',
        security: wawpCheckoutOtpAjax.nonce,

        /* -------------------------------------------------
         * Handy shortcuts used by your PHP handler
         * -------------------------------------------------*/
        phone_number: $('input[name="billing_phone"]').val(),
        first_name: $('input[name="billing_first_name"]').val(),
        last_name: $('input[name="billing_last_name"]').val(),
        email: $('input[name="billing_email"]').val(),

        /* -------------------------------------------------
         * Full billing address block
         * -------------------------------------------------*/
        billing_first_name: $('input[name="billing_first_name"]').val(),
        billing_last_name: $('input[name="billing_last_name"]').val(),
        billing_company: $('input[name="billing_company"]').val(),
        billing_address_1: $('input[name="billing_address_1"]').val(),
        billing_address_2: $('input[name="billing_address_2"]').val(),
        billing_city: $('input[name="billing_city"]').val(),
        billing_state: $('input[name="billing_state"]').val(),
        billing_postcode: $('input[name="billing_postcode"]').val(),
        billing_country: $('select[name="billing_country"]').val(),
        billing_phone: $('input[name="billing_phone"]').val(),   // duplicate of phone_number for convenience
        billing_email: $('input[name="billing_email"]').val(),   // duplicate of email        for convenience

        /* -------------------------------------------------
         * Full shipping address block
         * -------------------------------------------------*/
        shipping_first_name: $('input[name="shipping_first_name"]').val(),
        shipping_last_name: $('input[name="shipping_last_name"]').val(),
        shipping_company: $('input[name="shipping_company"]').val(),
        shipping_address_1: $('input[name="shipping_address_1"]').val(),
        shipping_address_2: $('input[name="shipping_address_2"]').val(),
        shipping_city: $('input[name="shipping_city"]').val(),
        shipping_state: $('input[name="shipping_state"]').val(),
        shipping_postcode: $('input[name="shipping_postcode"]').val(),
        shipping_country: $('select[name="shipping_country"]').val()
    };


    function showPopupMessage(msg, isSuccess) {
        var successClass = 'custom-message-success';
        var errorClass = 'custom-message-error';
        $popupMessage.removeClass(successClass + ' ' + errorClass);
        $popupMessage.addClass(isSuccess ? successClass : errorClass);
        $popupMessage.text(msg).show();
    }

    async function wawpRest(op, data = {}) {
        if (!wawpCheckoutOtpAjax.rest_url) {
            // Fallback to legacy AJAX
            return $.post(wawpCheckoutOtpAjax.ajaxurl, {
                action: op === 'send' ? 'send_otp' : (op === 'verify' ? 'verify_otp' : 'wawp_checkout_check_auth_status'),
                security: wawpCheckoutOtpAjax.nonce,
                ...data
            });
        }

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

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

    function startResendTimer() {
        $wawpResendOtpBtn.prop('disabled', true);
        updateResendTimerText();
        clearInterval(resendInterval);
        resendInterval = setInterval(function () {
            currentHoldTime--;
            updateResendTimerText();
            if (currentHoldTime <= 0) {
                clearInterval(resendInterval);
                $wawpResendOtpBtn.prop('disabled', false);
                $wawpResendTimer.text('');
            }
        }, 1000);
    }

    function updateResendTimerText() {
        $wawpResendTimer.text(' (' + currentHoldTime + 's)');
    }


    async function sendOtp(phoneNumber, firstName, lastName, email) {
        var method = wawp_translations.method || 'whatsapp';
        const $form = $checkoutForm;

        if (method === 'firebase') {
            try {
                if (typeof firebase === 'undefined') {
                    showPopupMessage('Firebase SDK not loaded.', false);
                    return;
                }
                if (!recaptchaVerifier) {
                    const config = wawpCheckoutFirebase.firebase_config;
                    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
                    };

                    firebase.initializeApp(firebaseConfig, 'wawp_checkout_app');
                    recaptchaVerifier = new firebase.auth.RecaptchaVerifier('wawp-recaptcha-checkout', {
                        'size': 'invisible'
                    }, firebase.app('wawp_checkout_app'));
                }

                // Ensure phone number is in E.164 format
                var formattedPhone = phoneNumber.startsWith('+') ? phoneNumber : '+' + phoneNumber;

                confirmationResult = await firebase.auth(firebase.app('wawp_checkout_app')).signInWithPhoneNumber(formattedPhone, recaptchaVerifier);
                showPopupMessage(wawp_translations.otp_sent_success, true);
                $wawpOtpPopup.show();
                otpSent = true;
                startResendTimer();
            } catch (error) {
                showPopupMessage(error.message || wawp_translations.otp_sent_failure, false);
            }
            return;
        }

        // Clear any old transient when starting a new request
        try {
            sessionStorage.removeItem('wawp_checkout_otp_transient');
            sessionStorage.removeItem('wawp_checkout_auth_id');
            sessionStorage.removeItem('wawp_checkout_phone');
        } catch (e) {}
        currentOtpTransient = null;
        currentAuthId = null;
        currentPhoneNumber = phoneNumber;

        try {
            const response = await wawpRest('send', {
                phone_number: phoneNumber,
                first_name: firstName,
                last_name: lastName,
                email: email
            });
            if (response.success) {
                // Store the transient key and auth_id for later verification
                // Note: REST API returns nested data structure
                currentOtpTransient = response.data.data?.otp_transient || response.data.otp_transient;
                currentAuthId = response.data.data?.auth_id || response.data.auth_id;
                try {
                    sessionStorage.setItem('wawp_checkout_otp_transient', currentOtpTransient);
                    if (currentAuthId) {
                        sessionStorage.setItem('wawp_checkout_auth_id', currentAuthId);
                    }
                    if (phoneNumber) {
                        sessionStorage.setItem('wawp_checkout_phone', phoneNumber);
                    }
                } catch (e) {
                    // sessionStorage not available
                }
                const authType = response.data.data?.whatsapp_auth_type || response.data.whatsapp_auth_type || 'otp';
                
                if (authType === 'list') {
                    // Interactive List Mode
                    $wawpOtpPopup.find('.wawp-otp-box, .wawp-otp-content').hide();
                    
                    let $waiting = $wawpOtpPopup.find('.wawp-list-waiting-container');
                    if (!$waiting.length) {
                        $waiting = $(`
                            <div class="wawp-list-waiting-container" style="padding: 20px; text-align: center;">
                                <div class="wawp-list-waiting-icon" style="width: 60px; height: 60px; background: #e0faec; color: #15803d; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 15px; font-size: 30px;">
                                    <i class="ri-shield-check-line"></i>
                                </div>
                                <h4 style="margin: 0 0 10px; font-size: 18px;">Verify Your Order</h4>
                                <p style="font-size: 13px; color: #666;">We sent a secure verification request.<br>Please check your device and approve it.</p>
                                <div style="margin-top: 15px;">
                                    <button type="button" class="js-wawp-cancel-list" style="background: none; border: none; color: #718096; text-decoration: underline; cursor: pointer; font-size: 12px;">Cancel or retry</button>
                                </div>
                            </div>
                        `);
                        $wawpOtpPopup.find('.wawp-otp-popup-content').append($waiting);
                    }
                    $waiting.show();
                    $wawpOtpPopup.css('display', 'flex').show();
                    startCheckoutListPolling(phoneNumber, currentOtpTransient, currentAuthId);
                } else {
                    $wawpOtpPopup.find('.wawp-list-waiting-container').hide();
                    $wawpOtpPopup.find('.wawp-otp-box, .wawp-otp-content').show();
                    showPopupMessage(wawp_translations.otp_sent_success, true);
                    $wawpOtpPopup.show();
                    otpSent = true;
                    startResendTimer();
                }
            } else {
                showPopupMessage(response.data || wawp_translations.otp_sent_failure, false);
            }
        } catch (error) {
            showPopupMessage(wawp_translations.otp_sent_failure, false);
        }
    }

    async function verifyOtp() {
        var otp = $wawpOtpInput.val().trim();
        if (otp.length < 6) {
            showPopupMessage('Please enter the 6-digit OTP.', false);
            return;
        }

        var method = wawp_translations.method || 'whatsapp';

        if (method === 'firebase' && confirmationResult) {
            try {
                await confirmationResult.confirm(otp);
                // Notify server about successful Firebase verification to set WC session
                await wawpRest('verify', {
                    firebase: true
                });
                showPopupMessage(wawp_translations.otp_verified_success, true);
                $wawpOtpPopup.hide();
                _wawp_locally_verified = true;
                $checkoutForm.submit();
            } catch (error) {
                showPopupMessage(error.message || wawp_translations.otp_incorrect, false);
            }
            return;
        }

        // Get stored values
        const transientToUse = currentOtpTransient || (() => {
            try {
                return sessionStorage.getItem('wawp_checkout_otp_transient');
            } catch (e) {
                return null;
            }
        })();
        
        const authIdToUse = currentAuthId || (() => {
            try {
                return sessionStorage.getItem('wawp_checkout_auth_id');
            } catch (e) {
                return null;
            }
        })();
        
        const phoneToUse = currentPhoneNumber || $('#billing_phone').val() || (() => {
            try {
                return sessionStorage.getItem('wawp_checkout_phone');
            } catch (e) {
                return null;
            }
        })();
        
        if (!transientToUse && !authIdToUse) {
            showPopupMessage('Session expired. Please request a new code.', false);
            return;
        }

        const verifyData = {
            otp: otp,
            phone_number: phoneToUse,
            method: wawp_translations.method || 'whatsapp'
        };
        
        if (transientToUse) {
            verifyData.otp_transient = transientToUse;
        }
        if (authIdToUse) {
            verifyData.auth_id = authIdToUse;
        }

        try {
            const response = await wawpRest('verify', verifyData);
            if (response.success) {
                // Clear sessionStorage on success
                try {
                    sessionStorage.removeItem('wawp_checkout_otp_transient');
                    sessionStorage.removeItem('wawp_checkout_auth_id');
                    sessionStorage.removeItem('wawp_checkout_phone');
                } catch (e) {}
                // Also clear the current variables
                currentOtpTransient = null;
                currentAuthId = null;
                currentPhoneNumber = null;
                showPopupMessage(wawp_translations.otp_verified_success, true);
                $wawpOtpPopup.hide();
                _wawp_locally_verified = true; // Set local flag to bypass interception
                $checkoutForm.submit();
            } else {
                showPopupMessage(response.data || wawp_translations.otp_incorrect, false);
            }
        } catch (error) {
            showPopupMessage(wawp_translations.otp_incorrect, false);
        }
    }

    var confirmationResult = null;
    var recaptchaVerifier = null;
    var _wawp_locally_verified = (wawpCheckoutOtpAjax.verified === 'true');

    function checkInterception() {
        if (_wawp_locally_verified) {
            return false;
        }

        var chosenPaymentMethod = $('input[name="payment_method"]:checked').val();
        if (typeof wawpDisable !== 'undefined' && wawpDisable && wawpDisable.disableMethods && Array.isArray(wawpDisable.disableMethods)) {
            if (wawpDisable.disableMethods.indexOf(chosenPaymentMethod) !== -1) {
                return false;
            }
        }

        var chosenShippingMethod = $('input[name^="shipping_method"]:checked').val() ||
            $('select[name^="shipping_method"]').val() ||
            $('input[name="shipping_method"]').val();

        if (typeof wawpDisableShipping !== 'undefined' && wawpDisableShipping && wawpDisableShipping.disableMethods && Array.isArray(wawpDisableShipping.disableMethods)) {
            if (wawpDisableShipping.disableMethods.indexOf(chosenShippingMethod) !== -1) {
                return false;
            }
        }

        return true;
    }

    function processInterception(e) {
        if (!checkInterception()) return true;

        var phoneNumber = $('#billing_phone').val() || $('input[name="billing_phone"]').val();
        if (!phoneNumber) {
            return true;
        }

        if ($wawpOtpPopup.is(':hidden')) {
            if (e) {
                if (e.preventDefault) e.preventDefault();
                if (e.stopImmediatePropagation) e.stopImmediatePropagation();
            }

            var firstName = $('#billing_first_name').val() || $('input[name="billing_first_name"]').val();
            var lastName = $('#billing_last_name').val() || $('input[name="billing_last_name"]').val();
            var email = $('#billing_email').val() || $('input[name="billing_email"]').val();

            $userPhoneNumber.text(phoneNumber);
            sendOtp(phoneNumber, firstName, lastName, email);
            $wawpOtpPopup.removeClass('wawp-hide').css({
                'display': 'flex',
                'align-items': 'center',
                'justify-content': 'center',
                'z-index': '999999999'
            }).show();
            setTimeout(function () { $wawpOtpInput.focus(); }, 100);
            return false;
        }

        if (e) {
            if (e.preventDefault) e.preventDefault();
            if (e.stopImmediatePropagation) e.stopImmediatePropagation();
        }
        return false;
    }

    $(document).on('click', '#place_order, .woocommerce-checkout-payment .button, button[name="woocommerce_checkout_place_order"]', function (e) {
        if (checkInterception() && $wawpOtpPopup.is(':hidden')) {
            return processInterception(e);
        }
    });

    $(document.body).on('checkout_place_order', function (e) {
        var shouldIntercept = checkInterception();
        if (shouldIntercept && $wawpOtpPopup.is(':hidden')) {
            return processInterception(e);
        }
        return !shouldIntercept;
    });

    $(document).on('checkout_error', function (e, error_messages) {
        var msgStr = JSON.stringify(error_messages);
        if (msgStr.indexOf("verify the OTP") !== -1 || msgStr.indexOf("changed your phone number") !== -1) {
            $('.woocommerce-NoticeGroup-checkout').empty();
            var phoneNumber = $('#billing_phone').val() || $('input[name="billing_phone"]').val();
            var firstName = $('#billing_first_name').val() || $('input[name="billing_first_name"]').val();
            var lastName = $('#billing_last_name').val() || $('input[name="billing_last_name"]').val();
            var email = $('#billing_email').val() || $('input[name="billing_email"]').val();

            if (phoneNumber) {
                $userPhoneNumber.text(phoneNumber);
                sendOtp(phoneNumber, firstName, lastName, email);
                $wawpOtpPopup.removeClass('wawp-hide').css({
                    'display': 'flex',
                    'align-items': 'center',
                    'justify-content': 'center',
                    'z-index': '999999999'
                }).show();
                $wawpOtpInput.focus();
            }
        }
    });

    $(document).on('click', '.wawp-otp-popup-close', function () {
        $wawpOtpPopup.hide();
        showPopupMessage('', false);
        otpSent = false;
        $wawpOtpInput.val('');
    });

    $wawpVerifyOtpBtn.on('click', function () {
        verifyOtp();
    });

    $wawpResendOtpBtn.on('click', function () {
        resendCount++;
        currentHoldTime = baseHoldTime * resendCount;
        var phoneNumber = $('#billing_phone').val();
        var firstName = $('#billing_first_name').val();
        var lastName = $('#billing_last_name').val();
        var email = $('#billing_email').val();
        sendOtp(phoneNumber, firstName, lastName, email);
    });
    $wawpOtpInput.on('keypress', function (e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            verifyOtp();
        }
    });

    $(document).on('click', '.js-wawp-cancel-list', function() {
        if (checkoutPollInterval) clearInterval(checkoutPollInterval);
        $wawpOtpPopup.hide();
        $('.wawp-list-waiting-container').hide();
        $wawpOtpPopup.find('.wawp-otp-box, .wawp-otp-content').show();
    });

    let checkoutPollInterval = null;
    let currentOtpTransient = null;
    let currentAuthId = null;
    let currentPhoneNumber = null;

    // Try to restore from sessionStorage on page load
    try {
        currentOtpTransient = sessionStorage.getItem('wawp_checkout_otp_transient');
        currentAuthId = sessionStorage.getItem('wawp_checkout_auth_id');
        currentPhoneNumber = sessionStorage.getItem('wawp_checkout_phone');
    } catch (e) {
        // sessionStorage not available
    }

    function startCheckoutListPolling(phoneNumber, transientKey, authId) {
        currentOtpTransient = transientKey;
        if (authId) {
            currentAuthId = authId;
        }
        try {
            if (transientKey) {
                sessionStorage.setItem('wawp_checkout_otp_transient', transientKey);
            }
            if (authId) {
                sessionStorage.setItem('wawp_checkout_auth_id', authId);
            }
        } catch (e) {
            // sessionStorage not available
        }
        if (checkoutPollInterval) clearInterval(checkoutPollInterval);
        
        let attempts = 0;
        const maxAttempts = 60;
        
        // Get auth_id from sessionStorage if not provided
        const authIdToUse = authId || (() => {
            try {
                return sessionStorage.getItem('wawp_checkout_auth_id');
            } catch (e) {
                return null;
            }
        })();
        
        checkoutPollInterval = setInterval(() => {
            attempts++;
            if (attempts > maxAttempts) {
                clearInterval(checkoutPollInterval);
                $wawpOtpPopup.hide();
                return;
            }

            const statusData = {
                whatsapp: phoneNumber,
                phone_number: phoneNumber,
                method: wawp_translations.method || 'whatsapp'
            };
            
            if (transientKey) {
                statusData.otp_transient = transientKey;
            }
            if (authIdToUse) {
                statusData.auth_id = authIdToUse;
            }
            
            wawpRest('status', statusData).then(resp => {
                if (resp.success && resp.data.verified) {
                    clearInterval(checkoutPollInterval);
                    $wawpOtpPopup.find('.wawp-list-waiting-container').html('<div class="wawp-list-waiting-icon" style="background:#15803d; color:white;"><i class="ri-check-line"></i></div><h4>Verified!</h4><p>Completing your order...</p>');
                    
                    setTimeout(() => {
                        $wawpOtpPopup.hide();
                        _wawp_locally_verified = true;
                        $checkoutForm.submit();
                    }, 1500);
                } else if (resp.success && resp.data.status === 'rejected') {
                    // User rejected the verification
                    clearInterval(checkoutPollInterval);
                    $wawpOtpPopup.find('.wawp-list-waiting-container').html('<div class="wawp-list-waiting-icon" style="background:#dc2626; color:white;"><i class="ri-close-line"></i></div><h4>Verification Rejected</h4><p>You rejected this verification request.</p>');
                    
                    setTimeout(() => {
                        $wawpOtpPopup.hide();
                        $('.wawp-list-waiting-container').hide();
                        $wawpOtpPopup.find('.wawp-otp-box, .wawp-otp-content').show();
                    }, 3000);
                }
            }).catch(() => {
                // Ignore polling errors
            });
        }, parseInt(wawpCheckoutOtpAjax.polling_interval) || 3000);
    }
});
