/*
 * Marketplace Stepper navigation – extracted from inline JS.
 *
 * Relies on global `window.collectAmazonMappingData` (defined by
 * amazon-template-mapping.js) when on step 2 for Amazon.
 */

/* global momcs_marketplaceStepperConfig, ajaxurl, jQuery */
(function ($) {
	const cfg = momcs_marketplaceStepperConfig || {};

	let currentStep = Number( cfg.currentStep );
	const {
		marketplace,
		channelUuid,
		nonces,
		strings,
	}               = cfg;

	const $nextBtn = $( '#momcs-stepper-next' );
	const $prevBtn = $( '#momcs-stepper-prev' );

	function localButtonLabel(step) {
		if (step === 2 || step === 3) {
			return strings.saveAndNext;
		}
		return strings.next;
	}

	function proceedToNextStep() {
		// Persist the new step in DB, then redirect.
		const newStep = currentStep + 1;
		const url     = new URL( window.location.href );
		url.searchParams.set( 'step', String( newStep ) );

		$.post(
			ajaxurl,
			{
				action: 'momcs_sync_update_step',
				step: newStep,
				marketplace: marketplace,
				channel_uuid: channelUuid,
				security: nonces.updateStep,
			}
		).always(
			function () {
				window.location.href = url.toString();
			}
		);
	}

	$prevBtn.on(
		'click',
		function () {
			if (currentStep <= 1) {
				return;
			}
			$prevBtn.prop( 'disabled', true ).text( strings.loading || 'Loading...' );
			const newStep = currentStep - 1;
			const url     = new URL( window.location.href );
			url.searchParams.set( 'step', String( newStep ) );

			$.post(
				ajaxurl,
				{
					action: 'momcs_sync_update_step',
					step: newStep,
					marketplace: marketplace,
					channel_uuid: channelUuid,
					security: nonces.updateStep,
				}
			).always(
				function () {
					window.location.href = url.toString();
				}
			);
		}
	);

	$nextBtn.on(
		'click',
		function () {
			$nextBtn.prop( 'disabled', true ).text( strings.saving );

			if (currentStep === 2 && marketplace === 'amazon') {
				// Delegate validation + AJAX saving to amazon-template-mapping.js so we avoid duplicate requests.
				const $saveBtn = $( '#momcs-template-mapping-save' );
				if ($saveBtn.length) {
					$saveBtn.trigger( 'click' );
				} else {
					// Fallback – still proceed if somehow not on mapping page.
					proceedToNextStep();
				}
			} else if (currentStep === 3) {
				// If premium not enabled or nonce missing, skip save and proceed
				if (!nonces || !nonces.saveSyncSettings) {
					proceedToNextStep();
					return;
				}
				if (typeof window.collectAmazonSyncSettingsData === 'function') {
					try {
						const result = window.collectAmazonSyncSettingsData();
						if (!result || result.isValid !== true) {
							$( document ).trigger( 'momcs_template_mapping_error' );
							return;
						}
						$.post(
							ajaxurl,
							{
								action: 'momcs_sync_save_sync_settings',
								channel_uuid: channelUuid,
								settings_data: result.settings_data,
								security: nonces.saveSyncSettings,
							}
						).done(function(resp){
							if (resp && resp.success) {
								proceedToNextStep();
							} else {
								$nextBtn.prop( 'disabled', false ).text( localButtonLabel( currentStep ) );
								alert( (strings.errorSaveSyncSettings || 'Error saving sync settings: ') + (resp && resp.data && resp.data.message ? resp.data.message : '') );
							}
						}).fail(function(){
							$nextBtn.prop( 'disabled', false ).text( localButtonLabel( currentStep ) );
							alert( strings.errorSaveSyncSettings || 'Error saving sync settings.' );
						});
					} catch (e) {
						$nextBtn.prop( 'disabled', false ).text( localButtonLabel( currentStep ) );
					}
				} else {
					// Collector not available; proceed without saving
					proceedToNextStep();
				}
			} else {
				proceedToNextStep();
			}
		}
	);

	// Once the mapping script confirms a successful save we can safely advance.
	$( document ).on(
		'momcs_template_mapping_saved',
		function () {
			localStorage.setItem( 'momcs_' + marketplace + '_mapping_saved', 'true' );
			proceedToNextStep();
		}
	);

	// If mapping reports an error, re-enable the Next button and restore label
	$( document ).on(
		'momcs_template_mapping_error',
		function () {
			$nextBtn.prop( 'disabled', false ).text( localButtonLabel( currentStep ) );
		}
	);
})( jQuery );
