(function( $ ) {
	'use strict';

	/**
	 * All of the code for your admin-facing JavaScript source
	 * should reside in this file.
	 *
	 * Note: It has been assumed you will write jQuery code here, so the
	 * $ function reference has been prepared for usage within the scope
	 * of this function.
	 *
	 * This enables you to define handlers, for when the DOM is ready:
	 *
	 * $(function() {
	 *
	 * });
	 *
	 * When the window is loaded:
	 *
	 * $( window ).load(function() {
	 *
	 * });
	 *
	 * ...and/or other possibilities.
	 *
	 * Ideally, it is not considered best practise to attach more than a
	 * single DOM-ready or window-load handler for a particular page.
	 * Although scripts in the WordPress core, Plugins and Themes may be
	 * practising this, we should strive to set a better example in our own work.
	 */

    $(document).ready(function () {
        $('#sync-facetwp-settings').click(function (e) {
            e.preventDefault();

            $('#sync-message').hide().text('');

            $.ajax({
                url: swFacetWp.ajax_url,
                type: 'POST',
                data: {
                    action: 'sync_facetwp_settings',
                    nonce: swFacetWp.nonce,
                },
                beforeSend: function () {
                    $('#sync-facetwp-settings').text('Syncing settings...').prop('disabled', true);
                },
                success: function (response) {
                    if (response.success) {
                        $('#sync-message')
                            .text('Settings synced. Syncing index...')
                            .css('color', 'green')
                            .show();

                        syncIndexBatch(1); // Start batch 1
                    } else {
                        $('#sync-message').text('Error: ' + response.data).css('color', 'red').show();
                        $('#sync-facetwp-settings').text('Sync FacetWP Settings').prop('disabled', false);
                    }
                },
                error: function () {
                    $('#sync-message').text('Unexpected error during settings sync.').css('color', 'red').show();
                    $('#sync-facetwp-settings').text('Sync FacetWP Settings').prop('disabled', false);
                }
            });

            function syncIndexBatch(batch, attempt = 1) {
                $.ajax({
                    url: swFacetWp.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'sync_index_batch',
                        nonce: swFacetWp.nonce,
                        batch: batch
                    },
                    success: function (response) {
                        if (response.success && response.data.next_batch !== false) {
                            $('#sync-message').text(`Index table batch ${batch} synced...`);
                            setTimeout(() => {
                                syncIndexBatch(response.data.next_batch);
                            }, 200); // Continue with next batch
                        } else if (response.success) {
                            $('#sync-message').text('All index batches synced. Reloading...');

                            setTimeout(() => {
                                location.reload();
                            }, 2000);
                        } else {
                            $('#sync-message').text('Error: ' + response.data).css('color', 'red');
                            $('#sync-facetwp-settings').text('Sync FacetWP Settings').prop('disabled', false);
                        }
                    },
                    error: function () {
                        if (attempt < 3) {
                            $('#sync-message').text(`Batch ${batch} failed. Retrying (${attempt + 1}/3)...`).css('color', 'orange');
                            setTimeout(() => {
                                syncIndexBatch(batch, attempt + 1); // Retry current batch
                            }, 1000);
                        } else {
                            $('#sync-message').text(`Batch ${batch} failed after 3 attempts.`).css('color', 'red');
                            $('#sync-facetwp-settings').text('Sync FacetWP Settings').prop('disabled', false);
                        }
                    }
                });
            }
        });

        $('#delete-facetwp-cache').click(function (e) {
            e.preventDefault();

            $('#delete-message').hide().text('');

            $.ajax({
                url: swFacetWp.ajax_url,
                type: 'POST',
                data: {
                    action: 'delete_facetwp_cache',
                    nonce: swFacetWp.nonce,
                },
                beforeSend: function () {
                    $('#delete-facetwp-cache').text('Deleting...').prop('disabled', true);
                },
                success: function (response) {
                    if (response.success) {
                        $('#delete-message').text('FacetWP cache cleared successfully!').css('color', 'green').show();
                    } else {
                        $('#delete-message').text('Error: ' + response.data).css('color', 'red').show();
                    }
                },
                complete: function () {
                    $('#delete-facetwp-cache').text('Delete FacetWP Cache').prop('disabled', false);
                }
            });
        });
    });

})( jQuery );
