(function () {
	'use strict';

	var config = window.wppsLoginAsSwitchBack || {};

	function runSwitchBack(trigger) {
		var nonce = config.ajaxNonce || window.wppsLoginAsNonce;
		if (!nonce) {
			return;
		}

		trigger.classList.add('is-busy');

		var fd = new FormData();
		fd.append('action', 'wp_powersuite_switch_back_user');
		fd.append('nonce', nonce);

		fetch(config.ajaxUrl || (typeof ajaxurl !== 'undefined' ? ajaxurl : ''), {
			method: 'POST',
			body: fd,
			credentials: 'same-origin',
		})
			.then(function (r) {
				return r.json();
			})
			.then(function (data) {
				if (data.success && data.data && data.data.redirect_url) {
					window.location.href = data.data.redirect_url;
				} else if (data.success) {
					window.location.reload();
				} else {
					window.alert((data.data && data.data.message) || config.errorMessage || 'An error occurred.');
					trigger.classList.remove('is-busy');
				}
			})
			.catch(function () {
				window.alert(config.errorRetryMessage || 'An error occurred. Please try again.');
				trigger.classList.remove('is-busy');
			});
	}

	document.addEventListener('click', function (e) {
		var trigger = e.target.closest('.wpps-switch-back-trigger');
		if (!trigger) {
			return;
		}
		e.preventDefault();
		runSwitchBack(trigger);
	});
})();
