/*
 * JS extracted from inline script of Amazon Sync Settings view.
 */
(function ($) {
	function toggleAmazonToWcScheduleFields() {
		const enabled = $('#momcs-amazon-to-wc-schedule-enabled').is(':checked');
		$('#momcs-amazon-to-wc-schedule-frequency, #momcs-amazon-to-wc-schedule-interval').prop('disabled', !enabled);
	}

	function toggleFbaStockScheduleFields() {
		const accountType = ($('input[name="account_settings[account_type]"]:checked').val() || 'fbm').toLowerCase();
		const isFbaAccount = accountType === 'fba';
		const $enabledCheckbox = $('#momcs-fba-stock-schedule-enabled');
		const scheduleEnabled = $enabledCheckbox.is(':checked');

		$enabledCheckbox.prop('disabled', !isFbaAccount);
		if (!isFbaAccount) {
			$enabledCheckbox.prop('checked', false);
		}

		const enableFields = isFbaAccount && scheduleEnabled;
		$('#momcs-fba-stock-schedule-frequency, #momcs-fba-stock-schedule-interval').prop('disabled', !enableFields);
	}

	function formatRecurrenceForCard(frequency, interval) {
		const n = parseInt(frequency, 10) || 1;
		if (n === 1) {
			if (interval === 'days') return 'Daily';
			if (interval === 'hours') return 'Every hour';
			if (interval === 'minutes') return 'Every minute';
			if (interval === 'months') return 'Monthly';
		}
		const label = interval === 'hours' ? 'hours' : (interval === 'days' ? 'days' : (interval === 'minutes' ? 'minutes' : 'months'));
		return 'Every ' + n + ' ' + label;
	}

	function updateScheduleCardRecurrenceDisplays() {
		const awcFreq = parseInt($('#momcs-amazon-to-wc-schedule-frequency').val(), 10) || 6;
		const awcInterval = $('#momcs-amazon-to-wc-schedule-interval').val() || 'hours';
		$('#momcs-amazon-to-wc-recurrence-display').text(formatRecurrenceForCard(awcFreq, awcInterval));

		const fbaFreq = parseInt($('#momcs-fba-stock-schedule-frequency').val(), 10) || 6;
		const fbaInterval = $('#momcs-fba-stock-schedule-interval').val() || 'hours';
		$('#momcs-fba-stock-recurrence-display').text(formatRecurrenceForCard(fbaFreq, fbaInterval));

		const orderFreq = parseInt($('#momcs-order-schedule-frequency').val(), 10) || 24;
		const orderInterval = $('#momcs-order-schedule-interval').val() || 'hours';
		$('#momcs-order-schedule-recurrence-display').text(formatRecurrenceForCard(orderFreq, orderInterval));
	}

    // Preload settings on document ready (premium only; backend decides nonce availability)
    $(function(){
        if (typeof momcs_sync_settings === 'object' && momcs_sync_settings && momcs_sync_settings.channel_uuid && momcs_sync_settings.nonce_get_sync) {
            $.post(
                momcs_sync_settings.ajax_url || ajaxurl,
                {
                    action: 'momcs_sync_get_sync_settings',
                    channel_uuid: momcs_sync_settings.channel_uuid,
                    security: momcs_sync_settings.nonce_get_sync,
                }
            ).done(function(resp){
                if (resp && resp.success && resp.data && resp.data.config) {
                    try {
                        const cfg = resp.data.config;
                        // Populate product sync price markup
                        if (cfg.product_sync && cfg.product_sync.sync_settings && cfg.product_sync.sync_settings.price_markup) {
                            const pm = cfg.product_sync.sync_settings.price_markup;
                            if (typeof pm.operator !== 'undefined') {
                                $('#momcs_markup_operator').val(pm.operator);
                            }
                            if (typeof pm.percentage !== 'undefined') {
                                $('#momcs_markup_percentage').val(pm.percentage);
                            }
                        }
                        
                        // Hide shimmer and show actual fields for price markup
                        $('#momcs-markup-operator-wrapper').removeClass('momcs-field-loading');
                        $('#momcs-markup-operator-wrapper .momcs-field-shimmer').hide();
                        $('#momcs_markup_operator').show();
                        
                        $('#momcs-markup-percentage-wrapper').removeClass('momcs-field-loading');
                        $('#momcs-markup-percentage-wrapper .momcs-field-shimmer').hide();
                        $('#momcs_markup_percentage').show();
                        
                        // Populate order auto-fulfillment setting
                        if (cfg.order_sync && cfg.order_sync.sync_settings && cfg.order_sync.sync_settings.auto_fulfillment) {
                            const autoFulfillment = cfg.order_sync.sync_settings.auto_fulfillment;
                            if (typeof autoFulfillment.enabled !== 'undefined') {
                                $('#momcs-order-auto-fulfillment-enabled').prop('checked', autoFulfillment.enabled === true);
                                console.log('- Auto fulfillment enabled:', autoFulfillment.enabled);
                            }
                        } else {
                            $('#momcs-order-auto-fulfillment-enabled').prop('checked', false);
                        }

                        // Populate order sync settings
                        if (cfg.order_sync && cfg.order_sync.sync_settings && cfg.order_sync.sync_settings.scheduled_sync) {
                            const orderSchedule = cfg.order_sync.sync_settings.scheduled_sync;
                            console.log('📦 Order sync settings found:', orderSchedule);
                            
                            // Populate enabled checkbox
                            if (typeof orderSchedule.enabled !== 'undefined') {
                                $('#momcs-order-schedule-enabled').prop('checked', orderSchedule.enabled === true);
                                console.log('- Enabled:', orderSchedule.enabled);
                            }
                            
                            // Populate frequency
                            if (typeof orderSchedule.frequency !== 'undefined') {
                                $('#momcs-order-schedule-frequency').val(orderSchedule.frequency);
                                console.log('- Frequency:', orderSchedule.frequency);
                            }
                            
                            // Populate interval
                            if (typeof orderSchedule.interval !== 'undefined') {
                                $('#momcs-order-schedule-interval').val(orderSchedule.interval);
                                console.log('- Interval:', orderSchedule.interval);
                            }
                            
                            // Enable/disable fields based on enabled state
                            const isEnabled = orderSchedule.enabled === true;
                            $('#momcs-order-schedule-frequency, #momcs-order-schedule-interval').prop('disabled', !isEnabled);
                            console.log('- Fields enabled:', isEnabled);
                            
                            // Update preview and card recurrence
                            if (typeof window.updateOrderSchedulePreview === 'function') {
                                window.updateOrderSchedulePreview();
                            }
                            updateScheduleCardRecurrenceDisplays();
                            
                            console.log('✅ Order sync settings populated successfully');
                        } else {
                            console.log('ℹ️ No order sync settings found in config');
                            // Disable fields by default if no settings found
                            $('#momcs-order-schedule-frequency, #momcs-order-schedule-interval').prop('disabled', true);
                        }

						// Populate Amazon -> WooCommerce scheduled sync settings.
						if (cfg.amazon_to_wc_scheduled_sync) {
							const reverseSchedule = cfg.amazon_to_wc_scheduled_sync;
							const reverseEnabled = reverseSchedule.enabled === true;

							$('#momcs-amazon-to-wc-schedule-enabled').prop('checked', reverseEnabled);
							if (typeof reverseSchedule.frequency !== 'undefined') {
								$('#momcs-amazon-to-wc-schedule-frequency').val(reverseSchedule.frequency);
							}
							if (typeof reverseSchedule.interval !== 'undefined') {
								$('#momcs-amazon-to-wc-schedule-interval').val(reverseSchedule.interval);
							}
						} else {
							$('#momcs-amazon-to-wc-schedule-enabled').prop('checked', false);
						}
						toggleAmazonToWcScheduleFields();
						updateScheduleCardRecurrenceDisplays();

						// Populate account settings.
						if (cfg.account_settings && typeof cfg.account_settings.account_type !== 'undefined') {
							$('input[name="account_settings[account_type]"][value="' + cfg.account_settings.account_type + '"]').prop('checked', true);
						}

						// Hide FBA/FBM shimmer and show the actual radio buttons
						$('#momcs-account-type-shimmer').hide();
						$('#momcs-account-type-wrapper .momcs-account-type-fieldset').show();

						// Populate FBA stock schedule settings.
						if (cfg.fba_stock_schedule) {
							const fbaSchedule = cfg.fba_stock_schedule;
							const fbaEnabled = fbaSchedule.enabled === true;

							$('#momcs-fba-stock-schedule-enabled').prop('checked', fbaEnabled);
							if (typeof fbaSchedule.frequency !== 'undefined') {
								$('#momcs-fba-stock-schedule-frequency').val(fbaSchedule.frequency);
							}
							if (typeof fbaSchedule.interval !== 'undefined') {
								$('#momcs-fba-stock-schedule-interval').val(fbaSchedule.interval);
							}
						} else {
							$('#momcs-fba-stock-schedule-enabled').prop('checked', false);
						}
						toggleFbaStockScheduleFields();
						updateScheduleCardRecurrenceDisplays();
                    } catch(e){ 
                        console.error('Error populating sync settings:', e);
                    }
                }
            }).fail(function() {
                // On failure, also hide shimmer and show fields
                $('#momcs-markup-operator-wrapper').removeClass('momcs-field-loading');
                $('#momcs-markup-operator-wrapper .momcs-field-shimmer').hide();
                $('#momcs_markup_operator').show();

                $('#momcs-markup-percentage-wrapper').removeClass('momcs-field-loading');
                $('#momcs-markup-percentage-wrapper .momcs-field-shimmer').hide();
                $('#momcs_markup_percentage').show();

                // Show FBA/FBM radio buttons even on failure
                $('#momcs-account-type-shimmer').hide();
                $('#momcs-account-type-wrapper .momcs-account-type-fieldset').show();

				toggleAmazonToWcScheduleFields();
				toggleFbaStockScheduleFields();
            });
        } else {
            // If no AJAX call is made, hide shimmer immediately
            $('#momcs-markup-operator-wrapper').removeClass('momcs-field-loading');
            $('#momcs-markup-operator-wrapper .momcs-field-shimmer').hide();
            $('#momcs_markup_operator').show();

            $('#momcs-markup-percentage-wrapper').removeClass('momcs-field-loading');
            $('#momcs-markup-percentage-wrapper .momcs-field-shimmer').hide();
            $('#momcs_markup_percentage').show();

            // Show FBA/FBM radio buttons immediately
            $('#momcs-account-type-shimmer').hide();
            $('#momcs-account-type-wrapper .momcs-account-type-fieldset').show();

			toggleAmazonToWcScheduleFields();
			toggleFbaStockScheduleFields();
        }
    });
	// ── Sidebar Navigation ──────────────────────────────────────
	// Tabs (including Order Sync / Schedule for free) are clickable so users can view disabled-state content.
	$( document ).on( 'click', '.momcs-sync-sidebar-link', function ( e ) {
		e.preventDefault();

		var $link = $( this );
		var $item = $link.closest( '.momcs-sync-sidebar-item' );

		var targetPanelId = $link.attr( 'href' );
		if ( ! targetPanelId ) {
			return;
		}

		// Update sidebar active state
		$( '.momcs-sync-sidebar-item' ).removeClass( 'momcs-sync-sidebar-item--active' );
		$item.addClass( 'momcs-sync-sidebar-item--active' );

		// Update aria attributes
		$( '.momcs-sync-sidebar-link' ).attr( 'aria-selected', 'false' );
		$link.attr( 'aria-selected', 'true' );

		// Show target panel, hide others (use class toggle only, no inline styles)
		$( '.momcs-sync-content-panel' ).removeClass( 'momcs-sync-content-panel--active' );
		$( targetPanelId ).addClass( 'momcs-sync-content-panel--active' );

		// Clear any active sub-link highlighting
		$( '.momcs-sync-sidebar-sublink' ).removeClass( 'momcs-sync-sidebar-sublink--active' );
	} );

	// ── Sub-link scroll-to-section ──────────────────────────────
	$( document ).on( 'click', '.momcs-sync-sidebar-sublink', function ( e ) {
		e.preventDefault();

		var $sublink = $( this );
		var sectionId = $sublink.attr( 'href' );

		// Ensure the parent panel is active
		var $parentItem = $sublink.closest( '.momcs-sync-sidebar-item' );
		if ( ! $parentItem.hasClass( 'momcs-sync-sidebar-item--active' ) ) {
			$parentItem.find( '> .momcs-sync-sidebar-link' ).trigger( 'click' );
		}

		// Highlight this sub-link
		$( '.momcs-sync-sidebar-sublink' ).removeClass( 'momcs-sync-sidebar-sublink--active' );
		$sublink.addClass( 'momcs-sync-sidebar-sublink--active' );

		// Scroll to the section within the page
		var $target = $( sectionId );
		if ( $target.length ) {
			$( 'html, body' ).animate( {
				scrollTop: $target.offset().top - 50
			}, 400 );
		}
	} );

	/**
	 * Collect all sync settings data – used by marketplace stepper.
	 *
	 * @returns {{isValid: boolean, settings_data: string}}
	 */
	function collectAllSyncSettingsData(){
		// Collect from main sync settings form
		const formArray  = $( '#momcs-sync-settings-form' ).serializeArray();
		const formObject = {};

	// Scheduled sync fields are now part of the main form
	const scheduledSyncFieldNames = [
		'momcs_scheduled_sync_nonce',
		'schedule_enabled',
		'schedule_time', 
		'schedule_frequency',
		'schedule_interval',
		'schedule_attributes'
	];

	// Order scheduled sync fields
	const orderScheduledSyncFieldNames = [
		'momcs_order_scheduled_sync_nonce',
		'order_auto_fulfillment_enabled',
		'order_schedule_enabled',
		'order_schedule_frequency',
		'order_schedule_interval'
	];

	// Amazon -> WooCommerce scheduled sync fields
	const amazonToWcScheduledSyncFieldNames = [
		'amazon_to_wc_schedule_enabled',
		'amazon_to_wc_schedule_frequency',
		'amazon_to_wc_schedule_interval'
	];

	// FBA stock scheduled sync fields
	const fbaStockScheduledSyncFieldNames = [
		'fba_stock_schedule_enabled',
		'fba_stock_schedule_frequency',
		'fba_stock_schedule_interval'
	];
	
	// Debug: Check scheduled sync form status
	console.log('🔍 Scheduled sync integration debug:');
	console.log('- Main form fields total:', formArray.length);
	console.log('- Looking for scheduled sync fields in main form...');

	function setDeep(target, parts, value) {
			let ref = target;
			for (let i = 0; i < parts.length; i++) {
				const key = parts[i];
				const isLast = i === parts.length - 1;
				if (isLast) {
					ref[key] = value;
				} else {
					if (typeof ref[key] !== 'object' || ref[key] === null) {
						ref[key] = {};
					}
					ref = ref[key];
				}
			}
		}

		// Process main form data and separate scheduled sync fields
		$.each(
			formArray,
			function (i, field) {
				if (field.name === 'momcs_sync_settings_nonce' || field.name === '_wp_http_referer') {
					return; // continue
				}
				
				// Check if this is a scheduled sync field
				const isScheduledSyncField = scheduledSyncFieldNames.includes(field.name) || 
				                           field.name.startsWith('schedule_') ||
				                           field.name === 'momcs_scheduled_sync_nonce';
				
				// Check if this is an order scheduled sync field
				const isOrderScheduledSyncField = orderScheduledSyncFieldNames.includes(field.name) || 
				                                 field.name.startsWith('order_schedule_') ||
				                                 field.name === 'momcs_order_scheduled_sync_nonce';

				// Check if this is an Amazon -> WooCommerce scheduled sync field
				const isAmazonToWcScheduledSyncField = amazonToWcScheduledSyncFieldNames.includes(field.name) ||
				                                       field.name.startsWith('amazon_to_wc_schedule_');

				// Check if this is an FBA stock scheduled sync field
				const isFbaStockScheduledSyncField = fbaStockScheduledSyncFieldNames.includes(field.name) ||
				                                     field.name.startsWith('fba_stock_schedule_');
				
				if (isScheduledSyncField) {
					// Skip the nonce field
					if (field.name === 'momcs_scheduled_sync_nonce') {
						return;
					}
					
					// Create scheduled_sync object if it doesn't exist
					if (!formObject.scheduled_sync) {
						formObject.scheduled_sync = {};
					}
					
					// Handle array fields (like schedule_attributes[])
					if (field.name.endsWith('[]')) {
						const cleanName = field.name.replace('[]', '');
						if (!formObject.scheduled_sync[cleanName]) {
							formObject.scheduled_sync[cleanName] = [];
						}
						formObject.scheduled_sync[cleanName].push(field.value);
					} else {
						// Convert checkbox 'on' value to 'yes' for backend compatibility
						if (field.name === 'schedule_enabled' && field.value === 'on') {
							formObject.scheduled_sync[field.name] = 'yes';
							console.log('- Found scheduled sync field:', field.name, '= (converted)', field.value, '→ yes');
						} else {
							formObject.scheduled_sync[field.name] = field.value;
							console.log('- Found scheduled sync field:', field.name, '=', field.value);
						}
					}
				} else if (isOrderScheduledSyncField) {
					// Skip the nonce field
					if (field.name === 'momcs_order_scheduled_sync_nonce') {
						return;
					}
					
					// Create nested order_sync structure if it doesn't exist
					if (!formObject.order_sync) {
						formObject.order_sync = {};
					}
					if (!formObject.order_sync.sync_settings) {
						formObject.order_sync.sync_settings = {};
					}
					if (!formObject.order_sync.sync_settings.scheduled_sync) {
						formObject.order_sync.sync_settings.scheduled_sync = {};
					}
					
					// Map field name to nested structure
					const cleanFieldName = field.name.replace('order_schedule_', '');
					
					// Convert checkbox 'on' value to boolean true for backend compatibility
					if (field.name === 'order_auto_fulfillment_enabled') {
						if (!formObject.order_sync.sync_settings.auto_fulfillment) {
							formObject.order_sync.sync_settings.auto_fulfillment = {};
						}
						formObject.order_sync.sync_settings.auto_fulfillment.enabled = (field.value === 'on');
						console.log('- Found order auto-fulfillment field:', field.name, '= (converted)', field.value, '→', (field.value === 'on'));
					} else if (field.name === 'order_schedule_enabled') {
						formObject.order_sync.sync_settings.scheduled_sync.enabled = (field.value === 'on');
						console.log('- Found order schedule field:', field.name, '= (converted)', field.value, '→', (field.value === 'on'));
					} else if (field.name === 'order_schedule_frequency') {
						formObject.order_sync.sync_settings.scheduled_sync.frequency = parseInt(field.value, 10);
						console.log('- Found order schedule field:', field.name, '=', field.value);
					} else if (field.name === 'order_schedule_interval') {
						formObject.order_sync.sync_settings.scheduled_sync.interval = field.value;
						console.log('- Found order schedule field:', field.name, '=', field.value);
					}
				} else if (isAmazonToWcScheduledSyncField) {
					if (!formObject.amazon_to_wc_scheduled_sync) {
						formObject.amazon_to_wc_scheduled_sync = {};
					}

					if (field.name === 'amazon_to_wc_schedule_enabled') {
						formObject.amazon_to_wc_scheduled_sync.enabled = (field.value === 'on');
					} else if (field.name === 'amazon_to_wc_schedule_frequency') {
						formObject.amazon_to_wc_scheduled_sync.frequency = parseInt(field.value, 10);
					} else if (field.name === 'amazon_to_wc_schedule_interval') {
						formObject.amazon_to_wc_scheduled_sync.interval = field.value;
					}
				} else if (isFbaStockScheduledSyncField) {
					if (!formObject.fba_stock_schedule) {
						formObject.fba_stock_schedule = {};
					}

					if (field.name === 'fba_stock_schedule_enabled') {
						formObject.fba_stock_schedule.enabled = (field.value === 'on');
					} else if (field.name === 'fba_stock_schedule_frequency') {
						formObject.fba_stock_schedule.frequency = parseInt(field.value, 10);
					} else if (field.name === 'fba_stock_schedule_interval') {
						formObject.fba_stock_schedule.interval = field.value;
					}
				} else {
					// Regular sync settings field
					// Convert bracket notation: a[b][c] -> ["a","b","c"]
					const parts = field.name.replace(/\]/g, '').split('[');
					setDeep(formObject, parts, field.value);
				}
			}
		);

		// No separate scheduled sync form processing needed - handled in main form loop above

		// Include unchecked checkboxes explicitly as "no" from main form
		$( '#momcs-sync-settings-form input[type="checkbox"]' ).each(
			function () {
				const name = $( this ).attr( 'name' );
				if (!name) { return; }
				
				// Check if this is a scheduled sync checkbox
				const isScheduledSyncCheckbox = scheduledSyncFieldNames.includes(name) || name.startsWith('schedule_');
				
				// Check if this is an order scheduled sync checkbox
				const isOrderScheduledSyncCheckbox = orderScheduledSyncFieldNames.includes(name) || name.startsWith('order_schedule_');

				// Check if this is an Amazon -> WooCommerce scheduled sync checkbox
				const isAmazonToWcScheduledSyncCheckbox = amazonToWcScheduledSyncFieldNames.includes(name) || name.startsWith('amazon_to_wc_schedule_');

				// Check if this is an FBA stock scheduled sync checkbox
				const isFbaStockScheduledSyncCheckbox = fbaStockScheduledSyncFieldNames.includes(name) || name.startsWith('fba_stock_schedule_');
				
				if (isScheduledSyncCheckbox) {
					// Handle scheduled sync checkboxes
					if (!formObject.scheduled_sync) {
						formObject.scheduled_sync = {};
					}
					// Always set the checkbox value to ensure accurate state (overwrite any previous value)
					formObject.scheduled_sync[name] = $( this ).is(':checked') ? 'yes' : 'no';
				} else if (isOrderScheduledSyncCheckbox) {
					// Handle order scheduled sync checkboxes
					if (!formObject.order_sync) {
						formObject.order_sync = {};
					}
					if (!formObject.order_sync.sync_settings) {
						formObject.order_sync.sync_settings = {};
					}
					if (name === 'order_auto_fulfillment_enabled') {
						if (!formObject.order_sync.sync_settings.auto_fulfillment) {
							formObject.order_sync.sync_settings.auto_fulfillment = {};
						}
						formObject.order_sync.sync_settings.auto_fulfillment.enabled = $( this ).is(':checked');
					} else {
						if (!formObject.order_sync.sync_settings.scheduled_sync) {
							formObject.order_sync.sync_settings.scheduled_sync = {};
						}
					}
					if (name === 'order_schedule_enabled') {
						// Always set the checkbox value to ensure accurate state
						formObject.order_sync.sync_settings.scheduled_sync.enabled = $( this ).is(':checked');
					}
				} else if (isAmazonToWcScheduledSyncCheckbox) {
					if (!formObject.amazon_to_wc_scheduled_sync) {
						formObject.amazon_to_wc_scheduled_sync = {};
					}
					if (name === 'amazon_to_wc_schedule_enabled') {
						formObject.amazon_to_wc_scheduled_sync.enabled = $( this ).is(':checked');
					}
				} else if (isFbaStockScheduledSyncCheckbox) {
					if (!formObject.fba_stock_schedule) {
						formObject.fba_stock_schedule = {};
					}
					if (name === 'fba_stock_schedule_enabled') {
						formObject.fba_stock_schedule.enabled = $( this ).is(':checked');
					}
				} else {
					// Handle main form checkboxes
					const parts = name.replace(/\]/g, '').split('[');

					// Resolve current value in formObject
					let ref = formObject;
					for (let i = 0; i < parts.length - 1; i++) {
						const key = parts[i];
						if (typeof ref[key] !== 'object' || ref[key] === null) {
							ref[key] = {};
						}
						ref = ref[key];
					}
					const lastKey = parts[parts.length - 1];
					if (typeof ref[lastKey] === 'undefined') {
						ref[lastKey] = 'no';
					} else if (ref[lastKey] === $( this ).val()) {
						ref[lastKey] = 'yes';
					}
				}
			}
		);

		// Collect multi-select values from scheduled sync fields in main form (including Tom Select)
		$( '#momcs-sync-settings-form select[multiple]' ).each(
			function () {
				const name = $( this ).attr( 'name' );
				if (!name) { return; }
				
				// Check if this is a scheduled sync multi-select
				const cleanName = name.replace('[]', '');
				const isScheduledSyncMultiSelect = scheduledSyncFieldNames.includes(cleanName) || cleanName.startsWith('schedule_');
				
				if (isScheduledSyncMultiSelect) {
					// Ensure scheduled_sync object exists
					if (!formObject.scheduled_sync) {
						formObject.scheduled_sync = {};
					}
					
					// Get values - handle Tom Select if initialized
					let selectedValues = [];
					if (window.scheduledSyncManager && window.scheduledSyncManager.tomSelectInstance) {
						// Get values from Tom Select instance
						const tomSelectValue = window.scheduledSyncManager.tomSelectInstance.getValue();
						selectedValues = Array.isArray(tomSelectValue) ? tomSelectValue : (tomSelectValue ? [tomSelectValue] : []);
						console.log('- Found Tom Select values for', cleanName, ':', selectedValues);
					} else {
						// Fallback to native select
						selectedValues = $( this ).val() || [];
						console.log('- Found native select values for', cleanName, ':', selectedValues);
					}
					
					// Only add if not already processed
					if (typeof formObject.scheduled_sync[cleanName] === 'undefined') {
						formObject.scheduled_sync[cleanName] = selectedValues;
						console.log('- Stored scheduled sync multi-select:', cleanName, '=', selectedValues);
					}
				}
			}
		);

		// Debug logging to verify scheduled sync integration
		console.log('Collected sync settings data:', formObject);
		if (formObject.scheduled_sync && Object.keys(formObject.scheduled_sync).length > 0) {
			console.log('✅ Scheduled sync data found:', formObject.scheduled_sync);
			console.log('✅ Schedule enabled value being sent:', formObject.scheduled_sync.schedule_enabled);
		} else {
			console.log('❌ No scheduled sync data collected - check form visibility and field names');
		}
		
		// Debug logging for order scheduled sync
		if (formObject.order_sync && formObject.order_sync.sync_settings && formObject.order_sync.sync_settings.scheduled_sync) {
			console.log('✅ Order scheduled sync data found:', formObject.order_sync.sync_settings.scheduled_sync);
		} else {
			console.log('ℹ️ No order scheduled sync data collected');
		}

		return { isValid: true, settings_data: JSON.stringify( formObject ) };
	}

	// expose to global (used by stepper)
	window.collectAmazonSyncSettingsData = collectAllSyncSettingsData;

	/**
	 * Update order schedule preview when settings are loaded or changed
	 */
	window.updateOrderSchedulePreview = function() {
		const enabled = $('#momcs-order-schedule-enabled').is(':checked');
		const frequency = $('#momcs-order-schedule-frequency').val() || 24;
		const interval = $('#momcs-order-schedule-interval').val() || 'hours';
		const previewContainer = $('.momcs-order-schedule-preview');
		const previewText = previewContainer.find('.momcs-order-schedule-preview-text');
		
		if (!enabled) {
			previewText.html('Order schedule is currently disabled. Enable it to see the next run times.');
			return;
		}
		
		// Calculate next run times
		const now = new Date();
		const runs = [];
		
		for (let i = 1; i <= 3; i++) {
			const nextRun = new Date(now);
			let intervalMs;
			
			if (interval === 'hours') {
				intervalMs = frequency * i * 60 * 60 * 1000;
			} else if (interval === 'days') {
				intervalMs = frequency * i * 24 * 60 * 60 * 1000;
			}
			
			nextRun.setTime(now.getTime() + intervalMs);
			runs.push(nextRun.toLocaleString());
		}
		
		const intervalText = frequency == 1 ? interval.slice(0, -1) : `${frequency} ${interval}`;
		let html = `<strong>Schedule:</strong> Fetch orders every ${intervalText}<br><br>`;
		html += '<strong>Next 3 scheduled runs:</strong><ol style="margin-left: 20px;">';
		runs.forEach(run => {
			html += `<li>${run}</li>`;
		});
		html += '</ol>';
		
		previewText.html(html);
	};
	
	// Schedule card accordion: toggle config visibility when arrow is clicked
	$(document).on('click', '.momcs-schedule-card-accordion-trigger', function() {
		const $btn = $(this);
		const $card = $btn.closest('.momcs-schedule-card');
		const expanded = $card.hasClass('momcs-schedule-card--expanded');
		$card.toggleClass('momcs-schedule-card--expanded', !expanded);
		$btn.attr('aria-expanded', !expanded);
	});

	// Bind order schedule field changes to update preview and card recurrence
	$(function() {
		$('#momcs-order-schedule-enabled, #momcs-order-schedule-frequency, #momcs-order-schedule-interval').on('change input', function() {
			window.updateOrderSchedulePreview();
			updateScheduleCardRecurrenceDisplays();
		});

		$('#momcs-order-schedule-enabled').on('change', function() {
			const enabled = $(this).is(':checked');
			$('#momcs-order-schedule-frequency, #momcs-order-schedule-interval').prop('disabled', !enabled);
			window.updateOrderSchedulePreview();
			updateScheduleCardRecurrenceDisplays();
		});

		$('#momcs-amazon-to-wc-schedule-enabled').on('change', function() {
			toggleAmazonToWcScheduleFields();
		});
		$('#momcs-amazon-to-wc-schedule-frequency, #momcs-amazon-to-wc-schedule-interval').on('change input', function() {
			updateScheduleCardRecurrenceDisplays();
		});

		$('input[name="account_settings[account_type]"]').on('change', function() {
			toggleFbaStockScheduleFields();
		});

		$('#momcs-fba-stock-schedule-enabled').on('change', function() {
			toggleFbaStockScheduleFields();
		});
		$('#momcs-fba-stock-schedule-frequency, #momcs-fba-stock-schedule-interval').on('change input', function() {
			updateScheduleCardRecurrenceDisplays();
		});

		toggleAmazonToWcScheduleFields();
		toggleFbaStockScheduleFields();
		updateScheduleCardRecurrenceDisplays();

		// ── Global Save Button (standalone sync settings page) ──
		$( '#momcs-global-save-btn' ).on( 'click', function () {
			if ( typeof momcs_sync_settings === 'undefined' || ! momcs_sync_settings.nonce_save_sync ) {
				return;
			}

			var $btn = $( this );
			$btn.prop( 'disabled', true ).text( 'Saving...' );

			if ( typeof window.collectAmazonSyncSettingsData === 'function' ) {
				var result = window.collectAmazonSyncSettingsData();
				if ( result && result.isValid === true ) {
					$.post( momcs_sync_settings.ajax_url || ajaxurl, {
						action: 'momcs_sync_save_sync_settings',
						channel_uuid: momcs_sync_settings.channel_uuid,
						settings_data: result.settings_data,
						security: momcs_sync_settings.nonce_save_sync
					}).done( function () {
						$btn.prop( 'disabled', false ).text( 'Save Settings' );
						// Show a brief success notice
						var $notice = $( '<div class="notice notice-success is-dismissible" style="margin: 10px 0;"><p>Settings saved successfully.</p></div>' );
						$( '.momcs-sync-settings-container' ).prepend( $notice );
						setTimeout( function () { $notice.fadeOut( 400, function () { $( this ).remove(); } ); }, 4000 );
					}).fail( function () {
						$btn.prop( 'disabled', false ).text( 'Save Settings' );
						var $notice = $( '<div class="notice notice-error is-dismissible" style="margin: 10px 0;"><p>Error saving settings.</p></div>' );
						$( '.momcs-sync-settings-container' ).prepend( $notice );
						setTimeout( function () { $notice.fadeOut( 400, function () { $( this ).remove(); } ); }, 4000 );
					});
				}
			}
		});
	});

})( jQuery );
