/**
 * Custom JS for theme elements.
 *
 * @package Euphony_Blocks
 */

( function () {
	'use strict';

	/**
	 * WooCommerce active class for the category list.
	 */
	var currentUrl = window.location.href;

	document.querySelectorAll( '.wc-block-product-categories-list li a' ).forEach( function ( item ) {
		if ( item.href === currentUrl ) {
			item.classList.add( 'active' );
		}
	} );

	/**
	 * Toggle a body class when the search or social control is clicked.
	 *
	 * @param {string} triggerSelector   Selector for the control that opens the panel.
	 * @param {string} containerSelector Selector for the panel itself.
	 * @param {string} openClass         Body class applied while the panel is open.
	 * @param {string} closeClass        Body class removed when this panel opens.
	 * @param {string} focusSelector     Optional selector to focus once open.
	 */
	function bindPanelToggle( triggerSelector, containerSelector, openClass, closeClass, focusSelector ) {
		var trigger = document.querySelector( triggerSelector );

		if ( ! trigger ) {
			return;
		}

		trigger.addEventListener( 'click', function () {
			document.body.classList.remove( closeClass );
			document.body.classList.add( openClass );

			document.body.addEventListener( 'click', function () {
				document.body.classList.remove( openClass );
			} );

			var container = document.querySelector( containerSelector );

			if ( container ) {
				container.addEventListener( 'click', function ( event ) {
					event.stopPropagation();
				} );
			}

			if ( focusSelector ) {
				var field = document.querySelector( focusSelector );

				if ( field ) {
					window.setTimeout( function () {
						field.focus();
					}, 0 );
				}
			}
		} );
	}

	function bindPanelClose( triggerSelector, openClass ) {
		var trigger = document.querySelector( triggerSelector );

		if ( ! trigger ) {
			return;
		}

		trigger.addEventListener( 'click', function () {
			document.body.classList.remove( openClass );
		} );
	}

	bindPanelToggle( '.search-controller svg.search', '.search-container', 'open-search', 'open-social', '.wp-block-search__input' );
	bindPanelClose( '.search-controller svg.cross', 'open-search' );

	bindPanelToggle( '.social-controller svg.social', '.social-container', 'open-social', 'open-search', '.wp-block-social__input' );
	bindPanelClose( '.social-controller svg.cross', 'open-social' );

	/**
	 * Put the caret in the search field when the social bar's search icon is used.
	 */
	var blinkerField = document.querySelector( '.social-controller svg.search' );

	if ( blinkerField ) {
		blinkerField.addEventListener( 'click', function () {
			var searchInput = document.querySelector( '.wp-block-search__input' );

			if ( searchInput ) {
				window.setTimeout( function () {
					searchInput.focus();
				}, 0 );
			}
		} );
	}

	/**
	 * Mark the current menu item so it can be styled.
	 */
	document.querySelectorAll( '.wp-block-navigation' ).forEach( function ( navBlock ) {
		var links = navBlock.querySelectorAll( 'a[href]' );

		links.forEach( function ( link ) {
			if ( link.href === window.location.href && link.parentNode ) {
				link.parentNode.classList.add( 'current-nav-item' );
			}
		} );
	} );

	/**
	 * Header search show/hide.
	 */
	document.querySelectorAll( '.wp-primary-search' ).forEach( function ( searchForm ) {
		var body               = document.body;
		var toggleIcon         = searchForm.querySelector( '.wp-search-toggle-container' );
		var searchInnerWrapper = searchForm.querySelector( '.wp-search-container' );
		var searchInput        = searchForm.querySelector( '.wp-block-search__input' );

		// Every one of these is required for the toggle to work; bail if the markup differs.
		if ( ! toggleIcon || ! searchInnerWrapper || ! searchInput ) {
			return;
		}

		document.querySelectorAll( '.search-controller .svg, .social-controller .svg' ).forEach( function ( searchButton ) {
			searchButton.addEventListener( 'click', function () {
				body.classList.remove( 'show-search' );
				searchForm.classList.remove( 'toggled-on' );
			} );
		} );

		toggleIcon.addEventListener( 'click', function () {
			searchForm.classList.toggle( 'toggled-on' );
			body.classList.toggle( 'show-search' );
			searchInput.focus();
		} );

		document.addEventListener( 'click', function ( event ) {
			if (
				! searchInput.contains( event.target ) &&
				! searchInnerWrapper.contains( event.target ) &&
				! toggleIcon.contains( event.target ) &&
				searchForm.classList.contains( 'toggled-on' )
			) {
				searchForm.classList.remove( 'toggled-on' );
				body.classList.remove( 'show-search' );
			}
		} );
	} );

	/**
	 * Add/remove a class for the mobile WooCommerce sidebar widgets and filters.
	 *
	 * @param {string} targetSelector Selector for the toggle buttons.
	 */
	function bindToggleClass( targetSelector ) {
		document.querySelectorAll( targetSelector ).forEach( function ( filterButton ) {
			filterButton.addEventListener( 'click', function () {
				filterButton.classList.toggle( 'toggled-on' );
			} );
		} );
	}

	bindToggleClass( '.btn-mobile-filters' );

	/**
	 * Plus/minus buttons on the product quantity input.
	 */
	var MAX_QTY = 99999;

	function buildQuantityControls() {
		document.querySelectorAll( '.quantity' ).forEach( function ( wrap ) {

			// Never add a second set of buttons when this runs again after a cart update.
			if ( wrap.querySelector( '.quantity-nav' ) ) {
				return;
			}

			var inputs = wrap.querySelectorAll( '.qty' );

			if ( ! inputs.length ) {
				return;
			}

			var nav  = document.createElement( 'div' );
			var up   = document.createElement( 'div' );
			var down = document.createElement( 'div' );

			up.innerHTML   = '+';
			down.innerHTML = '-';
			nav.appendChild( up );
			nav.appendChild( down );
			wrap.appendChild( nav );

			nav.setAttribute( 'class', 'quantity-nav' );
			up.setAttribute( 'class', 'quantity-button quantity-up' );
			down.setAttribute( 'class', 'quantity-button quantity-down' );

			inputs.forEach( function ( input ) {

				/*
				 * Grouped products start each line at zero. This used to key off "more than one
				 * .quantity on the page", which also zeroed every row of the cart.
				 */
				if ( wrap.closest( '.woocommerce-grouped-product-list' ) ) {
					input.value = 0;
				}

				function step( delta ) {
					var oldValue = parseFloat( input.value );

					if ( isNaN( oldValue ) ) {
						oldValue = 0;
					}

					var newValue = oldValue + delta;

					if ( newValue > MAX_QTY ) {
						newValue = MAX_QTY;
					}

					if ( newValue < 0 ) {
						newValue = 0;
					}

					input.value = newValue;
					input.dispatchEvent( new Event( 'change', { bubbles: true } ) );
				}

				up.addEventListener( 'click', function () {
					step( 1 );
				} );

				down.addEventListener( 'click', function () {
					step( -1 );
				} );
			} );
		} );
	}

	buildQuantityControls();

	/*
	 * WooCommerce replaces the cart markup after an update, so rebuild the controls then.
	 * updated_wc_div is the event WooCommerce fires once the new markup is in place, which
	 * is more reliable than the old fixed 5-second timeout.
	 */
	if ( window.jQuery ) {
		window.jQuery( document.body ).on( 'updated_wc_div updated_cart_totals wc_fragments_refreshed', function () {
			buildQuantityControls();
		} );
	}
}() );
