jQuery(document).ready(function($) {
    $('#plugcrux-form').on('submit', function(e) {
        $('#plugcrux-auth-error-message').hide();
        $('#plugcrux-auth-success-message').hide();
        e.preventDefault(); // Prevent default form submission behavior

        var $authButton = $(this).find('.plugcrux-submit-button');
        var platform_url_input = $('#plugcrux-platform-url').val();
        var api_key_input = $('#plugcrux-api-key').val();
        var nonce = plugcruxFunctions.check_auth_nonce; // Access the localized nonce
        //
        $authButton.text('Please wait ...');

        $.ajax({
            url: plugcruxFunctions.ajaxurl, // Use the localized AJAX URL
            type: 'post',
            data: {
                action: 'plugcrux_check_auth', // The action that will trigger the appropriate PHP function
                platform_url: platform_url_input,
                api_key: api_key_input,
                _ajax_nonce: nonce // Pass the nonce to the server for verification
            },
            success: function(response) {
                if (response.success) {
                    // Show success message
                    $('#plugcrux-auth-success-message').text(response.data.message).show();
                } else {

                    // Show error message
                    $('#plugcrux-auth-error-message').text(response.data.message).show();
                }
                $authButton.text('Submit');
            },
            error: function(xhr, status, error) {
                // Show generic error message if the request fails
                $('#plugcrux-auth-error-message').text('An error occurred while processing your request. Please try again.').show();
                $authButton.text('Submit');
            }
        });
       
    });
});
