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;
			var isSetupStart = window.location.search.indexOf('setup=start') !== -1;

		function getEstimatedTranslationTimeLabel(data, pending, processing, total, hasSetupBanner) {
			if (data.paused) {
				return 'Paused';
			}

			if (pending > 0 || processing > 0) {
				var stringPending = parseInt(data.string_pending) || 0;
				var heavyPending = parseInt(data.heavy_pending) || 0;
				var remainingSeconds = (stringPending * 0.1) + (heavyPending * 6.0);
				if (remainingSeconds < 60) {
					return 'Less than a minute';
				}

				var minutes = Math.ceil(remainingSeconds / 60);
				return '~' + minutes + ' ' + (minutes === 1 ? 'minute' : 'minutes');
			}

			if (total === 0 && hasSetupBanner) {
				return 'Calculating...';
			}

			return 'Complete';
		}

		function updateHealthItem(id, item) {
			if (!item) {
				return;
			}

			var $value = $('#' + id);
			$value.text(item.value || '');
			$value.closest('.teknotok-health-item')
				.toggleClass('is-ok', !!item.ok)
				.toggleClass('needs-attention', !item.ok);
		}

		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.quota) {
							$('#teknotok-health-quota-title').text(data.quota.title || '');
							$('#teknotok-health-quota-usage').text(data.quota.usage || '');
							$('#teknotok-health-quota-note').text(data.quota.note || '');
							$('#teknotok-health-quota-bar')
								.css('width', (parseInt(data.quota.percent) || 0) + '%')
								.toggleClass('is-exhausted', !!data.quota.is_exhausted);
						}
						if (data.health) {
							updateHealthItem('teknotok-health-license-value', data.health.license);
							updateHealthItem('teknotok-health-languages-value', data.health.languages);
							updateHealthItem('teknotok-health-queue-value', data.health.queue);
							updateHealthItem('teknotok-health-memory-value', data.health.memory);
						}
						var stringPending = parseInt(data.string_pending) || 0;
						var warmupPending = parseInt(data.warmup_pending) || 0;
						var heavyPending = Math.max(0, (parseInt(data.heavy_pending) || 0) - warmupPending);
						$('#queue-breakdown-help').text('Waiting items: ' + stringPending + ' short text items, ' + heavyPending + ' page/content items, ' + warmupPending + ' frontend URL checks.');

						if (data.paused) {
							$('#queue-paused-badge').show();
							$('#queue-paused-message').show();
							$('#teknotok-resume-queue').show();
							if (data.pause_is_limit) {
								$('#queue-resume-help').show();
							} else {
								$('#queue-resume-help').hide();
							}
							$('#teknotok-pause-queue').hide();
							$('#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();
							$('#teknotok-pause-queue').show();
							$('#queue-paused-reason').text('');
						}

						if (data.local_warmup_skipped) {
							$('#queue-local-warmup-reason').text(data.local_warmup_skipped);
							$('#queue-local-warmup-message').show();
						} else {
							$('#queue-local-warmup-message').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 staleLanguageJobs = parseInt(data.stale_language_jobs) || 0;
						var total = pending + processing + completed + failed;
						var estimatedTimeLabel = getEstimatedTranslationTimeLabel(data, pending, processing, total, isSetupStart);
						var $estimatedTimeValue = $('#teknotok-health-estimated-time-value');
						$estimatedTimeValue.text(estimatedTimeLabel);
						$estimatedTimeValue.closest('.teknotok-health-item')
							.toggleClass('is-ok', !data.paused)
							.toggleClass('needs-attention', !!data.paused);

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

						if (staleLanguageJobs > 0) {
							$('#teknotok-cancel-stale-language-jobs').show();
							$('#queue-cancel-stale-help').show();
						} else {
							$('#teknotok-cancel-stale-language-jobs').hide();
							$('#queue-cancel-stale-help').hide();
						}

						if ((pending > 0 || processing > 0) && !data.paused && !data.locked && !isRunningQueue) {
							$('#teknotok-run-queue-btn').show();
						} else {
							$('#teknotok-run-queue-btn').hide();
						}

						if (pending > 0 || processing > 0 || failed > 0) {
							$('#teknotok-cancel-waiting-jobs').show();
							$('#queue-cancel-waiting-help').show();
						} else {
							$('#teknotok-cancel-waiting-jobs').hide();
							$('#queue-cancel-waiting-help').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');
							}
						}

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

						// Dynamically update the log terminal
						if (data.logs && $('#log-terminal').length) {
							var $terminalBody = $('#log-terminal');
							var logLines = data.logs.split('\n');
							var newContentHtml = '';
							
							$.each(logLines, function(index, line) {
								if (!line.trim()) {
									return;
								}
								var className = 'log-line';
								if (line.toLowerCase().indexOf('error') !== -1 || line.toLowerCase().indexOf('exception') !== -1) {
									className += ' log-error';
								} else if (line.toLowerCase().indexOf('warning') !== -1) {
									className += ' log-warning';
								} else if (line.toLowerCase().indexOf('info') !== -1) {
									className += ' log-info';
								}
								
								// Clean and safely escape HTML in log message
								var escapedLine = $('<div>').text(line).html();
								newContentHtml += '<div class="' + className + '">' + escapedLine + '</div>';
							});
							
							if ($terminalBody.html() !== newContentHtml) {
								$terminalBody.html(newContentHtml);
								$terminalBody.scrollTop($terminalBody[0].scrollHeight);
							}
						}
					}
				}
			});
		}

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

			$button.prop('disabled', true).text('Resuming...');
			$('#queue-resume-help').hide();
			$.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 Translation');
					pollQueueStatus();
				}
			});
		});

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

			$button.prop('disabled', true).text('Pausing...');
			$.ajax({
				url: teknotokAitAdmin.ajaxUrl,
				type: 'POST',
				data: {
					action: 'teknotok_ait_pause_queue',
					nonce: teknotokAitAdmin.nonce
				},
				dataType: 'json',
				complete: function() {
					$button.prop('disabled', false).text('Pause Translation');
					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 Items');
					pollQueueStatus();
				}
			});
		});

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

			if (!window.confirm('Cancel unfinished jobs for languages that are no longer selected? Completed saved translations will stay in memory.')) {
				return;
			}

			$button.prop('disabled', true).text('Cancelling...');
			$.ajax({
				url: teknotokAitAdmin.ajaxUrl,
				type: 'POST',
				data: {
					action: 'teknotok_ait_cancel_stale_language_jobs',
					nonce: teknotokAitAdmin.nonce
				},
				dataType: 'json',
				complete: function() {
					$button.prop('disabled', false).text('Cancel Removed Languages');
					pollQueueStatus();
				}
			});
		});

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

			isRunningQueue = true;
			$button.prop('disabled', true).text('Continuing...');
			$.ajax({
				url: teknotokAitAdmin.ajaxUrl,
				type: 'POST',
				data: {
					action: 'teknotok_ait_run_queue_admin',
					nonce: teknotokAitAdmin.nonce
				},
				dataType: 'json',
				success: function(response) {
					$button.text('Continue Now');
				},
				error: function() {
					$button.text('Error occurred');
				},
				complete: function() {
					isRunningQueue = false;
					$button.prop('disabled', false);
					pollQueueStatus();
				}
			});
		});

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

			if (!window.confirm('Reset all waiting, processing, and failed translation jobs? Completed saved translations will stay in memory.')) {
				return;
			}

			$button.prop('disabled', true).text('Resetting...');
			$.ajax({
				url: teknotokAitAdmin.ajaxUrl,
				type: 'POST',
				data: {
					action: 'teknotok_ait_cancel_waiting_jobs',
					nonce: teknotokAitAdmin.nonce
				},
				dataType: 'json',
				complete: function() {
					$button.prop('disabled', false).text('Reset Waiting Jobs');
					pollQueueStatus();
				}
			});
		});

		// Poll every 5 seconds. Queue execution starts from Settings or the Continue Now button.
		pollInterval = setInterval(pollQueueStatus, 5000);
	}

	function updateLanguagePickerState($picker) {
		var selectedLabels = [];
		var selectedCount = 0;

		$picker.find('.teknotok-lang-checkbox-label input[type="checkbox"]').each(function() {
			var $input = $(this);
			var checked = $input.prop('checked');
			$input.closest('.teknotok-lang-checkbox-label').toggleClass('is-selected', checked);

			if (checked) {
				selectedCount++;
				selectedLabels.push({
					code: $input.val(),
					name: $input.data('language-name') || $.trim($input.closest('.teknotok-lang-checkbox-label').text())
				});
			}
		});

		$picker.find('.teknotok-language-total-count').text(selectedCount + ' selected');
		var $selected = $picker.find('.teknotok-selected-languages').empty();
		if (!selectedLabels.length) {
			$selected.append($('<span class="teknotok-selected-empty">No target language selected yet.</span>'));
		} else {
			$.each(selectedLabels, function(index, language) {
				$selected.append($('<span class="teknotok-selected-language"></span>').attr('data-language-code', language.code).text(language.name));
			});
		}

		$picker.find('.teknotok-language-group').each(function() {
			var $group = $(this);
			var selected = $group.find('input[type="checkbox"]:checked').length;
			var total = $group.find('input[type="checkbox"]').length;
			$group.find('.teknotok-language-group-count').text(selected + ' selected / ' + total);
		});

	}

	function getLanguagePickerLimit($picker) {
		var max = parseInt($picker.data('max-target-languages'), 10);

		if (max > 0) {
			return max;
		}

		return $picker.data('is-premium') === 1 || $picker.data('is-premium') === '1' ? 15 : 1;
	}

	function showLanguagePickerWarning($picker, selector) {
		$picker.find(selector).stop(true, true).show().delay(5200).fadeOut(200);
	}

	function filterLanguageDrawer($drawer) {
		var query = $.trim($drawer.find('.teknotok-language-search').val()).toLowerCase();
		var visibleCount = 0;

		$drawer.find('.teknotok-lang-checkbox-label').each(function() {
			var $label = $(this);
			var matches = !query || ($label.data('language-name') || '').indexOf(query) !== -1;
			$label.toggleClass('is-filtered-out', !matches);
			if (matches) {
				visibleCount++;
			}
		});

		$drawer.find('.teknotok-language-group').each(function() {
			$(this).toggleClass('is-filtered-out', $(this).find('.teknotok-lang-checkbox-label:not(.is-filtered-out)').length === 0);
		});
		$drawer.find('.teknotok-language-empty-search').toggle(visibleCount === 0);
	}

	function openLanguageDrawer($picker) {
		var $drawer = $picker.find('.teknotok-language-drawer');
		$drawer.addClass('is-open').attr('aria-hidden', 'false');
		$('body').addClass('teknotok-language-drawer-open');
		$drawer.find('.teknotok-language-search').val('');
		filterLanguageDrawer($drawer);
		setTimeout(function() {
			$drawer.find('.teknotok-language-search').trigger('focus');
		}, 50);
	}

	function closeLanguageDrawer($drawer) {
		$drawer.removeClass('is-open').attr('aria-hidden', 'true');
		if (!$('.teknotok-language-drawer.is-open').length) {
			$('body').removeClass('teknotok-language-drawer-open');
		}
	}

	$(document).on('click', '.teknotok-open-language-drawer', function(e) {
		e.preventDefault();
		var $picker = $(this).closest('.teknotok-language-picker');
		openLanguageDrawer($picker);
	});

	$(document).on('click', '.teknotok-close-language-drawer, .teknotok-language-drawer-backdrop', function(e) {
		e.preventDefault();
		closeLanguageDrawer($(this).closest('.teknotok-language-drawer'));
	});

	$(document).on('input', '.teknotok-language-search', function() {
		var $drawer = $(this).closest('.teknotok-language-drawer');
		filterLanguageDrawer($drawer);
	});

	$(document).on('keydown', function(e) {
		if (e.key === 'Escape') {
			closeLanguageDrawer($('.teknotok-language-drawer.is-open'));
		}
	});

	// Toggle checkbox label class for languages grid selection styling
	$(document).on('change', '.teknotok-lang-checkbox-label input[type="checkbox"]', function() {
		var $group = $(this).closest('.teknotok-language-group');
		var $picker = $(this).closest('.teknotok-language-picker');
		var isPremium = $picker.data('is-premium') === 1 || $picker.data('is-premium') === '1';
		var maxTargetLanguages = getLanguagePickerLimit($picker);

		if (!isPremium && this.checked) {
			$picker.find('.teknotok-lang-checkbox-label input[type="checkbox"]').not(this).prop('checked', false);
			showLanguagePickerWarning($picker, '.teknotok-free-language-warning');
		}

		if (isPremium && this.checked && maxTargetLanguages > 0 && $picker.find('.teknotok-lang-checkbox-label input[type="checkbox"]:checked').length > maxTargetLanguages) {
			this.checked = false;
			showLanguagePickerWarning($picker, '.teknotok-max-language-warning');
		}

		if ($picker.length) {
			updateLanguagePickerState($picker);
		} else if ($group.length) {
			var selected = $group.find('input[type="checkbox"]:checked').length;
			var total = $group.find('input[type="checkbox"]').length;
			$group.find('.teknotok-language-group-count').text(selected + ' selected / ' + total);
		}
	});

	$('.teknotok-language-picker').each(function() {
		updateLanguagePickerState($(this));
	});

	function hexToRgba(hex, opacityPercent) {
		var value = (hex || '#ffffff').replace('#', '');
		if (value.length === 3) {
			value = value[0] + value[0] + value[1] + value[1] + value[2] + value[2];
		}
		var opacity = Math.max(0.4, Math.min(1, (parseInt(opacityPercent, 10) || 100) / 100));
		var r = parseInt(value.substring(0, 2), 16) || 255;
		var g = parseInt(value.substring(2, 4), 16) || 255;
		var b = parseInt(value.substring(4, 6), 16) || 255;

		return 'rgba(' + r + ',' + g + ',' + b + ',' + opacity.toFixed(2) + ')';
	}

	function widgetDesignerControl($designer, key) {
		return $designer.find('[data-teknotok-widget-control="' + key + '"]');
	}

	function updateWidgetPreview($designer) {
		var preset = widgetDesignerControl($designer, 'preset').val() || 'glass';
		var showFlags = widgetDesignerControl($designer, 'show_flags').prop('checked');
		var opacity = widgetDesignerControl($designer, 'opacity').val() || 92;
		var textColor = widgetDesignerControl($designer, 'text_color').val() || '#1e293b';
		var bgColor = widgetDesignerControl($designer, 'background_color').val() || '#ffffff';
		var borderColor = widgetDesignerControl($designer, 'border_color').val() || '#93c5fd';
		var accentColor = widgetDesignerControl($designer, 'accent_color').val() || '#2563eb';
		var shape = widgetDesignerControl($designer, 'shape').val() || 'pill';
		var borderWidth = Math.max(0, Math.min(4, parseInt(widgetDesignerControl($designer, 'border_width').val(), 10) || 0));
		var radius = shape === 'square' ? '4px' : (shape === 'rounded' ? '12px' : '999px');
		var $preview = $designer.find('.teknotok-ait-switcher-container');

		$preview
			.removeClass('teknotok-ait-no-flags teknotok-ait-design-glass teknotok-ait-design-water teknotok-ait-design-clean teknotok-ait-design-dark teknotok-ait-shape-pill teknotok-ait-shape-rounded teknotok-ait-shape-square')
			.addClass('teknotok-ait-design-' + preset + ' teknotok-ait-shape-' + shape)
			.toggleClass('teknotok-ait-no-flags', !showFlags)
			.css({
				'--teknotok-switcher-bg': hexToRgba(bgColor, opacity),
				'--teknotok-switcher-bg-solid': bgColor,
				'--teknotok-switcher-text': textColor,
				'--teknotok-switcher-border': borderColor,
				'--teknotok-switcher-accent': accentColor,
				'--teknotok-switcher-radius': radius,
				'--teknotok-switcher-border-width': borderWidth + 'px'
			});
	}

	function applyWidgetPreset($designer) {
		var presets = $designer.data('presets') || {};
		var preset = widgetDesignerControl($designer, 'preset').val();
		var presetData = presets[preset];

		if (!presetData) {
			return;
		}

		widgetDesignerControl($designer, 'show_flags').prop('checked', presetData.show_flags === '1');
		widgetDesignerControl($designer, 'opacity').val(presetData.opacity);
		widgetDesignerControl($designer, 'text_color').val(presetData.text_color);
		widgetDesignerControl($designer, 'background_color').val(presetData.background_color);
		widgetDesignerControl($designer, 'border_color').val(presetData.border_color);
		widgetDesignerControl($designer, 'accent_color').val(presetData.accent_color);
		widgetDesignerControl($designer, 'shape').val(presetData.shape);
		widgetDesignerControl($designer, 'border_width').val(presetData.border_width);
	}

	$('.teknotok-widget-designer').each(function() {
		updateWidgetPreview($(this));
	});

	$(document).on('change', '[data-teknotok-widget-control="preset"]', function() {
		var $designer = $(this).closest('.teknotok-widget-designer');
		applyWidgetPreset($designer);
		updateWidgetPreview($designer);
	});

	$(document).on('input change', '.teknotok-widget-designer [data-teknotok-widget-control]', function() {
		var $control = $(this);
		if ($control.data('teknotok-widget-control') === 'preset') {
			return;
		}
		updateWidgetPreview($control.closest('.teknotok-widget-designer'));
	});

	$(document).on('submit', '.teknotok-ait-container form:first', function(e) {
		var submitter = e.originalEvent && e.originalEvent.submitter ? e.originalEvent.submitter : document.activeElement;
		var isStartButton = submitter && $(submitter).attr('name') === 'teknotok_ait_start_translation';
		if (isStartButton && $(this).find('.teknotok-language-picker input[type="checkbox"]:checked').length === 0) {
			e.preventDefault();
			alert('Select at least one target language before starting translation.');
		}
	});

	$(document).on('click', 'button[name="teknotok_ait_save_settings"]', function(e) {
		var $button = $(this);
		var $form = $button.closest('form');
		var showSaveNotice = function(type, message) {
			$('<div/>', {
				'class': 'notice notice-' + type + ' teknotok-save-settings-notice'
			}).append(
				$('<p/>').text(message)
			).insertBefore($button.closest('.teknotok-start-actions'));
		};

		if (!$form.length || $button.prop('disabled')) {
			return;
		}

		e.preventDefault();
		$button.prop('disabled', true).addClass('is-busy');
		$form.find('.teknotok-save-settings-notice').remove();

		$.post(teknotokAitAdmin.ajaxUrl, $form.serialize() + '&action=teknotok_ait_save_settings')
			.done(function(response) {
				var message = response && response.data && response.data.message ? response.data.message : 'Settings saved successfully.';
				showSaveNotice('success', message);
			})
			.fail(function(xhr) {
				var message = xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message ? xhr.responseJSON.data.message : 'Settings could not be saved.';
				showSaveNotice('error', message);
			})
			.always(function() {
				$button.prop('disabled', false).removeClass('is-busy');
			});
	});

	// 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/teknotok-ai-translator.php"] .deactivate a, #deactivate-teknotok-ai-translator', 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</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. 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;
				}
			});
		});
	}

	// Toggle OpenAI credentials visibility based on selected provider
	$(document).on('change', '#api_provider', function() {
		if ($(this).val() === 'openai') {
			$('.openai-credentials-row').show();
		} else {
			$('.openai-credentials-row').hide();
		}
	});

	// Copy system diagnostics report to clipboard
	$(document).on('click', '#teknotok-copy-report', function(e) {
		e.preventDefault();
		var $btn = $(this);
		var $text = $('#teknotok-copy-report-text');
		
		if ($btn.prop('disabled')) {
			return;
		}
		
		$btn.prop('disabled', true);
		var originalText = $text.text();
		$text.text('Compiling...');
		
		$.ajax({
			url: teknotokAitAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'teknotok_ait_copy_system_report',
				nonce: teknotokAitAdmin.nonce
			},
			dataType: 'json',
			success: function(response) {
				if (response.success && response.data) {
					var reportText = response.data;
					
					// Use Clipboard API to copy
					if (navigator.clipboard && window.isSecureContext) {
						navigator.clipboard.writeText(reportText).then(function() {
							showSuccess();
						}, function() {
							fallbackCopy(reportText);
						});
					} else {
						fallbackCopy(reportText);
					}
				} else {
					$text.text('Error compiling');
					setTimeout(resetButton, 2000);
				}
			},
			error: function() {
				$text.text('Request failed');
				setTimeout(resetButton, 2000);
			}
		});

		function showSuccess() {
			$text.text('Report Copied!');
			$btn.removeClass('button-secondary').addClass('button-primary');
			setTimeout(function() {
				$btn.removeClass('button-primary').addClass('button-secondary');
				resetButton();
			}, 2000);
		}

		function fallbackCopy(text) {
			var $temp = $('<textarea>');
			$('body').append($temp);
			$temp.val(text).select();
			try {
				document.execCommand('copy');
				showSuccess();
			} catch (err) {
				$text.text('Copy failed');
				setTimeout(resetButton, 2000);
			}
			$temp.remove();
		}

		function resetButton() {
			$text.text(originalText);
			$btn.prop('disabled', false);
		}
	});
});
