/* Yatoon Admin — remember filter state (v3.5.0)
 * Additive, defensive: only acts when the relevant elements exist on the
 * current screen, never touches anything else.
 */
(function ($) {
	'use strict';

	$(function () {
		/* ---------------- Bookings list: remember search + status filter ---------------- */
		var $search = $('#sbs-booking-search');
		var $status = $('#sbs-booking-status-filter');
		if ($search.length && $status.length) {
			var STORE_KEY = 'yatoon_bookings_filters_v1';

			// Only restore from storage if the URL didn't already set a value
			// (so a deep link with ?s=... always wins over a remembered filter).
			try {
				var saved = JSON.parse(localStorage.getItem(STORE_KEY) || '{}');
				var urlHasSearch = /[?&]s=/.test(window.location.search);
				if (!urlHasSearch && saved.search && !$search.val()) {
					$search.val(saved.search);
				}
				if (saved.status && !$status.val()) {
					$status.val(saved.status);
				}
				if ((!urlHasSearch && saved.search) || saved.status) {
					$search.trigger('input');
				}
			} catch (e) { /* localStorage unavailable — silently skip */ }

			function persistBookingFilters() {
				try {
					localStorage.setItem(STORE_KEY, JSON.stringify({
						search: $search.val() || '',
						status: $status.val() || ''
					}));
				} catch (e) {}
			}
			$search.add($status).on('input change', persistBookingFilters);
			$(document).on('click', '#sbs-booking-clear-filters', function () {
				try { localStorage.removeItem(STORE_KEY); } catch (e) {}
			});
		}

		/* ---------------- Calendar: remember last viewed date ---------------- */
		var $calWrap = $('#yatoon-calendar-wrap');
		if ($calWrap.length) {
			var DATE_KEY = 'yatoon_calendar_last_date_v1';
			var params = new URLSearchParams(window.location.search);
			var urlDate = params.get('date');

			if (urlDate) {
				try { localStorage.setItem(DATE_KEY, urlDate); } catch (e) {}
			} else {
				try {
					var savedDate = localStorage.getItem(DATE_KEY);
					var today = new Date().toISOString().slice(0, 10);
					if (savedDate && savedDate !== today) {
						params.set('date', savedDate);
						window.location.replace(window.location.pathname + '?' + params.toString());
					}
				} catch (e) {}
			}
		}
	});
})(jQuery);
