/**
 * Header search toggle + sticky transparent header.
 */
( function () {
	'use strict';

	function ready( fn ) {
		if ( document.readyState !== 'loading' ) {
			fn();
		} else {
			document.addEventListener( 'DOMContentLoaded', fn );
		}
	}

	ready( function () {
		var header = document.getElementById( 'header' );
		var searchToggle = document.querySelector( '.hbs-search-toggle' );
		var searchDropdown = document.getElementById( 'hbs-header-search-form' );

		if ( searchToggle && searchDropdown ) {
			searchToggle.addEventListener( 'click', function ( e ) {
				e.preventDefault();
				e.stopPropagation();
				var isOpen = ! searchDropdown.hasAttribute( 'hidden' );
				if ( isOpen ) {
					searchDropdown.setAttribute( 'hidden', '' );
					searchToggle.setAttribute( 'aria-expanded', 'false' );
				} else {
					searchDropdown.removeAttribute( 'hidden' );
					searchToggle.setAttribute( 'aria-expanded', 'true' );
					var input = searchDropdown.querySelector( 'input[type="search"], input[type="text"]' );
					if ( input ) {
						input.focus();
					}
				}
			} );

			document.addEventListener( 'click', function ( e ) {
				if ( ! e.target.closest( '.hbs-header-search' ) ) {
					searchDropdown.setAttribute( 'hidden', '' );
					searchToggle.setAttribute( 'aria-expanded', 'false' );
				}
			} );
		}

		if ( header && header.classList.contains( 'hbs-header--transparent' ) ) {
			var onScroll = function () {
				if ( window.scrollY > 40 ) {
					if ( ! header.classList.contains( 'is-scrolled' ) ) {
						header.classList.add( 'is-scrolled' );
						document.body.style.paddingTop = header.offsetHeight + 'px';
					}
				} else {
					header.classList.remove( 'is-scrolled' );
					document.body.style.paddingTop = '';
				}
			};
			onScroll();
			window.addEventListener( 'scroll', onScroll, { passive: true } );
		}
	} );
}() );
