(function ($) {
	'use strict';

	$(document).ready(function () {
		$(document).on('click', '.js-plugin-required-install', function (e) {
			e.preventDefault();

			const $button = $(this);
			const action = $button.data('action');

			if ($button.hasClass('is-loading')) {
				return;
			}

			$button.addClass('is-loading');
			$button.append(`<img src="${kubelioAdminParams.images_url}/spiner-light.svg" class="rta-spinner" alt="">`);

			$.ajax({
				url: kubelioAdminParams.ajax_url,
				type: 'POST',
				data: {
					action: action,
					nonce: kubelioAdminParams.nonce,
				},
				success: function (response) {
					if (response.success) {
						if (response.data.redirect) {
							window.location.href = response.data.redirect;
						} else {
							window.location.reload();
						}
					} else {
						alert(response.data || 'Something went wrong');
						$button.removeClass('is-loading');
						$button.find('.rta-spinner').remove();
					}
				},
				error: function () {
					alert('AJAX error');
					$button.removeClass('is-loading');
					$button.find('.rta-spinner').remove();
				}
			});
		});
	});

})(jQuery);
