(function ($) {
	'use strict';

	$(function () {
		var settings = window.wswwSettings || {};
		var ajaxurl = settings.ajaxurl || window.ajaxurl || '';

		var $tabs = $('.nav-tab-wrapper .nav-tab');
		var $tabContents = $('.wsww-tab-content');

		$tabs.on('click', function (e) {
			e.preventDefault();

			var targetId = $(this).data('wsww-tab');
			if (!targetId) {
				return;
			}

			$tabs.removeClass('nav-tab-active');
			$(this).addClass('nav-tab-active');
			$tabContents.hide();
			$('#' + targetId).show();
		});

		$tabContents.hide();
		var requestedTabId = '';

		try {
			var urlParams = new URLSearchParams(window.location.search);
			requestedTabId = urlParams.get('wsww_tab') || '';
		} catch (error) {
			requestedTabId = '';
		}

		if (!requestedTabId && window.location.hash) {
			requestedTabId = window.location.hash.replace('#', '');
		}

		var $activeTab = requestedTabId
			? $tabs.filter('[data-wsww-tab="' + requestedTabId + '"]').first()
			: $tabs.filter('.nav-tab-active').first();

		if (!$activeTab.length) {
			$activeTab = $tabs.filter('.nav-tab-active').first();
		}

		if ($activeTab.length) {
			$tabs.removeClass('nav-tab-active');
			$activeTab.addClass('nav-tab-active');
			var activeId = $activeTab.data('wsww-tab');
			if (activeId) {
				$('#' + activeId).show();
			}
		}

		var $button = $('#wsww-mailchimp-connect-button');
		var $disconnect = $('#wsww-mailchimp-disconnect-button');
		var $status = $('#wsww-mailchimp-connect-status');
		var $apiKey = $('#wsww-mailchimp-api-key');
		var $listSel = $('#wsww-mailchimp-list-id');
		var $enabledField = $('#wsww-mailchimp-enabled');
		var $apiRow = $('#wsww-mailchimp-api-row');
		var $listRow = $('#wsww-mailchimp-list-row');
		var $tagRow = $('#wsww-mailchimp-tag-row');
		var wasConnected = $button.data('connected') === 1 || $button.data('connected') === '1';
		var isConnected = wasConnected;
		var labelConnect = $button.data('label-connect') || 'Connect';
		var labelConnected = $button.data('label-connected') || 'Connected';

		function wswwUpdateMailchimpVisibility() {
			var enabled = $enabledField.is(':checked');
			$apiRow.toggle(enabled);
			var showAdvanced = enabled && isConnected;
			$listRow.toggle(showAdvanced);
			$tagRow.toggle(showAdvanced);
		}

		function wswwSetMailchimpConnectedState(connected) {
			isConnected = !!connected;

			if (isConnected) {
				$button.addClass('wsww-mailchimp-connected').text(labelConnected);
				$disconnect.addClass('wsww-mailchimp-disconnect').show();
			} else {
				$button.removeClass('wsww-mailchimp-connected').text(labelConnect);
				$disconnect.removeClass('wsww-mailchimp-disconnect').hide();
			}

			wswwUpdateMailchimpVisibility();
		}

		wswwSetMailchimpConnectedState(wasConnected);

		if (!$button.length) {
			return;
		}

		$enabledField.on('change', function () {
			wswwUpdateMailchimpVisibility();
		});

		$button.on('click', function (e) {
			e.preventDefault();
			var apiKey = $apiKey.val();

			if (!apiKey) {
				$status.text(settings.msgEnterApiKey || '');
				return;
			}

			$status.text(settings.msgConnecting || '');

			$.post(ajaxurl, {
				action: 'wsww_mailchimp_connect',
				api_key: apiKey,
				nonce: settings.nonce || ''
			})
				.done(function (response) {
					if (!response || !response.success || !response.data) {
						$status.text(settings.msgUnableToConnect || '');
						wswwSetMailchimpConnectedState(false);
						return;
					}

					$status.text(response.data.message || settings.msgConnected || '');
					wswwSetMailchimpConnectedState(true);

					if (response.data.lists) {
						$listSel.empty();
						$listSel.append(
							$('<option/>', {
								value: '',
								text: settings.msgSelectAudience || ''
							})
						);

						$.each(response.data.lists, function (id, name) {
							$listSel.append(
								$('<option/>', {
									value: id,
									text: name
								})
							);
						});
					}
				})
				.fail(function () {
					$status.text(settings.msgConnectionFailed || '');
					wswwSetMailchimpConnectedState(false);
				});
		});

		$disconnect.on('click', function (e) {
			e.preventDefault();
			$status.text(settings.msgDisconnecting || '');

			$.post(ajaxurl, {
				action: 'wsww_mailchimp_disconnect',
				nonce: settings.nonce || ''
			})
				.done(function (response) {
					if (!response || !response.success || !response.data) {
						$status.text(settings.msgUnableToDisconnect || '');
						return;
					}

					$apiKey.val('');
					$listSel.val('');
					$status.text(response.data.message || settings.msgDisconnected || '');
					wswwSetMailchimpConnectedState(false);
				})
				.fail(function () {
					$status.text(settings.msgDisconnectFailed || '');
				});
		});
	});
})(jQuery);
