/* global two_factor_auth, jQuery */
/**
                 * Generates a new QR code.
                 */
function generateQRCode() {
    
    jQuery('#generate-qr').prop('disabled', true);
    var $spinner = jQuery('.qr-code .spinner');
    $spinner.addClass('is-active');
    
    // Clear any previous errors
    jQuery('#qr-code-img-err').empty();

    jQuery.ajax({
        url: two_factor_auth.ajaxurl,
        type: 'POST',
        data: {
            action: 'secnin_generate_qr_code',
            temp_token: two_factor_auth.temp_token
        },
        success: function (response) {
            jQuery('#generate-qr').prop('disabled', false);
            $spinner.removeClass('is-active');
            
            if (response.success && response.data && response.data.qr_code) {
                jQuery('#qr-code-img-err').empty();
                // The QR code is already base64 encoded, use it directly
                jQuery('#qr-code-img').attr('src', response.data.qr_code);
            } else {
                jQuery('#qr-code-img-err').html('<p class="errmsg">' + 
                    (response.data && response.data.message ? response.data.message : two_factor_auth.messages.qr_error) + '</p>');
            }
        },
        error: function () {
            // Error handling - no debug output in production
            jQuery('#generate-qr').prop('disabled', false);
            $spinner.removeClass('is-active');
            jQuery('#qr-code-img-err').html('<p class="errmsg">' + two_factor_auth.messages.network_error + '</p>');
        }
    });
}

/**
 * Sends a new 2FA email code.
 */
function sendEmailCode() {
    jQuery('#send-email').prop('disabled', true);
    var $status = jQuery('#email-status');
    $status.html('<p class="okmsg">' + two_factor_auth.messages.sending_email + '</p>');

    jQuery.ajax({
        url: two_factor_auth.ajaxurl,
        type: 'POST',
        data: {
            action: 'secnin_send_2fa_email',
            temp_token: two_factor_auth.temp_token
        },
        success: function (response) {
            jQuery('#send-email').prop('disabled', false);
            
            if (response.success) {
                $status.html('<p class="okmsg">' + response.data.message + '</p>');
            } else {
                $status.html('<p class="errmsg">' + 
                    (response.data && response.data.message ? response.data.message : two_factor_auth.messages.email_error) + '</p>');
            }
        },
        error: function () {
            jQuery('#send-email').prop('disabled', false);
            $status.html('<p class="errmsg">' + two_factor_auth.messages.network_error + '</p>');
        }
    });
}

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

    var $form = jQuery('#twofa-form-verify');
    var $input = jQuery('#twofa-code');
    var $button = jQuery('#verify-2fa');

    // Check if the form element exists and initialize accordingly
    if (jQuery('.qr-code').length) {
        generateQRCode();
    }

    // Auto-send email code if email method is used (for both new and existing users)
    if (jQuery('.email-2fa').length) {
        sendEmailCode();
    }

    $input.on('input', function () {
        var inputValue = jQuery(this).val();
        
        // Remove any non-digit characters
        inputValue = inputValue.replace(/\D/g, '');
        
        // Limit to 6 digits
        inputValue = inputValue.slice(0, 6);
        
        // Update input value
        jQuery(this).val(inputValue);
        
        // Enable/disable submit button based on input validity
        $button.prop('disabled', inputValue.length !== 6);
    });

    $form.on('submit', function (e) {
        e.preventDefault();
        var twofacode = $input.val();

        jQuery('#twofa-verify-msg').html('<p class="okmsg">' + two_factor_auth.messages.verifying + '</p>');

        $button.prop('disabled', true);
        $input.prop('disabled', true);

        $.ajax({
            url: two_factor_auth.ajaxurl,
            type: 'POST',
            data: {
                action: 'secnin_verify_2fa_code',
                code: twofacode,
                nonce: two_factor_auth.verify_nonce,
                temp_token: two_factor_auth.temp_token,
                user_id: two_factor_auth.user_id,
                user_ip: two_factor_auth.user_ip,
                user_agent: two_factor_auth.user_agent
            },
            success: function (response) {
                
                if (response.success) {
                    jQuery('#twofa-verify-msg').html('<p class="okmsg">' + response.data.message + '</p>');
                    
                    // Perform redirection after a short delay
                    setTimeout(function() {
                        window.location.href = response.data.redir_to;
                    }, 1000); // 1 second delay
                } else {

                    $button.prop('disabled', false);
                    $input.prop('disabled', false);
                    jQuery('#twofa-verify-msg').html('<p class="errmsg">' + response.data.message + '</p>');
                }
            },
            error: function () {
              
                jQuery('#twofa-verify-msg').html('<p class="errmsg">' + two_factor_auth.messages.network_error + '</p>');
                $button.prop('disabled', false);
                $input.prop('disabled', false);
            }
        });
    });

    jQuery('.skip-2fa-link').on('click', function(e) {
        e.preventDefault();
        
        // Disable all interactive elements
        var $skipLink = jQuery('.skip-2fa-link');
        var $verifyButton = jQuery('#verify-2fa');
        var $generateQrButton = jQuery('#generate-qr');
        var $sendEmailButton = jQuery('#send-email');
        var $twofaInput = jQuery('#twofa-code');
        
        $skipLink.css('opacity', '0.5').css('pointer-events', 'none');
        $verifyButton.prop('disabled', true);
        $generateQrButton.prop('disabled', true);
        $sendEmailButton.prop('disabled', true);
        $twofaInput.prop('disabled', true);
        
        jQuery.ajax({
            url: two_factor_auth.ajaxurl,
            type: 'POST',
            data: {
                action: 'secnin_skip_2fa',
                temp_token: two_factor_auth.temp_token
            },
            success: function(response) {
                if (response.success) {
                    window.location.href = response.data.redirect_url;
                } else {
                    // Re-enable all interactive elements
                    $skipLink.css('opacity', '').css('pointer-events', '');
                    $verifyButton.prop('disabled', false);
                    $generateQrButton.prop('disabled', false);
                    $sendEmailButton.prop('disabled', false);
                    $twofaInput.prop('disabled', false);
                    alert(response.data.message || two_factor_auth.messages.unknown_error);
                }
            },
            error: function() {
                // Re-enable all interactive elements
                $skipLink.css('opacity', '').css('pointer-events', '');
                $verifyButton.prop('disabled', false);
                $generateQrButton.prop('disabled', false);
                $sendEmailButton.prop('disabled', false);
                $twofaInput.prop('disabled', false);
                alert(two_factor_auth.messages.network_error);
            }
        });
    });

    // Add click handler for the Generate QR button
    $('#generate-qr').on('click', function(e) {
        e.preventDefault();
        generateQRCode();
    });

    // Add click handler for the Send Email button
    $('#send-email').on('click', function(e) {
        e.preventDefault();
        sendEmailCode();
    });
});
