/**
 * This function initializes the Matador Jobs Pro orderby functionality.
 * It adds an event listener to the orderby select element, which updates the URL with the selected orderby value.
 * Additionally, it hides the re-order submit button if it exists.
 *
 * @since 3.9.0
 *
 * @returns {void}
 */
(function () {
    'use strict';

    /**
     * Select elements with class 'matador-orderby-form > select'
     * @type {NodeList}
     */
    const orderbySelects = document.querySelectorAll( '.matador-orderby-form > select' );

    // If no orderby select elements found, return early
    if (  !orderbySelects || orderbySelects.length === 0  ) return;

    // If more than one orderby select element found, log an error and return early
    if ( 1 < orderbySelects.length) return console.error( 'Multiple Matador Orderby elements found on this page. Only one per page is supported.' );

    /**
     * The first orderby select element
     * @type {HTMLSelectElement}
     */
    const orderbySelect = orderbySelects[0];

    // Add event listener to the orderby select element
    orderbySelect.addEventListener('change', function (event) {
        event.preventDefault();

        // Create a new URL object from the current window location
        const currentUrl = new URL(window.location.href);

        // Update the search parameters with the selected orderby value
        currentUrl.searchParams.set('matador-jobs-orderby', event.target.value);

        // Redirect to the updated URL
        window.location.href = currentUrl.toString();
    });

    /**
     * The re-order submit button
     * @type {HTMLButtonElement}
     */
    const reOrderButton = document.querySelector('#re-order-submit');

    // If the re-order submit button exists, hide it as submitting the form is handled by the event listener above
    if ( reOrderButton ) { 
        reOrderButton.style.display = 'none';
    }
})();
