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

    // Manually attach a click handler to the validate button (new key)
    $('#validate-api-key').on('click', function() {
        var apiKey = $('#mementor_tts_api_key').val();
        var nonce = $('#mementor_tts_nonce').val();

        if (!apiKey) {
            alert('Please enter an API key first.');
            return;
        }

        // Show processing state
        $(this).prop('disabled', true).text('Validating key & checking permissions...');

        $.post(
            mementorTTSValidation.ajaxUrl,
            {
                action: 'mementor_tts_verify_api_key',
                api_key: apiKey,
                nonce: nonce
            },
            function(response) {
                if (response.success) {
                    updateApiKeyStatus(true);

                    // Insert the permission notice HTML into the page
                    if (response.data && response.data.notice_html) {
                        $('#mementor-tts-validation-notice').remove();
                        $('.mementor-tts-api-actions').before(response.data.notice_html);
                    }

                    // Reload to update page state (buttons, stats, etc.)
                    if (response.data && response.data.reload === true) {
                        setTimeout(function() {
                            location.reload();
                        }, 100);
                    }
                } else {
                    updateApiKeyStatus(false);
                    var errorMsg = 'API key validation failed: ' + (response.data && response.data.message ? response.data.message : 'Unknown error');
                    alert(errorMsg);
                }
            }
        ).fail(function(xhr, textStatus, errorThrown) {
            updateApiKeyStatus(false);
            alert('Error validating API key: ' + errorThrown);
        }).always(function() {
            $('#validate-api-key').prop('disabled', false).text(mementorTTSValidation.validateButtonText);
        });
    });

    // Re-validate permissions for an already-stored key
    $('#revalidate-api-key').on('click', function() {
        var nonce = $('#mementor_tts_nonce').val();
        var btn = $(this);

        btn.prop('disabled', true).find('.dashicons').addClass('dashicons-update-spin');
        btn.contents().last()[0].textContent = ' Checking permissions...';

        $.post(
            mementorTTSValidation.ajaxUrl,
            {
                action: 'mementor_tts_revalidate_permissions',
                nonce: nonce
            },
            function(response) {
                if (response.success) {
                    // Reload to show updated permission status
                    location.reload();
                } else {
                    alert('Re-validation failed: ' + (response.data && response.data.message ? response.data.message : 'Unknown error'));
                }
            }
        ).fail(function(xhr, textStatus, errorThrown) {
            alert('Error re-validating: ' + errorThrown);
        }).always(function() {
            btn.prop('disabled', false).find('.dashicons').removeClass('dashicons-update-spin');
            btn.contents().last()[0].textContent = ' Re-validate Permissions';
        });
    });

    // Helper function to update the API key status UI
    function updateApiKeyStatus(isConnected) {
        const statusElement = $('.mementor-tts-api-status');

        if (isConnected) {
            statusElement.removeClass('not-connected').addClass('connected');
            statusElement.html('<span class="dashicons dashicons-yes-alt"></span> Connected');
        } else {
            statusElement.removeClass('connected').addClass('not-connected');
            statusElement.html('<span class="dashicons dashicons-trash"></span> Not Connected');
        }
    }
});
