/* Yatoon App Shell interactions (v3.5.0) */
(function ($) {
	'use strict';

	$(function () {
		var $sidebar = $('.yatoon-app-sidebar');
		var $toggle = $('.yatoon-app-menu-toggle');
		var $search = $('#yatoon-app-search-input');
		var $results = $('#yatoon-app-search-results');
		var navStorageKey = 'yatoon-app-collapsed-groups';
		var savedCollapsed = null;
		try {
			savedCollapsed = JSON.parse(window.localStorage.getItem(navStorageKey) || 'null');
		} catch (e) {
			savedCollapsed = null;
		}

		function setGroupCollapsed($group, collapsed) {
			$group.toggleClass('is-collapsed', collapsed);
			$group.children('.yatoon-app-nav-label').attr('aria-expanded', collapsed ? 'false' : 'true');
		}

		function persistGroups() {
			var collapsed = [];
			$('.yatoon-app-nav-group.is-collapsed').each(function () {
				collapsed.push($(this).children('.yatoon-app-nav-label').find('span').first().text().trim());
			});
			try {
				window.localStorage.setItem(navStorageKey, JSON.stringify(collapsed));
			} catch (e) {
				// Storage can be unavailable in privacy-restricted browsers.
			}
		}

		$('.yatoon-app-nav-group').each(function (index) {
			var $group = $(this);
			var label = $group.children('.yatoon-app-nav-label').find('span').first().text().trim();
			var collapsed = $group.hasClass('has-active') ? false : Array.isArray(savedCollapsed)
				? savedCollapsed.indexOf(label) !== -1
				: (!$group.hasClass('has-active') && index > 0);
			setGroupCollapsed($group, collapsed);
		});

		$('.yatoon-app-nav-label').on('click', function () {
			var $group = $(this).closest('.yatoon-app-nav-group');
			setGroupCollapsed($group, !$group.hasClass('is-collapsed'));
			persistGroups();
		});

		$toggle.on('click', function () {
			$sidebar.toggleClass('is-open');
			$toggle.attr('aria-expanded', $sidebar.hasClass('is-open') ? 'true' : 'false');
		});

		// Click outside closes mobile sidebar
		$(document).on('click', function (e) {
			if (!$sidebar.hasClass('is-open')) return;
			if ($(e.target).closest('.yatoon-app-sidebar, .yatoon-app-menu-toggle').length) return;
			$sidebar.removeClass('is-open');
			$toggle.attr('aria-expanded', 'false');
		});

		if (!$search.length || typeof yatoonAppShell === 'undefined') return;

		var items = yatoonAppShell.searchIndex || [];

		function renderResults(query) {
			query = query.trim().toLowerCase();
			if (!query) {
				$results.removeClass('is-open').empty();
				return;
			}
			var seen = {};
			var matches = items.map(function (it, position) {
				var label = (it.label || '').toLowerCase();
				var keywords = (it.keywords || '').toLowerCase();
				var score = label === query ? 0 : label.indexOf(query) === 0 ? 1 : label.indexOf(query) !== -1 ? 2 : keywords.indexOf(query) !== -1 ? 3 : 99;
				return {item: it, score: score, position: position};
			}).filter(function (row) {
				if (row.score === 99) return false;
				var key = row.item.label + '|' + row.item.url;
				if (seen[key]) return false;
				seen[key] = true;
				return true;
			}).sort(function (a, b) {
				return a.score - b.score || a.position - b.position;
			}).slice(0, 10).map(function (row) { return row.item; });

			$results.empty();
			if (!matches.length) {
				$results.append('<div class="yatoon-app-search-empty">' + yatoonAppShell.noResultsText + '</div>');
			} else {
				matches.forEach(function (it) {
					var $a = $('<a></a>').attr('href', it.url);
					$('<span></span>').addClass('dashicons ' + (it.icon || 'dashicons-admin-generic')).appendTo($a);
					$a.append(document.createTextNode(' ' + (it.label || '')));
					$results.append($a);
				});
			}
			$results.addClass('is-open');
		}

		$search.on('input', function () {
			renderResults($(this).val());
		});
		$search.on('focus', function () {
			if ($(this).val().trim()) renderResults($(this).val());
		});
		$(document).on('click', function (e) {
			if ($(e.target).closest('.yatoon-app-search').length) return;
			$results.removeClass('is-open');
		});

		// Keyboard shortcut: "/" focuses search (when not already typing in a field)
		$(document).on('keydown', function (e) {
			var tag = (e.target.tagName || '').toLowerCase();
			if (tag === 'input' || tag === 'textarea' || e.target.isContentEditable) return;
			if (e.key === '/') {
				e.preventDefault();
				$search.trigger('focus');
			}
		});
	});
})(jQuery);
