(function ($, document, window, undefined) {
	'use strict';

	function formToJSON(f) {
		var fd = $(f).serializeArray();
		var d = {};
		$(fd).each(function () {
			if (this.name.includes("[]")) {
				if (!Array.isArray(d[this.name])) {
					d[this.name] = [];
				}
				d[this.name].push(this.value);
			} else {
				d[this.name] = this.value;
			}
		});
		return d;
	}

	var $catProtection = $('#cat_protection'),
		$catPasswords = $('#cat_passwords');

	var updateProdCatVisibility = function () {
		$catProtection.toggle($('#protected_visibility').prop('checked'));
	};

	$('#cat_visibility').on('change', 'input:radio', function () {
		updateProdCatVisibility();
	});

	$catProtection.on('change', 'input:checkbox', function () {
		var $protectionField = $(this).parent('label').next('.cat-protection__field');
		$protectionField.toggle($(this).prop('checked'));
	});

	$catPasswords.on('click', 'a.cat-password__icon', function () {
		var $passwordField = $(this).parents('.cat-password');

		if ('add' === $(this).data('action')) {
			// Add password field
			var $passwordClone = $passwordField.clone(),
				index = $catPasswords.children('.cat-password').last().data('index') + 1;

			if (!$passwordClone.find('.cat-password__icon--delete').length) {
				$passwordClone.children('.cat-password__icons').append('<a class="cat-password__icon cat-password__icon--delete" data-action="delete" href="#"><span class="dashicons dashicons-minus"></span></a>');
			}

			$passwordClone
				.attr({ 'data-first': false, 'data-index': index })
				.find('.cat-password__field')
				.attr({ 'id': 'cat_password_' + index, 'value': '' });

			$passwordClone.appendTo($catPasswords);

		} else if ('delete' === $(this).data('action')) {
			// Remove password field
			var pass = $passwordField.find('input').val();

			// Remove if no password entered or if user confirms
			if (!pass || (pass && confirm(ppc_params.confirm_delete))) {
				$passwordField.remove();
			}
		}
		return false;
	});

	$(function () {
		if ($('#addtag, #edittag').length) {
			updateProdCatVisibility();

			if ('select2' in $.fn) {
				$('#cat_user_roles').select2();

				// On search.
				$('#cat_users').select2({
					minimumInputLength: 3,
					ajax: {
						type: 'POST',
						delay: 250,
						url: PPC_Admin.ajaxUrl,
						data: function (params) {
							var data = {
								action: 'ppc_get_users',
								nonce: PPC_Admin.users_nonce,
								search_term: params.term
							};
							return data;
						},
						processResults: function (data) {
							return {
								results: data
							};
						},
					}
				});

				// Find details of pre-selected values for the edit screen.
				var userSelect = $('#cat_users');

				if (userSelect.data('users').length > 0) {
					var data = {
						action: 'ppc_preload_users',
						nonce: PPC_Admin.users_nonce,
						users: userSelect.data('users')
					};

					$.post({
						url: PPC_Admin.ajaxUrl,
						data: data,
					}).then(function (data) {
						var selected = userSelect.data('users') ?? [];

						if (Array.isArray(data) && data.length > 0) {
							data.forEach((element, index) => {
								var option = new Option(element.user_login, element.ID, false, selected.includes(element.ID));
								userSelect.append(option).trigger('change');
							})

							userSelect.trigger({
								type: 'select2:select',
								params: {
									data: data
								}
							});
						}
					});
				}

			}

			// Create an observer to monitor when a new category is added to table so we can reset Visibility options.
			if ($('#addtag').length && ('MutationObserver' in window)) {
				// Select the node that will be observed for mutations
				var targetNode = document.getElementById('the-list');

				// Options for the observer (which mutations to observe)
				var config = { childList: true };

				// Callback function to execute when mutations are observed
				var callback = function (mutationsList, observer) {
					$.each(mutationsList, function (i, mutation) {
						if (mutation.type == 'childList') {
							// Reset visibility options
							var $catProtection = $('#cat_protection');
							$catProtection.find('.cat-password__field, .cat-protection__select').val(null).change();
							$catProtection.find('.cat-password').not(':eq(0)').remove();
							$catProtection.find('.cat-protection__check').prop('checked', false).change();
							$('#public_visibility').prop('checked', true).change();
						}
					});
				};

				// Create an observer instance linked to the callback function
				var observer = new MutationObserver(callback);

				// Start observing the target node for configured mutations
				observer.observe(targetNode, config);
			}
		}

		// JS validation when there is empty protection 
		if ($("#edittag").length) {
			$("#edittag").on("submit", function (e) {
				$(".ppc-notice").addClass("hidden");

				var $data = formToJSON("#edittag");
				if ($data["cat_visibility"] == "protected") {
					var $emptyError = false;
					if (!("cat_protection[]" in $data)) {
						$emptyError = true;
					}
					else if (!$data["cat_protection[]"].includes("password")) {
						$emptyError = true;
						$data["cat_protection[]"].forEach(function ($item) {
							if ($item == "user_role" && "cat_user_roles[]" in $data) {
								$emptyError = false;
							}
							if ($item == "user" && "cat_users[]" in $data) {
								$emptyError = false;
							}
						});
					}

					if ($emptyError) {
						e.preventDefault();
						$(".ppc-notice").removeClass("hidden");
					}
				}
			});
		}
	});

	/* SETTINGS PAGE */
	var toggleChildSettings = function ($parent) {
		var show = false;
		var toggleVal = $parent.data('toggleVal');
		var $children = $parent.closest('.form-table').find('.' + $parent.data('childClass')).closest('tr');

		if ('radio' === $parent.attr('type')) {
			show = $parent.prop('checked') && toggleVal == $parent.val();
		} else if ('checkbox' === $parent.attr('type')) {
			if (typeof toggleVal === 'undefined' || 1 == toggleVal) {
				show = $parent.prop('checked');
			} else {
				show = !$parent.prop('checked');
			}
		} else {
			show = (toggleVal == $parent.val());
		}

		$children.toggle(show);
	};

	var $formTables = $('.form-table');

	$formTables.on('change', '.toggle-parent', function () {
		toggleChildSettings($(this));
	});

	var fetch_users = function () {
		var endpoint = PPC_Admin.ajaxUrl;

		var data = {
			action: 'ppc_get_users',
			nonce: PPC_Admin.users_nonce
		};

		var settings = {
			dataType: 'text', // better JSON error handling
			done: (resp) => {
				console.log(resp)
			},
			fail: (err) => {
				console.log(err);
			}
		};

		$.post(endpoint, data, settings);
	}

	$(function () {

		$formTables.find('.toggle-parent').each(function () {
			toggleChildSettings($(this));
		});

		if ($.isFunction($.fn.tipTip)) {
			$('.b2-help-tip').tipTip({
				'attribute': 'data-tip',
				'fadeIn': 50,
				'fadeOut': 50,
				'delay': 200,
				'keepAlive': true,
				'defaultPosition': "right",
			});
		}

		//fetch_users();

	});

})(jQuery, document, window);
