/**
 * Northfield Theatre — Homepage JavaScript
 *
 * Accessible tab switching and hero image rotation.
 * No dependencies — vanilla JS only.
 *
 * @package Northfield_Theatre
 * @since 1.0.0
 */

(function () {
	'use strict';

	function prefersReducedMotion() {
		return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
	}

	/* ======================================================================
	   1. TABBED SECTION — "This Week" / "Free things" / "Plan your visit"
	   Implements WAI-ARIA Tabs pattern:
	   https://www.w3.org/WAI/ARIA/apg/patterns/tabs/
	   ====================================================================== */

	function initTabs() {
		var tablist = document.querySelector('.this-week__tabs[role="tablist"]');
		if (!tablist) {
			return;
		}

		var tabs = Array.from(tablist.querySelectorAll('[role="tab"]'));
		var panels = [];

		tabs.forEach(function (tab) {
			var panelId = tab.getAttribute('aria-controls');
			var panel = document.getElementById(panelId);
			if (panel) {
				panels.push(panel);
			}
		});

		if (tabs.length === 0 || panels.length === 0) {
			return;
		}

		function activateTab(newTab) {
			// Deactivate all tabs.
			tabs.forEach(function (tab) {
				tab.setAttribute('aria-selected', 'false');
				tab.setAttribute('tabindex', '-1');
				tab.classList.remove('this-week__tab--active');
			});

			// Hide all panels.
			panels.forEach(function (panel) {
				panel.hidden = true;
			});

			// Activate selected tab.
			newTab.setAttribute('aria-selected', 'true');
			newTab.setAttribute('tabindex', '0');
			newTab.classList.add('this-week__tab--active');

			// Show corresponding panel.
			var panelId = newTab.getAttribute('aria-controls');
			var panel = document.getElementById(panelId);
			if (panel) {
				panel.hidden = false;
			}

			newTab.focus();
		}

		// Click handler.
		tabs.forEach(function (tab) {
			tab.addEventListener('click', function () {
				activateTab(tab);
			});
		});

		// Keyboard navigation.
		tablist.addEventListener('keydown', function (e) {
			var currentIndex = tabs.indexOf(document.activeElement);
			if (currentIndex === -1) {
				return;
			}

			var newIndex;

			switch (e.key) {
				case 'ArrowRight':
				case 'ArrowDown':
					e.preventDefault();
					newIndex = (currentIndex + 1) % tabs.length;
					activateTab(tabs[newIndex]);
					break;

				case 'ArrowLeft':
				case 'ArrowUp':
					e.preventDefault();
					newIndex = (currentIndex - 1 + tabs.length) % tabs.length;
					activateTab(tabs[newIndex]);
					break;

				case 'Home':
					e.preventDefault();
					activateTab(tabs[0]);
					break;

				case 'End':
					e.preventDefault();
					activateTab(tabs[tabs.length - 1]);
					break;
			}
		});
	}

	/* ======================================================================
	   2. HERO IMAGE ROTATION
	   Crossfade between background images. Pauses on hover/focus and
	   when the user prefers reduced motion.
	   ====================================================================== */

	function initHeroSlider() {
		var backdrop = document.getElementById('hero-backdrop');
		if (!backdrop) {
			return;
		}

		var slides = Array.from(backdrop.querySelectorAll('.hero__slide'));
		if (slides.length <= 1) {
			return; // No rotation needed for single or zero slides.
		}

		if (prefersReducedMotion()) {
			return; // Respect reduced motion preference.
		}

		var currentIndex = 0;
		var intervalMs = 9000;
		var timer = null;
		var isPaused = false;

		function showSlide(index) {
			slides.forEach(function (slide, i) {
				if (i === index) {
					slide.classList.add('hero__slide--active');
				} else {
					slide.classList.remove('hero__slide--active');
				}
			});
		}

		function nextSlide() {
			currentIndex = (currentIndex + 1) % slides.length;
			showSlide(currentIndex);
		}

		function startRotation() {
			if (!isPaused && !timer) {
				timer = setInterval(nextSlide, intervalMs);
			}
		}

		function stopRotation() {
			if (timer) {
				clearInterval(timer);
				timer = null;
			}
		}

		// Pause on hover.
		var hero = backdrop.closest('.hero');
		if (hero) {
			hero.addEventListener('mouseenter', function () {
				isPaused = true;
				stopRotation();
			});

			hero.addEventListener('mouseleave', function () {
				isPaused = false;
				startRotation();
			});

			// Pause when any focusable element inside hero receives focus.
			hero.addEventListener('focusin', function () {
				isPaused = true;
				stopRotation();
			});

			hero.addEventListener('focusout', function () {
				isPaused = false;
				startRotation();
			});
		}

		// Pause when page is not visible.
		document.addEventListener('visibilitychange', function () {
			if (document.hidden) {
				stopRotation();
			} else if (!isPaused) {
				startRotation();
			}
		});

		startRotation();
	}

	/* ======================================================================
	   3. INITIALISE
	   ====================================================================== */

	function init() {
		initTabs();
		initHeroSlider();
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', init);
	} else {
		init();
	}
})();
