/**
 * Northfield Theatre — Core JavaScript
 *
 * Mobile menu, alert banner, scroll animations, keyboard navigation.
 * No dependencies — vanilla JS only.
 *
 * @package Northfield_Theatre
 * @since 1.0.0
 */

(function () {
	'use strict';

	/**
	 * Check if user prefers reduced motion.
	 * @returns {boolean}
	 */
	function prefersReducedMotion() {
		return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
	}

	/* ======================================================================
	   1. MOBILE MENU
	   ====================================================================== */

	function initMobileMenu() {
		var toggle = document.getElementById('mobile-menu-toggle');
		var nav = document.getElementById('mobile-nav');
		var close = document.getElementById('mobile-nav-close');

		if (!toggle || !nav) {
			return;
		}

		var focusableSelector = 'a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])';
		var firstFocusable = null;
		var lastFocusable = null;

		function openMenu() {
			nav.classList.add('is-open');
			nav.setAttribute('aria-hidden', 'false');
			toggle.setAttribute('aria-expanded', 'true');
			document.body.classList.add('mobile-nav-open');

			// Set focus trap
			var focusables = nav.querySelectorAll(focusableSelector);
			if (focusables.length > 0) {
				firstFocusable = focusables[0];
				lastFocusable = focusables[focusables.length - 1];
				firstFocusable.focus();
			}
		}

		function closeMenu() {
			nav.classList.remove('is-open');
			nav.setAttribute('aria-hidden', 'true');
			toggle.setAttribute('aria-expanded', 'false');
			document.body.classList.remove('mobile-nav-open');
			toggle.focus();
		}

		toggle.addEventListener('click', function () {
			var isOpen = nav.classList.contains('is-open');
			if (isOpen) {
				closeMenu();
			} else {
				openMenu();
			}
		});

		if (close) {
			close.addEventListener('click', closeMenu);
		}

		// Close on Escape key
		document.addEventListener('keydown', function (e) {
			if (e.key === 'Escape' && nav.classList.contains('is-open')) {
				closeMenu();
			}
		});

		// Focus trap within mobile nav
		nav.addEventListener('keydown', function (e) {
			if (e.key !== 'Tab') {
				return;
			}

			if (!firstFocusable || !lastFocusable) {
				return;
			}

			if (e.shiftKey) {
				if (document.activeElement === firstFocusable) {
					e.preventDefault();
					lastFocusable.focus();
				}
			} else {
				if (document.activeElement === lastFocusable) {
					e.preventDefault();
					firstFocusable.focus();
				}
			}
		});

		// Close menu if viewport resizes past mobile breakpoint
		var desktopQuery = window.matchMedia('(min-width: 1024px)');
		desktopQuery.addEventListener('change', function (e) {
			if (e.matches && nav.classList.contains('is-open')) {
				closeMenu();
			}
		});
	}

	/* ======================================================================
	   2. ALERT BANNER DISMISS
	   ====================================================================== */

	function initAlertBanner() {
		var banner = document.getElementById('alert-banner');
		var dismiss = document.getElementById('alert-banner-dismiss');

		if (!banner || !dismiss) {
			return;
		}

		// Check if banner was previously dismissed this session
		var dismissed = sessionStorage.getItem('northfield_alert_dismissed');
		if (dismissed === 'true') {
			banner.hidden = true;
			return;
		}

		dismiss.addEventListener('click', function () {
			banner.hidden = true;
			sessionStorage.setItem('northfield_alert_dismissed', 'true');
		});
	}

	/* ======================================================================
	   3. FADE-IN ON SCROLL — Intersection Observer
	   ====================================================================== */

	function initFadeInOnScroll() {
		if (prefersReducedMotion()) {
			// Make all fade-in elements visible immediately
			var elements = document.querySelectorAll('.fade-in-up');
			for (var i = 0; i < elements.length; i++) {
				elements[i].classList.add('is-visible');
			}
			return;
		}

		if (!('IntersectionObserver' in window)) {
			// Fallback: show everything
			var fallbackElements = document.querySelectorAll('.fade-in-up');
			for (var j = 0; j < fallbackElements.length; j++) {
				fallbackElements[j].classList.add('is-visible');
			}
			return;
		}

		var observer = new IntersectionObserver(
			function (entries) {
				entries.forEach(function (entry) {
					if (entry.isIntersecting) {
						entry.target.classList.add('is-visible');
						observer.unobserve(entry.target);
					}
				});
			},
			{
				root: null,
				rootMargin: '0px 0px -60px 0px',
				threshold: 0.1,
			}
		);

		var targets = document.querySelectorAll('.fade-in-up');
		targets.forEach(function (target) {
			observer.observe(target);
		});
	}

	/* ======================================================================
	   4. DESKTOP NAVIGATION — Keyboard support for dropdowns
	   ====================================================================== */

	function initDesktopNav() {
		var navItems = document.querySelectorAll('.primary-nav__item');

		navItems.forEach(function (item) {
			var link = item.querySelector('.primary-nav__link');
			var dropdown = item.querySelector('.primary-nav__dropdown');

			if (!link || !dropdown) {
				return;
			}

			// Toggle aria-expanded on hover/focus
			function showDropdown() {
				link.setAttribute('aria-expanded', 'true');
			}

			function hideDropdown() {
				link.setAttribute('aria-expanded', 'false');
			}

			item.addEventListener('mouseenter', showDropdown);
			item.addEventListener('mouseleave', hideDropdown);
			item.addEventListener('focusin', showDropdown);
			item.addEventListener('focusout', function (e) {
				// Only hide if focus leaves the entire nav item
				if (!item.contains(e.relatedTarget)) {
					hideDropdown();
				}
			});

			// Close dropdown on Escape
			item.addEventListener('keydown', function (e) {
				if (e.key === 'Escape') {
					hideDropdown();
					link.focus();
				}
			});
		});
	}

	/* ======================================================================
	   5. ACCORDION — WAI-ARIA Accordion pattern
	   ====================================================================== */

	function initAccordions() {
		var accordions = document.querySelectorAll('.accordion');
		accordions.forEach(function (accordion) {
			var triggers = accordion.querySelectorAll('.accordion__trigger');

			triggers.forEach(function (trigger) {
				trigger.addEventListener('click', function () {
					var expanded = this.getAttribute('aria-expanded') === 'true';
					var panelId = this.getAttribute('aria-controls');
					var panel = document.getElementById(panelId);

					this.setAttribute('aria-expanded', !expanded);
					if (panel) {
						panel.hidden = expanded;
					}
				});
			});
		});
	}

	/* ======================================================================
	   6. EXTERNAL LINK HANDLING
	   ====================================================================== */

	function initExternalLinks() {
		var links = document.querySelectorAll('a[target="_blank"]');
		links.forEach(function (link) {
			// Ensure rel attributes are set for security
			if (!link.getAttribute('rel') || link.getAttribute('rel').indexOf('noopener') === -1) {
				var rel = link.getAttribute('rel') || '';
				link.setAttribute('rel', (rel + ' noopener noreferrer').trim());
			}
		});
	}

	/* ======================================================================
	   6. INITIALISE EVERYTHING ON DOM READY
	   ====================================================================== */

	function init() {
		initMobileMenu();
		initAlertBanner();
		initFadeInOnScroll();
		initDesktopNav();
		initAccordions();
		initExternalLinks();
	}

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