jQuery(document).ready(function ($) {
	const trigger_btn = $('#trigger-error'),
		email_field = $('#email'),
		spinner = $('#spinner');

	if (email_field.val() !== '') {
		trigger_btn.attr('disabled', false);
	}

	email_field.on('input', function () {
		return trigger_btn.attr('disabled', this.value === '' || !this.checkValidity());
	});

	trigger_btn.on('click', function (e) {
		e.preventDefault();
		e.stopPropagation();

		if (trigger_btn.attr('disabled') === 'disabled') {
			return;
		}

		spinner.toggleClass('d-none d-inline-block');

		trigger_btn.attr('disabled', true);
		$('#trigger-error-alert').remove();

		let data = {
			action: 'enot_trigger_error',
			_ajax_nonce: enotData.ajax_nonce,
			trigger_error_type: 'email',
			email: email_field.val(),
		};

		$.post(window.ajaxurl || enotData.ajax_url, data, function (response) {
			response = JSON.parse(response);
			trigger_btn.attr('disabled', false);
			trigger_btn.after('<div id="trigger-error-alert" class="alert mt-3 p-3">' + response.message + '</div>');
		}).fail(function (response) {
			alert('Error: ' + response.responseText);
			trigger_btn.attr('disabled', false);
		}).always(function () {
			spinner.toggleClass('d-none d-inline-block')
		});
	});
});
