/**
 * Elementor frontend handler — Product Filter widget.
 *
 * On submit it collapses the checkbox groups into the comma-separated query
 * parameters WooCommerce's WC_Query understands (filter_<attr> + query_type_<attr>
 * and rating_filter), and trims empty fields so the resulting URL stays clean.
 *
 * @package captain-widgets-kit
 * @since   1.3.0
 */
( function ( $, window, document ) {
	'use strict';

	/**
	 * Per-instance handler.
	 *
	 * @param {HTMLElement} form Filter form element.
	 */
	function setupInstance( form ) {
		if ( ! form || form.captwikiFilterReady ) {
			return;
		}
		form.captwikiFilterReady = true;

		form.addEventListener( 'submit', function () {

			// Remove hidden inputs added by a previous (cancelled) submit attempt.
			form.querySelectorAll( '.captwiki-filter__built' ).forEach( function ( el ) {
				el.parentNode.removeChild( el );
			} );

			// Group checked boxes by their target query key.
			var groups = {};
			form.querySelectorAll( '.captwiki-filter__check:checked' ).forEach( function ( box ) {
				var key = box.getAttribute( 'data-key' );
				if ( ! key ) {
					return;
				}
				( groups[ key ] = groups[ key ] || [] ).push( box.value );
			} );

			Object.keys( groups ).forEach( function ( key ) {
				addHidden( form, key, groups[ key ].join( ',' ) );

				// Attribute filters need a matching query_type_<attr>=or.
				if ( key.indexOf( 'filter_' ) === 0 ) {
					addHidden( form, 'query_type_' + key.slice( 7 ), 'or' );
				}
			} );

			// Drop empty price / category fields so they don't pollute the URL.
			form.querySelectorAll( '.captwiki-filter__price' ).forEach( function ( input ) {
				if ( ! input.value ) {
					input.disabled = true;
				}
			} );

			var checkedCat = form.querySelector( 'input[name="product_cat"]:checked' );
			if ( checkedCat && ! checkedCat.value ) {
				checkedCat.disabled = true;
			}
		} );
	}

	/**
	 * Append a disabled-safe hidden input to the form.
	 *
	 * @param {HTMLElement} form  Form element.
	 * @param {string}      name  Field name.
	 * @param {string}      value Field value.
	 */
	function addHidden( form, name, value ) {
		var input = document.createElement( 'input' );
		input.type = 'hidden';
		input.name = name;
		input.value = value;
		input.className = 'captwiki-filter__built';
		form.appendChild( input );
	}

	$( window ).on( 'elementor/frontend/init', function () {
		elementorFrontend.hooks.addAction(
			'frontend/element_ready/captwiki-woo-product-filter.default',
			function ( $scope ) {
				setupInstance( $scope[ 0 ].querySelector( '.captwiki-filter' ) );
			}
		);
	} );

	$( function () {
		document.querySelectorAll( '.captwiki-filter' ).forEach( setupInstance );
	} );

} )( jQuery, window, document );
