/**
 * Marketplace Tab View JS
 *
 * Handles: global save, reauthorize button, and notice display
 * for the 2-tab Edit Supplier layout.
 */
/* global momcs_marketplaceTabConfig, ajaxurl, jQuery */
(function ($) {
	'use strict';

	var cfg = momcs_marketplaceTabConfig || {};
	var nonces  = cfg.nonces  || {};
	var strings = cfg.strings || {};

	// ── Notice Helper ──────────────────────────────────────────────
	function showNotice( type, message ) {
		var $notice = $( '<div class="momcs-tab-notice momcs-tab-notice-' + type + '">' + message + '</div>' );
		$( '.momcs-tab-content' ).prepend( $notice );
		setTimeout( function() {
			$notice.fadeOut( 400, function() { $( this ).remove(); } );
		}, 4000 );
	}

	$( function () {

		// ── Global Save Button ────────────────────────────────────
		$( '#momcs-global-save-btn' ).on( 'click', function () {
			var $btn = $( this );
			$btn.prop( 'disabled', true ).text( strings.saving || 'Saving...' );

			var promises = [];

			// 1. Save mapping (trigger existing template mapping save if present)
			var $templateSaveBtn = $( '#momcs-template-mapping-save' );
			if ( $templateSaveBtn.length ) {
				var mappingDeferred = $.Deferred();

				$( document ).one( 'momcs_template_mapping_saved', function () {
					mappingDeferred.resolve();
				});
				$( document ).one( 'momcs_template_mapping_error', function ( e, errorData ) {
					mappingDeferred.reject( errorData && errorData.message ? errorData.message : 'Mapping error' );
				});

				$templateSaveBtn.trigger( 'click' );
				promises.push( mappingDeferred.promise() );
			}

			// 2. Save sync settings
			if ( nonces.saveSyncSettings && typeof window.collectAmazonSyncSettingsData === 'function' ) {
				var result = window.collectAmazonSyncSettingsData();
				if ( result && result.isValid === true ) {
					var syncPromise = $.post( ajaxurl, {
						action: 'momcs_sync_save_sync_settings',
						channel_uuid: cfg.channelUuid,
						settings_data: result.settings_data,
						security: nonces.saveSyncSettings
					});
					promises.push( syncPromise );
				}
			}

			if ( promises.length === 0 ) {
				// Nothing to save (e.g. free plan with no visible mapping)
				$btn.prop( 'disabled', false ).text( strings.saveSettings || 'Save Settings' );
				showNotice( 'success', strings.savedOk || 'Settings saved successfully.' );
				return;
			}

			// Wait for all saves to complete
			$.when.apply( $, promises ).done( function () {
				$btn.prop( 'disabled', false ).text( strings.saveSettings || 'Save Settings' );
				showNotice( 'success', strings.savedOk || 'Settings saved successfully.' );
			}).fail( function ( err ) {
				$btn.prop( 'disabled', false ).text( strings.saveSettings || 'Save Settings' );
				var msg = strings.errorSaving || 'Error saving settings.';
				if ( typeof err === 'string' ) {
					msg += ' ' + err;
				}
				showNotice( 'error', msg );
			});
		});

		// ── Reauthorize Button ────────────────────────────────────
		$( document ).on( 'click', '#momcs-reauthorize-btn', function () {
			$( '.momcs-auth-connected-status' ).hide();
			$( '#momcs-reauthorize-form-wrapper' ).show();
		});

	});

})( jQuery );
