(function () {
	'use strict';

	var config = window.wppsLoginAsAdmin || {};

	document.addEventListener('click', function (e) {
		var link = e.target.closest('.wpps-login-as-user-link');
		if (!link) {
			return;
		}

		e.preventDefault();

		var userId = link.dataset.userId;
		var userNonce = link.dataset.nonce;

		if (!userId || !userNonce) {
			return;
		}

		link.classList.add('is-busy');
		var originalText = link.textContent;
		link.textContent = config.loggingInLabel || 'Logging in...';

		var formData = new FormData();
		formData.append('action', 'wp_powersuite_login_as_user');
		formData.append('nonce', config.ajaxNonce || '');
		formData.append('user_id', userId);
		formData.append('user_nonce', userNonce);

		fetch(config.ajaxUrl || ajaxurl, {
			method: 'POST',
			body: formData,
			credentials: 'same-origin',
		})
			.then(function (response) {
				return response.json();
			})
			.then(function (data) {
				if (data.success) {
					if (data.data && data.data.redirect_url) {
						window.location.href = data.data.redirect_url;
					} else {
						window.location.reload();
					}
					return;
				}

				window.alert((data.data && data.data.message) || config.errorMessage || 'An error occurred.');
				link.classList.remove('is-busy');
				link.textContent = originalText;
			})
			.catch(function () {
				window.alert(config.errorRetryMessage || 'An error occurred. Please try again.');
				link.classList.remove('is-busy');
				link.textContent = originalText;
			});
	});
})();
