(function () {
	var cfg = window.neurogenesisThemeOnboardingNotice || {};

	function postAction(noticeAction) {
		if (cfg.debug || !cfg.ajaxUrl || !cfg.nonce) {
			return Promise.resolve();
		}

		var body = new URLSearchParams();
		body.append('action', 'neurogenesis_theme_onboarding_notice');
		body.append('nonce', cfg.nonce);
		body.append('notice_action', noticeAction);

		return fetch(cfg.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
			body: body.toString(),
		}).catch(function () {
			return null;
		});
	}

	function installRecommendedPlugin() {
		if (!cfg.ajaxUrl || !cfg.installNonce) {
			return Promise.reject(new Error((cfg.i18n && cfg.i18n.error) || 'Installation failed.'));
		}

		var body = new FormData();
		body.append('action', 'neurogenesis_theme_install_recommended_plugin');
		body.append('nonce', cfg.installNonce);

		return fetch(cfg.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			body: body,
		})
			.then(function (response) {
				return response.json();
			})
			.then(function (payload) {
				if (!payload || !payload.success) {
					var message =
						payload && payload.data && payload.data.message
							? payload.data.message
							: (cfg.i18n && cfg.i18n.error) || 'Installation failed.';
					throw new Error(message);
				}

				return payload.data || {};
			});
	}

	function setCtaBusy(cta, busy, label) {
		if (!cta) {
			return;
		}

		if (busy) {
			cta.setAttribute('aria-busy', 'true');
			cta.classList.add('is-busy');
			if (label) {
				cta.dataset.originalLabel = cta.textContent;
				cta.textContent = label;
			}
			return;
		}

		cta.removeAttribute('aria-busy');
		cta.classList.remove('is-busy');
		if (cta.dataset.originalLabel) {
			cta.textContent = cta.dataset.originalLabel;
			delete cta.dataset.originalLabel;
		}
	}

	function bindDismiss() {
		var notice = document.querySelector('[data-neurogenesis-theme-onboarding]');

		if (!notice) {
			return;
		}

		notice.addEventListener('click', function (event) {
			var dismiss = event.target.closest('.notice-dismiss');

			if (!dismiss || !notice.contains(dismiss)) {
				return;
			}

			postAction('dismiss');
		});
	}

	function bindCta() {
		var notice = document.querySelector('[data-neurogenesis-theme-onboarding]');
		var cta = notice ? notice.querySelector('[data-onboarding-cta]') : null;

		if (!cta) {
			return;
		}

		cta.addEventListener('click', function (event) {
			var status = cta.getAttribute('data-plugin-status') || 'not_installed';

			// Plugin already active: follow href (dashboard, or plugin-filtered URL).
			if (status === 'active') {
				return;
			}

			event.preventDefault();

			if (cta.getAttribute('aria-busy') === 'true') {
				return;
			}

			var i18n = cfg.i18n || {};
			var busyLabel = status === 'inactive' ? i18n.activating || 'Activating…' : i18n.installing || 'Installing…';

			setCtaBusy(cta, true, busyLabel);

			installRecommendedPlugin()
				.then(function (data) {
					// Prefer post-activation URLs from AJAX (admin.php once the plugin owns the menu).
					window.location.href =
						(data && data.redirect_url) ||
						(data && data.dashboard_url) ||
						cfg.importUrl ||
						cfg.dashboardUrl ||
						cta.getAttribute('href') ||
						'admin.php';
				})
				.catch(function (error) {
					setCtaBusy(cta, false);
					window.alert(error && error.message ? error.message : (i18n.error || 'Installation failed.'));
				});
		});
	}

	function init() {
		bindDismiss();
		bindCta();
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', init);
	} else {
		init();
	}
})();
