jQuery(document).ready(function($) {
	// Tab switching logic
	$('.teknotok-ait-wrap .nav-tab-wrapper a').on('click', function(e) {
		e.preventDefault();
		
		// Remove active classes
		$('.teknotok-ait-wrap .nav-tab').removeClass('nav-tab-active');
		$('.teknotok-ait-wrap .tab-content').hide();
		
		// Add active class to clicked tab
		$(this).addClass('nav-tab-active');
		
		// Show corresponding content block
		var targetTab = $(this).attr('href');
		$(targetTab).show();
	});

	// Auto-scroll the log terminal to the bottom on load
	var $terminal = $('#log-terminal');
	if ($terminal.length) {
		$terminal.scrollTop($terminal[0].scrollHeight);
	}

	// Live status polling for Diagnostics page
	if ($('#queue-count-pending').length) {
		var pollInterval = null;
		var isRunningQueue = false;

		function triggerQueueExecution() {
			if (isRunningQueue) {
				return;
			}
			isRunningQueue = true;
			$.ajax({
				url: teknotokAitAdmin.ajaxUrl,
				type: 'POST',
				data: {
					action: 'teknotok_ait_run_queue_admin',
					nonce: teknotokAitAdmin.nonce
				},
				dataType: 'json',
				complete: function() {
					isRunningQueue = false;
					pollQueueStatus();
				}
			});
		}

		function pollQueueStatus() {
			$.ajax({
				url: teknotokAitAdmin.ajaxUrl,
				type: 'GET',
				data: {
					action: 'teknotok_ait_get_queue_status',
					nonce: teknotokAitAdmin.nonce
				},
				dataType: 'json',
				success: function(response) {
					if (response.success && response.data) {
						var data = response.data;
						
						// Update DOM values
						$('#queue-count-pending').text(data.pending);
						$('#queue-count-processing').text(data.processing);
						$('#queue-count-completed').text(data.completed);
						$('#queue-count-failed').text(data.failed);

						if (data.paused) {
							$('#queue-paused-badge').show();
							$('#queue-paused-message').show();
							$('#teknotok-resume-queue').show();
							$('#queue-resume-help').show();
							$('#queue-paused-reason').text(data.pause_reason || 'Translation provider limit reached.');
						} else {
							$('#queue-paused-badge').hide();
							$('#queue-paused-message').hide();
							$('#teknotok-resume-queue').hide();
							$('#queue-resume-help').hide();
						}

						var pending = parseInt(data.pending) || 0;
						var processing = parseInt(data.processing) || 0;
						var completed = parseInt(data.completed) || 0;
						var failed = parseInt(data.failed) || 0;
						var retryableFailed = parseInt(data.retryable_failed) || 0;
						var total = pending + processing + completed + failed;
						var $banner = $('#queue-calc-banner');

						if (retryableFailed > 0) {
							$('#teknotok-retry-failed-jobs').show();
							$('#queue-retry-help').show();
						} else {
							$('#teknotok-retry-failed-jobs').hide();
							$('#queue-retry-help').hide();
						}

						if ($banner.length && pending === 0 && processing === 0 && total > 0) {
							$banner.hide();
						}
						
						if (total > 0) {
							$('.teknotok-progress-container').show();
							var pct = Math.round((completed / total) * 100);
							$('#queue-progress-percentage').text(pct + '%');
							$('#queue-progress-bar').css('width', pct + '%');
							if (pending > 0 || processing > 0) {
								$('#queue-progress-bar').addClass('teknotok-progress-animated');
							} else {
								$('#queue-progress-bar').removeClass('teknotok-progress-animated');
							}
						}

						// Handle setup calc banner update and estimation
						if ($banner.length) {
							if (data.paused) {
								$('#queue-calc-title').text('Queue paused');
								$('#queue-calc-desc').text(data.pause_reason || 'Translation is paused until the license or quota issue is fixed.');
								$('#queue-calc-icon').attr('class', 'dashicons dashicons-warning');
							} else if (total === 0) {
								// Queue calculation in progress
								$('#queue-calc-title').text('Calculating translation time...');
								$('#queue-calc-desc').text('Please wait while the plugin calculates the total items and processes the initial translation batch. The live progress bar below will update automatically.');
								$('#queue-calc-icon').attr('class', 'dashicons dashicons-update spin');
							} else if (pending > 0 || processing > 0) {
								// Jobs are running, calculate estimate remaining time at ~1.5s per job
								var remainingSeconds = (pending + processing) * 1.5;
								var timeString = '';
								if (remainingSeconds < 60) {
									timeString = 'Less than a minute remaining';
								} else {
									var mins = Math.ceil(remainingSeconds / 60);
									timeString = '~' + mins + ' minutes remaining';
								}
								
								$('#queue-calc-title').text('Estimated Translation Time: ' + timeString);
								$('#queue-calc-desc').text('The plugin is translating your content in the background. You can see the progress live on this page or safely navigate away; translations will continue automatically.');
								$('#queue-calc-icon').attr('class', 'dashicons dashicons-clock').removeClass('spin');
							} else {
								// Queue is finished
								$banner.slideUp(400);
							}
						}

						var $processingIcon = $('.status-processing .status-icon .dashicons');
						if (processing > 0 || pending > 0) {
							$processingIcon.addClass('spin');
							if (!data.paused) {
								triggerQueueExecution();
							}
						} else {
							$processingIcon.removeClass('spin');
						}
					}
				}
			});
		}

		$(document).on('click', '#teknotok-resume-queue', function(e) {
			e.preventDefault();
			var $button = $(this);
			if ($button.prop('disabled')) {
				return;
			}

			$button.prop('disabled', true).text('Resuming...');
			$.ajax({
				url: teknotokAitAdmin.ajaxUrl,
				type: 'POST',
				data: {
					action: 'teknotok_ait_resume_queue',
					nonce: teknotokAitAdmin.nonce
				},
				dataType: 'json',
				complete: function() {
					$button.prop('disabled', false).text('Resume Queue');
					pollQueueStatus();
				}
			});
		});

		$(document).on('click', '#teknotok-retry-failed-jobs', function(e) {
			e.preventDefault();
			var $button = $(this);
			if ($button.prop('disabled')) {
				return;
			}

			$button.prop('disabled', true).text('Retrying...');
			$.ajax({
				url: teknotokAitAdmin.ajaxUrl,
				type: 'POST',
				data: {
					action: 'teknotok_ait_retry_failed_jobs',
					nonce: teknotokAitAdmin.nonce
				},
				dataType: 'json',
				complete: function() {
					$button.prop('disabled', false).text('Retry Failed Jobs');
					pollQueueStatus();
				}
			});
		});

		// Initial check values
		var initialPending = parseInt($('#queue-count-pending').text()) || 0;
		var initialProcessing = parseInt($('#queue-count-processing').text()) || 0;

		// Poll every 5 seconds always, run queue immediately if there are pending jobs
		pollInterval = setInterval(pollQueueStatus, 5000);
		if ((initialPending > 0 || initialProcessing > 0) && !$('#queue-paused-badge').is(':visible')) {
			triggerQueueExecution();
		}
	}

	// Toggle checkbox label class for languages grid selection styling
	$(document).on('change', '.teknotok-lang-checkbox-label input[type="checkbox"]', function() {
		$(this).parent('.teknotok-lang-checkbox-label').toggleClass('is-selected', this.checked);
	});

	// Deactivation modal hook
	if (typeof teknotokAitAdmin !== 'undefined' && parseInt(teknotokAitAdmin.isPluginsPage) === 1) {
		var deactivateUrl = '';

		// Listen on the deactivation link
		$(document).on('click', 'tr[data-plugin="teknotok-ai-translator-pro/teknotok-ai-translator-pro.php"] .deactivate a, #deactivate-teknotok-ai-translator-pro', function(e) {
			e.preventDefault();
			deactivateUrl = $(this).attr('href');

			// If the modal doesn't exist, create it
			if ($('#teknotok-deactivate-modal').length === 0) {
				var modalHtml = 
					'<div id="teknotok-deactivate-modal" class="teknotok-modal-overlay">' +
						'<div class="teknotok-modal-window">' +
							'<div class="teknotok-modal-header">' +
								'<h3><span class="dashicons dashicons-warning"></span> Deactivate AI Translator Pro</h3>' +
								'<button type="button" class="teknotok-modal-close"><span class="dashicons dashicons-no-alt"></span></button>' +
							'</div>' +
							'<div class="teknotok-modal-body">' +
								'<p>You are about to deactivate TeknoTok AI Translator Pro. Please choose whether you want to delete all plugin-related data when the plugin is deleted.</p>' +
								'<div class="teknotok-cleanup-option selected">' +
									'<input type="radio" name="teknotok_cleanup" id="teknotok-cleanup-no" value="0" checked>' +
									'<div class="teknotok-cleanup-option-content">' +
										'<label for="teknotok-cleanup-no" class="teknotok-cleanup-option-title">Keep My Data (Recommended)</label>' +
										'<span class="teknotok-cleanup-option-desc">Keep your translations cache, database tables, and settings intact in case you reinstall later.</span>' +
									'</div>' +
								'</div>' +
								'<div class="teknotok-cleanup-option">' +
									'<input type="radio" name="teknotok_cleanup" id="teknotok-cleanup-yes" value="1">' +
									'<div class="teknotok-cleanup-option-content">' +
										'<label for="teknotok-cleanup-yes" class="teknotok-cleanup-option-title">Clean Up Data</label>' +
										'<span class="teknotok-cleanup-option-desc">Permanently delete all custom database tables, queue jobs, translation memory cache, and options when you delete the plugin.</span>' +
									'</div>' +
								'</div>' +
							'</div>' +
							'<div class="teknotok-modal-footer">' +
								'<button type="button" class="teknotok-modal-btn teknotok-modal-btn-cancel">Cancel</button>' +
								'<button type="button" class="teknotok-modal-btn teknotok-modal-btn-submit">Deactivate</button>' +
							'</div>' +
						'</div>' +
					'</div>';
				
				$('body').append(modalHtml);
			}

			// Open the modal with animation
			var $modal = $('#teknotok-deactivate-modal');
			$modal.show();
			setTimeout(function() {
				$modal.addClass('active');
			}, 10);
		});

		// Close modal handlers
		$(document).on('click', '#teknotok-deactivate-modal .teknotok-modal-close, #teknotok-deactivate-modal .teknotok-modal-btn-cancel', function() {
			var $modal = $('#teknotok-deactivate-modal');
			$modal.removeClass('active');
			setTimeout(function() {
				$modal.hide();
			}, 300);
		});

		// Toggle class on clicking cleanup option container
		$(document).on('click', '.teknotok-cleanup-option', function(e) {
			if (!$(e.target).is('input[type="radio"]')) {
				$(this).find('input[type="radio"]').prop('checked', true);
			}
			$('.teknotok-cleanup-option').removeClass('selected');
			$(this).addClass('selected');
		});

		// Submit choice handler
		$(document).on('click', '#teknotok-deactivate-modal .teknotok-modal-btn-submit', function() {
			var $btn = $(this);
			var deleteData = $('input[name="teknotok_cleanup"]:checked').val();

			$btn.addClass('loading');

			// Send AJAX request to save preference
			$.ajax({
				url: teknotokAitAdmin.ajaxUrl,
				type: 'POST',
				data: {
					action: 'teknotok_ait_set_uninstall_cleanup',
					nonce: teknotokAitAdmin.nonce,
					delete_data: deleteData
				},
				dataType: 'json',
				complete: function() {
					// Proceed to deactivation link regardless of success/error to avoid locking user out
					window.location.href = deactivateUrl;
				}
			});
		});
	}
});
