(function ($) {
	'use strict';

	var bbcsMalwarePollInterval = null;
	var bbcsMalwarePollMs = 2000;
	var bbcsMalwarePollMaxRetries = 5;
	var bbcsMalwarePollRetries = 0;
	var bbcsMalwareReloadScheduled = false;

	function bbcsMalwareStartPolling() {
		var bar = $('#bbcs-malware-progress-bar');
		if (!bar.length) return;

		bbcsMalwarePollRetries = 0;
		bbcsMalwareStopPolling();
		bbcsMalwarePollInterval = setInterval(bbcsMalwareFetchProgress, bbcsMalwarePollMs);
		bbcsMalwareFetchProgress();
	}

	function bbcsMalwareStopPolling() {
		if (bbcsMalwarePollInterval) {
			clearInterval(bbcsMalwarePollInterval);
			bbcsMalwarePollInterval = null;
		}
	}

	function bbcsMalwareReloadResults() {
		if (bbcsMalwareReloadScheduled) return;
		bbcsMalwareReloadScheduled = true;
		window.bbcsBypassUnsavedPrompt = true;

		setTimeout(function () {
			var url = new URL(window.location.href);
			url.searchParams.delete('bbcs_malware_started');
			url.searchParams.delete('bbcs_malware_disabled');
			url.searchParams.delete('bbcs_malware_cleared');
			url.searchParams.delete('bbcs_malware_scanned');
			url.hash = 'addon-bbcs-malware';
			window.bbcsBypassUnsavedPrompt = true;
			window.location.replace(url.toString());
		}, 800);
	}

	function bbcsMalwareInitTables() {
		if (!$.fn.DataTable) return;

		$('.bbcs-malware-results-table').each(function () {
			if ($.fn.DataTable.isDataTable(this)) return;

			$(this).DataTable({
				paging: false,
				searching: false,
				info: false,
				order: [],
				autoWidth: false
			});
		});
	}

	function bbcsMalwareFetchProgress() {
		if (typeof botblockerData === 'undefined' || !botblockerData.ajaxurl) {
			bbcsMalwareStopPolling();
			return;
		}

		$.ajax({
			url: botblockerData.ajaxurl,
			method: 'POST',
			dataType: 'json',
			data: {
				action: 'bbcs_malware_progress',
				nonce: botblockerData.nonce
			},
			success: function (response) {
				if (!response || !response.success || !response.data) {
					bbcsMalwarePollRetries++;
					if (bbcsMalwarePollRetries >= bbcsMalwarePollMaxRetries) {
						bbcsMalwareStopPolling();
					}
					return;
				}

				bbcsMalwarePollRetries = 0;
				bbcsMalwareRenderProgress(response.data);

				if (!response.data.running) {
					bbcsMalwareStopPolling();
				}
			},
			error: function () {
				bbcsMalwarePollRetries++;
				if (bbcsMalwarePollRetries >= bbcsMalwarePollMaxRetries) {
					bbcsMalwareStopPolling();
				}
			}
		});
	}

	function bbcsMalwareRenderProgress(data) {
		var container = $('#bbcs-malware-progress-container');
		if (!container.length) return;

		if (data.running) {
			container.show();
		}

		var bar = $('#bbcs-malware-progress-bar');
		var text = $('#bbcs-malware-progress-text');
		var detail = $('#bbcs-malware-progress-detail');
		var fileLabel = $('#bbcs-malware-progress-current-file');

		var pct = Math.min(100, Math.max(0, parseFloat(data.progress) || 0));
		bar.css('width', pct + '%').attr('aria-valuenow', Math.round(pct));
		text.text(Math.round(pct) + '%');

		var detailParts = [];
		if (data.files_scanned || data.files_queued) {
			detailParts.push((data.files_scanned || 0) + ' / ' + (data.files_queued || 0) + ' files');
		}
		if (data.findings) {
			detailParts.push(data.findings + ' finding' + (data.findings !== 1 ? 's' : ''));
		}
		detail.text(detailParts.join(' | '));

		if (fileLabel.length && data.current_file) {
			fileLabel.text(data.current_file).show();
		} else if (fileLabel.length) {
			fileLabel.hide();
		}

		if (!data.running && (data.status === 'completed' || pct >= 100)) {
			detail.text('Scan completed. Refreshing results...');
			bbcsMalwareReloadResults();
		}
	}

	$(function () {
		$(document).on('click', '[data-bbcs-malware-start]', function () {
			window.bbcsBypassUnsavedPrompt = true;
			var container = $('#bbcs-malware-progress-container');
			if (!container.length) return;

			container.show();
			$('#bbcs-malware-progress-bar').css('width', '0%').attr('aria-valuenow', 0);
			$('#bbcs-malware-progress-text').text('0%');
			$('#bbcs-malware-progress-detail').text('Starting scan...');
			$('#bbcs-malware-progress-current-file').hide();
		});

		$(document).on('click', '[data-bbcs-bypass-dirty]', function () {
			window.bbcsBypassUnsavedPrompt = true;
		});

		var progressContainer = $('#bbcs-malware-progress-container');
		bbcsMalwareInitTables();

		if (progressContainer.length && (progressContainer.data('bbcs-malware-running') === 1 || progressContainer.is(':visible'))) {
			bbcsMalwareStartPolling();
		}
	});
})(jQuery);
