/**
 * Responsive Mobile Select Menu - Frontend JavaScript
 *
 * @package ResponsiveMobileSelect
 * @since 2.0.0
 */

(function($) {
	'use strict';

	/**
	 * Responsive Mobile Select Menu functionality
	 */
	class ResponsiveMobileSelect {
		constructor() {
			this.selects = $('.responsive-menu-select');
			this.maxWidth = this.getBreakpointFromCSS();
			this.isInitialized = false;
			
			this.init();
		}

		/**
		 * Initialize the plugin
		 */
		init() {
			if (this.selects.length === 0) {
				return;
			}

			this.bindEvents();
			this.updateVisibility();
			
			this.isInitialized = true;
		}

		/**
		 * Bind event handlers
		 */
		bindEvents() {
			// Handle select change
			this.selects.on('change', this.handleSelectChange.bind(this));

			// Handle window resize
			$(window).on('resize', this.debounce(this.updateVisibility.bind(this), 250));

			// Handle orientation change
			$(window).on('orientationchange', this.handleOrientationChange.bind(this));

			// Handle keyboard navigation
			this.selects.on('keydown', this.handleKeyboardNavigation.bind(this));

			// Handle focus management
			this.selects.on('focus blur', this.handleFocusManagement.bind(this));
		}

		/**
		 * Handle select menu change
		 */
		handleSelectChange(event) {
			const $select = $(event.target);
			const selectedValue = $select.val();

			// Don't navigate if no value is selected
			if (!selectedValue || selectedValue === '') {
				return;
			}

			// Validate URL
			try {
				const url = new URL(selectedValue, window.location.origin);
				
				// Only save if we're navigating to a different page
				if (url.href !== window.location.href) {
					// Save the selected option to localStorage for persistence
					this.saveSelectedOption($select, selectedValue);
				}
				
				// Navigate to selected page
				window.location.href = url.href;
			} catch (error) {
				console.warn('Invalid URL in responsive menu:', selectedValue);
			}
		}

		/**
		 * Save selected option to localStorage
		 */
		saveSelectedOption($select, value) {
			const menuId = this.getMenuIdentifier($select);
			if (menuId) {
				localStorage.setItem(`responsive-menu-selection-${menuId}`, value);
			}
		}

		/**
		 * Restore selected option from localStorage
		 */
		restoreSelectedOption($select) {
			const menuId = this.getMenuIdentifier($select);
			if (menuId) {
				const savedValue = localStorage.getItem(`responsive-menu-selection-${menuId}`);
				if (savedValue && savedValue !== '') {
					// Check if the saved option still exists in the select
					const $option = $select.find(`option[value="${savedValue}"]`);
					if ($option.length > 0) {
						// Check if we're currently on the saved page
						const currentUrl = window.location.href;
						if (savedValue === currentUrl) {
							// We're on the saved page, show it as selected
							$select.val(savedValue);
							return true;
						} else {
							// We're not on the saved page, clear the selection to show placeholder
							$select.val('');
							// Remove the saved value since we're not on that page anymore
							localStorage.removeItem(`responsive-menu-selection-${menuId}`);
							return false;
						}
					}
				}
			}
			return false;
		}

		/**
		 * Get unique identifier for the menu
		 */
		getMenuIdentifier($select) {
			// Use data attributes from the select element itself
			const themeLocation = $select.attr('data-theme-location');
			const menuId = $select.attr('data-menu-id');
			
			if (themeLocation && themeLocation !== '') {
				return `theme-${themeLocation}`;
			}
			
			if (menuId && menuId !== '') {
				return `menu-${menuId}`;
			}
			
			// Fallback: use the select's position in the document
			return `select-${$select.index()}`;
		}

		/**
		 * Update visibility based on viewport width
		 */
		updateVisibility() {
			const windowWidth = $(window).width();
			const isMobile = windowWidth <= this.maxWidth;

			this.selects.each((index, select) => {
				const $select = $(select);
				const $desktopMenu = $select.siblings('.responsive-menu-desktop');

				if (isMobile) {
					// Show select, hide desktop menu
					$select.removeAttr('aria-hidden').attr('aria-expanded', 'false');
					$desktopMenu.attr('aria-hidden', 'true');
					
					// Add mobile-specific classes
					$select.addClass('is-mobile');
					$desktopMenu.addClass('is-hidden');
					
					// Restore previously selected option if available
					this.restoreSelectedOption($select);
				} else {
					// Hide select, show desktop menu
					$select.attr('aria-hidden', 'true');
					$desktopMenu.removeAttr('aria-hidden');
					
					// Remove mobile-specific classes
					$select.removeClass('is-mobile');
					$desktopMenu.removeClass('is-hidden');
				}
			});

			// Trigger custom event
			$(document).trigger('responsiveMenuVisibilityChanged', [isMobile]);
		}

		/**
		 * Handle orientation change
		 */
		handleOrientationChange() {
			// Delay update to allow orientation change to complete
			setTimeout(() => {
				this.updateVisibility();
			}, 100);
		}

		/**
		 * Handle keyboard navigation
		 */
		handleKeyboardNavigation(event) {
			const $select = $(event.target);
			const key = event.key;

			switch (key) {
				case 'Enter':
				case ' ':
					// Prevent default for space to avoid scrolling
					if (key === ' ') {
						event.preventDefault();
					}
					$select.focus();
					break;

				case 'Escape':
					// Close select and return focus
					$select.blur();
					break;

				case 'ArrowUp':
				case 'ArrowDown':
					// Let the browser handle these naturally
					break;

				default:
					// For other keys, let the browser handle them
					return;
			}
		}

		/**
		 * Handle focus management
		 */
		handleFocusManagement(event) {
			const $select = $(event.target);
			const isFocus = event.type === 'focus';

			if (isFocus) {
				$select.addClass('has-focus');
				
				// Announce to screen readers
				this.announceToScreenReader(
					window.responsiveMobileSelect?.i18n?.selectPlaceholder || 'Select a page to navigate to'
				);
			} else {
				$select.removeClass('has-focus');
			}
		}

		/**
		 * Announce message to screen readers
		 */
		announceToScreenReader(message) {
			// Create or get existing announcement element
			let $announcement = $('#responsive-menu-announcement');
			
			if ($announcement.length === 0) {
				$announcement = $('<div>', {
					id: 'responsive-menu-announcement',
					'aria-live': 'polite',
					'aria-atomic': 'true',
					class: 'screen-reader-text',
					style: 'position: absolute; left: -10000px; width: 1px; height: 1px; overflow: hidden;'
				}).appendTo('body');
			}

			// Update and announce
			$announcement.text(message);
		}

		/**
		 * Debounce function to limit function calls
		 */
		debounce(func, wait) {
			let timeout;
			return function executedFunction(...args) {
				const later = () => {
					clearTimeout(timeout);
					func(...args);
				};
				clearTimeout(timeout);
				timeout = setTimeout(later, wait);
			};
		}

		/**
		 * Get breakpoint from CSS media query
		 */
		getBreakpointFromCSS() {
			// Try to get breakpoint from CSS custom property or data attribute
			const $select = this.selects.first();
			if ($select.length) {
				const dataBreakpoint = $select.data('breakpoint');
				if (dataBreakpoint) {
					return parseInt(dataBreakpoint, 10);
				}
			}
			
			// Default fallback
			return 960;
		}

		/**
		 * Get current breakpoint
		 */
		getBreakpoint() {
			return this.maxWidth;
		}

		/**
		 * Set custom breakpoint
		 */
		setBreakpoint(width) {
			this.maxWidth = parseInt(width, 10) || 960;
			this.updateVisibility();
		}

		/**
		 * Destroy the plugin
		 */
		destroy() {
			if (!this.isInitialized) {
				return;
			}

			// Remove event handlers
			this.selects.off('change keydown focus blur');
			$(window).off('resize orientationchange');

			// Remove classes and attributes
			this.selects.removeClass('is-mobile has-focus').removeAttr('aria-hidden aria-expanded');
			$('.responsive-menu-desktop').removeClass('is-hidden').removeAttr('aria-hidden');

			// Remove announcement element
			$('#responsive-menu-announcement').remove();

			// Clean up localStorage entries for this instance
			this.cleanupLocalStorage();

			this.isInitialized = false;
		}

		/**
		 * Clean up localStorage entries
		 */
		cleanupLocalStorage() {
			// Remove all responsive menu related localStorage entries
			const keysToRemove = [];
			for (let i = 0; i < localStorage.length; i++) {
				const key = localStorage.key(i);
				if (key && key.startsWith('responsive-menu-selection-')) {
					keysToRemove.push(key);
				}
			}
			
			keysToRemove.forEach(key => {
				localStorage.removeItem(key);
			});
		}
	}

	// Initialize when DOM is ready
	$(document).ready(function() {
		// Create global instance
		window.responsiveMobileSelectInstance = new ResponsiveMobileSelect();

		// Make it available globally
		window.ResponsiveMobileSelect = ResponsiveMobileSelect;
	});

	// Handle AJAX-loaded content
	$(document).on('responsiveMenuContentLoaded', function() {
		if (window.responsiveMobileSelectInstance) {
			window.responsiveMobileSelectInstance.destroy();
		}
		window.responsiveMobileSelectInstance = new ResponsiveMobileSelect();
	});

})(jQuery);
