(function($) {
	'use strict';

	var config = window.seovaultseo_legacy_settings || {};
	var i18n = config.i18n || {};

	function setStatus($element, text, state) {
		$element.text(text || '').css('color', 'error' === state ? '#d63638' : ('pending' === state ? '#2271b1' : '#00a32a'));
	}

	function appendLog($log, text) {
		$log.append($('<div>').text(text));
		if ($log[0]) {
			$log.scrollTop($log[0].scrollHeight);
		}
	}

	$(window).on('load', function() {
		var $legacyRoot = $('.seovaultseo-legacy-settings');
		var $legacyTabs = $legacyRoot.find('.nav-tab:not([data-seovaultseo-server-tab])');
		$legacyTabs.on('click', function(event) {
			event.preventDefault();
			$legacyTabs.removeClass('nav-tab-active');
			$(this).addClass('nav-tab-active');
			$legacyRoot.find('.seovault-ai-tab-content').hide();
			$($(this).attr('href')).show();
		});

		$('#seovaultseo-indexnow-submit-btn').on('click', function(event) {
			event.preventDefault();
			var $button = $(this);
			var $urls = $('#seovaultseo-indexnow-urls');
			var $result = $('#seovaultseo-indexnow-submit-result');
			if (!$urls.val().trim()) {
				setStatus($result, i18n.enter_url, 'error');
				return;
			}
			$button.prop('disabled', true);
			setStatus($result, i18n.submitting, 'pending');
			$.post(config.ajax_url, {
				action: 'seovaultseo_indexnow_submit',
				nonce: config.indexnow_nonce,
				urls: $urls.val()
			}).done(function(response) {
				$button.prop('disabled', false);
				if (response.success) {
					setStatus($result, response.data.message, 'success');
					$urls.val('');
				} else {
					setStatus($result, (response.data && response.data.message) || i18n.submission_failed, 'error');
				}
			}).fail(function() {
				$button.prop('disabled', false);
				setStatus($result, i18n.submission_failed, 'error');
			});
		});

		$('#seovaultseo-indexnow-clear-log-btn').on('click', function(event) {
			event.preventDefault();
			var $button = $(this).prop('disabled', true);
			$.post(config.ajax_url, {
				action: 'seovaultseo_indexnow_clear_log',
				nonce: config.indexnow_nonce
			}).done(function(response) {
				if (response.success) {
					window.location.reload();
				} else {
					$button.prop('disabled', false);
				}
			}).fail(function() { $button.prop('disabled', false); });
		});

		$('#seovault-import-btn').on('click', function(event) {
			event.preventDefault();
			if (!config.site_key) {
				window.alert(i18n.site_key_missing);
				return;
			}
			var $button = $(this).prop('disabled', true);
			var $progress = $('#seovault-import-progress').show();
			var $log = $('#seovault-import-log').empty();
			var overwrite = $('#seovault_import_overwrite').is(':checked') ? 1 : 0;
			var offset = 0;
			var imported = 0;
			var skipped = 0;

			function importBatch() {
				$.ajax({
					url: config.import_url,
					method: 'POST',
					headers: {'X-Site-Key': config.site_key, 'Content-Type': 'application/json'},
					data: JSON.stringify({overwrite: overwrite, offset: offset, limit: 50})
				}).done(function(response) {
					if (!response.success) {
						appendLog($log, 'Error: ' + (response.message || 'Import failed.'));
						$button.prop('disabled', false);
						return;
					}
					imported += response.imported;
					skipped += response.skipped;
					appendLog($log, 'Batch processed: ' + response.total + ' posts. Imported: ' + response.imported + ', Skipped: ' + response.skipped);
					if (response.has_more) {
						offset = response.offset;
						window.setTimeout(importBatch, 500);
					} else {
						appendLog($log, '=== Import Complete ===');
						appendLog($log, 'Total Imported: ' + imported + ' | Total Skipped: ' + skipped);
						$button.prop('disabled', false);
					}
				}).fail(function(xhr, status, error) {
					appendLog($log, 'Error: ' + error);
					$button.prop('disabled', false);
				});
			}

			void $progress;
			importBatch();
		});

		var scanTotal = 0;
		$('#seovault-thirdparty-block-scan-btn').on('click', function(event) {
			event.preventDefault();
			var $button = $(this).prop('disabled', true);
			var $summary = $('#seovault-thirdparty-block-summary').hide().empty();
			var $convert = $('#seovault-thirdparty-block-convert-btn').prop('disabled', true);
			$.post(config.ajax_url, {
				action: 'seovaultseo_thirdparty_block_scan',
				nonce: config.thirdparty_nonce
			}).done(function(response) {
				$button.prop('disabled', false);
				if (!response.success || !response.data) {
					$summary.show().text(i18n.scan_failed).addClass('notice notice-error inline');
					return;
				}
				var data = response.data;
				scanTotal = parseInt(data.post_total, 10) || 0;
				var lines = [
					i18n.posts_found + ' ' + scanTotal,
					i18n.convertible + ' ' + (data.convertible_count || 0),
					i18n.blocked + ' ' + (data.blocked_count || 0)
				];
				if (data.by_source) {
					var sources = [];
					$.each(data.by_source, function(name, count) { sources.push(name + ': ' + count); });
					if (sources.length) {
						lines.push(i18n.by_source + ' ' + sources.join(', '));
					}
				}
				$summary.show().text(lines.join('\n')).addClass('notice notice-info inline');
				$convert.prop('disabled', scanTotal <= 0);
			}).fail(function() {
				$button.prop('disabled', false);
				$summary.show().text(i18n.scan_request_failed).addClass('notice notice-error inline');
			});
		});

		$('#seovault-thirdparty-block-convert-btn').on('click', function(event) {
			event.preventDefault();
			if (scanTotal <= 0 || !window.confirm(i18n.confirm_convert)) {
				return;
			}
			var $button = $(this).prop('disabled', true);
			var $scan = $('#seovault-thirdparty-block-scan-btn').prop('disabled', true);
			var $log = $('#seovault-thirdparty-block-log').empty();
			$('#seovault-thirdparty-block-progress').show();
			var totals = {posts: 0, blocks: 0, failed: 0, started: scanTotal};

			function convertBatch() {
				$.post(config.ajax_url, {
					action: 'seovaultseo_thirdparty_block_convert_batch',
					nonce: config.thirdparty_nonce,
					confirm: 1,
					limit: 10
				}).done(function(response) {
					if (!response.success || !response.data) {
						appendLog($log, (response.data && response.data.message) || i18n.batch_failed);
						$button.prop('disabled', false);
						$scan.prop('disabled', false);
						return;
					}
					var data = response.data;
					totals.posts += data.converted_posts || 0;
					totals.blocks += data.converted_blocks || 0;
					totals.failed += data.failed || 0;
					appendLog($log, 'Batch: converted ' + (data.converted_posts || 0) + ' posts / ' + (data.converted_blocks || 0) + ' blocks. Remaining: ' + (data.remaining || 0));
					if (data.has_more) {
						window.setTimeout(convertBatch, 300);
					} else {
						appendLog($log, '=== Conversion Complete ===');
						appendLog($log, 'Posts converted: ' + totals.posts + ' | Blocks: ' + totals.blocks + ' | Failed: ' + totals.failed + ' | Started with: ' + totals.started);
						scanTotal = data.remaining || 0;
						$button.prop('disabled', scanTotal > 0);
						$scan.prop('disabled', false);
					}
				}).fail(function(xhr, status, error) {
					appendLog($log, 'AJAX Error: ' + error);
					$button.prop('disabled', false);
					$scan.prop('disabled', false);
				});
			}

			convertBatch();
		});
	});

	document.addEventListener('click', function(event) {
		var target = event.target.closest('[data-seovaultseo-confirm]');
		if (target && !window.confirm(target.getAttribute('data-seovaultseo-confirm'))) {
			event.preventDefault();
		}
		var selectTarget = event.target.closest('.seovaultseo-select-on-click');
		if (selectTarget) {
			selectTarget.select();
		}
	});
}(jQuery));
