/**
 * Busy overlay + estimated progress for long metrix scans (niche research, sync, inspect).
 */
(function (window, document) {
	'use strict';

	var cfg = window.icommSmBusy || {};
	var overlay = null;
	var bar = null;
	var titleEl = null;
	var stepEl = null;
	var pctEl = null;
	var timer = null;
	var stepIndex = 0;
	var currentSteps = [];
	var softPct = 0;

	function ensureDom() {
		if (overlay) {
			return;
		}
		overlay = document.createElement('div');
		overlay.id = 'icomm-sm-busy-overlay';
		overlay.className = 'icomm-sm-busy-overlay';
		overlay.setAttribute('role', 'alertdialog');
		overlay.setAttribute('aria-modal', 'true');
		overlay.setAttribute('aria-live', 'assertive');
		overlay.innerHTML =
			'<div class="icomm-sm-busy-card">' +
			'<div class="icomm-sm-busy-spinner" aria-hidden="true"></div>' +
			'<p class="icomm-sm-busy-title"></p>' +
			'<p class="icomm-sm-busy-step"></p>' +
			'<div class="icomm-sm-busy-track"><div class="icomm-sm-busy-bar"></div></div>' +
			'<p class="icomm-sm-busy-pct"></p>' +
			'<p class="icomm-sm-busy-hint"></p>' +
			'</div>';
		document.body.appendChild(overlay);
		titleEl = overlay.querySelector('.icomm-sm-busy-title');
		stepEl = overlay.querySelector('.icomm-sm-busy-step');
		bar = overlay.querySelector('.icomm-sm-busy-bar');
		pctEl = overlay.querySelector('.icomm-sm-busy-pct');
		var hint = overlay.querySelector('.icomm-sm-busy-hint');
		if (hint) {
			hint.textContent = cfg.hint || '';
		}
	}

	function setVisual(pct, stepText) {
		ensureDom();
		softPct = Math.max(0, Math.min(99, Math.round(pct)));
		if (bar) {
			bar.style.width = softPct + '%';
		}
		if (pctEl) {
			pctEl.textContent = softPct + '%';
		}
		if (stepEl && typeof stepText === 'string' && stepText !== '') {
			stepEl.textContent = stepText;
		}
	}

	function clearTimer() {
		if (timer) {
			window.clearInterval(timer);
			timer = null;
		}
	}

	function startStepCycle(steps, intervalMs) {
		clearTimer();
		currentSteps = Array.isArray(steps) && steps.length ? steps : [{ pct: 30, text: cfg.working || '' }];
		stepIndex = 0;
		var first = currentSteps[0];
		setVisual(first.pct || 10, first.text || '');
		timer = window.setInterval(function () {
			stepIndex = Math.min(stepIndex + 1, currentSteps.length - 1);
			var s = currentSteps[stepIndex];
			var target = s.pct || softPct;
			// Ease toward target without jumping to 100 until finish().
			var next = Math.max(softPct + 2, Math.min(target, softPct + 8));
			if (stepIndex >= currentSteps.length - 1 && next > 92) {
				next = 92;
			}
			setVisual(next, s.text || '');
			if (stepIndex >= currentSteps.length - 1 && softPct >= 92) {
				clearTimer();
			}
		}, intervalMs || 2200);
	}

	function show(options) {
		options = options || {};
		ensureDom();
		document.body.classList.add('icomm-sm-busy-open');
		overlay.classList.add('is-visible');
		if (titleEl) {
			titleEl.textContent = options.title || cfg.defaultTitle || '';
		}
		document.querySelectorAll('form[data-icomm-sm-busy] button, form[data-icomm-sm-busy] input[type="submit"]').forEach(function (el) {
			el.disabled = true;
		});
		startStepCycle(options.steps || cfg.defaultSteps || [], options.intervalMs || 2200);
	}

	function finish(doneText) {
		clearTimer();
		setVisual(100, doneText || cfg.done || '');
	}

	function hide() {
		clearTimer();
		if (overlay) {
			overlay.classList.remove('is-visible');
		}
		document.body.classList.remove('icomm-sm-busy-open');
		document.querySelectorAll('form[data-icomm-sm-busy] button, form[data-icomm-sm-busy] input[type="submit"]').forEach(function (el) {
			el.disabled = false;
		});
	}

	function presets(name) {
		var map = cfg.presets || {};
		return map[name] || null;
	}

	function runFetch(opts) {
		opts = opts || {};
		var preset = presets(opts.preset) || {};
		show({
			title: opts.title || preset.title,
			steps: opts.steps || preset.steps,
			intervalMs: opts.intervalMs || preset.intervalMs,
		});

		var body = opts.body;
		if (!(body instanceof window.FormData) && body && typeof body === 'object') {
			var fd = new window.FormData();
			Object.keys(body).forEach(function (k) {
				fd.append(k, body[k]);
			});
			body = fd;
		}

		return window
			.fetch(opts.url || cfg.ajaxUrl, {
				method: 'POST',
				credentials: 'same-origin',
				body: body,
			})
			.then(function (res) {
				return res.json().then(function (data) {
					return { okHttp: res.ok, data: data };
				});
			})
			.then(function (pack) {
				var data = pack.data || {};
				if (!pack.okHttp || !data || data.success === false) {
					var msg =
						(data && data.data && data.data.message) ||
						(data && data.message) ||
						cfg.error ||
						'Error';
					hide();
					window.alert(msg);
					return data;
				}
				finish(cfg.done || '');
				var redirect = (data.data && data.data.redirect) || data.redirect || opts.redirect;
				window.setTimeout(function () {
					if (redirect) {
						window.location.href = redirect;
					} else {
						window.location.reload();
					}
				}, 350);
				return data;
			})
			.catch(function () {
				hide();
				window.alert(cfg.error || 'Error');
			});
	}

	function bindForms() {
		document.querySelectorAll('form[data-icomm-sm-busy]').forEach(function (form) {
			if (form.getAttribute('data-icomm-sm-busy-bound') === '1') {
				return;
			}
			form.setAttribute('data-icomm-sm-busy-bound', '1');
			form.addEventListener('submit', function (e) {
				var presetName = form.getAttribute('data-icomm-sm-busy') || 'default';
				var preset = presets(presetName) || {};
				var useAjax = form.getAttribute('data-icomm-sm-ajax') === '1';
				if (!useAjax) {
					show({
						title: preset.title,
						steps: preset.steps,
						intervalMs: preset.intervalMs,
					});
					return;
				}
				e.preventDefault();
				var fd = new window.FormData(form);
				var ajaxAction = form.getAttribute('data-icomm-sm-ajax-action') || '';
				if (ajaxAction) {
					fd.set('action', ajaxAction);
				}
				runFetch({
					preset: presetName,
					body: fd,
				});
			});
		});
	}

	function bindLinks() {
		document.querySelectorAll('a.icomm-sm-busy-link').forEach(function (a) {
			if (a.getAttribute('data-icomm-sm-busy-bound') === '1') {
				return;
			}
			a.setAttribute('data-icomm-sm-busy-bound', '1');
			a.addEventListener('click', function (e) {
				if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || a.target === '_blank') {
					return;
				}
				var presetName = a.getAttribute('data-icomm-sm-busy') || 'sync';
				var preset = presets(presetName) || {};
				show({
					title: preset.title,
					steps: preset.steps,
					intervalMs: preset.intervalMs,
				});
			});
		});
	}

	function bindInspectForm() {
		var form = document.getElementById('icomm_sm_inspect_form');
		var action = document.getElementById('icomm_sm_inspect_action');
		if (!form || form.getAttribute('data-icomm-sm-busy-bound') === '1') {
			return;
		}
		form.setAttribute('data-icomm-sm-busy-bound', '1');
		form.addEventListener('submit', function () {
			if (!action || action.value !== 'icomm_sm_inspect_urls') {
				return;
			}
			var preset = presets('inspect') || {};
			show({
				title: preset.title,
				steps: preset.steps,
				intervalMs: preset.intervalMs || 3000,
			});
		});
	}

	document.addEventListener('DOMContentLoaded', function () {
		bindForms();
		bindLinks();
		bindInspectForm();
	});

	window.icommSmBusyUi = {
		show: show,
		hide: hide,
		finish: finish,
		runFetch: runFetch,
	};
})(window, document);
