( function() {
	'use strict';

	/* ---------------------------------------------------------------
	   SEARCH OVERLAY
	   Replaces the inline WP search expansion with a full-screen
	   overlay modal for a clean UX on all screen sizes.
	   --------------------------------------------------------------- */
	function init() {
		initSearchOverlay();
	}

	function initSearchOverlay() {
		var searchBtn = document.querySelector(
			'.larder-header-search .wp-block-search__button'
		);
		if ( ! searchBtn ) {
			return;
		}

		var overlay = createSearchOverlay();
		document.body.appendChild( overlay );

		var field = overlay.querySelector( '.larder-search-overlay__field' );
		var closeBtn = overlay.querySelector( '.larder-search-overlay__close' );

		searchBtn.addEventListener( 'click', function( e ) {
			e.preventDefault();
			e.stopPropagation();
			openSearch( overlay, field );
		} );

		closeBtn.addEventListener( 'click', function() {
			closeSearch( overlay );
		} );

		overlay.addEventListener( 'click', function( e ) {
			if ( e.target === overlay ) {
				closeSearch( overlay );
			}
		} );

		document.addEventListener( 'keydown', function( e ) {
			if (
				e.key === 'Escape' &&
				overlay.classList.contains( 'is-active' )
			) {
				closeSearch( overlay );
			}
		} );
	}

	function createSearchOverlay() {
		var i18n = window.larderSearch || {};
		var overlay = document.createElement( 'div' );
		overlay.className = 'larder-search-overlay';
		overlay.setAttribute( 'role', 'dialog' );
		overlay.setAttribute( 'aria-label', i18n.label || 'Search' );
		overlay.innerHTML =
			'<button class="larder-search-overlay__close" aria-label="' + ( i18n.close || 'Close search' ) + '">&times;</button>' +
			'<div class="larder-search-overlay__inner">' +
			'<form role="search" action="' +
			( window.location.origin || '/' ) +
			'/">' +
			'<input class="larder-search-overlay__field" type="search" name="s" placeholder="' + ( i18n.placeholder || 'Type to search\u2026' ) + '" autocomplete="off" />' +
			'</form></div>';
		return overlay;
	}

	function openSearch( overlay, field ) {
		overlay.classList.add( 'is-active' );
		document.body.style.overflow = 'hidden';
		setTimeout( function() {
			field.focus();
		}, 100 );
	}

	function closeSearch( overlay ) {
		overlay.classList.remove( 'is-active' );
		document.body.style.overflow = '';
	}

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