/**
 * Northfield Theatre — Header search autocomplete
 *
 * Debounced live suggestions from the Spektrix mock REST endpoint.
 * Keyboard: ArrowDown/Up to move, Enter to go, Escape to close.
 *
 * @package Northfield_Theatre
 * @since 1.0.0
 */

(function () {
	'use strict';

	var input = document.getElementById('header-search-input');
	var results = document.getElementById('search-autocomplete-results');
	var form = input ? input.closest('form') : null;
	if (!input || !results || !form) {
		return;
	}

	var restUrl = (typeof northfieldData !== 'undefined' && northfieldData.restUrl) || '/wp-json/spektrix-mock/v1/';
	var siteUrl = (typeof northfieldData !== 'undefined' && northfieldData.siteUrl) || '/';

	var debounceTimer = null;
	var currentController = null;
	var activeIndex = -1;
	var items = [];

	function setExpanded(expanded) {
		form.setAttribute('aria-expanded', expanded ? 'true' : 'false');
		results.hidden = !expanded;
	}

	function escapeHtml(str) {
		var div = document.createElement('div');
		div.textContent = str;
		return div.innerHTML;
	}

	function formatDate(iso) {
		if (!iso) return '';
		var d = new Date(iso);
		if (isNaN(d.getTime())) return '';
		return d.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
	}

	function render(events, query) {
		results.innerHTML = '';
		items = [];

		if (!events || events.length === 0) {
			var empty = document.createElement('div');
			empty.className = 'search-autocomplete__empty';
			empty.textContent = query ? 'No shows match "' + query + '".' : '';
			results.appendChild(empty);
			setExpanded(Boolean(query));
			return;
		}

		events.slice(0, 6).forEach(function (ev, idx) {
			var a = document.createElement('a');
			a.className = 'search-autocomplete__item';
			a.setAttribute('role', 'option');
			a.setAttribute('id', 'search-item-' + idx);
			a.href = ev.url || (siteUrl + 'events/' + ev.slug + '/');

			var cat = ev.category || '';
			var date = ev.dateDisplay || formatDate(ev.firstDate || '');
			var meta = [cat, date].filter(Boolean).join(' · ');

			a.innerHTML =
				'<span class="search-autocomplete__title">' + escapeHtml(ev.name || '') + '</span>' +
				'<span class="search-autocomplete__meta">' + escapeHtml(meta) + '</span>';

			a.addEventListener('mouseenter', function () {
				setActive(idx);
			});
			results.appendChild(a);
			items.push(a);
		});

		activeIndex = -1;
		setExpanded(true);
	}

	function setActive(idx) {
		items.forEach(function (item, i) {
			if (i === idx) {
				item.setAttribute('aria-selected', 'true');
				item.classList.add('is-active');
			} else {
				item.removeAttribute('aria-selected');
				item.classList.remove('is-active');
			}
		});
		activeIndex = idx;
		if (idx >= 0) {
			input.setAttribute('aria-activedescendant', 'search-item-' + idx);
		} else {
			input.removeAttribute('aria-activedescendant');
		}
	}

	function fetchResults(query) {
		if (currentController) {
			currentController.abort();
		}
		currentController = new AbortController();

		var url = restUrl + 'events?search=' + encodeURIComponent(query) + '&limit=6&sale_status=OnSale';
		fetch(url, { signal: currentController.signal })
			.then(function (r) { return r.ok ? r.json() : { data: [] }; })
			.then(function (payload) {
				var events = (payload && payload.data) ? payload.data : [];
				render(events, query);
			})
			.catch(function (err) {
				if (err.name !== 'AbortError') {
					setExpanded(false);
				}
			});
	}

	function handleInput() {
		var query = input.value.trim();

		clearTimeout(debounceTimer);
		if (query.length < 2) {
			setExpanded(false);
			return;
		}
		debounceTimer = setTimeout(function () {
			fetchResults(query);
		}, 180);
	}

	function handleKeydown(e) {
		if (results.hidden || items.length === 0) {
			return;
		}
		switch (e.key) {
			case 'ArrowDown':
				e.preventDefault();
				setActive((activeIndex + 1) % items.length);
				break;
			case 'ArrowUp':
				e.preventDefault();
				setActive(activeIndex <= 0 ? items.length - 1 : activeIndex - 1);
				break;
			case 'Enter':
				if (activeIndex >= 0 && items[activeIndex]) {
					e.preventDefault();
					window.location.href = items[activeIndex].href;
				}
				break;
			case 'Escape':
				setExpanded(false);
				input.blur();
				break;
		}
	}

	input.addEventListener('input', handleInput);
	input.addEventListener('keydown', handleKeydown);

	// Close on outside click
	document.addEventListener('click', function (e) {
		if (!form.contains(e.target) && !results.contains(e.target)) {
			setExpanded(false);
		}
	});
})();
