function searchTable() {
    const input = document.getElementById("searchInput");
    const filter = input.value; // Entfernung von .toUpperCase()
    const table = document.getElementById("phonebookTable");
    const tr = table.getElementsByTagName("tr");

    for (let i = 1; i < tr.length; i++) {
        let visible = false;
        const td = tr[i].getElementsByTagName("td");
        for (let j = 0; j < td.length; j++) {
            if (td[j]) {
                const txtValue = td[j].textContent || td[j].innerText;
                if (txtValue.indexOf(filter) > -1) { // Entfernung von .toUpperCase()
                    visible = true;
                    break;
                }
            }
        }
        tr[i].style.display = visible ? "" : "none";
    }
}

let lastSortedColumn = 0;
let sortDirections = Array(document.querySelectorAll('#phonebookTable th').length).fill('asc');

// Array to keep track of the sort state for each column
let sortStates = [];

function sortTable(n) {
    const table = document.getElementById("phonebookTable");
    const tbody = table.querySelector("tbody");
    const rows = Array.from(tbody.querySelectorAll("tr"));
    const th = table.querySelectorAll("th")[n];

    // Initialize sort state if not set
    if (sortStates[n] === undefined) {
        sortStates[n] = 'asc';
    } else {
        // Toggle sort direction
        sortStates[n] = sortStates[n] === 'asc' ? 'desc' : 'asc';
    }

    const isAsc = sortStates[n] === 'asc';

    // Clear all sorting classes
    table.querySelectorAll("th").forEach(header => header.classList.remove("asc", "desc"));

    // Set the appropriate class for the clicked header
    th.classList.add(isAsc ? "asc" : "desc");

    rows.sort((a, b) => {
        let aValue = a.cells[n].textContent.trim();
        let bValue = b.cells[n].textContent.trim();

        // Check if the values are numbers
        if (!isNaN(aValue) && !isNaN(bValue)) {
            return isAsc ? aValue - bValue : bValue - aValue;
        }

        // For non-numeric values, use localeCompare for proper string comparison
        return isAsc ? 
            aValue.localeCompare(bValue, undefined, {sensitivity: 'base'}) :
            bValue.localeCompare(aValue, undefined, {sensitivity: 'base'});
    });

    // Remove all existing rows
    while (tbody.firstChild) {
        tbody.removeChild(tbody.firstChild);
    }

    // Add sorted rows
    tbody.append(...rows);
}

// Add event listeners to table headers and initial sort
document.addEventListener('DOMContentLoaded', function() {
    const headers = document.querySelectorAll('#phonebookTable th');
    headers.forEach((header, index) => {
        header.addEventListener('click', () => sortTable(index));
    });

    // Initial sort on the first column (index 0) in ascending order
    sortTable(0);
});