jQuery(document).ready(function($) {
    $('#easy_gpt_youtube_api_key').on('change', function() {
        var apiKey = $(this).val();
        
        $.ajax({
            url: easyGptYoutubeAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'validate_youtube_api_key',
                security: easyGptYoutubeAjax.nonce,
                api_key: apiKey
            },
            success: function(response) {
                var validationDiv = $('#easy_gpt_youtube_api_key_validation');
                if (response.success) {
                    validationDiv.html("<span style='color: green;'>YouTube API Key is valid.</span>");
                } else {
                    validationDiv.html("<span style='color: red;'>YouTube API Key is invalid.</span>");
                }
            },
            error: function() {
                $('#easy_gpt_youtube_api_key_validation').html("<span style='color: red;'>Error validating the YouTube API Key.</span>");
            }
        });
    });
});