/**
 * ActiveTrail Admin Script
 *
 * @package ActiveTrail_WooCommerce
 * @since 1.0.0
 */

(function ($) {
	'use strict';

	var ActiveTrailAdmin = {

		/**
		 * Store previous API key to detect changes
		 */
		previousApiKey: '',

		/**
		 * Initialize
		 */
		init: function () {
			// Store initial API key value
			this.previousApiKey = $( '#activetrail_api_key' ).val() || '';

		this.bindEvents();
		this.initTooltips();
		this.checkApiKey();

			// Check for API key change after page load (e.g., after form save and reload)
			// This helps detect when API key was changed and groups need to be reloaded
			var self = this;
			setTimeout(
				function () {
					self.checkApiKeyChange();
				},
				1000
			); // Check after 1 second to ensure page is fully loaded
		},

		/**
		 * Bind events
		 */
		bindEvents: function () {
			// Save API key button
			$( document ).on( 'click', '#activetrail-save-api-key-btn', this.saveApiKey );

			// Connect Store button
			$( document ).on( 'click', '#activetrail-connect-store-btn', this.connectStore );

			// Save group button
			$( document ).on( 'click', '#activetrail-save-group-btn', this.saveGroup );

			// Load more groups (select change)
			$( document ).on( 'change', '#activetrail_group_id', this.onGroupSelectChange );

			// Historical sync buttons
			$( document ).on( 'click', '#start-sync-contacts-only, #start-sync-contacts-orders', this.handleSyncClick );

			// Cancel historical sync button
			$( document ).on( 'click', '#cancel-historical-sync', this.cancelHistoricalSync );

			// Delete coupon button
			$( document ).on( 'click', '.delete-coupon', this.deleteCoupon );

			// Reset form button
			$( document ).on( 'click', '#reset-form', this.resetForm );

			// Load groups when API key changes (on blur)
			var self = this;
			$( document ).on(
				'blur',
				'#activetrail_api_key',
				function () {
					var newApiKey = $( this ).val() || '';
					// Only load if API key actually changed
					if (newApiKey && newApiKey.length > 10 && newApiKey !== self.previousApiKey) {
						self.previousApiKey = newApiKey;
						self.loadGroups( null, true ); // Force refresh when manually changed
					}
				}
			);

			// Refresh groups button - force refresh when clicking
			var self = this;
			$( document ).on(
				'click',
				'#activetrail-refresh-groups',
				function (e) {
					e.preventDefault();
					// Update button text to show loading state
					var $button         = $( this );
					var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';
					var originalText    = $button.text();

					if (currentLanguage === 'he_IL') {
						$button.prop( 'disabled', true ).text( 'מרענן קבוצות...' );
					} else if (currentLanguage === 'es_ES') {
						$button.prop( 'disabled', true ).text( 'Actualizando grupos...' );
					} else if (currentLanguage === 'fr_FR') {
						$button.prop( 'disabled', true ).text( 'Actualisation des groupes...' );
					} else {
						$button.prop( 'disabled', true ).text( 'Refreshing groups...' );
					}

					// Call loadGroups with forceRefresh = true
					self.loadGroups( e, true );

					// Restore button text after a delay (will be updated by loadGroups complete callback)
					setTimeout(
						function () {
							$button.prop( 'disabled', false ).text( originalText );
						},
						3000
					);
				}
			);

			// Copy feed URLs
			$( document ).on( 'click', '.activetrail-copy-url', this.copyUrl );

			// Copy URL buttons (for feed URLs)
			$( document ).on( 'click', '.copy-url-btn', this.copyFeedUrl );

			// Refresh feed key buttons
			$( document ).on( 'click', '.refresh-key-btn', this.refreshFeedKey );

			// Toggle sections
			$( document ).on( 'click', '.activetrail-toggle-section', this.toggleSection );

			// Form validation for required fields
			$( document ).on( 'submit', 'form:not(#activetrail-create-coupon-form)', this.validateRequiredFields );

			// Initialize save button translation
			this.initSaveButtonTranslation();
		},

		/**
		 * Initialize tooltips
		 */
		initTooltips: function () {
			// Only initialize tooltips if jQuery UI tooltip is available
			if ($.fn.tooltip) {
				$( '.activetrail-tooltip' ).tooltip(
					{
						position: { my: 'left+15 center', at: 'right center' }
					}
				);
			}
		},

		/**
		 * Check API key on load
		 */
		checkApiKey: function () {
			var apiKey = $( '#activetrail_api_key' ).val();
			if (apiKey && apiKey.length > 10) {
				// Groups are already rendered by PHP on page load.
				// Just initialise the pagination counter so 'Load more' starts at page 2.
				$( '#activetrail_group_id' ).data( 'at-page', 1 );
			}
		},

		/**
		 * Check if API key changed after page load (e.g., after form save)
		 */
		checkApiKeyChange: function () {
			var self          = this;
			var currentApiKey = $( '#activetrail_api_key' ).val() || '';

			// If API key changed (different from previous), reload groups
			if (currentApiKey && currentApiKey.length > 10 && currentApiKey !== this.previousApiKey) {
				// Update stored value
				this.previousApiKey = currentApiKey;

				// Force refresh groups (bypass cache)
				setTimeout(
					function () {
						self.loadGroups( null, true );
					},
					500
				); // Small delay to ensure settings are saved
			}
		},

		/**
		 * Test API connection
		 */
		testConnection: function (e) {
			e.preventDefault();

			var $button = $( this );
			var $status = $( '#activetrail-connection-status' );
			var apiKey  = $( '#activetrail_api_key' ).val();

			if ( ! apiKey) {
				$status.html( '<span class="error">❌ ' + activetrail_admin.strings.connection_failed + ' API key is required</span>' );
				return;
			}

			// Get current language for proper translations
			var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';

			// Update button text to loading state in current language
			if (currentLanguage === 'he_IL') {
				$button.prop( 'disabled', true ).text( 'בודק חיבור...' );
			} else if (currentLanguage === 'es_ES') {
				$button.prop( 'disabled', true ).text( 'Probando conexión...' );
			} else if (currentLanguage === 'fr_FR') {
				$button.prop( 'disabled', true ).text( 'Test de la connexion...' );
			} else {
				$button.prop( 'disabled', true ).text( activetrail_admin.strings.testing_connection );
			}

			// Show loading status in current language
			if (currentLanguage === 'he_IL') {
				$status.html( '<span class="loading">⏳ בודק חיבור...</span>' );
			} else if (currentLanguage === 'es_ES') {
				$status.html( '<span class="loading">⏳ Probando conexión...</span>' );
			} else if (currentLanguage === 'fr_FR') {
				$status.html( '<span class="loading">⏳ Test de la connexion...</span>' );
			} else {
				$status.html( '<span class="loading">⏳ ' + activetrail_admin.strings.testing_connection + '</span>' );
			}

			$.ajax(
				{
					url: activetrail_admin.ajax_url,
					type: 'POST',
					data: {
						action: 'activetrail_test_api',
						api_key: apiKey,
						nonce: activetrail_admin.nonce
					},
					success: function (response) {
						// Log the full response for debugging
						console.log( 'API Connection Response:', response );

						if (response.success) {
							// Handle successful connection
							var timestamp = new Date().toLocaleString();
							if (currentLanguage === 'he_IL') {
								$status.html( '<span class="success">✅ החיבור הצליח! (' + timestamp + ')</span>' );
							} else if (currentLanguage === 'es_ES') {
								$status.html( '<span class="success">✅ ¡Conexión exitosa! (' + timestamp + ')</span>' );
							} else if (currentLanguage === 'fr_FR') {
								$status.html( '<span class="success">✅ Connexion réussie ! (' + timestamp + ')</span>' );
							} else {
								$status.html( '<span class="success">✅ ' + activetrail_admin.strings.connection_successful + ' (' + timestamp + ')</span>' );
							}
							// Load groups after successful connection
							ActiveTrailAdmin.loadGroups();
						} else {
							// Handle error response
							var errorMessage = 'Unknown error';

							// Check if response has data.message first (structured error)
							if (response.data && response.data.message && response.data.message !== 'undefined') {
								errorMessage = response.data.message;
							}
							// Then check for direct message property
							else if (response.message && response.message !== 'undefined') {
								errorMessage = response.message;
							}
							// If we still have undefined, use a clear fallback message
							else if (errorMessage === 'undefined' || errorMessage === undefined) {
								errorMessage = 'Unable to connect to ActiveTrail API. Please check your API key and internet connection.';
							}

							// Log the error for debugging
							console.log( 'API Connection Error:', response );

							// Display localized error message
							if (currentLanguage === 'he_IL') {
								$status.html( '<span class="error">❌ החיבור נכשל: ' + errorMessage + '</span>' );
							} else if (currentLanguage === 'es_ES') {
								$status.html( '<span class="error">❌ Conexión fallida: ' + errorMessage + '</span>' );
							} else if (currentLanguage === 'fr_FR') {
								$status.html( '<span class="error">❌ Échec de la connexion : ' + errorMessage + '</span>' );
							} else {
								$status.html( '<span class="error">❌ ' + activetrail_admin.strings.connection_failed + ' ' + errorMessage + '</span>' );
							}
						}
					},
					error: function (xhr, status, error) {
						// Log the error details for debugging
						console.log( 'API Connection AJAX Error:', {xhr: xhr, status: status, error: error} );

						// Provide a more descriptive network error message
						var networkErrorMsg = 'Network error: Unable to connect to the server. Please check your internet connection.';

						if (currentLanguage === 'he_IL') {
							$status.html( '<span class="error">❌ החיבור נכשל: שגיאת רשת. אנא בדוק את חיבור האינטרנט שלך.</span>' );
						} else if (currentLanguage === 'es_ES') {
							$status.html( '<span class="error">❌ Conexión fallida: Error de red. Por favor, compruebe su conexión a Internet.</span>' );
						} else if (currentLanguage === 'fr_FR') {
							$status.html( '<span class="error">❌ Échec de la connexion : Erreur réseau. Veuillez vérifier votre connexion Internet.</span>' );
						} else {
							$status.html( '<span class="error">❌ ' + activetrail_admin.strings.connection_failed + ' ' + networkErrorMsg + '</span>' );
						}
					},
					complete: function () {
						$button.prop( 'disabled', false );
					}
				}
			);
		},

		/**
		 * Save API key
		 */
		saveApiKey: function (e) {
			e.preventDefault();
			e.stopPropagation();

			var $button = $( this );
			var $input = $( '#activetrail_api_key' );
			var $status = $( '#activetrail-api-key-status' );
			var apiKeyValue = $input.val();

			// Get current language for proper translations
			var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';

			if ( ! apiKeyValue || apiKeyValue.trim() === '' ) {
				var errorMsg = 'API Key is required. Please enter your API key.';
				if (currentLanguage === 'he_IL') {
					errorMsg = 'נדרש מפתח API. אנא הזן את מפתח ה-API שלך.';
				} else if (currentLanguage === 'es_ES') {
					errorMsg = 'Se requiere la clave API. Por favor, ingrese su clave API.';
				} else if (currentLanguage === 'fr_FR') {
					errorMsg = 'La clé API est requise. Veuillez entrer votre clé API.';
				}
				$status.html( '<div class="notice notice-error inline"><p>' + errorMsg + '</p></div>' );
				$input.focus();
				return false;
			}

			// Check if button is disabled
			if ( $button.prop( 'disabled' ) ) {
				console.log( '[ActiveTrail] Save button is disabled' );
				return false;
			}

			// Store original text
			var originalText = $button.text();

			// Update button text to loading state in current language
			if (currentLanguage === 'he_IL') {
				$button.prop( 'disabled', true ).text( 'שומר מפתח...' );
			} else if (currentLanguage === 'es_ES') {
				$button.prop( 'disabled', true ).text( 'Guardando clave...' );
			} else if (currentLanguage === 'fr_FR') {
				$button.prop( 'disabled', true ).text( 'Enregistrement de la clé...' );
			} else {
				$button.prop( 'disabled', true ).text( 'Saving API key...' );
			}

			// Show loading status in current language
			if (currentLanguage === 'he_IL') {
				$status.html( '<div class="notice notice-info inline"><p>שומר מפתח...</p></div>' );
			} else if (currentLanguage === 'es_ES') {
				$status.html( '<div class="notice notice-info inline"><p>Guardando clave...</p></div>' );
			} else if (currentLanguage === 'fr_FR') {
				$status.html( '<div class="notice notice-info inline"><p>Enregistrement de la clé...</p></div>' );
			} else {
				$status.html( '<div class="notice notice-info inline"><p>Saving API key...</p></div>' );
			}

			console.log( '[ActiveTrail] Starting API key save request...' );

			$.ajax( {
				url: activetrail_admin.ajax_url,
				type: 'POST',
				timeout: 35000,
				data: {
					action: 'activetrail_save_api_key',
					api_key: apiKeyValue,
					nonce: activetrail_admin.nonce
				},
				success: function (response) {
					console.log( '[ActiveTrail] API key save response:', response );
					if ( response && response.success ) {
						var successMsg = 'API key saved successfully!';
						if (currentLanguage === 'he_IL') {
							successMsg = 'מפתח API נשמר בהצלחה!';
						} else if (currentLanguage === 'es_ES') {
							successMsg = '¡Clave API guardada con éxito!';
						} else if (currentLanguage === 'fr_FR') {
							successMsg = 'Clé API enregistrée avec succès !';
						}
						$status.html( '<div class="notice notice-success inline"><p>✅ ' + successMsg + '</p></div>' );
						setTimeout( function () { $status.fadeOut(); }, 3000 );
						
						// Update stored API key
						ActiveTrailAdmin.previousApiKey = apiKeyValue;
						
						// Refresh groups dropdown
						ActiveTrailAdmin.loadGroups( null, true );

						// Unlock Group section now that the API key is saved
						$( '#activetrail-group-section-wrapper' ).removeClass( 'at-group-locked' );
					} else {
						var errorMessage = ( response && response.data ) ? response.data : 'Unknown error';
						if ( typeof errorMessage === 'object' && errorMessage.message ) {
							errorMessage = errorMessage.message;
						}
						$status.html( '<div class="notice notice-error inline"><p>❌ ' + errorMessage + '</p></div>' );
					}
				},
				error: function (xhr, status, error) {
					console.error( '[ActiveTrail] API key save error:', status, error, xhr );
					var errorMessage = 'Network error occurred';
					
					if ( status === 'timeout' ) {
						errorMessage = 'Request timeout. The API key test took too long. Please check your connection and try again.';
						if (currentLanguage === 'he_IL') {
							errorMessage = 'פג תוקף הבקשה. בדיקת מפתח ה-API ארכה זמן רב מדי. אנא בדוק את החיבור שלך ונסה שוב.';
						} else if (currentLanguage === 'es_ES') {
							errorMessage = 'Tiempo de espera agotado. La prueba de la clave API tardó demasiado. Por favor, verifique su conexión e intente nuevamente.';
						} else if (currentLanguage === 'fr_FR') {
							errorMessage = 'Délai d\'attente dépassé. Le test de la clé API a pris trop de temps. Veuillez vérifier votre connexion et réessayer.';
						}
					} else {
						if ( xhr.responseJSON && xhr.responseJSON.data ) {
							errorMessage = xhr.responseJSON.data;
						} else if ( xhr.responseText ) {
							try {
								var response = JSON.parse( xhr.responseText );
								if ( response.data ) {
									errorMessage = response.data;
								}
							} catch ( e ) {
								console.error( '[ActiveTrail] Failed to parse error response:', e );
							}
						}
					}
					
					$status.html( '<div class="notice notice-error inline"><p>❌ ' + errorMessage + '</p></div>' );
				},
				complete: function () {
					console.log( '[ActiveTrail] API key save request completed' );
					// Restore button text in current language
					if (currentLanguage === 'he_IL') {
						$button.prop( 'disabled', false ).text( 'שמור מפתח' );
					} else if (currentLanguage === 'es_ES') {
						$button.prop( 'disabled', false ).text( 'Guardar clave' );
					} else if (currentLanguage === 'fr_FR') {
						$button.prop( 'disabled', false ).text( 'Enregistrer la clé' );
					} else {
						$button.prop( 'disabled', false ).text( originalText || 'Save API Key' );
					}
				}
			} );

			return false;
		},

		/**
		 * Save group
		 */
		saveGroup: function (e) {
			e.preventDefault();
			e.stopPropagation();

			var $button = $( this );
			var $select = $( '#activetrail_group_id' );
			var $status = $( '#activetrail-group-status' );
			var selectedValue = $select.val();
			var selectedText = $select.find( 'option:selected' ).text();

			// Get current language for proper translations
			var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';

			if ( ! selectedValue || selectedValue === '' ) {
				var errorMsg = 'Please select a group.';
				if (currentLanguage === 'he_IL') {
					errorMsg = 'אנא בחר קבוצה.';
				} else if (currentLanguage === 'es_ES') {
					errorMsg = 'Por favor, seleccione un grupo.';
				} else if (currentLanguage === 'fr_FR') {
					errorMsg = 'Veuillez sélectionner un groupe.';
				}
				$status.html( '<div class="notice notice-error inline"><p>' + errorMsg + '</p></div>' );
				$select.focus();
				return false;
			}

			// Store original text
			var originalText = $button.text();

			// Update button text to loading state in current language
			if (currentLanguage === 'he_IL') {
				$button.prop( 'disabled', true ).text( 'שומר קבוצה...' );
			} else if (currentLanguage === 'es_ES') {
				$button.prop( 'disabled', true ).text( 'Guardando grupo...' );
			} else if (currentLanguage === 'fr_FR') {
				$button.prop( 'disabled', true ).text( 'Enregistrement du groupe...' );
			} else {
				$button.prop( 'disabled', true ).text( 'Saving...' );
			}

			// Show loading status in current language
			if (currentLanguage === 'he_IL') {
				$status.html( '<div class="notice notice-info inline"><p>שומר קבוצה...</p></div>' );
			} else if (currentLanguage === 'es_ES') {
				$status.html( '<div class="notice notice-info inline"><p>Guardando grupo...</p></div>' );
			} else if (currentLanguage === 'fr_FR') {
				$status.html( '<div class="notice notice-info inline"><p>Enregistrement du groupe...</p></div>' );
			} else {
				$status.html( '<div class="notice notice-info inline"><p>Saving group...</p></div>' );
			}

			$.ajax( {
				url: activetrail_admin.ajax_url,
				type: 'POST',
				data: {
					action: 'activetrail_save_group',
					group_id: selectedValue,
					nonce: activetrail_admin.nonce
				},
				success: function (response) {
					if ( response.success ) {
						var successMsg = 'Group saved successfully! (' + selectedText + ')';
						if (currentLanguage === 'he_IL') {
							successMsg = 'קבוצה נשמרה בהצלחה! (' + selectedText + ')';
						} else if (currentLanguage === 'es_ES') {
							successMsg = '¡Grupo guardado con éxito! (' + selectedText + ')';
						} else if (currentLanguage === 'fr_FR') {
							successMsg = 'Groupe enregistré avec succès ! (' + selectedText + ')';
						}
						$status.html( '<div class="notice notice-success inline"><p>✅ ' + successMsg + '</p></div>' );
						setTimeout( function () { $status.fadeOut(); }, 3000 );
						console.log( '[ActiveTrail] Group saved:', {
							group_id: selectedValue,
							group_name: selectedText,
							timestamp: new Date().toISOString()
						} );

						// Enable Connect Store button now that a group is saved
						var $connectBtn = $( '#activetrail-connect-store-btn' );
						if ( ! $connectBtn.hasClass( 'at-connect-ready' ) ) {
							$connectBtn.prop( 'disabled', false ).addClass( 'at-connect-ready' );
						}

					} else {
						var errorMsg = response.data || 'Unknown error';
						$status.html( '<div class="notice notice-error inline"><p>❌ ' + errorMsg + '</p></div>' );
					}
				},
				error: function (xhr, status, error) {
					console.error( '[ActiveTrail] Error saving group:', status, error );
					var errorMsg = 'Network error occurred';
					if (currentLanguage === 'he_IL') {
						errorMsg = 'אירעה שגיאת רשת';
					} else if (currentLanguage === 'es_ES') {
						errorMsg = 'Error de red';
					} else if (currentLanguage === 'fr_FR') {
						errorMsg = 'Erreur réseau';
					}
					$status.html( '<div class="notice notice-error inline"><p>❌ ' + errorMsg + '</p></div>' );
				},
				complete: function () {
					$button.prop( 'disabled', false );
				}
			} );

			return false;
		},

		/**
		 * Handle group select change — triggers "load more" when that option is chosen
		 */
		onGroupSelectChange: function () {
			var $select = $( this );
			if ($select.val() === '__load_more__') {
				// Restore the previously selected real group so selection isn't lost
				var previousValue = $select.data( 'at-selected' ) || '';
				$select.val( previousValue );
				var nextPage = ( $select.data( 'at-page' ) || 1 ) + 1;
				ActiveTrailAdmin.loadGroups( null, false, nextPage );
			} else if ($select.val() !== '' && $select.val() !== null) {
				// Track the last real group selection
				$select.data( 'at-selected', $select.val() );
			}
		},

		/**
		 * Connect store to ActiveTrail
		 */
		connectStore: function (e) {
			e.preventDefault();
			e.stopPropagation();

			var $button = $( this );
			var $status = $( '#activetrail-connect-store-status' );
			var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';

			if ( $button.prop( 'disabled' ) ) {
				return false;
			}

			// Show loading state
			var originalText = $button.text();
			$button.prop( 'disabled', true ).text(
				activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.connecting_store
					? activetrail_admin.strings.connecting_store
					: 'Connecting...'
			);
			$status.html( '' );

			$.ajax( {
				url: activetrail_admin.ajax_url,
				type: 'POST',
				data: {
					action: 'activetrail_connect_store',
					nonce: activetrail_admin.nonce
				},
				success: function (response) {
					if ( response && response.success ) {
						var successMsg = ( activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.store_connected )
							? activetrail_admin.strings.store_connected
							: 'Store connected successfully!';
						$status.html( '<div class="notice notice-success inline"><p>✅ ' + successMsg + '</p></div>' );
						setTimeout( function () { $status.fadeOut(); }, 3000 );

						// Update button to connected state immediately — no page reload needed.
						var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';
						var connectedLabel;
						if ( currentLanguage === 'he_IL' ) {
							connectedLabel = activetrail_admin.strings.store_connected_hebrew || 'החנות מחוברת בהצלחה!';
						} else if ( currentLanguage === 'es_ES' ) {
							connectedLabel = activetrail_admin.strings.store_connected_spanish || '¡Tienda conectada exitosamente!';
						} else if ( currentLanguage === 'fr_FR' ) {
							connectedLabel = activetrail_admin.strings.store_connected_french || 'Boutique connectée avec succès !';
						} else {
							connectedLabel = activetrail_admin.strings.store_connected || 'Store connected successfully!';
						}
						$button.text( connectedLabel ).css( {
							'pointer-events': 'none',
							'cursor': 'default',
							'background-color': '#21C49B',
							'border-color': '#1aab87',
							'color': '#fff'
						} ).prop( 'disabled', false );
						activetrail_admin.store_is_connected = true;
					} else {
						var errorMsg = ( response && response.data ) ? response.data : 'Connection failed';
						$status.html( '<div class="notice notice-error inline"><p>❌ ' + errorMsg + '</p></div>' );
						$button.prop( 'disabled', false ).text( originalText );
					}
				},
				error: function () {
					$status.html( '<div class="notice notice-error inline"><p>❌ Network error occurred</p></div>' );
					$button.prop( 'disabled', false ).text( originalText );
				},
				complete: function () {}
			} );

			return false;
		},

		/**
		 * Format number with commas for display
		 */
		formatSyncNumber: function (num) {
			if (num === null || num === undefined || num === '' || num === '-') return '-';
			var number = parseInt(num, 10);
			if (isNaN(number)) return '-';
			return number.toLocaleString();
		},

		/**
		 * Update progress display with sync data
		 */
		updateSyncProgress: function (data) {
			if (!data) {
				console.warn('[ActiveTrail] updateSyncProgress called with no data');
				return;
			}
			
			var status = data.status || '';
			var $messageDiv = $( '#sync-status-message' );
			var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';
			var message = '';
			var messageType = 'info';
			
			// Show simple status messages based on sync status
			if (status === 'running') {
				if (currentLanguage === 'he_IL') {
					message = 'בתהליך...';
				} else if (currentLanguage === 'es_ES') {
					message = 'En proceso...';
				} else if (currentLanguage === 'fr_FR') {
					message = 'En cours...';
				} else {
					message = 'In process...';
				}
				messageType = 'info';
			} else if (status === 'completed') {
				if (currentLanguage === 'he_IL') {
					message = 'הסתיים בהצלחה';
				} else if (currentLanguage === 'es_ES') {
					message = 'Completado con éxito';
				} else if (currentLanguage === 'fr_FR') {
					message = 'Terminé avec succès';
				} else {
					message = 'Completed successfully';
				}
				messageType = 'success';
			} else if (status === 'cancelled') {
				if (currentLanguage === 'he_IL') {
					message = 'בוטל';
				} else if (currentLanguage === 'es_ES') {
					message = 'Cancelado';
				} else if (currentLanguage === 'fr_FR') {
					message = 'Annulé';
				} else {
					message = 'Cancelled';
				}
				messageType = 'warning';
			} else if (status === 'error' || status === 'failed') {
				if (currentLanguage === 'he_IL') {
					message = 'נכשל';
				} else if (currentLanguage === 'es_ES') {
					message = 'Falló';
				} else if (currentLanguage === 'fr_FR') {
					message = 'Échoué';
				} else {
					message = 'Failed';
				}
				messageType = 'error';
			}
			
			// Update message display
			$messageDiv.removeClass( 'info success error warning' ).addClass( messageType );
			$messageDiv.html( message ).show();
			
			// Show errors if any
			if (data.errors && data.errors.length > 0) {
				var errorList = $( '#error-list' );
				errorList.empty();
				data.errors.forEach( function (error) {
					var errorText = error.email ? (error.email + ': ') : '';
					errorText += error.error || error.message || 'Unknown error';
					errorList.append( '<li>' + errorText + '</li>' );
				} );
				$( '#sync-errors' ).show();
			} else {
				$( '#sync-errors' ).hide();
			}
			
			// Show failed contacts CSV if available
			if (data.failed_contacts_csv && data.failed_contacts_csv.url) {
				$( '#download-failed-csv' ).attr( 'href', data.failed_contacts_csv.url );
				if (data.failed_contacts_csv.count) {
					var contactText = data.failed_contacts_csv.count === 1 ? 'contact' : 'contacts';
					$( '#failed-csv-count' ).text( '(' + data.failed_contacts_csv.count + ' ' + contactText + ' failed)' );
				}
				$( '#failed-contacts-csv' ).show();
			} else {
				$( '#failed-contacts-csv' ).hide();
			}
		},

		/**
		 * Start progress polling for sync
		 */
		startProgressPolling: function () {
			if (window.activetrailSyncInterval) {
				return; // Already polling
			}
			
			var ajaxUrl = activetrail_admin.ajax_url;
			var nonce = activetrail_admin.nonce;
			var errorCount = 0;
			var maxErrors = 10; // Stop after 10 consecutive errors
			
			// Start polling every 2 seconds
			window.activetrailSyncInterval = setInterval( function () {
				$.ajax( {
					url: ajaxUrl,
					type: 'POST',
					data: {
						action: 'activetrail_get_sync_progress',
						nonce: nonce
					},
					success: function (response) {
						errorCount = 0; // Reset error count on success
						if (response && response.success) {
							if (response.data) {
								ActiveTrailAdmin.updateSyncProgress( response.data );
								
								if (response.data.status === 'completed' || response.data.status === 'cancelled') {
									ActiveTrailAdmin.stopProgressPolling();
									if (response.data.status === 'completed') {
										// Reload page after 2 seconds
										setTimeout( function () {
											location.reload();
										}, 2000 );
									}
									$( '#start-sync-contacts-only, #start-sync-contacts-orders' ).show();
									$( '#cancel-historical-sync' ).hide();
								}
							} else {
								console.warn( '[ActiveTrail] Progress response missing data:', response );
							}
						} else {
							console.warn( '[ActiveTrail] Progress response not successful:', response );
						}
					},
					error: function (xhr, status, error) {
						errorCount++;
						console.error( '[ActiveTrail] Error fetching sync progress:', {xhr: xhr, status: status, error: error, errorCount: errorCount} );
						
						// Stop polling after too many errors
						if (errorCount >= maxErrors) {
							console.error( '[ActiveTrail] Too many errors, stopping polling' );
							ActiveTrailAdmin.stopProgressPolling();
						}
					}
				} );
			}, 2000 );
		},

		/**
		 * Stop progress polling
		 */
		stopProgressPolling: function () {
			if (window.activetrailSyncInterval) {
				clearInterval( window.activetrailSyncInterval );
				window.activetrailSyncInterval = null;
			}
		},

		/**
		 * Check sync status on page load
		 */
		checkSyncStatus: function () {
			var ajaxUrl = activetrail_admin.ajax_url;
			var nonce = activetrail_admin.nonce;
			
			$.ajax( {
				url: ajaxUrl,
				type: 'POST',
				data: {
					action: 'activetrail_get_sync_progress',
					nonce: nonce
				},
				success: function (response) {
					if (response.success && response.data) {
						var status = response.data.status;
						if (status === 'running') {
							// Sync is running - show status message and start polling
							$( '#sync-progress-container' ).show();
							$( '#start-sync-contacts-only, #start-sync-contacts-orders' ).hide();
							$( '#cancel-historical-sync' ).show();
							ActiveTrailAdmin.updateSyncProgress( response.data );
							ActiveTrailAdmin.startProgressPolling();
						} else if (status === 'completed' || status === 'cancelled') {
							// Show last status message
							$( '#sync-progress-container' ).show();
							$( '#start-sync-contacts-only, #start-sync-contacts-orders' ).show();
							$( '#cancel-historical-sync' ).hide();
							ActiveTrailAdmin.updateSyncProgress( response.data );
						} else {
							// No sync running - hide progress container
							$( '#sync-progress-container' ).hide();
						}
					} else {
						// No sync data - hide progress container
						$( '#sync-progress-container' ).hide();
					}
				},
				error: function (xhr, status, error) {
					console.error( '[ActiveTrail] Error checking sync status:', error );
					// Hide progress container on error
					$( '#sync-progress-container' ).hide();
				}
			} );
		},

		/**
		 * Handle historical sync button click
		 */
		handleSyncClick: function (e) {
			e.preventDefault();
			e.stopPropagation();

			var $button = $( this );
			console.log( '[ActiveTrail Historical Sync] Button clicked:', $button.attr( 'id' ) );

			// Check if button is disabled
			if ( $button.prop( 'disabled' ) ) {
				console.log( '[ActiveTrail Historical Sync] Button is disabled' );
				return false;
			}

			var syncType = $button.data( 'sync-type' );
			var ajaxUrl = activetrail_admin.ajax_url;
			var nonce = activetrail_admin.nonce;

			// Get date range from form inputs
			var dateFrom = $( '#sync-date-from' ).val() || '';
			var dateTo = $( '#sync-date-to' ).val() || '';

			// Determine sync options based on sync type
			var syncContacts = ( syncType === 'contacts' || syncType === 'all' );
			var syncOrders = ( syncType === 'all' );

			// Get current language for proper translations
			var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';

			// Store original HTML
			var originalHtml = $button.html();

			// Disable buttons and show loading state
			$button.prop( 'disabled', true );

			// Update button text based on language and sync type
			var loadingText = '';
			if ( syncType === 'contacts' ) {
				if (currentLanguage === 'he_IL') {
					loadingText = '<span class="dashicons dashicons-update spin"></span> מתחיל סנכרון אנשי קשר...';
				} else if (currentLanguage === 'es_ES') {
					loadingText = '<span class="dashicons dashicons-update spin"></span> Iniciando sincronización de contactos...';
				} else if (currentLanguage === 'fr_FR') {
					loadingText = '<span class="dashicons dashicons-update spin"></span> Démarrage de la synchronisation des contacts...';
				} else {
					loadingText = '<span class="dashicons dashicons-update spin"></span> Starting Contacts Sync...';
				}
			} else {
				if (currentLanguage === 'he_IL') {
					loadingText = '<span class="dashicons dashicons-update spin"></span> מתחיל סנכרון מלא...';
				} else if (currentLanguage === 'es_ES') {
					loadingText = '<span class="dashicons dashicons-update spin"></span> Iniciando sincronización completa...';
				} else if (currentLanguage === 'fr_FR') {
					loadingText = '<span class="dashicons dashicons-update spin"></span> Démarrage de la synchronisation complète...';
				} else {
					loadingText = '<span class="dashicons dashicons-update spin"></span> Starting Full Sync...';
				}
			}
			$button.html( loadingText );

			console.log( '[ActiveTrail Historical Sync] Starting sync:', {
				syncType: syncType,
				dateFrom: dateFrom,
				dateTo: dateTo,
				syncContacts: syncContacts,
				syncOrders: syncOrders
			} );

			$.ajax( {
				url: ajaxUrl,
				type: 'POST',
				data: {
					action: 'activetrail_start_historical_sync',
					sync_type: syncType,
					date_from: dateFrom,
					date_to: dateTo,
					sync_contacts: syncContacts,
					sync_orders: syncOrders,
					nonce: nonce
				},
				success: function (response) {
					console.log( '[ActiveTrail Historical Sync] Response:', response );
					if ( response.success ) {
						// Show status message container
						$( '#sync-progress-container' ).show();
						$( '#start-sync-contacts-only, #start-sync-contacts-orders' ).hide();
						$( '#cancel-historical-sync' ).show();
						
						// Show "Starting..." message
						var $messageDiv = $( '#sync-status-message' );
						var startingMessage = '';
						if (currentLanguage === 'he_IL') {
							startingMessage = 'מתחיל...';
						} else if (currentLanguage === 'es_ES') {
							startingMessage = 'Iniciando...';
						} else if (currentLanguage === 'fr_FR') {
							startingMessage = 'Démarrage...';
						} else {
							startingMessage = 'Starting...';
						}
						$messageDiv.removeClass( 'info success error warning' ).addClass( 'info' );
						$messageDiv.html( startingMessage ).show();
						
						// Check sync status immediately to update from "Starting" to "In process"
						$.ajax( {
							url: ajaxUrl,
							type: 'POST',
							data: {
								action: 'activetrail_get_sync_progress',
								nonce: nonce
							},
							success: function (statusResponse) {
								if ( statusResponse && statusResponse.success && statusResponse.data ) {
									if ( typeof ActiveTrailAdmin !== 'undefined' && typeof ActiveTrailAdmin.updateSyncProgress === 'function' ) {
										ActiveTrailAdmin.updateSyncProgress( statusResponse.data );
									}
								}
							}
						} );
						
						// Start progress polling only when button is clicked
						if ( typeof window.activetrailStartProgressPolling === 'function' ) {
							window.activetrailStartProgressPolling();
						} else if ( typeof ActiveTrailAdmin !== 'undefined' && typeof ActiveTrailAdmin.startProgressPolling === 'function' ) {
							ActiveTrailAdmin.startProgressPolling();
						}
					} else {
						// Show error message
						var errorMsg = response.data && response.data.message ? response.data.message : 'Failed to start sync';
						if (currentLanguage === 'he_IL') {
							errorMsg = 'נכשל בהתחלת הסנכרון: ' + errorMsg;
						} else if (currentLanguage === 'es_ES') {
							errorMsg = 'Error al iniciar la sincronización: ' + errorMsg;
						} else if (currentLanguage === 'fr_FR') {
							errorMsg = 'Échec du démarrage de la synchronisation : ' + errorMsg;
						} else {
							errorMsg = 'Error: ' + errorMsg;
						}
						alert( errorMsg );
						// Re-enable buttons
						$button.prop( 'disabled', false ).html( originalHtml );
					}
				},
				error: function (xhr, status, error) {
					console.error( '[ActiveTrail Historical Sync] AJAX error:', {xhr: xhr, status: status, error: error} );
					var errorMsg = 'Network error: ' + error;
					if (currentLanguage === 'he_IL') {
						errorMsg = 'שגיאת רשת: ' + error;
					} else if (currentLanguage === 'es_ES') {
						errorMsg = 'Error de red: ' + error;
					} else if (currentLanguage === 'fr_FR') {
						errorMsg = 'Erreur réseau : ' + error;
					}
					alert( errorMsg );
					// Re-enable buttons
					$button.prop( 'disabled', false ).html( originalHtml );
				}
			} );

			return false;
		},

		/**
		 * Cancel historical sync
		 */
		cancelHistoricalSync: function (e) {
			e.preventDefault();
			e.stopPropagation();

			var $button = $( this );
			var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';

			// Store original HTML
			var originalHtml = $button.html();

			// Disable button and show loading
			$button.prop( 'disabled', true );

			// Update button text based on language
			var loadingText = '';
			if (currentLanguage === 'he_IL') {
				loadingText = '<span class="dashicons dashicons-update spin"></span> מבטל...';
			} else if (currentLanguage === 'es_ES') {
				loadingText = '<span class="dashicons dashicons-update spin"></span> Cancelando...';
			} else if (currentLanguage === 'fr_FR') {
				loadingText = '<span class="dashicons dashicons-update spin"></span> Annulation...';
			} else {
				loadingText = '<span class="dashicons dashicons-update spin"></span> Cancelling...';
			}
			$button.html( loadingText );

			console.log( '[ActiveTrail Historical Sync] Cancelling sync' );

			$.ajax( {
				url: activetrail_admin.ajax_url,
				type: 'POST',
				data: {
					action: 'activetrail_cancel_historical_sync',
					nonce: activetrail_admin.nonce
				},
				success: function (response) {
					console.log( '[ActiveTrail Historical Sync] Cancel sync response:', response );
					
					// Stop progress polling
					if ( typeof window.activetrailStopProgressPolling === 'function' ) {
						window.activetrailStopProgressPolling();
					} else {
						ActiveTrailAdmin.stopProgressPolling();
					}

					// Reset sync interface
					$( '#start-sync-contacts-only, #start-sync-contacts-orders' ).show();
					$( '#cancel-historical-sync' ).hide();
					$( '#sync-progress-container' ).hide();

					$button.prop( 'disabled', false ).html( originalHtml );
				},
				error: function (xhr, status, error) {
					console.error( '[ActiveTrail Historical Sync] AJAX error cancelling sync:', {xhr: xhr, status: status, error: error} );
					var errorMsg = 'Error cancelling sync: ' + error;
					if (currentLanguage === 'he_IL') {
						errorMsg = 'שגיאה בביטול הסנכרון: ' + error;
					} else if (currentLanguage === 'es_ES') {
						errorMsg = 'Error al cancelar la sincronización: ' + error;
					} else if (currentLanguage === 'fr_FR') {
						errorMsg = 'Erreur lors de l\'annulation de la synchronisation : ' + error;
					}
					alert( errorMsg );
					$button.prop( 'disabled', false ).html( originalHtml );
				}
			} );

			return false;
		},

		/**
		 * Delete coupon
		 */
		deleteCoupon: function (e) {
			e.preventDefault();
			e.stopPropagation();

			var $button = $( this );
			var couponId = $button.data( 'coupon-id' );
			var couponCode = $button.data( 'coupon-code' );

			// Get current language for proper translations
			var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';

			// Confirm deletion
			var confirmMsg = 'Are you sure you want to delete the coupon "' + couponCode + '"?';
			if (currentLanguage === 'he_IL') {
				confirmMsg = 'האם אתה בטוח שברצונך למחוק את הקופון "' + couponCode + '"?';
			} else if (currentLanguage === 'es_ES') {
				confirmMsg = '¿Está seguro de que desea eliminar el cupón "' + couponCode + '"?';
			} else if (currentLanguage === 'fr_FR') {
				confirmMsg = 'Êtes-vous sûr de vouloir supprimer le coupon "' + couponCode + '"?';
			}

			if ( ! confirm( confirmMsg ) ) {
				return false;
			}

			$button.prop( 'disabled', true );

			$.ajax( {
				url: activetrail_admin.ajax_url,
				type: 'POST',
				data: {
					action: 'activetrail_delete_coupon',
					nonce: activetrail_admin.nonce,
					coupon_id: couponId
				},
				success: function (response) {
					if ( response.success ) {
						// Remove row from table
						$button.closest( 'tr' ).fadeOut( function () {
							$( this ).remove();

							// Check if table is empty
							if ( $( '.coupons-table tbody tr' ).length === 0 ) {
								var noCouponsMsg = 'No coupons found. Create your first coupon using the form above.';
								if (currentLanguage === 'he_IL') {
									noCouponsMsg = 'לא נמצאו קופונים. צור את הקופון הראשון שלך באמצעות הטופס למעלה.';
								} else if (currentLanguage === 'es_ES') {
									noCouponsMsg = 'No se encontraron cupones. Cree su primer cupón usando el formulario de arriba.';
								} else if (currentLanguage === 'fr_FR') {
									noCouponsMsg = 'Aucun coupon trouvé. Créez votre premier coupon en utilisant le formulaire ci-dessus.';
								}
								$( '.coupons-table-container' ).html( '<div class="no-coupons-message"><p>' + noCouponsMsg + '</p></div>' );
							}
						} );
					} else {
						var errorMsg = 'Failed to delete coupon: ' + ( response.data || 'Unknown error' );
						if (currentLanguage === 'he_IL') {
							errorMsg = 'נכשל במחיקת הקופון: ' + ( response.data || 'שגיאה לא ידועה' );
						} else if (currentLanguage === 'es_ES') {
							errorMsg = 'Error al eliminar el cupón: ' + ( response.data || 'Error desconocido' );
						} else if (currentLanguage === 'fr_FR') {
							errorMsg = 'Échec de la suppression du coupon : ' + ( response.data || 'Erreur inconnue' );
						}
						alert( errorMsg );
					}
				},
				error: function (xhr, status, error) {
					console.error( '[ActiveTrail] Error deleting coupon:', status, error );
					var errorMsg = 'Error deleting coupon';
					if (currentLanguage === 'he_IL') {
						errorMsg = 'שגיאה במחיקת הקופון';
					} else if (currentLanguage === 'es_ES') {
						errorMsg = 'Error al eliminar el cupón';
					} else if (currentLanguage === 'fr_FR') {
						errorMsg = 'Erreur lors de la suppression du coupon';
					}
					alert( errorMsg );
				},
				complete: function () {
					$button.prop( 'disabled', false );
				}
			} );

			return false;
		},

		/**
		 * Reset form
		 */
		resetForm: function (e) {
			e.preventDefault();
			e.stopPropagation();

			var $form = $( '#activetrail-create-coupon-form' );
			if ( $form.length ) {
				$form[0].reset();
			}

			return false;
		},

		/**
		 * Load groups from API
		 */
		loadGroups: function (e, forceRefresh, page) {
			if (e) {
				e.preventDefault();
			}

			page = page || 1;

			var $select = $( '#activetrail_group_id' );
			var $status = $( '#activetrail-groups-status' );
			var apiKey  = $( '#activetrail_api_key' ).val();

			if ( ! apiKey) {
				return;
			}

			// Get current language for proper translations
			var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';

			// Save current selection before any changes
			var currentValue = $select.val();

			// On page 1 disable the select; on subsequent pages keep it usable
			if (page === 1) {
				$select.prop( 'disabled', true );
			}

			// Remove any existing "load more" option before issuing the request
			$select.find( 'option[value="__load_more__"]' ).remove();

			// Show loading status in current language
			if (currentLanguage === 'he_IL') {
				$status.html( '<span class="loading">⏳ טוען קבוצות...</span>' );
			} else if (currentLanguage === 'es_ES') {
				$status.html( '<span class="loading">⏳ Cargando grupos...</span>' );
			} else if (currentLanguage === 'fr_FR') {
				$status.html( '<span class="loading">⏳ Chargement des groupes...</span>' );
			} else {
				$status.html( '<span class="loading">' + activetrail_admin.strings.loading_groups + '</span>' );
			}

			// Log for debugging
			if (forceRefresh) {
				console.log( '[ActiveTrail] Refreshing groups from API (force refresh = true)' );
			}

			$.ajax(
				{
					url: activetrail_admin.ajax_url,
					type: 'POST',
					data: {
						action: 'activetrail_get_groups',
						api_key: apiKey,
						force_refresh: forceRefresh ? 1 : 0,
						page: page,
						nonce: activetrail_admin.nonce
					},
					success: function (response) {
						console.log( '[ActiveTrail] Groups response:', response );

						if (response.success && response.data && response.data.groups) {
							var groups      = response.data.groups;
							var groupsCount = groups.length;
							var hasMore     = response.data.has_more;

							// Log groups count for debugging
							console.log( '[ActiveTrail] Groups loaded - Count: ' + groupsCount + ', hasMore: ' + hasMore + ', page: ' + page );

							if (page === 1) {
								// Page 1: replace all options
								if (currentLanguage === 'he_IL') {
									$select.empty().append( '<option value="">בחר קבוצה...</option>' );
								} else if (currentLanguage === 'es_ES') {
									$select.empty().append( '<option value="">Seleccionar grupo...</option>' );
								} else if (currentLanguage === 'fr_FR') {
									$select.empty().append( '<option value="">Sélectionner un groupe...</option>' );
								} else {
									$select.empty().append( '<option value="">Select a group...</option>' );
								}
							}

							// Append fetched groups
							$.each(
								groups,
								function (index, group) {
									var groupId   = group.id || group.Id || '';
									var groupName = group.name || group.Name || '';
									var selected  = (groupId == currentValue) ? 'selected' : '';
									$select.append( '<option value="' + groupId + '" ' + selected + '>' + groupName + '</option>' );
								}
							);

							// Store current page on the element for the "load more" handler
							$select.data( 'at-page', page );

							// Always show "Load more" on page 1, or if a subsequent page returned results.
							// Remove it (don't add) only when a subsequent page returns 0 groups (end of list).
							if (page === 1 || groupsCount > 0) {
								var loadMoreText = currentLanguage === 'he_IL' ? '── טען עוד... ──' :
									currentLanguage === 'es_ES' ? '── Cargar más... ──' :
									currentLanguage === 'fr_FR' ? '── Charger plus... ──' :
									'── Load more... ──';
								$select.append( '<option value="__load_more__">' + loadMoreText + '</option>' );
							}

							// Restore the previously selected value on page 1
							if (page === 1 && currentValue) {
								$select.val( currentValue );
							}

							// Show success status with total count of loaded options
							var totalShown = $select.find( 'option:not([value=""]):not([value="__load_more__"])' ).length;
							if (currentLanguage === 'he_IL') {
								$status.html( '<span class="success">✅ הקבוצות נטענו בהצלחה (' + totalShown + ' קבוצות)</span>' );
							} else if (currentLanguage === 'es_ES') {
								$status.html( '<span class="success">✅ Grupos cargados exitosamente (' + totalShown + ' grupos)</span>' );
							} else if (currentLanguage === 'fr_FR') {
								$status.html( '<span class="success">✅ Groupes chargés avec succès (' + totalShown + ' groupes)</span>' );
							} else {
								$status.html( '<span class="success">' + activetrail_admin.strings.groups_loaded + ' (' + totalShown + ' groups)</span>' );
							}
						} else {
							// Show error status in current language
							if (currentLanguage === 'he_IL') {
								$status.html( '<span class="error">❌ נכשל בטעינת הקבוצות: ' + (response.message || 'שגיאה לא ידועה') + '</span>' );
							} else if (currentLanguage === 'es_ES') {
								$status.html( '<span class="error">❌ Error al cargar grupos: ' + (response.message || 'Error desconocido') + '</span>' );
							} else if (currentLanguage === 'fr_FR') {
								$status.html( '<span class="error">❌ Échec du chargement des groupes : ' + (response.message || 'Erreur inconnue') + '</span>' );
							} else {
								$status.html( '<span class="error">' + activetrail_admin.strings.groups_failed + ' ' + (response.message || 'Unknown error') + '</span>' );
							}
						}
					},
					error: function () {
						// Show network error in current language
						if (currentLanguage === 'he_IL') {
							$status.html( '<span class="error">❌ נכשל בטעינת הקבוצות: שגיאת רשת</span>' );
						} else if (currentLanguage === 'es_ES') {
							$status.html( '<span class="error">❌ Error al cargar grupos: Error de red</span>' );
						} else if (currentLanguage === 'fr_FR') {
							$status.html( '<span class="error">❌ Échec du chargement des groupes : Erreur réseau</span>' );
						} else {
							$status.html( '<span class="error">' + activetrail_admin.strings.groups_failed + ' Network error</span>' );
						}
					},
					complete: function () {
						$select.prop( 'disabled', false );

						// Restore refresh button state
						var $refreshButton = $( '#activetrail-refresh-groups' );
						if ($refreshButton.length) {
							var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';
							var buttonText      = '';

							if (currentLanguage === 'he_IL') {
								buttonText = activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.refresh_groups_hebrew ? activetrail_admin.strings.refresh_groups_hebrew : 'רענן קבוצות';
							} else if (currentLanguage === 'es_ES') {
								buttonText = activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.refresh_groups_spanish ? activetrail_admin.strings.refresh_groups_spanish : 'Actualizar grupos';
							} else if (currentLanguage === 'fr_FR') {
								buttonText = activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.refresh_groups_french ? activetrail_admin.strings.refresh_groups_french : 'Actualiser les groupes';
							} else {
								buttonText = activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.refresh_groups ? activetrail_admin.strings.refresh_groups : 'Refresh Groups';
							}

							$refreshButton.prop( 'disabled', false ).text( buttonText );
						}

						setTimeout(
							function () {
								$status.fadeOut();
							},
							3000
						);
					}
				}
			);
		},

		/**
		 * Copy URL to clipboard
		 */
		copyUrl: function (e) {
			e.preventDefault();

			var $button = $( this );
			var url     = $button.data( 'url' );

			// Create temporary input
			var $temp = $( '<input>' );
			$( 'body' ).append( $temp );
			$temp.val( url ).select();

			try {
				document.execCommand( 'copy' );
				$button.text( 'Copied!' ).addClass( 'copied' );

				setTimeout(
					function () {
						$button.text( 'Copy' ).removeClass( 'copied' );
					},
					2000
				);
			} catch (err) {
				console.error( 'Failed to copy URL:', err );
			}

			$temp.remove();
		},

		/**
		 * Copy feed URL to clipboard
		 */
		copyFeedUrl: function (e) {
			e.preventDefault();
			e.stopPropagation();

			var $button = $( this );
			var targetId = $button.data( 'clipboard-target' );
			var $input = $( targetId );
			var textToCopy = $input.val();

			// Get current language for proper translations
			var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';

			if ( ! textToCopy ) {
				var errorMsg = 'No URL to copy';
				if (currentLanguage === 'he_IL') {
					errorMsg = 'אין כתובת URL להעתקה';
				} else if (currentLanguage === 'es_ES') {
					errorMsg = 'No hay URL para copiar';
				} else if (currentLanguage === 'fr_FR') {
					errorMsg = 'Aucune URL à copier';
				}
				alert( errorMsg );
				return false;
			}

			// Try modern Clipboard API first
			if ( navigator.clipboard && window.isSecureContext ) {
				navigator.clipboard.writeText( textToCopy ).then( function () {
					var originalText = $button.html();
					var copiedText = 'Copied!';
					if (currentLanguage === 'he_IL') {
						copiedText = 'הועתק!';
					} else if (currentLanguage === 'es_ES') {
						copiedText = '¡Copiado!';
					} else if (currentLanguage === 'fr_FR') {
						copiedText = 'Copié !';
					}
					$button.addClass( 'copied' ).html( '<span class="dashicons dashicons-yes"></span>' + copiedText );

					setTimeout( function () {
						$button.removeClass( 'copied' ).html( originalText );
					}, 2000 );
				} ).catch( function (err) {
					console.error( 'Failed to copy:', err );
					ActiveTrailAdmin.fallbackCopyText( textToCopy, $button, $input );
				} );
			} else {
				ActiveTrailAdmin.fallbackCopyText( textToCopy, $button, $input );
			}

			return false;
		},

		/**
		 * Fallback copy function
		 */
		fallbackCopyText: function (text, $button, $input) {
			var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';
			var textarea = document.createElement( 'textarea' );
			textarea.value = text;
			textarea.style.position = 'fixed';
			textarea.style.left = '-999999px';
			textarea.style.top = '-999999px';
			document.body.appendChild( textarea );
			textarea.focus();
			textarea.select();

			try {
				var successful = document.execCommand( 'copy' );
				if ( successful ) {
					var originalText = $button.html();
					var copiedText = 'Copied!';
					if (currentLanguage === 'he_IL') {
						copiedText = 'הועתק!';
					} else if (currentLanguage === 'es_ES') {
						copiedText = '¡Copiado!';
					} else if (currentLanguage === 'fr_FR') {
						copiedText = 'Copié !';
					}
					$button.addClass( 'copied' ).html( '<span class="dashicons dashicons-yes"></span>' + copiedText );

					setTimeout( function () {
						$button.removeClass( 'copied' ).html( originalText );
					}, 2000 );
				} else {
					var errorMsg = 'Failed to copy';
					if (currentLanguage === 'he_IL') {
						errorMsg = 'נכשל בהעתקה';
					} else if (currentLanguage === 'es_ES') {
						errorMsg = 'Error al copiar';
					} else if (currentLanguage === 'fr_FR') {
						errorMsg = 'Échec de la copie';
					}
					alert( errorMsg );
				}
			} catch (err) {
				console.error( 'Fallback copy failed:', err );
				var errorMsg = 'Failed to copy';
				if (currentLanguage === 'he_IL') {
					errorMsg = 'נכשל בהעתקה';
				} else if (currentLanguage === 'es_ES') {
					errorMsg = 'Error al copiar';
				} else if (currentLanguage === 'fr_FR') {
					errorMsg = 'Échec de la copie';
				}
				alert( errorMsg );
			} finally {
				document.body.removeChild( textarea );
			}
		},

		/**
		 * Refresh feed key
		 */
		refreshFeedKey: function (e) {
			e.preventDefault();
			e.stopPropagation();

			var $button = $( this );
			var feedType = $button.data( 'feed-type' );
			var originalText = $button.html();

			// Get current language for proper translations
			var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';

			if ( ! feedType ) {
				var errorMsg = 'Invalid feed type';
				if (currentLanguage === 'he_IL') {
					errorMsg = 'סוג הזנה לא תקין';
				} else if (currentLanguage === 'es_ES') {
					errorMsg = 'Tipo de feed inválido';
				} else if (currentLanguage === 'fr_FR') {
					errorMsg = 'Type de flux invalide';
				}
				alert( errorMsg );
				return false;
			}

			// Show notice before refresh
			if ( feedType === 'google' ) {
				$( '#google-refresh-notice' ).show();
			} else if ( feedType === 'facebook' ) {
				$( '#facebook-refresh-notice' ).show();
			}

			// Get base URL
			var baseUrl = window.location.origin + window.location.pathname.replace( /\/wp-admin.*/, '' );

			// Update button to loading state
			var loadingText = '';
			if (currentLanguage === 'he_IL') {
				loadingText = '<span class="dashicons dashicons-update spin"></span> מרענן...';
			} else if (currentLanguage === 'es_ES') {
				loadingText = '<span class="dashicons dashicons-update spin"></span> Actualizando...';
			} else if (currentLanguage === 'fr_FR') {
				loadingText = '<span class="dashicons dashicons-update spin"></span> Actualisation...';
			} else {
				loadingText = '<span class="dashicons dashicons-update spin"></span> Refreshing...';
			}
			$button.prop( 'disabled', true ).html( loadingText );

			$.ajax( {
				url: activetrail_admin.ajax_url,
				type: 'POST',
				data: {
					action: 'activetrail_refresh_feed_key',
					feed_type: feedType,
					nonce: activetrail_admin.nonce
				},
				success: function (response) {
					if ( response.success ) {
						// Update the hidden key input
						if ( feedType === 'google' ) {
							$( '#google-feed-key' ).val( response.data.new_key );
							var newUrl = baseUrl + '/?activetrail_export=google&key=' + response.data.new_key;
							$( '#google-feed-url' ).val( newUrl );
						} else if ( feedType === 'facebook' ) {
							$( '#facebook-feed-key' ).val( response.data.new_key );
							var newUrl = baseUrl + '/?activetrail_export=facebook&key=' + response.data.new_key;
							$( '#facebook-feed-url' ).val( newUrl );
						}

						// Show success message
						var successMsg = activetrail_admin.strings && activetrail_admin.strings.key_refreshed 
							? activetrail_admin.strings.key_refreshed 
							: 'Key refreshed successfully';
						$( '<div class="notice notice-success is-dismissible"><p>' + successMsg + '</p></div>' )
							.insertAfter( '.activetrail-export-feeds-simple' )
							.delay( 5000 )
							.fadeOut();
					} else {
						var errorMsg = 'Failed to refresh key: ' + ( response.data || 'Unknown error' );
						if (currentLanguage === 'he_IL') {
							errorMsg = 'נכשל ברענון המפתח: ' + ( response.data || 'שגיאה לא ידועה' );
						} else if (currentLanguage === 'es_ES') {
							errorMsg = 'Error al actualizar la clave: ' + ( response.data || 'Error desconocido' );
						} else if (currentLanguage === 'fr_FR') {
							errorMsg = 'Échec de l\'actualisation de la clé : ' + ( response.data || 'Erreur inconnue' );
						}
						alert( errorMsg );
					}
				},
				error: function (xhr, status, error) {
					console.error( '[ActiveTrail] AJAX Error refreshing feed key:', status, error );
					var errorMsg = 'Network error: ' + error;
					if (currentLanguage === 'he_IL') {
						errorMsg = 'שגיאת רשת: ' + error;
					} else if (currentLanguage === 'es_ES') {
						errorMsg = 'Error de red: ' + error;
					} else if (currentLanguage === 'fr_FR') {
						errorMsg = 'Erreur réseau : ' + error;
					}
					alert( errorMsg );
				},
				complete: function () {
					$button.prop( 'disabled', false ).html( originalText );
				}
			} );

			return false;
		},

		/**
		 * Toggle section visibility
		 */
		toggleSection: function (e) {
			e.preventDefault();

			var $button  = $( this );
			var $section = $button.closest( '.activetrail-section' );
			var $content = $section.find( '.activetrail-section-content' );

			$content.slideToggle();
			$button.toggleClass( 'collapsed' );
		},

		/**
		 * Validate required fields before form submission
		 */
		validateRequiredFields: function (e) {
			var $form        = $( e.target );
			var isValid      = true;
			var errorMessage = '';

			// Check if we're on the ActiveTrail settings page
			if ($form.find( '#activetrail_api_key' ).length === 0) {
				return true; // Not our form, allow submission
			}

			// Validate API Key field
			var $apiKeyField = $( '#activetrail_api_key' );
			var apiKey       = $apiKeyField.val();

			if ( ! $apiKeyField.length || ! apiKey || apiKey.trim() === '') {
				isValid = false;

				// Get current language for error message
				var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';

				if (currentLanguage === 'he_IL') {
					errorMessage = 'מפתח API הוא שדה חובה. אנא הזן את מפתח ה-API שלך.';
				} else if (currentLanguage === 'es_ES') {
					errorMessage = 'La clave API es obligatoria. Por favor ingrese su clave API.';
				} else if (currentLanguage === 'fr_FR') {
					errorMessage = 'La clé API est obligatoire. Veuillez saisir votre clé API.';
				} else {
					errorMessage = 'API Key is required. Please enter your API key.';
				}

				// Show error message
				alert( errorMessage );

				// Focus on the field
				$apiKeyField.focus();

				// Scroll to the field
				$( 'html, body' ).animate(
					{
						scrollTop: $apiKeyField.offset().top - 100
					},
					500
				);

				return false;
			}

			// Validate Group ID field
			var $groupSelect = $( '#activetrail_group_id' );
			var groupId      = $groupSelect.val();

			if ( ! $groupSelect.length || ! groupId || groupId === '') {
				isValid = false;

				// Get current language for error message
				var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';

				if (currentLanguage === 'he_IL') {
					errorMessage = 'מזהה הקבוצה הוא שדה חובה. אנא בחר קבוצה.';
				} else if (currentLanguage === 'es_ES') {
					errorMessage = 'El ID del grupo es obligatorio. Por favor seleccione un grupo.';
				} else if (currentLanguage === 'fr_FR') {
					errorMessage = 'L\'ID du groupe est obligatoire. Veuillez sélectionner un groupe.';
				} else {
					errorMessage = 'Group ID is required. Please select a group.';
				}

				// Show error message
				if ($( '#activetrail-group-status' ).length) {
					$( '#activetrail-group-status' ).html( '<div class="notice notice-error inline"><p>' + errorMessage + '</p></div>' );
				} else {
					alert( errorMessage );
				}

				// Focus on the field
				$groupSelect.focus();

				// Scroll to the field
				$( 'html, body' ).animate(
					{
						scrollTop: $groupSelect.offset().top - 100
					},
					500
				);
			}

			if ( ! isValid) {
				e.preventDefault();
				return false;
			}

			return true;
		},

		/**
		 * Initialize save button translation
		 */
		initSaveButtonTranslation: function () {
			var self = this;

			// Function to update save button text based on current language
			function updateSaveButtonText() {
				var $saveButton = $( '.woocommerce-save-button' );
				if ($saveButton.length > 0) {
					var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';

					if (currentLanguage === 'he_IL') {
						$saveButton.text( 'שמירת שינויים' ).attr( 'value', 'שמירת שינויים' );
					} else if (currentLanguage === 'es_ES') {
						$saveButton.text( 'Guardar cambios' ).attr( 'value', 'Guardar cambios' );
					} else if (currentLanguage === 'fr_FR') {
						$saveButton.text( 'Enregistrer les modifications' ).attr( 'value', 'Enregistrer les modifications' );
					} else {
						$saveButton.text( 'Save Changes' ).attr( 'value', 'Save Changes' );
					}
				}
			}

			// Function to update all ActiveTrail buttons based on current language
			function updateAllActiveTrailButtons() {
				var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';


				// Update Refresh Groups button
				var $refreshButton = $( '#activetrail-refresh-groups' );
				if ($refreshButton.length > 0) {
					if (currentLanguage === 'he_IL') {
						$refreshButton.text( 'רענן קבוצות' );
					} else if (currentLanguage === 'es_ES') {
						$refreshButton.text( 'Actualizar grupos' );
					} else if (currentLanguage === 'fr_FR') {
						$refreshButton.text( 'Actualiser les groupes' );
					} else {
						$refreshButton.text( 'Refresh Groups' );
					}
				}

				// Update Save Group button
				var $saveGroupButton = $( '#activetrail-save-group-btn' );
				if ($saveGroupButton.length > 0) {
					if (currentLanguage === 'he_IL') {
						$saveGroupButton.text( 'שמור קבוצה' );
					} else if (currentLanguage === 'es_ES') {
						$saveGroupButton.text( 'Guardar grupo' );
					} else if (currentLanguage === 'fr_FR') {
						$saveGroupButton.text( 'Enregistrer le groupe' );
					} else {
						$saveGroupButton.text( 'Save Group' );
					}
				}

				// Update Connect Store button text
				var $connectStoreButton = $( '#activetrail-connect-store-btn' );
				if ($connectStoreButton.length > 0) {
					if ( activetrail_admin.store_is_connected ) {
						if (currentLanguage === 'he_IL') {
							$connectStoreButton.text( activetrail_admin.strings.store_connected_hebrew || 'החנות מחוברת בהצלחה!' );
						} else if (currentLanguage === 'es_ES') {
							$connectStoreButton.text( activetrail_admin.strings.store_connected_spanish || '¡Tienda conectada exitosamente!' );
						} else if (currentLanguage === 'fr_FR') {
							$connectStoreButton.text( activetrail_admin.strings.store_connected_french || 'Boutique connectée avec succès !' );
						} else {
							$connectStoreButton.text( activetrail_admin.strings.store_connected || 'Store connected successfully!' );
						}
					} else {
						if (currentLanguage === 'he_IL') {
							$connectStoreButton.text( activetrail_admin.strings.connect_store_hebrew || 'חבר חנות' );
						} else if (currentLanguage === 'es_ES') {
							$connectStoreButton.text( activetrail_admin.strings.connect_store_spanish || 'Conectar tienda' );
						} else if (currentLanguage === 'fr_FR') {
							$connectStoreButton.text( activetrail_admin.strings.connect_store_french || 'Connecter la boutique' );
						} else {
							$connectStoreButton.text( activetrail_admin.strings.connect_store || 'Connect Store' );
						}
					}
				}
			}

			// Function to update all status messages based on current language
			function updateAllStatusMessages() {
				var currentLanguage = $( '.activetrail-language-select' ).val() || 'en_US';

				// Update connection status messages
				var $connectionStatus = $( '#activetrail-connection-status' );
				if ($connectionStatus.length > 0) {
					var $statusContent = $connectionStatus.find( 'span' );
					if ($statusContent.length > 0) {
						var currentClass = $statusContent.attr( 'class' );
						var currentText  = $statusContent.text();

						if (currentClass && currentClass.includes( 'loading' )) {
							if (currentLanguage === 'he_IL') {
								$statusContent.html( '⏳ בודק חיבור...' );
							} else if (currentLanguage === 'es_ES') {
								$statusContent.html( '⏳ Probando conexión...' );
							} else if (currentLanguage === 'fr_FR') {
								$statusContent.html( '⏳ Test de la connexion...' );
							} else {
								$statusContent.html( '⏳ Testing connection...' );
							}
						} else if (currentClass && currentClass.includes( 'success' )) {
							var timestamp = currentText.match( /\(([^)]+)\)/ );
							if (timestamp) {
								if (currentLanguage === 'he_IL') {
									$statusContent.html( '✅ החיבור הצליח! (' + timestamp[1] + ')' );
								} else if (currentLanguage === 'es_ES') {
									$statusContent.html( '✅ ¡Conexión exitosa! (' + timestamp[1] + ')' );
								} else if (currentLanguage === 'fr_FR') {
									$statusContent.html( '✅ Connexion réussie ! (' + timestamp[1] + ')' );
								} else {
									$statusContent.html( '✅ Connection successful! (' + timestamp[1] + ')' );
								}
							}
						} else if (currentClass && currentClass.includes( 'error' )) {
							var errorMessage = currentText.replace( /^❌\s*/, '' ).replace( /^Connection failed:\s*/, '' );
							if (currentLanguage === 'he_IL') {
								$statusContent.html( '❌ החיבור נכשל: ' + errorMessage );
							} else if (currentLanguage === 'es_ES') {
								$statusContent.html( '❌ Conexión fallida: ' + errorMessage );
							} else if (currentLanguage === 'fr_FR') {
								$statusContent.html( '❌ Échec de la connexion : ' + errorMessage );
							}
						}
					}
				}

				// Update groups status messages
				var $groupsStatus = $( '#activetrail-groups-status' );
				if ($groupsStatus.length > 0) {
					var $statusContent = $groupsStatus.find( 'span' );
					if ($statusContent.length > 0) {
						var currentClass = $statusContent.attr( 'class' );
						var currentText  = $statusContent.text();

						if (currentClass && currentClass.includes( 'loading' )) {
							if (currentLanguage === 'he_IL') {
								$statusContent.html( '⏳ טוען קבוצות...' );
							} else if (currentLanguage === 'es_ES') {
								$statusContent.html( '⏳ Cargando grupos...' );
							} else if (currentLanguage === 'fr_FR') {
								$statusContent.html( '⏳ Chargement des groupes...' );
							} else {
								$statusContent.html( '⏳ Loading groups...' );
							}
						} else if (currentClass && currentClass.includes( 'success' )) {
							if (currentLanguage === 'he_IL') {
								$statusContent.html( '✅ הקבוצות נטענו בהצלחה' );
							} else if (currentLanguage === 'es_ES') {
								$statusContent.html( '✅ Grupos cargados exitosamente' );
							} else if (currentLanguage === 'fr_FR') {
								$statusContent.html( '✅ Groupes chargés avec succès' );
							} else {
								$statusContent.html( '✅ Groups loaded successfully' );
							}
						} else if (currentClass && currentClass.includes( 'error' )) {
							var errorMessage = currentText.replace( /^❌\s*/, '' ).replace( /^Failed to load groups:\s*/, '' );
							if (currentLanguage === 'he_IL') {
								$statusContent.html( '❌ נכשל בטעינת הקבוצות: ' + errorMessage );
							} else if (currentLanguage === 'es_ES') {
								$statusContent.html( '❌ Error al cargar grupos: ' + errorMessage );
							} else if (currentLanguage === 'fr_FR') {
								$statusContent.html( '❌ Échec du chargement des groupes : ' + errorMessage );
							}
						}
					}
				}

				// Update group select placeholder
				var $groupSelect = $( '#activetrail_group_id' );
				if ($groupSelect.length > 0) {
					var $firstOption = $groupSelect.find( 'option:first' );
					if ($firstOption.length > 0 && $firstOption.val() === '') {
						if (currentLanguage === 'he_IL') {
							$firstOption.text( 'בחר קבוצה...' );
						} else if (currentLanguage === 'es_ES') {
							$firstOption.text( 'Seleccionar grupo...' );
						} else if (currentLanguage === 'fr_FR') {
							$firstOption.text( 'Sélectionner un groupe...' );
						} else {
							$firstOption.text( 'Select a group...' );
						}
					}
				}
			}

			// Update on page load
			setTimeout(
				function () {
					updateSaveButtonText();
					updateAllActiveTrailButtons();
					updateAllStatusMessages(); // Update status messages on page load
				},
				500
			);

			// Update when language changes
			$( '.activetrail-language-select' ).on(
				'change',
				function () {
					setTimeout(
						function () {
							updateSaveButtonText();
							updateAllActiveTrailButtons();
							updateAllStatusMessages(); // Update status messages on language change
						},
						100
					);
				}
			);

			// Monitor for dynamically added save buttons
			var observer = new MutationObserver(
				function (mutations) {
					mutations.forEach(
						function (mutation) {
							if (mutation.type === 'childList') {
								mutation.addedNodes.forEach(
									function (node) {
										if (node.nodeType === 1) { // Element node
											var $node = $( node );
											if ($node.hasClass( 'woocommerce-save-button' ) || $node.find( '.woocommerce-save-button' ).length > 0) {
												setTimeout( updateSaveButtonText, 100 );
											}
											// Also check for ActiveTrail buttons
											if ($node.attr( 'id' ) === 'activetrail-refresh-groups' ||
											$node.attr( 'id' ) === 'activetrail-save-group-btn') {
												setTimeout( updateAllActiveTrailButtons, 100 );
											}
										}
									}
								);
							}
						}
					);
				}
			);

			// Start observing
			observer.observe(
				document.body,
				{
					childList: true,
					subtree: true
				}
			);
		},

		/**
		 * Show notification
		 */
		showNotification: function (message, type) {
			type = type || 'info';

			var $notification = $( '<div class="notice notice-' + type + ' is-dismissible"><p>' + message + '</p></div>' );
			$( '.wrap h1' ).after( $notification );

			setTimeout(
				function () {
					$notification.fadeOut();
				},
				5000
			);
		},

		/**
		 * Format number with commas
		 */
		formatNumber: function (num) {
			return num.toString().replace( /\B(?=(\d{3})+(?!\d))/g, ',' );
		},

		/**
		 * Debounce function
		 */
		debounce: function (func, wait, immediate) {
			var timeout;
			return function () {
				var context = this, args = arguments;
				var later   = function () {
					timeout = null;
					if ( ! immediate) {
						func.apply( context, args );
					}
				};
				var callNow = immediate && ! timeout;
				clearTimeout( timeout );
				timeout = setTimeout( later, wait );
				if (callNow) {
					func.apply( context, args );
				}
			};
		},

		/**
		 * Log debug information to server
		 */
		logToServer: function (context, message, data) {
			// Only log if activetrail_admin is available
			if (typeof activetrail_admin === 'undefined') {
				return;
			}

			$.ajax(
				{
					url: activetrail_admin.ajax_url,
					type: 'POST',
					data: {
						action: 'activetrail_log_debug',
						context: context,
						message: message,
						data: JSON.stringify( data ),
						nonce: activetrail_admin.nonce
					},
					success: function (response) {
						// Silent success - don't spam console
					},
					error: function () {
						// Silent error - don't spam console
					}
				}
			);
		}
	};

	// Initialize when document is ready
	$( document ).ready(
		function () {
			console.log( '[ActiveTrail Debug] Document ready, initializing...' );

			ActiveTrailAdmin.init();
		}
	);

	// Add refresh groups button after group select
	function createRefreshGroupsButton() {
		var $groupField = $( '#activetrail_group_id' );
		if ($groupField.length && ! $( '#activetrail-refresh-groups' ).length) {
			var buttonText     = activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.refresh_groups ? activetrail_admin.strings.refresh_groups : 'Refresh Groups';
			var $refreshButton = $( '<button type="button" id="activetrail-refresh-groups" class="button button-secondary">' + buttonText + '</button>' );
			var $status        = $( '<span id="activetrail-groups-status" style="flex: 1; min-width: 0;"></span>' );

			// Insert refresh button after the select, inside the flex row.
			// Insert groups-status before group-status so it stays inside the flex row.
			$groupField.after( $refreshButton );
			$( '#activetrail-group-status' ).before( $status );
		}
	}

	// Create button when DOM is ready and when translations are loaded
	$( document ).ready(
		function () {
			// Try to create button immediately
			createRefreshGroupsButton();

			// If translations aren't loaded yet, wait a bit and try again
			if ( ! activetrail_admin || ! activetrail_admin.strings) {
				setTimeout( createRefreshGroupsButton, 100 );
				setTimeout( createRefreshGroupsButton, 500 );
				setTimeout( createRefreshGroupsButton, 1000 );
			}
		}
	);

	// Add feed URLs display
	$( document ).ready(
		function () {
			var $feedSection = $( '#activetrail_feed_settings' );
			if ($feedSection.length) {
				var siteUrl = window.location.origin;
				var xmlUrl  = siteUrl + '/activetrail-feed.xml';
				var jsonUrl = siteUrl + '/activetrail-feed.json';

				var feedTitle    = activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.product_feed_urls ? activetrail_admin.strings.product_feed_urls : 'Product Feed URLs:';
				var xmlFeedText  = activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.xml_feed ? activetrail_admin.strings.xml_feed : 'XML Feed:';
				var jsonFeedText = activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.json_feed ? activetrail_admin.strings.json_feed : 'JSON Feed:';
				var copyText     = activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.copy ? activetrail_admin.strings.copy : 'Copy';
				var useUrlsText  = activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.use_these_urls ? activetrail_admin.strings.use_these_urls : 'Use these URLs in your ActiveTrail campaigns or external integrations.';

				var $feedUrls = $(
					'<div class="activetrail-feed-urls" style="margin-top: 20px; padding: 15px; background: #f9f9f9; border-left: 4px solid #0073aa;">' +
					'<h4>' + feedTitle + '</h4>' +
					'<p><strong>' + xmlFeedText + '</strong> <code>' + xmlUrl + '</code> <button type="button" class="button button-small activetrail-copy-url" data-url="' + xmlUrl + '">' + copyText + '</button></p>' +
					'<p><strong>' + jsonFeedText + '</strong> <code>' + jsonUrl + '</code> <button type="button" class="button button-small activetrail-copy-url" data-url="' + jsonUrl + '">' + copyText + '</button></p>' +
					'<p><em>' + useUrlsText + '</em></p>' +
					'</div>'
				);

				$feedSection.after( $feedUrls );
			}
		}
	);

	// Make ActiveTrailAdmin globally available
	window.ActiveTrailAdmin = ActiveTrailAdmin;

	// Language switching functionality
	$( document ).ready(
		function () {
			$( '.activetrail-language-select' ).on(
				'change',
				function () {
					var selectedLanguage = $( this ).val();
					var $form            = $( this ).closest( 'form' );

					// Add visual feedback
					$form.addClass( 'activetrail-language-switching' );

					// Show language change notification
					var message;
					if (selectedLanguage === 'he_IL') {
						message = activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.plugin_language_change_hebrew ? activetrail_admin.strings.plugin_language_change_hebrew : 'שפת התוסף תשתנה לעברית לאחר שמירת ההגדרות';
					} else if (selectedLanguage === 'es_ES') {
						message = activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.plugin_language_change_spanish ? activetrail_admin.strings.plugin_language_change_spanish : 'El idioma del plugin cambiará a español después de guardar la configuración';
					} else if (selectedLanguage === 'fr_FR') {
						message = activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.plugin_language_change_french ? activetrail_admin.strings.plugin_language_change_french : 'La langue du plugin changera en français après l\'enregistrement des paramètres';
					} else {
						message = activetrail_admin && activetrail_admin.strings && activetrail_admin.strings.plugin_language_change_english ? activetrail_admin.strings.plugin_language_change_english : 'Plugin language will change to English after saving settings';
					}

					var $notice = $( '<div class="activetrail-language-notice">' + message + '</div>' );
					$( this ).closest( 'tr' ).after( '<tr><td colspan="2">' + $notice.prop( 'outerHTML' ) + '</td></tr>' );

					// Apply language-specific styling for preview (but don't change page direction)
					if (selectedLanguage === 'he_IL') {
						$( '.activetrail-admin-section, .activetrail-sub-nav-wrapper, .activetrail-status-table-container, .activetrail-export-container, .activetrail-coupon-manager' ).addClass( 'activetrail-hebrew' );
					} else {
						$( '.activetrail-admin-section, .activetrail-sub-nav-wrapper, .activetrail-status-table-container, .activetrail-export-container, .activetrail-coupon-manager' ).removeClass( 'activetrail-hebrew' );
					}

					// Remove animation class after animation completes
					setTimeout(
						function () {
							$form.removeClass( 'activetrail-language-switching' );
						},
						500
					);

					// Auto-hide notice after 5 seconds
					setTimeout(
						function () {
							$( '.activetrail-language-notice' ).closest( 'tr' ).fadeOut();
						},
						5000
					);
				}
			);

			// Don't change WordPress direction - respect user's original settings
			// Only apply language-specific styling to ActiveTrail elements if needed
			var currentLanguage = $( '.activetrail-language-select' ).val();
			if (currentLanguage === 'he_IL') {
				// For Hebrew, we might need some specific styling but don't change page direction
				$( '.activetrail-admin-section, .activetrail-sub-nav-wrapper, .activetrail-status-table-container, .activetrail-export-container, .activetrail-coupon-manager' ).addClass( 'activetrail-hebrew' );
			} else {
				// Remove Hebrew-specific styling for other languages
				$( '.activetrail-admin-section, .activetrail-sub-nav-wrapper, .activetrail-status-table-container, .activetrail-export-container, .activetrail-coupon-manager' ).removeClass( 'activetrail-hebrew' );
			}

			// Handle form submission with language change
			$( 'form' ).on(
				'submit',
				function (e) {
					var $form = $( this );

					// Check if we're on export tab
					var currentSection = new URLSearchParams( window.location.search ).get( 'section' );
					if (currentSection && ['export'].indexOf( currentSection ) !== -1) {
						return;
					}

					// Only show language overlay for main settings form
					if ($form.find( '#activetrail_api_key' ).length === 0) {
						return;
					}

					var selectedLanguage = $( '.activetrail-language-select' ).val();
					var currentLanguage  = $( '.activetrail-language-select' ).val() || 'en_US';

					// Show saving message in appropriate language
					var savingMessage;
					if (selectedLanguage === 'he_IL') {
						savingMessage = 'שומר הגדרות ומחליף שפה...';
					} else if (selectedLanguage === 'es_ES') {
						savingMessage = 'Guardando configuración y cambiando idioma...';
					} else if (selectedLanguage === 'fr_FR') {
						savingMessage = 'Enregistrement des paramètres et changement de langue...';
					} else {
						savingMessage = 'Saving settings and switching language...';
					}

					var $overlay = $( '<div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999; display: flex; align-items: center; justify-content: center; color: white; font-size: 18px;">' + savingMessage + '</div>' );
					$( 'body' ).append( $overlay );

					// Apply language change immediately
					if (selectedLanguage === 'he_IL') {
						$( '.activetrail-admin-section, .activetrail-sub-nav-wrapper, .activetrail-status-table-container, .activetrail-export-container, .activetrail-coupon-manager' ).addClass( 'activetrail-hebrew' );
						// Update save button text immediately
						$( '.woocommerce-save-button' ).text( 'שמירת שינויים' ).attr( 'value', 'שמירת שינויים' );
					} else if (selectedLanguage === 'es_ES') {
						$( '.activetrail-admin-section, .activetrail-sub-nav-wrapper, .activetrail-status-table-container, .activetrail-export-container, .activetrail-coupon-manager' ).removeClass( 'activetrail-hebrew' );
						$( '.woocommerce-save-button' ).text( 'Guardar cambios' ).attr( 'value', 'Guardar cambios' );
					} else if (selectedLanguage === 'fr_FR') {
						$( '.activetrail-admin-section, .activetrail-sub-nav-wrapper, .activetrail-status-table-container, .activetrail-export-container, .activetrail-coupon-manager' ).removeClass( 'activetrail-hebrew' );
						$( '.woocommerce-save-button' ).text( 'Enregistrer les modifications' ).attr( 'value', 'Enregistrer les modifications' );
					} else {
						$( '.activetrail-admin-section, .activetrail-sub-nav-wrapper, .activetrail-status-table-container, .activetrail-export-container, .activetrail-coupon-manager' ).removeClass( 'activetrail-hebrew' );
						$( '.woocommerce-save-button' ).text( 'Save Changes' ).attr( 'value', 'Save Changes' );
					}

					// Check if API key changed before reload
					var apiKeyBeforeSubmit = ActiveTrailAdmin.previousApiKey;
					var apiKeyAfterSubmit  = $( '#activetrail_api_key' ).val() || '';

					// Update stored API key
					ActiveTrailAdmin.previousApiKey = apiKeyAfterSubmit;

					// Add page refresh after form submission
					setTimeout(
						function () {
							window.location.reload();
						},
						2000
					); // Wait 2 seconds for the form to submit
				}
			);
		}
	);

})( jQuery );
