(function ($) {
	'use strict';

	$(function () {
		var $adminMenu = $('#adminmenu');
		if (!$adminMenu.length) {
			return;
		}

		var strings = window.wppsMenuOrganizerToggle || {};
		var $toggle = $adminMenu.find('.wpps-show-all-toggle > a .wp-menu-name');
		var initialCount = $adminMenu.find('.wpps-soft-hidden').length;

		function getShowAllLabel(count) {
			if (strings.showAll && strings.showAll.indexOf('%') !== -1) {
				return strings.showAll.replace('%d', String(count));
			}
			return 'Show All (' + count + ')';
		}

		if ($toggle.length && initialCount > 0) {
			$toggle.text(getShowAllLabel(initialCount));
		}

		$adminMenu.on('click', '.wpps-show-all-toggle > a', function (e) {
			e.preventDefault();
			var expanded = $adminMenu.toggleClass('wpps-show-hidden').hasClass('wpps-show-hidden');
			var count = $adminMenu.find('.wpps-soft-hidden').length;

			if ($toggle.length) {
				$toggle.text(expanded ? (strings.showLess || 'Show Less') : getShowAllLabel(count));
			}

			try {
				localStorage.setItem('wpps_menu_show_hidden', expanded ? '1' : '0');
			} catch (err) {
				// Ignore storage errors.
			}

			$(document).trigger('wp-window-resized');
		});

		try {
			if (localStorage.getItem('wpps_menu_show_hidden') === '1') {
				$adminMenu.addClass('wpps-show-hidden');
				if ($toggle.length) {
					$toggle.text(strings.showLess || 'Show Less');
				}
			}
		} catch (err) {
			// Ignore storage errors.
		}
	});
})(jQuery);
