jQuery(function() {
    const filterInput = jQuery('#vwpte-excel-table-filter');
    const vwpete_tableElement = jQuery('#vwpte-excel-table'); 
    const vwpete_tableBody = vwpete_tableElement.find('tbody');  
    const vwpete_rows = vwpete_tableBody.children('tr');        
    let timeoutId;
    const debounceDelay = 200; // milliseconds

    filterInput.on('keyup', function() {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
            const query = jQuery(this).val().toLowerCase().split(',').map(s => s.trim()).filter(s => s);

            for (let i = 0; i < vwpete_rows.length; i++) {
                const vwpete_row = vwpete_rows[i];
                const vwpete_rowText = vwpete_row.textContent.toLowerCase();
                const match = query.every(term => vwpete_rowText.includes(term));
                vwpete_row.style.display = match ? '' : 'none';
            }
        }, debounceDelay);
    });

    
});


let sortDirection = 1; // 1 = asc, -1 = desc

  jQuery('#vwpte-excel-table th').on('click', function() {
    const colIndex = jQuery(this).index();
    const rows = jQuery('#vwpte-excel-table tbody tr').get();

    const isNumeric = jQuery.isNumeric(jQuery(rows[0]).children('td').eq(colIndex).text());

    rows.sort(function(a, b) {
      const A = jQuery(a).children('td').eq(colIndex).text();
      const B = jQuery(b).children('td').eq(colIndex).text();

      return isNumeric
        ? (parseFloat(A) - parseFloat(B)) * sortDirection
        : A.localeCompare(B) * sortDirection;
    });

    // Toggle direction for next click
    sortDirection *= -1;

    jQuery.each(rows, function(index, row) {
      jQuery('#vwpte-excel-table tbody').append(row);
    });
});