jQuery( document ).ready(
	function ($) {
		$( '#x4email-test-mail-form' ).on(
			'submit',
			function (e) {
				e.preventDefault();

				let form       = $( this );
				let email      = form.find( 'input[name="test_email_to"]' ).val();
				let subject    = form.find( 'input[name="test_email_subject"]' ).val();
				let body       = form.find( 'textarea[name="test_email_body"]' ).val();
				let nonce      = form.find( 'input[name="x4email_test_mail_nonce"]' ).val();
				var loadingDiv = document.getElementById( 'loading' );

				// Basic validation
				if ( ! email || ! subject || ! body) {
					$( '#x4email-response' ).html( '<div class="notice notice-error"><p>Please fill in all required fields.</p></div>' );
					return;
				}

				// Email validation
				if ( ! isValidEmail( email )) {
					$( '#x4email-response' ).html( '<div class="notice notice-error"><p>Please enter a valid email address.</p></div>' );
					return;
				}

				loadingDiv.style.display = 'block';
				$.ajax(
					{
						url: x4email_ajax_obj.ajaxurl,
						method: 'POST',
						data: {
							action: 'x4email_send_test_mail',
							nonce: nonce,
							test_email_to: email,
							test_email_subject: subject,
							test_email_body: body
						},
						success: function (response) {
							loadingDiv.style.display = 'none';
							if (response.success) {
								let message   = response.data.message;
								let debug     = response.data.debug || [];
								let debugHtml = debug.length > 0 ? '<div class="debug-info"><pre>' + debug.join( '\n' ) + '</pre></div>' : '';
								$( '#x4email-response' ).html( '<div class="notice notice-success"><p>' + message + '</p>' + debugHtml + '</div>' );
							} else {
								let message   = response.data.message;
								let debug     = response.data.debug || [];
								let error     = response.data.error || '';
								let debugHtml = debug.length > 0 ? '<div class="debug-info"><pre>' + debug.join( '\n' ) + '</pre></div>' : '';
								let errorHtml = error ? '<div class="error-info"><pre>' + error + '</pre></div>' : '';
								$( '#x4email-response' ).html( '<div class="notice notice-error"><p>' + message + '</p>' + debugHtml + errorHtml + '</div>' );
							}
						},
						error: function (xhr, status, error) {
							loadingDiv.style.display = 'none';
							let errorMessage         = 'AJAX request failed.';
							if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
								errorMessage = xhr.responseJSON.data.message;
							}
							$( '#x4email-response' ).html( '<div class="notice notice-error"><p>' + errorMessage + '</p></div>' );
						}
					}
				);
			}
		);

		// Email validation function
		function isValidEmail(email) {
			var re = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
			return re.test( email );
		}
	}
);
