(function ($) {
	'use strict';

	$(function () {
		var config = window.wppsMenuOrganizerApplied || {};
		var customLinks = config.customLinks || {};
		var openNewTabSlugs = config.openNewTabSlugs || [];
		var adminPageBase = config.adminPageBase || '';

		var matchers = [];

		Object.keys(customLinks).forEach(function (slug) {
			var entry = customLinks[slug];
			if (!slug || !entry || !entry.url) {
				return;
			}
			matchers.push({
				slug: slug,
				url: entry.url,
				openNewTab: !!entry.openNewTab
			});
		});

		openNewTabSlugs.forEach(function (slug) {
			if (!slug || customLinks[slug]) {
				return;
			}
			matchers.push({
				slug: slug,
				url: null,
				openNewTab: true
			});
		});

		if (!matchers.length) {
			return;
		}

		$('#adminmenu').find('a[href]').each(function () {
			var $link = $(this);
			var href = $link.attr('href') || '';
			if (!href) {
				return;
			}

			for (var i = 0; i < matchers.length; i++) {
				var matcher = matchers[i];
				if (href.indexOf(matcher.slug) === -1 && href !== adminPageBase + matcher.slug) {
					continue;
				}
				if (matcher.url) {
					$link.attr('href', matcher.url);
				}
				if (matcher.openNewTab) {
					$link.attr('target', '_blank').attr('rel', 'noopener noreferrer');
				}
				break;
			}
		});
	});
})(jQuery);
