(function($) {
    'use strict';

    $(document).ready(function() {
        const messageContainer = $('#unlockafe-sync-message');

        /**
         * Hides the Client ID and Secret fields when connected to Google,
         * as they are only needed for the initial connection.
         * Other fields like Sheet ID remain visible for editing.
         */
        function toggleApiFieldsVisibility() {
            // Check for the green "Connected" status text to determine connection state.
            const isConnected = $('#setting-section-google_connection_status').find('p[style*="color: green"]').length > 0;

            if (isConnected) {
                // If connected, hide the sensitive credential fields.
                $('#google_client_id').closest('tr').hide();
                $('#google_client_secret').closest('tr').hide();
            } else {
                // If not connected, ensure they are visible.
                $('#google_client_id').closest('tr').show();
                $('#google_client_secret').closest('tr').show();
            }
        }

        // Run the check as soon as the page loads.
        toggleApiFieldsVisibility();

        // This function handles the AJAX call for both sync buttons.
        $('#sync-all-orders, #unlockafe-manual-sync').on('click', function(e) {
            e.preventDefault();

            const $button = $(this);
            const originalButtonText = $button.html();
            // Determine which AJAX action to call based on the button clicked.
            const action = $button.is('#sync-all-orders') ? 'sync_advantage_export_all' : 'unlockafe_manual_sync';
            const $spinner = $button.next('.spinner');

            // Disable button and show spinner to provide user feedback.
            $button.prop('disabled', true).html('Syncing...');
            if ($spinner.length) {
                $spinner.addClass('is-active');
            }

            // Reset the message container before the new request.
            messageContainer.hide().removeClass('notice-error notice-success notice-info').html('');

            $.ajax({
                url: syncAdvantageSettings.ajax_url,
                type: 'POST',
                data: {
                    action: action,
                    nonce: syncAdvantageSettings.nonce
                },
                success: function(response) {
                    if (response.success) {
                        messageContainer.removeClass('notice-error').addClass('notice-success').html('<p>' + response.data.message + '</p>').show();
                    } else {
                        messageContainer.removeClass('notice-success').addClass('notice-error').html('<p>' + (response.data.message || 'An unknown error occurred.') + '</p>').show();
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    let errorMessage = 'AJAX Error: ' + errorThrown;
                    if (jqXHR.responseJSON && jqXHR.responseJSON.data && jqXHR.responseJSON.data.message) {
                        errorMessage = jqXHR.responseJSON.data.message;
                    }
                    messageContainer.removeClass('notice-success').addClass('notice-error').html('<p>' + errorMessage + '</p>').show();
                },
                complete: function() {
                    // Re-enable the button and hide the spinner.
                    $button.prop('disabled', false).html(originalButtonText);
                    if ($spinner.length) {
                        $spinner.removeClass('is-active');
                    }
                }
            });
        });

        // Clean the URL by removing the 'status' parameter to prevent the notice
        // from showing up again on a manual page refresh.
        if (window.history.replaceState) {
            const url = new URL(window.location.href);
            if (url.searchParams.has('status')) {
                url.searchParams.delete('status');
                window.history.replaceState({ path: url.href }, '', url.href);
            }
        }
    });

})(jQuery);
