/**
 * Eronex Theme - JavaScript
 *
 * Front-end behavior for the Eronex WordPress theme (preloader, sticky header,
 * search toggle, hamburger menu, and sliding navigation).
 *
 * Author: Deveasel
 * Version: 0.0.1
 *
 * Note: Please make sure that jQuery is loaded before this script.
 */

(function ($) {
	'use strict';

	/* ===================================
		Preloader
	====================================== */

	$(document).ready(function () {
		let selector = $('.eronex-preloader-wrapper');
		if (selector.length) {
			let timeout = selector.data('preloader-timeout') ?? 0.3;
			selector.delay(timeout * 100).fadeOut(500);
		}

		$(window).scroll(function () {
			let scroll_top_selector = $('.eronex-scroll-top');
			if(scroll_top_selector.length) {
				if ($(this).scrollTop() > 500) {
					scroll_top_selector.fadeIn('300');
				} else {
					scroll_top_selector.fadeOut('300');
				}
			}
		});

		$('.eronex-scroll-top').on('click', function (e) {
			e.preventDefault();
			$('body,html').animate({scrollTop: 0}, 500);
		})

	});

	/* ===================================
		Header Sticky
	====================================== */

	const header_sticky = $('header.eronex-sticky');

	if (header_sticky.length) {

		let lastScrollTop = 0;
		let header_sticky_effect = header_sticky.data('sticky-effect');
		let outer_height = header_sticky.outerHeight() || 100;
		header_sticky.css('min-height', outer_height + 'px');

		$(window).scroll(function () {

				//Scroll Down
				if(header_sticky_effect === 'scroll-down'){
					if ($(this).scrollTop() > outer_height) {
						header_sticky.addClass( 'eronex-appear' );
					} else {
						header_sticky.removeClass( 'eronex-appear' );
					}
				}

				//Scroll Up
				if(header_sticky_effect === 'scroll-up') {
					let scrollTop = $(this).scrollTop();
					if (scrollTop > outer_height && scrollTop < lastScrollTop) {
						header_sticky.addClass('eronex-appear');
					} else {
						header_sticky.removeClass('eronex-appear');
					}

					lastScrollTop = scrollTop;
				}

			});

	}

	/* ===================================
    	Header Search
	====================================== */

	$(document).on('click', function(e) {
		if($('.eronex-search-expand').length){
			if (!$(e.target).closest('.eronex-header-search').length) {
				let _this = $('.eronex-header-search .search-submit'),
					navbar = _this.parents('.eronex-navbar');
				navbar.toggleClass('eronex-search-expand');
				_this.find('.mi-magnifying-glass').toggleClass('mi-x-mark');
				syncHeaderSearch();
			}
		}
	});

	$('.eronex-header-search .search-submit').on('click',function (e) {
		e.preventDefault();
		let _this = $(this),
		navbar = _this.parents('.eronex-navbar');
		navbar.toggleClass('eronex-search-expand');
		_this.find('.mi-magnifying-glass').toggleClass('mi-x-mark');
		syncHeaderSearch();
	});

	/* ===================================
			Hamburger
	====================================== */

	(function () {
		const $toggle = $( '.eronex-hamburger-toggle-btn' );
		const $wrapper = $( '.eronex-hamburger-wrapper' );
		const $dialog = $wrapper.find( '.eronex-hamburger-menu-wrapper' );
		const $close = $wrapper.find( '.eronex-hamburger-close-btn' );
		const focusableSelector = 'a[href]:not([tabindex="-1"]), button:not([disabled]):not([tabindex="-1"]), input:not([disabled]):not([tabindex="-1"]), select:not([disabled]):not([tabindex="-1"]), textarea:not([disabled]):not([tabindex="-1"]), [tabindex]:not([tabindex="-1"])';
		let lastFocused = null;

		if ( ! $wrapper.length || ! $dialog.length ) {
			return;
		}

		function setHamburgerInert( isInert ) {
			const wrapperEl = $wrapper.get( 0 );
			if ( 'inert' in wrapperEl ) {
				wrapperEl.inert = isInert;
			} else if ( isInert ) {
				wrapperEl.setAttribute( 'inert', '' );
			} else {
				wrapperEl.removeAttribute( 'inert' );
			}
		}

		function getFocusableElements() {
			const dialogEl = $dialog.get( 0 );
			const dialogRect = dialogEl.getBoundingClientRect();

			return $dialog.find( focusableSelector ).filter( function () {
				if ( this.closest( '[inert]' ) ) {
					return false;
				}

				const style = window.getComputedStyle( this );
				if ( 'none' === style.display || 'hidden' === style.visibility ) {
					return false;
				}

				const rect = this.getBoundingClientRect();
				if ( rect.width <= 0 || rect.height <= 0 ) {
					return false;
				}

				return rect.right > dialogRect.left &&
					rect.left < dialogRect.right &&
					rect.bottom > dialogRect.top &&
					rect.top < dialogRect.bottom;
			} );
		}

		function isOpen() {
			return $wrapper.hasClass( 'active' );
		}

		function openHamburger() {
			lastFocused = document.activeElement;
			$toggle.add( $wrapper ).addClass( 'active' );
			$toggle.attr( 'aria-expanded', 'true' );
			$wrapper.attr( 'aria-hidden', 'false' );
			setHamburgerInert( false );

			window.setTimeout( function () {
				$close.trigger( 'focus' );
			}, 50 );
		}

		function closeHamburger() {
			$toggle.add( $wrapper ).removeClass( 'active' );
			$toggle.attr( 'aria-expanded', 'false' );
			$wrapper.attr( 'aria-hidden', 'true' );
			setHamburgerInert( true );

			if ( lastFocused && typeof lastFocused.focus === 'function' ) {
				lastFocused.focus();
			} else {
				$toggle.trigger( 'focus' );
			}
		}

		function toggleHamburger() {
			if ( isOpen() ) {
				closeHamburger();
			} else {
				openHamburger();
			}
		}

		$( '.eronex-hamburger-toggle-btn, .eronex-hamburger-overlay, .eronex-hamburger-close-btn' ).on(
			'click',
			function ( e ) {
				e.preventDefault();
				toggleHamburger();
			}
		);

		$( document ).on( 'keydown', function ( e ) {
			if ( ! isOpen() ) {
				return;
			}

			if ( 'Escape' === e.key ) {
				e.preventDefault();
				closeHamburger();
				return;
			}

			if ( 'Tab' !== e.key ) {
				return;
			}

			const $focusables = getFocusableElements();
			if ( ! $focusables.length ) {
				e.preventDefault();
				$close.trigger( 'focus' );
				return;
			}

			const closeEl = $close.get( 0 );
			const firstEl = $focusables.get( 0 );
			const lastEl = $focusables.get( $focusables.length - 1 );
			const firstContentEl = firstEl === closeEl ? $focusables.get( 1 ) : firstEl;
			const active = document.activeElement;

			if ( $focusables.length === 1 ) {
				e.preventDefault();
				firstEl.focus();
				return;
			}

			// Tab past the last menu item → close button.
			if ( ! e.shiftKey && active === lastEl ) {
				e.preventDefault();
				closeEl.focus();
				return;
			}

			// Shift+Tab on the close button → last menu item.
			if ( e.shiftKey && active === closeEl ) {
				e.preventDefault();
				lastEl.focus();
				return;
			}

			// Shift+Tab on the first content element → close button.
			if ( e.shiftKey && firstContentEl && active === firstContentEl ) {
				e.preventDefault();
				closeEl.focus();
			}
		} );
	}());

	/* ===================================
			Dropdown
	====================================== */

	$( '.eronex-navbar nav ul.sub-menu' ).each(
		function () {
			const submenu       = $( this );
			const submenuOffset = submenu.offset();
			const submenuWidth  = submenu.outerWidth();
			const bodyWidth     = $( 'body' ).width();

			if (submenuOffset.left + submenuWidth > bodyWidth) {
				submenu.addClass( 'eronex-submenu-edge' );
			}
		}
	);

	const $desktopNav = $( '.eronex-navbar .eronex-nav' );

	function getDirectSubmenuFocusables( submenu ) {
		return $( submenu ).children( 'li' ).find( '> a, > button, > .menu-item-span > a, > .menu-item-span > button' );
	}

	function setSubmenuInert( submenu, isInert ) {
		if ( 'inert' in submenu ) {
			submenu.inert = isInert;
		}

		submenu.setAttribute( 'aria-hidden', isInert ? 'true' : 'false' );

		getDirectSubmenuFocusables( submenu ).each( function () {
			if ( isInert ) {
				if ( ! this.hasAttribute( 'data-eronex-tabindex' ) ) {
					this.setAttribute( 'data-eronex-tabindex', this.hasAttribute( 'tabindex' ) ? this.getAttribute( 'tabindex' ) : '' );
				}
				this.setAttribute( 'tabindex', '-1' );
			} else if ( this.hasAttribute( 'data-eronex-tabindex' ) ) {
				const prev = this.getAttribute( 'data-eronex-tabindex' );
				this.removeAttribute( 'data-eronex-tabindex' );
				if ( '' === prev ) {
					this.removeAttribute( 'tabindex' );
				} else {
					this.setAttribute( 'tabindex', prev );
				}
			}
		} );
	}

	function syncDesktopSubmenus() {
		$desktopNav.find( 'ul.sub-menu' ).each( function () {
			const $parent = $( this ).parent( 'li' );
			const isOpen = $parent.hasClass( 'focus' ) || $parent.is( ':hover' );
			setSubmenuInert( this, ! isOpen );
		} );
	}

	function syncHeaderSearch() {
		$( '.eronex-header-search' ).each( function () {
			const expanded = $( this ).closest( '.eronex-navbar' ).hasClass( 'eronex-search-expand' );
			const label = $( this ).find( '.search-form label' ).get( 0 );
			const field = $( this ).find( '.search-field' ).get( 0 );

			if ( label && 'inert' in label ) {
				label.inert = ! expanded;
			}

			if ( field ) {
				if ( expanded ) {
					field.removeAttribute( 'tabindex' );
				} else {
					field.setAttribute( 'tabindex', '-1' );
				}
			}
		} );
	}

	if ( $desktopNav.length ) {
		syncDesktopSubmenus();

		$desktopNav.on( 'focusin', 'li', function () {
			$( this ).addClass( 'focus' );
			syncDesktopSubmenus();
		} ).on( 'focusout', 'li', function () {
			const $item = $( this );
			window.setTimeout( function () {
				if ( ! $item.find( ':focus' ).length ) {
					$item.removeClass( 'focus' );
					syncDesktopSubmenus();
				}
			}, 0 );
		} ).on( 'mouseenter mouseleave', 'li', function () {
			syncDesktopSubmenus();
		} );
	}

	syncHeaderSearch();

	/* ===================================
			Hamburger Sliding Menu
	====================================== */

	$( '.eronex-hamburger-nav' ).eronexSlideMenu(
		{
			dropdownSelector: '.eronex-dropdown-icon',
		}
	);

}(jQuery));
