(function ($) {
	'use strict';

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

		var matchers = [];

		function escapeRegExp(value) {
			return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
		}

		function hrefMatchesSlug(href, slug) {
			if (!href || !slug) {
				return false;
			}
			if (href === slug || href === adminPageBase + slug) {
				return true;
			}
			try {
				var re = new RegExp('(?:\\?|&)page=' + escapeRegExp(slug) + '(?:&|#|$)');
				return re.test(href);
			} catch (e) {
				return false;
			}
		}

		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 (!hrefMatchesSlug(href, matcher.slug)) {
					continue;
				}
				if (matcher.url) {
					$link.attr('href', matcher.url);
				}
				if (matcher.openNewTab) {
					$link.attr('target', '_blank').attr('rel', 'noopener noreferrer');
				}
				break;
			}
		});
	});
})(jQuery);
