/**
 * Admin JavaScript for miniOrange WooCommerce Amazon Sync Plugin
 *
 * @package    MOMCS_Sync
 */

jQuery( document ).ready(
	function ($) {
		/**
		 * Dark mode toggle
		 * Applies body class from saved preference and handles toggle click with AJAX save.
		 */
		(function initDarkMode() {
			if (typeof momcsDarkMode === 'undefined') {
				return;
			}
			var $body = $(document.body);
			var $input = $('.momcs-dark-mode-toggle-input');
			if (!$input.length) {
				return;
			}
			if (momcsDarkMode.enabled) {
				$body.addClass('momcs-dark-mode');
				$input.prop('checked', true);
			}
			$input.on('change', function() {
				var enabled = $(this).prop('checked');
				$body.toggleClass('momcs-dark-mode', enabled);
				var value = enabled ? '1' : '0';
				$.post(momcsDarkMode.ajaxUrl, {
					action: 'momcs_save_dark_mode',
					nonce: momcsDarkMode.nonce,
					enabled: value
				}).fail(function() {
					$body.toggleClass('momcs-dark-mode', !enabled);
					$input.prop('checked', !enabled);
				});
			});
		})();

		/**
		 * License Enforcement Module
		 *
		 * Checks license status and disables premium features when license
		 * is expired or missing. This provides frontend enforcement in addition
		 * to backend verification.
		 *
		 * Note: License notice banners are handled by the license library.
		 */
		(function initLicenseEnforcement() {
			// Check if license data is available.
			if (typeof momcs_license === 'undefined') {
				return;
			}

			// If license is expired or missing, enforce restrictions.
			if (momcs_license.is_expired || !momcs_license.has_license) {
				enforceLicenseRestrictions();
			}

			/**
			 * Apply license restrictions to premium features.
			 */
			function enforceLicenseRestrictions() {
				// Determine the appropriate message for tooltips.
				var message = momcs_license.has_license 
					? momcs_license.expired_message 
					: momcs_license.no_license_message;

				// Premium feature button selectors.
				var premiumButtonSelectors = [
					'.momcs-add-connection-btn:not(.momcs-upgrade-btn)',  // Add Marketplace button
					'.momcs-sync-modal-sync',                             // Sync modal sync button
					'#momcs-sync-apply-action',                           // Bulk sync apply action
					'#momcs_fetch_orders',                                // Fetch orders button
					'.momcs-schedule-save-btn',                           // Schedule save button
					'.momcs-start-sync-btn',                              // Start sync buttons
					'button[data-action="schedule-sync"]',                // Schedule sync buttons
					'#momcs-sync-from-amazon-btn',                        // Sync Products from Amazon button
					'#momcs-sync-asin-btn'                                // ASIN Sync button
				];

				// Disable premium buttons.
				$(premiumButtonSelectors.join(', ')).each(function() {
					var $btn = $(this);
					
					// Skip if already an upgrade button.
					if ($btn.hasClass('momcs-upgrade-btn')) {
						return;
					}

					$btn.addClass('momcs-license-disabled')
						.prop('disabled', true)
						.attr('title', message)
						.css({
							'opacity': '0.6',
							'cursor': 'not-allowed',
							'pointer-events': 'none'
						});
				});

				// Intercept AJAX calls for premium features.
				interceptPremiumAjax();
			}

			/**
			 * Intercept AJAX calls for premium features and show error.
			 */
			function interceptPremiumAjax() {
				// Override jQuery AJAX to intercept premium calls.
				var originalAjax = $.ajax;
				$.ajax = function(settings) {
					// List of premium AJAX actions.
					var premiumActions = [
						'momcs_create_schedule',
						'momcs_update_schedule',
						'momcs_get_schedule_settings',
						'momcs_start_order_fetch_background',
						'momcs_sync_products_bulk',
						'momcs_unlist_products_bulk',
						'momcs_start_amazon_product_sync',
						'momcs_get_amazon_product_sync_progress',
						'momcs_pause_amazon_product_sync',
						'momcs_resume_amazon_product_sync',
						'momcs_stop_amazon_product_sync',
						'momcs_start_asin_sync',
						'momcs_get_asin_sync_progress'
					];

					// Check if this is a premium action.
					var actionData = settings.data;
					var isPremiumAction = false;

					if (typeof actionData === 'string') {
						premiumActions.forEach(function(action) {
							if (actionData.indexOf('action=' + action) !== -1) {
								isPremiumAction = true;
							}
						});
					} else if (typeof actionData === 'object' && actionData.action) {
						isPremiumAction = premiumActions.indexOf(actionData.action) !== -1;
					}

					// If premium action and license expired, block the request.
					if (isPremiumAction && (momcs_license.is_expired || !momcs_license.has_license)) {
						var deferred = $.Deferred();

						// Return rejected promise (backend will also reject with 403).
						if (settings.error) {
							settings.error({status: 403}, 'error', 'License expired');
						}
						return deferred.reject({status: 403}, 'error', 'License expired').promise();
					}

					// Otherwise, proceed with normal AJAX.
					return originalAjax.apply(this, arguments);
				};
			}
		})();

		// If we navigated here after triggering a sync, show the started notice (once)
		if ( $('.momcs-sync-products-container').length && window.sessionStorage && sessionStorage.getItem('momcsSyncStarted') === '1') {
			showSyncStartedNotice();
			sessionStorage.removeItem('momcsSyncStarted');
		}

		// Handle bulk action for product sync
		$( '#momcs-sync-apply-action' ).on(
			'click',
			function () {
				// After reload notice: if previous sync set a flag, show it now and clear
				if ( $('.momcs-sync-products-container').length && window.sessionStorage && sessionStorage.getItem('momcsSyncStarted') === '1') {
					showSyncStartedNotice();
					sessionStorage.removeItem('momcsSyncStarted');
				}
				const selectedAction = $( '#momcs-sync-list-action' ).val();

				if ( ! selectedAction) {
					alert( momcsAmazonSync.strings.no_action );
					return;
				}

				// Get selected products
				const selectedProducts = [];
				$( 'input[name="product_ids[]"]:checked' ).each(
					function () {
						selectedProducts.push( $( this ).val() );
					}
				);

				if (selectedProducts.length === 0) {
					alert( momcsAmazonSync.strings.no_products );
					return;
				}

				if (selectedAction === 'list' || selectedAction === 'unlist') {
					window.showChannelSelectionPopup( selectedProducts, selectedAction );
				}
			}
		);

		// Function to show channel selection popup (made globally available)
		window.showChannelSelectionPopup = function showChannelSelectionPopup(selectedProducts, actionType = 'list') {
			// Create modal overlay
			const $overlay = $( '<div id="momcs-sync-modal-overlay"></div>' );
			const $modal   = $( '<div id="momcs-sync-modal"></div>' );

			// Determine modal content based on action type
			let modalTitle       = 'Select Channel';
			let modalDescription = 'Choose the channel you want to sync your products to.';
			let buttonText       = 'Sync Products';

			// Icon SVG per action type
			const iconList = '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>';
			const iconSync = '<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m17 18-1.535 1.605a5 5 0 0 1-8-1.5"/><path d="M17 22v-4h-4"/><path d="M20.996 15.251A4.5 4.5 0 0 0 17.495 8h-1.79a7 7 0 1 0-12.709 5.607"/><path d="M7 10v4h4"/><path d="m7 14 1.535-1.605a5 5 0 0 1 8 1.5"/></svg>';

			let titleIcon = iconList;

			if (actionType === 'asin-sync') {
				modalTitle       = 'Select Channels for ASIN Sync';
				modalDescription = 'Choose one or more Amazon channels to sync ASINs from.';
				buttonText       = 'Start ASIN Sync';
				titleIcon        = iconSync;
			} else if (actionType === 'amazon-product-sync') {
				modalTitle       = 'Select Channels for Product Sync';
				modalDescription = 'Choose one or more Amazon channels to import complete product details from. All matching products will be synced from Amazon into WooCommerce.';
				buttonText       = 'Start Product Sync';
				titleIcon        = iconSync;
			} else if (actionType === 'unlist') {
				modalTitle       = 'Select Channel to Unlist From';
				modalDescription = 'Choose the channel you want to remove the selected products from.';
				buttonText       = 'Unlist Products';
			}

			// Build modal HTML
			const $modalContent = $(
				`<div class="momcs-csp-modal">
					<div class="momcs-csp-header">
						<span class="momcs-csp-header-icon">${titleIcon}</span>
						<h2 class="momcs-csp-title">${modalTitle}</h2>
						<button type="button" class="momcs-csp-close momcs-sync-modal-cancel" aria-label="Close">
							<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
						</button>
					</div>
					<div class="momcs-csp-body">
						<div class="momcs-csp-notice">
							<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="momcs-csp-notice-icon"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>
							<p class="momcs-csp-notice-text">${modalDescription}</p>
						</div>
						<div class="momcs-sync-channel-list">
							<div class="momcs-sync-spinner-container">
								<span class="momcs-csp-spinner"></span>
								<p class="momcs-csp-loading-text">Loading channels&hellip;</p>
							</div>
						</div>
					</div>
					<div class="momcs-csp-footer">
						<button type="button" class="momcs-csp-btn momcs-csp-btn-cancel momcs-sync-modal-cancel">Cancel</button>
						<button type="button" class="momcs-csp-btn momcs-csp-btn-confirm momcs-sync-modal-sync" disabled>${buttonText}</button>
					</div>
				</div>`
			);

			// Append modal to body
			$modal.append( $modalContent );
			$( 'body' ).append( $overlay ).append( $modal );

			// Channel list is inside the modal we just created (use closure so we always target this modal)
			const $channelList = $modal.find( '.momcs-sync-channel-list' );

			// Load channels via AJAX
			$.ajax(
				{
					url: momcsAmazonSync.ajaxUrl,
					type: 'POST',
					data: {
						action: 'momcs_get_channels',
						nonce: momcsAmazonSync.nonce
					},
					success: function (response) {
						$channelList.empty();

						if (response.success && response.data && response.data.channels && response.data.channels.length > 0) {
							const channels = response.data.channels;
							
							// Check plan status
							const isPremium = (typeof momcsAmazonSync !== 'undefined' && momcsAmazonSync.isPremium) || false;
							
							// Determine input type: checkbox for premium (list/unlist) or ASIN sync or Amazon product sync, else radio
							const inputType = (actionType === 'asin-sync' || actionType === 'amazon-product-sync' || (isPremium && (actionType === 'list' || actionType === 'unlist'))) 
								? 'checkbox' 
								: 'radio';
							
							// Adjust input name accordingly
							const inputName = (inputType === 'checkbox') ? 'sync_channels[]' : 'sync_channel';

						// Create channel selection inputs (radio for regular sync, checkbox for ASIN sync)
						channels.forEach(
							function (channel) {
								const inputId    = `momcs-channel-${channel.uuid}`;
								const $channelItem = $(
									`<div class="momcs-sync-channel-item momcs-csp-channel-card">
										<label for="${inputId}" class="momcs-csp-channel-label">
											<input type="${inputType}" id="${inputId}" name="${inputName}" value="${channel.uuid}" class="momcs-csp-channel-input">
											<span class="momcs-csp-channel-check"></span>
											<img src="${channel.icon}" alt="${channel.name}" width="28" height="28" class="momcs-csp-channel-icon">
											<span class="momcs-csp-channel-info">
												<span class="momcs-csp-channel-name">${channel.name}</span>
												<span class="momcs-csp-channel-region">${channel.region}</span>
											</span>
										</label>
									</div>`
								);
								$channelList.append( $channelItem );
							}
						);

						// Mark card variant class for checkbox vs radio
						$channelList.find( '.momcs-csp-channel-card' ).each( function () {
							if (inputType === 'checkbox') {
								$( this ).addClass( 'is-checkbox' );
							}
						} );

						// Enable sync button when a channel is selected; toggle selected state on cards
						if (inputType === 'checkbox') {
							$channelList.find( 'input[name="sync_channels[]"]' ).on(
								'change',
								function () {
									const $card = $( this ).closest( '.momcs-csp-channel-card' );
									if ( $( this ).is( ':checked' ) ) {
										$card.addClass( 'is-selected' );
									} else {
										$card.removeClass( 'is-selected' );
									}
									const selectedCount = $channelList.find( 'input[name="sync_channels[]"]:checked' ).length;
									$modal.find( '.momcs-sync-modal-sync' ).prop( 'disabled', selectedCount === 0 );
								}
							);
							// Row clicks for checkboxes (same idea as radio branch; CSS also fixes native hit target).
							$( document ).off( 'click.momcsChannelCheckbox' ).on( 'click.momcsChannelCheckbox', '#momcs-sync-modal .momcs-csp-channel-card.is-checkbox', function ( e ) {
								const $card  = $( this );
								const $input = $card.find( 'input[name="sync_channels[]"]' );
								if ( ! $input.length ) {
									return;
								}
								if ( e.target === $input[0] ) {
									return;
								}
								e.preventDefault();
								$input.prop( 'checked', ! $input.prop( 'checked' ) ).trigger( 'change' );
							} );
						} else {
							// Change handler — the single source of truth for UI update.
							// Fires on both native clicks and programmatic trigger('change').
							$channelList.off( 'change.momcsChannelRadio' ).on( 'change.momcsChannelRadio', 'input[name="sync_channel"]', function () {
								const $card = $( this ).closest( '.momcs-csp-channel-card' );
								$modal.find( '.momcs-csp-channel-card' ).removeClass( 'is-selected' );
								$card.addClass( 'is-selected' );
								$modal.find( '.momcs-sync-modal-sync' ).prop( 'disabled', false );
							} );

							// Document-level delegation handles clicks on the card row area.
							$( document ).off( 'click.momcsChannelCard' ).on( 'click.momcsChannelCard', '#momcs-sync-modal .momcs-csp-channel-card', function ( e ) {
								const $card  = $( this );
								const $input = $card.find( 'input[name="sync_channel"]' );
								if ( ! $input.length || 'radio' !== $input[0].type ) {
									return;
								}
								// When the transparent radio overlay was clicked, the browser
								// will naturally check the radio and fire the change event.
								// Just let it propagate so change.momcsChannelRadio handles UI.
								if ( e.target === $input[0] ) {
									return;
								}
								// Click landed elsewhere on the card (e.g. the icon or text).
								// Manually check the radio and trigger change for UI update.
								e.preventDefault();
								$input.prop( 'checked', true ).trigger( 'change' );
							} );
						}

							// Do not auto-select any channel; require explicit user choice.
						} else {
							let errorMessage = 'No channels found. Please <a href="admin.php?page=momcs-sync-channels">connect a channel</a> first.';

							if ( ! response.success && response.data && response.data.message) {
								errorMessage = `Error: ${response.data.message}`;
							}

							$channelList.html( `<div class="momcs-csp-error"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg><p>${errorMessage}</p></div>` );
						}
					},
				error: function (xhr, status, error) {
					const $channelList = $( '.momcs-sync-channel-list' );
					$channelList.empty();

					const errorMessage = `Error loading channels: ${error}. Please try again.`;
					$channelList.html( `<div class="momcs-csp-error"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg><p>${errorMessage}</p></div>` );
				}
				}
			);

			// Handle cancel button — scope to $modal so stale handlers never leak.
			$modal.find( '.momcs-sync-modal-cancel' ).on(
				'click',
				function () {
					window.closeChannelSelectionPopup();
				}
			);

			// Handle sync button — scope to $modal.
			$modal.find( '.momcs-sync-modal-sync' ).on(
				'click',
				function () {
					var $syncBtn = $( this ).prop( 'disabled', true );

					// Handle ASIN sync differently from regular sync
					if (actionType === 'asin-sync') {
						// Get all selected channels for ASIN sync
						const selectedChannels = [];
						$modal.find( 'input[name="sync_channels[]"]:checked' ).each(
							function () {
								selectedChannels.push( $( this ).val() );
							}
						);

						if (selectedChannels.length === 0) {
							$syncBtn.prop( 'disabled', false );
							return;
						}

						// Close modal and trigger ASIN sync
						window.closeChannelSelectionPopup();
						
						// Trigger ASIN sync if manager is available
						if (typeof window.asinSyncManager !== 'undefined' && window.asinSyncManager.handleSyncStart) {
							window.asinSyncManager.handleSyncStart(selectedChannels);
						} else {
							alert('ASIN sync manager not available. Please refresh the page and try again.');
						}
					} else if (actionType === 'amazon-product-sync') {
						// Handle Amazon Product Sync - syncs complete product details from Amazon
						const selectedChannels = [];
						$modal.find( 'input[name="sync_channels[]"]:checked' ).each(
							function () {
								selectedChannels.push( $( this ).val() );
							}
						);

						if (selectedChannels.length === 0) {
							$syncBtn.prop( 'disabled', false );
							return;
						}

						// Close modal and trigger Amazon Product sync
						window.closeChannelSelectionPopup();
						
						// Trigger Amazon Product sync if manager is available
						if (typeof window.amazonProductSyncManager !== 'undefined' && window.amazonProductSyncManager.handleSyncStart) {
							window.amazonProductSyncManager.handleSyncStart(selectedChannels);
						} else {
							alert('Amazon Product sync manager not available. Please refresh the page and try again.');
						}
					} else {
						// Handle regular product sync
						// Check plan status for multi-channel support
						const isPremium = (typeof momcsAmazonSync !== 'undefined' && momcsAmazonSync.isPremium) || false;
						const useMultiChannel = isPremium && $modal.find( 'input[name="sync_channels[]"]' ).length > 0;

						let channelData = {};
						if (useMultiChannel) {
							// Premium: collect array
							const selectedChannels = [];
							$modal.find( 'input[name="sync_channels[]"]:checked' ).each( function () {
								selectedChannels.push( $( this ).val() );
							} );
							if (selectedChannels.length === 0) {
								$syncBtn.prop( 'disabled', false );
								return;
							}
							channelData.channel_ids = selectedChannels;
						} else {
							// Free: single channel via radio
							const channelId = $modal.find( 'input[name="sync_channel"]:checked' ).val();
							if ( ! channelId ) {
								$syncBtn.prop( 'disabled', false );
								return;
							}
							channelData.channel_id = channelId;
						}
						
						const ajaxAction = (actionType === 'list') ? 'momcs_sync_products_bulk' : 'momcs_unlist_products_bulk';
						$.ajax(
							{
								url: momcsAmazonSync.ajaxUrl,
								type: 'POST',
								data: {
									action: ajaxAction,
									nonce: momcsAmazonSync.nonce,
									product_ids: selectedProducts,
									...channelData
								},
								success: function (response) {
									// Persist a flag across reload to show the notice after page loads
									try { if (window.sessionStorage) { sessionStorage.setItem('momcsSyncStarted', '1'); } } catch(e) {}
									window.closeChannelSelectionPopup(function(){ location.reload(); });
								},
								error: function (xhr, status, error) {
									alert( 'AJAX Error: ' + error );
									$syncBtn.prop( 'disabled', false );
								}
							}
						);
					}
				}
			);
		}

		// Function to close channel selection popup (made globally available)
		window.closeChannelSelectionPopup = function closeChannelSelectionPopup(callback) {
			var $overlay = $( '#momcs-sync-modal-overlay' );
			var $modal   = $( '#momcs-sync-modal' );
			var $both    = $overlay.add( $modal );

			// Unbind card click so no stray handlers remain
			$( document ).off( 'click.momcsChannelCard' );
			$( document ).off( 'click.momcsChannelCheckbox' );

			if ( ! $overlay.length && ! $modal.length) {
				if (typeof callback === 'function') {
					callback(); }
				return;
			}

			// Fade both simultaneously and remove after animation completes.
			$both.stop( true, true ).fadeOut( 120 );
			$both.promise().done(
				function () {
					$overlay.remove();
					$modal.remove();
					if (typeof callback === 'function') {
						callback(); }
				}
			);
		}

		// Show a disappearing Sync Queue style notice for 5 seconds
		function showSyncStartedNotice() {
			// Remove any existing notice first
			$( '.momcs-sync-products-container .momcs-orders-notice' ).remove();
			const html = '<div class="momcs-orders-notice" style="margin: 0 0 15px 0; display:none;">' +
				'<p><span class="dashicons dashicons-info" style="color:#00a0d2;margin-right:5px;"></span>' +
				(momcsAmazonSync && momcsAmazonSync.strings && momcsAmazonSync.strings.sync_started_notice ? momcsAmazonSync.strings.sync_started_notice : 'Sync has started. Please go to Sync Queue to view the status.') +
				'</p></div>';
			// Insert just under the products header-actions block so it’s visible
			$( '.momcs-sync-products-header' ).after( html );
			const $notice = $( '.momcs-sync-products-container .momcs-orders-notice' );
			$notice.slideDown( 150 );
			setTimeout( function() { $notice.slideUp( 150, function(){ $(this).remove(); }); }, 5000 );
		}

		// Function to update product sync status in the UI
		function updateProductSyncStatus(productId, status) {
			const $row        = $( 'input[name="product_ids[]"][value="' + productId + '"]' ).closest( 'tr' );
			const $statusCell = $row.find( '.column-sync-status' );

			$statusCell.empty();

			if (status === 'success') {
				$statusCell.html( '<div class="momcs-sync-status-chip success"><span class="momcs-sync-status-dot"></span>Uploaded</div>' );
			} else if (status === 'error') {
				$statusCell.html( '<div class="momcs-sync-status-chip warning"><span class="momcs-sync-status-dot"></span>Error</div>' );
			}
		}

		// Cached orders and UI state.
		var allOrders      = [];
		var orderListState = {
			search: '',
			statusFilter: '',
			fulfillmentFilter: '',
			dateFrom: '',
			dateTo: ''
		};

		// Helper – apply front-end filters and render.
		function applyFilters() {
			var filtered = allOrders.filter(
				function (o) {
					// Skip orders with missing critical data
					if ( ! o) {
						return false;
					}

					// Status filter (case-insensitive).
					if (orderListState.statusFilter) {
						var orderStatus = o.OrderStatus || '';
						if (String( orderStatus ).toLowerCase() !== orderListState.statusFilter.toLowerCase()) {
							return false;
						}
					}

					// Fulfilment filter with alias mapping (FBA ↔ AFN, FBM ↔ MFN).
					if (orderListState.fulfillmentFilter) {
						var fulfAliases = {
							'FBA': ['FBA', 'AFN'],
							'AFN': ['FBA', 'AFN'],
							'FBM': ['FBM', 'MFN'],
							'MFN': ['FBM', 'MFN']
						};
						var allowed           = fulfAliases[orderListState.fulfillmentFilter] || [orderListState.fulfillmentFilter];
						var fulfillmentChannel = o.FulfillmentChannel || '';
						if (allowed.indexOf( String( fulfillmentChannel ).toUpperCase() ) === -1) {
							return false;
						}
					}
					// Search filter (simple contains on AmazonOrderId / status).
					if (orderListState.search) {
						var term        = orderListState.search.toLowerCase();
						var amazonId    = o.AmazonOrderId || '';
						var orderStatus = o.OrderStatus || '';
						if (String( amazonId ).toLowerCase().indexOf( term ) === -1 && String( orderStatus ).toLowerCase().indexOf( term ) === -1) {
							return false;
						}
					}
					// Date range filter.
					if (orderListState.dateFrom || orderListState.dateTo) {
						if ( ! o.PurchaseDate) {
							return false;
						}
						var purchaseDate = new Date( o.PurchaseDate );
						if (orderListState.dateFrom) {
							var from = new Date( orderListState.dateFrom + 'T00:00:00' );
							if (purchaseDate < from) {
								return false; }
						}
						if (orderListState.dateTo) {
							var to = new Date( orderListState.dateTo + 'T23:59:59' );
							if (purchaseDate > to) {
								return false; }
						}
					}
					return true;
				}
			);

			displayOrders( filtered );
			updatePaginationInfo( filtered.length, 1 );
		}

		// Function to show skeleton loader for orders table
		function momcsAmazonShowOrdersSkeleton() {
			var $ordersTable = jQuery( '#momcs_orders_list' );
			if ( ! $ordersTable.length ) {
				return;
			}

			// Clear existing rows and insert placeholder skeleton rows
			$ordersTable.empty();

			for ( var i = 0; i < 5; i++ ) {
				$ordersTable.append( '<tr class="loading-placeholder"><td colspan="9"><div class="momcs-sync-skeleton-row"></div></td></tr>' );
			}
		}

		// Handle fetch orders button click
	$( '#momcs_fetch_orders' ).on(
		'click',
		function () {
			var $button  = $( this );
			var dateFrom = $( '#date_from' ).val();
			var dateTo   = $( '#date_to' ).val();

			// If no dates selected, default to last 24 hours
			if ( ! dateFrom) {
				var yesterday = new Date();
				yesterday.setDate( yesterday.getDate() - 1 );
				dateFrom = yesterday.toISOString().split( 'T' )[0];
				$( '#date_from' ).val( dateFrom );
			}

			if ( ! dateTo) {
				var today = new Date();
				dateTo    = today.toISOString().split( 'T' )[0];
				$( '#date_to' ).val( dateTo );
			}

			// Disable button and show loading state
			$button.prop( 'disabled', true )
			.find( '.dashicons' ).addClass( 'spin' );

			// Check if premium plan for background processing
			if (typeof momcs_sync_params !== 'undefined' && momcs_sync_params.isPremium) {
				// Premium: Use background job with progress tracking
				startBackgroundOrderFetch(dateFrom, dateTo, $button);
			} else {
				// Free: Use synchronous fetch (existing behavior)
				fetchOrdersSynchronous(dateFrom, dateTo, $button);
			}
		}
	);

	/**
	 * Fetch orders synchronously (for free users)
	 */
	function fetchOrdersSynchronous(dateFrom, dateTo, $button) {
		$.ajax(
			{
				url: momcs_sync_params.ajaxurl,
				type: 'POST',
				data: {
					action: 'momcs_fetch_orders',
					nonce: momcs_sync_params.nonce,
					fetch_new: 1,
					date_from: dateFrom,
					date_to: dateTo
				},
				success: function (response) {
					if (response.success) {
						// Cache orders and update state.
						allOrders = response.data.orders || [];
						// Clear date filters so newly created orders are visible immediately.
						orderListState.dateFrom = '';
						orderListState.dateTo   = '';
						$( '#date_from' ).val( '' );
						$( '#date_to' ).val( '' );
						applyFilters();

						// Show success message
						alert( response.data.message );
					} else {
						alert( response.data.message || 'Failed to fetch orders.' );
					}
				},
				error: function () {
					alert( 'Failed to connect to the server.' );
				},
				complete: function () {
					// Re-enable button and stop loading animation
					$button.prop( 'disabled', false )
					.find( '.dashicons' ).removeClass( 'spin' );
				}
			}
		);
	}

	/**
	 * Start background order fetch job (for premium users)
	 */
	function startBackgroundOrderFetch(dateFrom, dateTo, $button) {
		// Note: Background job will handle all channels internally
		// channel_uuid is determined server-side by looping through active channels
		$.ajax(
			{
				url: momcs_sync_params.ajaxurl,
				type: 'POST',
				data: {
					action: 'momcs_start_order_fetch_background',
					nonce: momcs_sync_params.nonce,
					channel_uuid: '', // Empty means all channels
					date_from: dateFrom,
					date_to: dateTo
				},
				success: function (response) {
					if (response.success && response.data.job_id) {
						// Show progress modal and start polling
						showProgressModal();
						startProgressPolling(response.data.job_id, $button);
					} else {
						alert( response.data.message || 'Failed to start background job.' );
						$button.prop( 'disabled', false )
						.find( '.dashicons' ).removeClass( 'spin' );
					}
				},
				error: function () {
					alert( 'Failed to connect to the server.' );
					$button.prop( 'disabled', false )
					.find( '.dashicons' ).removeClass( 'spin' );
				}
			}
		);
	}

	/**
	 * Show progress modal
	 */
	function showProgressModal() {
		var $modal   = $( '#order-fetch-progress-modal' );
		var $overlay = $( '#order-fetch-progress-modal-overlay' );
		
		if ($modal.length) {
			$overlay.show();
			$modal.show();
			// Hide close button initially
			$( '#close-progress-modal' ).hide();
			// Initialize with correct keys
			updateProgressUI({
				status: 'processing',
				total_fetched: 0,
				total_created: 0,
				total_failed: 0,
				total_skipped: 0,
				batches_completed: 0
			});
		}
	}

	/**
	 * Hide progress modal
	 */
	function hideProgressModal() {
		var $modal   = $( '#order-fetch-progress-modal' );
		var $overlay = $( '#order-fetch-progress-modal-overlay' );
		
		if ($modal.length) {
			$modal.hide();
			$overlay.hide();
		}
	}

	/**
	 * Start polling for progress updates
	 */
	function startProgressPolling(jobId, $button) {
		var pollInterval = setInterval(
			function () {
				$.ajax(
					{
						url: momcs_sync_params.ajaxurl,
						type: 'POST',
						data: {
							action: 'momcs_order_fetch_progress',
							nonce: momcs_sync_params.nonce,
							job_id: jobId
						},
						success: function (response) {
							if (response.success) {
								updateProgressUI( response.data );
								
								// Check if completed
								if (response.data.status === 'completed' || response.data.status === 'complete') {
									clearInterval( pollInterval );
									handleJobComplete( response.data, $button );
								} else if (response.data.status === 'failed' || response.data.status === 'error') {
									// If error but orders were created, show success instead
									var fetched = response.data.total_fetched || 0;
									var created = response.data.total_created || 0;
									
									if (created > 0 || fetched > 0) {
										// Job completed successfully but transient expired
										clearInterval( pollInterval );
										handleJobComplete( response.data, $button );
									} else {
										// Actual error - no orders processed
										clearInterval( pollInterval );
										handleJobError( response.data, $button );
									}
								}
							}
						},
						error: function () {
							clearInterval( pollInterval );
							alert( 'Failed to get progress update.' );
							hideProgressModal();
							$button.prop( 'disabled', false )
							.find( '.dashicons' ).removeClass( 'spin' );
						}
					}
				);
			},
			2000 // Poll every 2 seconds
		);
	}

	/**
	 * Update progress UI
	 */
	function updateProgressUI(progress) {
		var $modal = $( '#order-fetch-progress-modal' );
		
		if ( ! $modal.length) {
			return;
		}

		// Use correct keys from backend response
		var fetched = progress.total_fetched || 0;
		var created = progress.total_created || 0;
		var failed = progress.total_failed || 0;
		var skipped = progress.total_skipped || 0;

		// Calculate progress percentage (if we have batch info)
		var percent = 0;
		if (progress.batches_completed > 0) {
			// Show some progress even if we don't know total
			percent = Math.min(fetched * 10, 90); // Cap at 90% until complete
		}
		
		// Update progress bar
		$modal.find( '.progress-bar-fill' ).css( 'width', percent + '%' );
		
		// Update progress text
		var progressText = '';
		if (fetched > 0) {
			progressText = 'Fetched: ' + fetched + ' orders | ' +
						   'Created: ' + created + ' | ' +
						   'Failed: ' + failed;
			
			if (skipped > 0) {
				progressText += ' | Skipped: ' + skipped;
			}
		} else {
			progressText = 'Fetching orders from Amazon...';
		}
		
		$modal.find( '.progress-text' ).text( progressText );
	}

	/**
	 * Handle job completion
	 */
	function handleJobComplete(data, $button) {
		// Re-enable button
		$button.prop( 'disabled', false )
		.find( '.dashicons' ).removeClass( 'spin' );
		
		// Show close button in modal
		$( '#close-progress-modal' ).show().off('click').on(
			'click',
			function () {
				hideProgressModal();
				// Reload orders to show newly imported ones
				loadOrders();
			}
		);
		
		// Use correct keys from backend response
		var fetched = data.total_fetched || 0;
		var created = data.total_created || 0;
		var failed = data.total_failed || 0;
		var skipped = data.total_skipped || 0;
		
		// Determine status text
		var statusText = 'Completed!';
		if (data.status === 'error' && (created > 0 || fetched > 0)) {
			statusText = 'Completed with success!';
		}
		
		// Update progress text to show completion
		var completionText = '<strong>' + statusText + '</strong><br>' +
			'Total: ' + fetched + ' | ' +
			'Created: ' + created + ' | ' +
			'Failed: ' + failed;
		
		if (skipped > 0) {
			completionText += ' | Skipped: ' + skipped;
		}
		
		$( '#order-fetch-progress-modal .progress-text' ).html( completionText );
		
		// Set progress bar to 100%
		$( '#order-fetch-progress-modal .progress-bar-fill' ).css( 'width', '100%' );
	}

	/**
	 * Handle job error
	 */
	function handleJobError(data, $button) {
		hideProgressModal();
		alert( 'Error: ' + (data.message || 'Failed to fetch orders.') );
		
		// Re-enable button
		$button.prop( 'disabled', false )
		.find( '.dashicons' ).removeClass( 'spin' );
	}

		// Handle filter button click
		$( '#filter-orders' ).on(
			'click',
			function () {
				orderListState.statusFilter      = $( '#filter_status' ).val();
				orderListState.fulfillmentFilter = $( '#filter_fulfillment' ).val();
				orderListState.dateFrom          = $( '#date_from' ).val();
				orderListState.dateTo            = $( '#date_to' ).val();
				applyFilters();
			}
		);

		// Function to load orders with current filters
		function loadOrders() {
			// Show shimmer placeholders while the AJAX request is in progress.
			momcsAmazonShowOrdersSkeleton();
			$.ajax(
				{
					url: momcs_sync_params.ajaxurl,
					type: 'POST',
					data: {
						action: 'momcs_fetch_orders',
						nonce: momcs_sync_params.nonce,
						page: orderListState.page,
						per_page: orderListState.perPage,
						status: orderListState.statusFilter,
						fulfillment: orderListState.fulfillmentFilter,
						date_from: orderListState.dateFrom,
						date_to: orderListState.dateTo,
						search: orderListState.search
					},
					success: function (response) {
						if (response.success) {
							allOrders = response.data.orders || [];
							applyFilters();
						} else {
							alert( response.data.message || 'Failed to load orders.' );
						}
					},
					error: function () {
						alert( 'Failed to connect to the server.' );
					}
				}
			);
		}

		// Display orders in the table
		function displayOrders(orders) {
			var $ordersTable = $( '#momcs_orders_list' );
			$ordersTable.empty();

			if ( ! orders || orders.length === 0) {
				$ordersTable.html( '<tr class="no-items"><td class="colspanchange" colspan="9"><div class="momcs-orders-empty"><div class="momcs-orders-empty-icon"><svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M22 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg></div><h3>No Orders Found</h3><p>Use the Fetch Orders button to sync orders from Amazon.</p></div></td></tr>' );
				return;
			}

			orders.forEach(
				function (order) {
					// Safely handle missing OrderTotal data (common for cancelled orders)
					var orderTotal = '-';
					if (order.OrderTotal && order.OrderTotal.CurrencyCode && order.OrderTotal.Amount) {
						orderTotal = order.OrderTotal.CurrencyCode + ' ' + order.OrderTotal.Amount;
					}

					// Get customer name
					var customerName = '-';
					if (order.CustomerName) {
						customerName = order.CustomerName;
					} else if (order.BuyerInfo && order.BuyerInfo.BuyerName) {
						customerName = order.BuyerInfo.BuyerName;
					} else if (order.WooCommerceOrderId) {
						// Try to get from WooCommerce order if available
						// This would require an AJAX call, so we'll use a placeholder for now
						customerName = 'Customer';
					}

					// Format order ID link
					var orderIdLink = '-';
					if (order.WooCommerceOrderId) {
						var editUrl = '/wp-admin/post.php?post=' + order.WooCommerceOrderId + '&action=edit';
						orderIdLink = '<a href="' + editUrl + '" class="momcs-order-id">#' + order.WooCommerceOrderId + '</a>';
					}

					// Format status badges
					var wcStatusBadge = formatWcStatusBadge(order.WooCommerceStatus);
					var amazonStatusBadge = formatAmazonStatusBadge(order.OrderStatus);
					var fulfillmentBadge = formatFulfillmentBadge(order.FulfillmentChannel);

					// Format date
					var formattedDate = '-';
					if (order.PurchaseDate) {
						var date = new Date(order.PurchaseDate);
						formattedDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
					}

					// Format items count
					var itemsCount = order.OrderItems ? order.OrderItems.length : 0;
					var itemsText = itemsCount + ' ' + (itemsCount === 1 ? 'item' : 'items');

					var row = '<tr>' +
						'<td class="column-order-details">' +
							'<div class="momcs-order-details">' +
								orderIdLink +
								'<div class="momcs-order-customer">' + escapeHtml(customerName) + '</div>' +
							'</div>' +
						'</td>' +
						'<td class="column-wc-status">' + wcStatusBadge + '</td>' +
						'<td class="column-amazon-order-id">' + (order.AmazonOrderId || '-') + '</td>' +
						'<td class="column-amazon-status">' + amazonStatusBadge + '</td>' +
						'<td class="column-items">' + itemsText + '</td>' +
						'<td class="column-total"><span class="momcs-order-total">' + escapeHtml(orderTotal) + '</span></td>' +
						'<td class="column-fulfillment">' + fulfillmentBadge + '</td>' +
						'<td class="column-created">' + escapeHtml(formattedDate) + '</td>' +
						'<td class="column-actions">' +
							'<div class="momcs-order-actions">' +
								'<a href="' + (order.WooCommerceOrderId ? '/wp-admin/post.php?post=' + order.WooCommerceOrderId + '&action=edit' : '#') + '" class="momcs-action-btn">View</a>' +
								'<div class="momcs-action-menu">' +
									'<button type="button" class="momcs-action-menu-trigger" aria-label="More actions"></button>' +
									'<div class="momcs-action-menu-dropdown">' +
										(order.WooCommerceOrderId ? '<a href="/wp-admin/post.php?post=' + order.WooCommerceOrderId + '&action=edit" class="momcs-action-menu-item">View in WooCommerce</a>' : '') +
										(order.AmazonOrderId ? '<a href="#" class="momcs-action-menu-item" data-amazon-order-id="' + escapeHtml(order.AmazonOrderId) + '">View on Amazon</a>' : '') +
										'<a href="#" class="momcs-action-menu-item sync-status" data-amazon-order-id="' + (order.AmazonOrderId || '') + '">Sync Status</a>' +
									'</div>' +
								'</div>' +
							'</div>' +
						'</td>' +
					'</tr>';
					$ordersTable.append( row );
				}
			);
		}

		/**
		 * Title-case known order status slugs for display; keeps slug for CSS class.
		 *
		 * @param {string} status Raw status from API.
		 * @return {string} Human-readable label.
		 */
		function formatStatusLabel(status) {
			if (!status) {
				return '';
			}
			var raw = String(status).trim();
			var slug = raw.toLowerCase().replace(/\s+/g, '-');
			var map = {
				'completed': 'Completed',
				'processing': 'Processing',
				'pending': 'Pending',
				'on-hold': 'On Hold',
				'cancelled': 'Cancelled',
				'canceled': 'Canceled',
				'refunded': 'Refunded',
				'failed': 'Failed',
				'shipped': 'Shipped',
				'unshipped': 'Unshipped',
				'partially-shipped': 'Partially Shipped'
			};
			if (map[slug]) {
				return map[slug];
			}
			return raw.split(/[\s_-]+/).map(function (word) {
				return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
			}).join(' ');
		}

		// Helper: format WooCommerce status badge
		function formatWcStatusBadge(status) {
			if (!status) {
				return '-';
			}
			var slug = String(status).toLowerCase().replace(/\s+/g, '-');
			var statusClass = 'momcs-order-status-badge status-' + slug;
			var label = formatStatusLabel(status);
			return '<span class="' + statusClass + '">' + escapeHtml(label) + '</span>';
		}

		// Helper: format Amazon status badge
		function formatAmazonStatusBadge(status) {
			if (!status) {
				return '-';
			}
			var slug = String(status).toLowerCase().replace(/\s+/g, '-');
			var statusClass = 'momcs-order-status-badge status-' + slug;
			var label = formatStatusLabel(status);
			return '<span class="' + statusClass + '">' + escapeHtml(label) + '</span>';
		}

		// Helper: format fulfillment badge
		function formatFulfillmentBadge(fulfillment) {
			if (!fulfillment) {
				return '-';
			}
			var fulfillmentClass = 'momcs-fulfillment-badge fulfillment-' + String(fulfillment).toLowerCase();
			return '<span class="' + fulfillmentClass + '">' + escapeHtml(fulfillment) + '</span>';
		}

		// Helper: escape HTML
		function escapeHtml(text) {
			if (!text) {
				return '';
			}
			var div = document.createElement('div');
			div.textContent = text;
			return div.innerHTML;
		}

		// Update pagination information
		function updatePaginationInfo(total, maxPages) {
			orderListState.totalOrders = total;
			orderListState.maxPages    = maxPages;

			// Update order count badge
			$('#momcs-orders-count').text(total + ' ' + (total === 1 ? 'order' : 'orders'));

			// Show pagination if we have orders
			if (total > 0) {
				$('#momcs-pagination-top, #momcs-pagination-bottom').show();
			} else {
				$('#momcs-pagination-top, #momcs-pagination-bottom').hide();
			}

			// Calculate pagination info
			var perPage = orderListState.perPage || 10;
			var currentPage = orderListState.page || 1;
			var start = (currentPage - 1) * perPage + 1;
			var end = Math.min(currentPage * perPage, total);
			var paginationInfo = 'Showing ' + start + '-' + end + ' of ' + total + ' orders';

			// Update pagination info
			$('#momcs-pagination-info-top, #momcs-pagination-info-bottom').html(paginationInfo);

			// Build pagination navigation
			var paginationNav = buildPaginationNav(currentPage, maxPages);
			$('#momcs-pagination-nav-top, #momcs-pagination-nav-bottom').html(paginationNav);
		}

		// Build pagination navigation HTML
		function buildPaginationNav(currentPage, maxPages) {
			if (maxPages <= 1) {
				return '';
			}

			var html = '';
			var showEllipsis = maxPages > 7;

			// First button
			html += '<button type="button" class="momcs-page-btn momcs-page-first" data-action="first" ' + (currentPage === 1 ? 'disabled' : '') + '>First</button>';

			// Previous button
			html += '<button type="button" class="momcs-page-btn momcs-page-prev" data-action="prev" ' + (currentPage === 1 ? 'disabled' : '') + '>Prev</button>';

			// Page numbers
			html += '<div class="momcs-page-numbers">';

			if (showEllipsis) {
				// Show first page
				if (currentPage > 3) {
					html += '<button type="button" class="momcs-page-num' + (1 === currentPage ? ' active' : '') + '" data-page="1">1</button>';
					if (currentPage > 4) {
						html += '<span class="momcs-page-ellipsis">...</span>';
					}
				}

				// Show pages around current
				var start = Math.max(1, currentPage - 2);
				var end = Math.min(maxPages, currentPage + 2);

				for (var i = start; i <= end; i++) {
					html += '<button type="button" class="momcs-page-num' + (i === currentPage ? ' active' : '') + '" data-page="' + i + '">' + i + '</button>';
				}

				// Show last page
				if (currentPage < maxPages - 2) {
					if (currentPage < maxPages - 3) {
						html += '<span class="momcs-page-ellipsis">...</span>';
					}
					html += '<button type="button" class="momcs-page-num' + (maxPages === currentPage ? ' active' : '') + '" data-page="' + maxPages + '">' + maxPages + '</button>';
				}
			} else {
				// Show all pages
				for (var i = 1; i <= maxPages; i++) {
					html += '<button type="button" class="momcs-page-num' + (i === currentPage ? ' active' : '') + '" data-page="' + i + '">' + i + '</button>';
				}
			}

			html += '</div>';

			// Next button
			html += '<button type="button" class="momcs-page-btn momcs-page-next" data-action="next" ' + (currentPage === maxPages ? 'disabled' : '') + '>Next</button>';

			// Last button
			html += '<button type="button" class="momcs-page-btn momcs-page-last" data-action="last" ' + (currentPage === maxPages ? 'disabled' : '') + '>Last</button>';

			return html;
		}

		// Handle per page change - sync both selects
		$( '#orders_per_page, #orders_per_page_bottom' ).on(
			'change',
			function () {
				var perPage = parseInt( $( this ).val() );
				orderListState.perPage = perPage;
				orderListState.page    = 1;
				
				// Sync the other select
				if ($(this).attr('id') === 'orders_per_page') {
					$('#orders_per_page_bottom').val(perPage);
				} else {
					$('#orders_per_page').val(perPage);
				}
				
				applyFilters();
			}
		);

		// Handle search - updated for new search input ID
		var searchTimeout;
		$( '#momcs-order-search' ).on(
			'input',
			function () {
				clearTimeout( searchTimeout );
				searchTimeout = setTimeout(
					function () {
						orderListState.search = $( '#momcs-order-search' ).val();
						orderListState.page   = 1;
						applyFilters();
					},
					500
				);
			}
		);

		// Handle delete channel action
		$( document ).on(
			'click',
			'.momcs-sync-delete-channel',
			function (e) {
				e.preventDefault();
				if ( ! confirm( 'Are you sure you want to delete this channel? This action cannot be undone.' )) {
					return;
				}
				const channelId = $( this ).data( 'id' );
				const $button   = $( this );
				$button.prop( 'disabled', true );

				$.post(
					momcs_sync_params.ajaxurl,
					{
						action: 'momcs_delete_channel',
						nonce: momcs_sync_params.nonce,
						channel_id: channelId
					},
					function (response) {
						if (response.success) {
							location.reload();
						} else {
							alert( response.data && response.data.message ? response.data.message : 'Failed to delete channel' );
							$button.prop( 'disabled', false );
						}
					}
				).fail(
					function () {
						alert( 'Request failed. Please try again.' );
						$button.prop( 'disabled', false );
					}
				);
			}
		);

		// Toggle logger visibility
		$( '#momcs-sync-toggle-logger' ).on(
			'click',
			function () {
				$( '#momcs-sync-logger-content' ).toggle();
				$( this ).text(
					function (i, text) {
						return text === "Hide Logs" ? "Show Logs" : "Hide Logs";
					}
				);
			}
		);

		// Clear logger content
		$( '#momcs-sync-clear-logger' ).on(
			'click',
			function () {
				$( '#momcs-sync-logger-content' ).empty();
			}
		);

		// Initial load – fetch previously synced orders only if orders table exists.
		if ( typeof loadOrders === 'function' && $( '#momcs_orders_list' ).length ) {
			loadOrders();
		}

		// Helper: format WooCommerce status into chip HTML.
		function formatWcStatus(status) {
			if ( ! status) {
				return '-';
			}
			var slug = String( status ).toLowerCase().replace( /\s+/g, '-' );
			return '<span class="momcs-sync-chip wc-status-' + slug + '">' + status + '</span>';
		}

	}
); 