/* jshint esversion: 6 */
if ( 'function' !== typeof window.vcexSearchbarClear ) {
	window.vcexSearchbarClear = function() {

		const removeClasses = ( el ) => {
			el.classList.remove( 'vcex-searchbar-clear--hidden', 'wpex-invisible', 'wpex-opacity-0' );
		};

		const addClasses = ( el ) => {
			el.classList.add( 'vcex-searchbar-clear--hidden', 'wpex-invisible', 'wpex-opacity-0' );
		};

		document.querySelectorAll( '.vcex-searchbar-clear' ).forEach( ( button ) => {
			const element = button.closest( '.vcex-searchbar' );
			const input = element.querySelector( '.vcex-searchbar-input' );
			const onClick = () => {
				input.value = '';
				input.focus();
				addClasses( button );
			};
			if ( input && input.value ) {
				removeClasses( button );
			}
			input.addEventListener( 'input', function() {
				if ( input.value ) {
					removeClasses( button );
				} else {
					addClasses( button );
				}
			} );
			button.addEventListener( 'click', onClick );
			button.addEventListener( 'keypress', onClick );
		} );
	};
}

if ( document.readyState === 'interactive' || document.readyState === 'complete' ) {
	setTimeout( vcexSearchbarClear, 0 );
} else {
	document.addEventListener( 'DOMContentLoaded', vcexSearchbarClear, false );
}