(function ($) {
	'use strict';

	const providerSelector = '.mail-doctor-onboarding__provider input[type="radio"]';

	function renderTestResults(data, $container) {
		if (!data || !data.badges) {
			$container.empty().append($('<p/>').text('Connection test failed.'));
			return;
		}

		const badges = $('<div/>');
		$.each(data.badges, (key, value) => {
			const $badge = $('<span/>')
				.addClass('mail-doctor-badge')
				.toggleClass('is-ok', Boolean(value))
				.toggleClass('is-fail', key === 'sent' && !value)
				.toggleClass('is-warn', key !== 'sent' && !value)
				.text(key.toUpperCase());
			badges.append($badge);
		});

		const $message = $('<p/>').text(data.message || '');
		const $details = $('<div/>');

		if (Array.isArray(data.details) && data.details.length) {
			const $list = $('<ul/>').addClass('mail-doctor-inline-list');
			data.details.forEach((item) => {
				if (item) {
					$list.append($('<li/>').text(item));
				}
			});
			if ($list.children().length) {
				$details.append($list);
			}
		}

		if (Array.isArray(data.debug) && data.debug.length) {
			const $debug = $('<details/>').addClass('mail-doctor-debug');
			$debug.append($('<summary/>').text('SMTP Debug'));
			$debug.append($('<pre/>').addClass('mail-doctor-debug-log').text(data.debug.join('\n')));
			$details.append($debug);
		}

		$container.empty().append(badges, $message);
		if ($details.children().length) {
			$container.append($details);
		}
	}

	function testConnection($button) {
		const transport = $('#omd-onboarding-transport').val();

		const payload = {
			action: 'mail_doctor_test_connection',
			_wpnonce: MailDoctorOnboarding.connectionNonce,
			provider: $('#omd-onboarding-provider').val() || 'default',
			transport,
			host: $('#omd-onboarding-smtp-host').val(),
			port: $('#omd-onboarding-smtp-port').val(),
			encryption: $('select[name="smtp_encryption"]').val(),
			username: $('#omd-onboarding-username').val(),
			password: $('#omd-onboarding-password').val(),
			from_email: $('#omd-onboarding-from-email').val(),
			from_name: $('#omd-onboarding-from-name').val(),
			mailgun_api_key: $('#omd-onboarding-mailgun-key').val(),
			mailgun_api_domain: $('#omd-onboarding-mailgun-domain').val(),
			mailgun_api_endpoint: $('#omd-onboarding-mailgun-endpoint').val(),
			sendgrid_api_key: $('#omd-onboarding-sendgrid-key').val(),
			postmark_api_token: $('#omd-onboarding-postmark-token').val(),
			sparkpost_api_key: $('#omd-onboarding-sparkpost-key').val(),
			sparkpost_api_endpoint: $('#omd-onboarding-sparkpost-endpoint').val(),
			ses_api_key: $('#omd-onboarding-ses-key').val(),
			ses_api_secret: $('#omd-onboarding-ses-secret').val(),
			ses_api_session_token: $('#omd-onboarding-ses-token').val(),
			ses_api_region: $('#omd-onboarding-ses-region').val(),
			generic_api_endpoint: $('#omd-onboarding-generic-endpoint').val(),
			generic_api_method: $('#omd-onboarding-generic-method').val(),
			generic_api_auth_token: $('#omd-onboarding-generic-token').val(),
		};

		const $container = $('.mail-doctor-test-results');
		$button.prop('disabled', true);
		$container.html($('<p/>').text('Testing connection…'));

		$.post(MailDoctorOnboarding.ajaxUrl, payload)
			.done((response) => {
				if (response && response.success) {
					renderTestResults(response.data, $container);
				} else {
					$container.html($('<p/>').text('Connection test failed.'));
				}
			})
			.fail(() => {
				$container.html($('<p/>').text('Connection test failed.'));
			})
			.always(() => {
				$button.prop('disabled', false);
			});
	}

	$(document).on('change', providerSelector, function () {
		$(providerSelector)
			.closest('.mail-doctor-onboarding__provider')
			.toggleClass('is-selected', false);

		$(this)
			.closest('.mail-doctor-onboarding__provider')
			.toggleClass('is-selected', true);

		$('#omd-onboarding-provider').val($(this).val());
	});

	$(document).on('click', '.mail-doctor-test-connection', function (event) {
		event.preventDefault();
		testConnection($(this));
	});

	function toggleTransport() {
		const transport = $('#omd-onboarding-transport').val();
		const map = {
			smtp: ['smtp'],
			mailgun_api: ['mailgun'],
			sendgrid_api: ['sendgrid'],
			postmark_api: ['postmark'],
			sparkpost_api: ['sparkpost'],
			ses_api: ['ses'],
			generic_http: ['generic'],
		};
		const active = map[transport] || map.smtp;

		const $sections = $('.mail-doctor-transport-field');
		$sections
			.hide()
			.find('input, select, textarea')
			.prop('disabled', true)
			.prop('required', false);

		active.forEach((slug) => {
			$(`.mail-doctor-transport-${slug}`)
				.show()
				.find('input, select, textarea')
				.prop('disabled', false)
				.prop('required', false);
		});
	}

	$(document).on('change', '#omd-onboarding-transport', toggleTransport);
	$(function () {
		toggleTransport();
	});

	// If a provider is pre-selected, ensure the visual state is correct.
	$(providerSelector + ':checked').trigger('change');
}(jQuery));
