/*
 * Product Settings Meta-box interactions for miniOrange WooCommerce Amazon Sync
 *
 * Handles the “Sync to Amazon Now” button behaviour.
 *
 * @package MOMCS_Sync
 */

/* global ajaxurl, momcsAmazonProductSettings */

document.addEventListener(
	'DOMContentLoaded',
	() => {
    const $        = jQuery;
    const $syncBtn = $( '#momcs-amz-sync-now' );
    // Bail early if the button does not exist on the current screen.
		if ( ! $syncBtn.length) {
			return;
		}

		$syncBtn.on(
			'click',
			function () {
				const $btn = $( this );

				$btn.prop( 'disabled', true ).text( momcsAmazonProductSettings.strings.syncing );

				$.post(
					ajaxurl,
					{
						action: 'momcs_amz_product_sync_now',
						product_id: $( '#post_ID' ).val(),
						security: $( '#momcs_amz_product_sync_now_nonce' ).val(),
					}
				).done(
					function (resp) {
						if (resp.success) {
							alert( momcsAmazonProductSettings.strings.success );
						} else if (resp.data && resp.data.message) {
							alert( resp.data.message );
						} else {
							alert( 'Unknown error' );
						}
					}
				).fail(
					function () {
						alert( 'Request failed.' );
					}
				).always(
					function () {
						$btn.prop( 'disabled', false ).text( momcsAmazonProductSettings.strings.sync_now );
					}
				);
			}
		);
	}
);
