if ( 'function' !== typeof window.wpexWcCartDropdown ) {
	window.wpexWcCartDropdown = function() {
		var cartDropdown = document.querySelector( '#current-shop-items-dropdown' );

		if ( ! cartDropdown ) {
			return;
		}

		var toggleBtn = null;
		var isOpen    = false;
		var targets   = 'a.toggle-cart-widget, li.toggle-cart-widget > a, li.toggle-header-cart > a, .wpex-header-cart-icon button';

		var show = function() {
			cartDropdown.classList.add( 'show' );
			cartDropdown.classList.remove( 'wpex-invisible', 'wpex-opacity-0' );

			document.querySelectorAll( targets ).forEach( function( element ) {
				element.classList.add( 'active' );
				element.setAttribute( 'aria-expanded', 'true' );
			} );

			if ( 'function' === typeof jQuery ) {
				jQuery( document ).trigger( 'show.wpex.menuCart' );
			}

			var focus = function( event ) {
				if ( 'object' === typeof wpex && 'function' === typeof wpex.focusOnElement ) {
					wpex.focusOnElement( cartDropdown );
				}
				cartDropdown.removeEventListener( 'transitionend', focus ); // remove event as it keeps triggering.
			};

			// Focus on the search when opening after transition is complete to prevent issues.
			cartDropdown.addEventListener( 'transitionend', focus );

			isOpen = true;
		};

		var hide = function() {
			cartDropdown.classList.remove( 'show' );
			cartDropdown.classList.add( 'wpex-invisible', 'wpex-opacity-0' );
			document.querySelectorAll( targets ).forEach( function( element ) {
				element.classList.remove( 'active' );
				element.setAttribute( 'aria-expanded', 'false' );
			} );
			if ( toggleBtn ) {
				toggleBtn.focus();
			}
			isOpen = false;
		};

		document.addEventListener( 'click', function( event ) {
			toggleBtn = event.target.closest( targets );
			if ( ! toggleBtn ) {
				if ( ! event.target.closest( '#current-shop-items-dropdown' ) && isOpen ) {
					hide();
				}
				return;
			}
			if ( toggleBtn.classList.contains( 'go-to-shop' ) ) {
				return;
			}
			event.preventDefault();
			if ( isOpen ) {
				hide();
			} else {
				show();
			}
		} );

		document.addEventListener( 'keydown', function( event ) {
			var code = event.keyCode || event.which;
			if ( 27 === code && isOpen ) {
				hide();
			}
		} );
	};
}

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