(function ($) {
	'use strict';

	$(function () {
		var $button = $('#devikit-sellsy-test-connection');
		if (!$button.length || typeof devikitSellsySettings === 'undefined') {
			return;
		}

		$button.on('click', function () {
			var clientId = $('#devikit_sellsy_client_id').val() || '';
			var clientSecret = $('#devikit_sellsy_client_secret').val() || '';
			var $result = $('#devikit-sellsy-connection-result');

			if (!clientId && !clientSecret) {
				$result
					.removeClass('is-success')
					.addClass('is-error')
					.text(devikitSellsySettings.i18n.noToken);
				return;
			}

			$button.prop('disabled', true);
			$result
				.removeClass('is-success is-error')
				.text(devikitSellsySettings.i18n.testing);

			$.post(devikitSellsySettings.ajaxUrl, {
				action: 'devikit_sellsy_test_connection',
				nonce: devikitSellsySettings.nonce,
				client_id: clientId,
				client_secret: clientSecret
			})
				.done(function (response) {
					if (response && response.success) {
						var message = response.data && response.data.message
							? response.data.message
							: devikitSellsySettings.i18n.success;
						$result.removeClass('is-error').addClass('is-success').text(message);
					} else {
						var errorMessage = response && response.data && response.data.message
							? response.data.message
							: devikitSellsySettings.i18n.failed;
						$result.removeClass('is-success').addClass('is-error').text(errorMessage);
					}
				})
				.fail(function () {
					$result.removeClass('is-success').addClass('is-error').text(devikitSellsySettings.i18n.failed);
				})
				.always(function () {
					$button.prop('disabled', false);
				});
		});
	});
})(jQuery);
