/// --------------------------------------------------
/// Multiselect Dropdown JS for W2PShop Settings Page
/// ---------------------------------------------------
jQuery( document ).ready(
	function () {
		jQuery( '.w2p-multiselect-dropdown' ).each(
			function () {
				let select    = jQuery( this ),
				options       = select.find( 'option' ),
				hiddenElement = jQuery( '#' + select.data( 'input' ) );

				// Create a container to hold the checkboxes
				let container = jQuery( '<div class="w2pshop-multi-select-container"></div>' );
				select.before( container );

				// Hide the original select
				select.hide();

				// Add checkboxes for each option
				options.each(
					function () {
						let option    = jQuery( this );
						let isChecked = option.is( ':selected' );
						let checkbox  = jQuery( '<label><input type="checkbox" value="' + option.val() + '"' + (isChecked ? ' checked' : '') + '>' + option.text() + '</label>' );

						// Append the checkbox to the container
						container.append( checkbox );

						// Pre-select the option in the original select if necessary
						if (isChecked) {
							option.prop( 'selected', true );
						}

						// Update the select when a checkbox is changed
						checkbox.on(
							'change',
							'input[type="checkbox"]',
							function () {
								option.prop( 'selected', jQuery( this ).is( ':checked' ) );
								updateHiddenInput( hiddenElement );
							}
						);
					}
				);

				// Function to update the hidden input
				function updateHiddenInput(hiddenElement) {
					if (typeof hiddenElement === 'undefined') {
						return;
					}

					let selectedOptions = [];
					container.find( 'input[type="checkbox"]:checked' ).each(
						function () {
							selectedOptions.push( jQuery( this ).val() );
						}
					);
					hiddenElement.val( selectedOptions.join( ',' ) );
				}

				// Initial update in case some checkboxes are pre-checked
				updateHiddenInput( hiddenElement );
			}
		);
	}
);