/**
 * @fileoverview Manages the contacts filtering functionality.
 * This file handles:
 * - Contact search with debounced input
 * - Filter form submission
 * - Search state persistence
 * - Filter clearing functionality
 */

/**
 * Creates a debounced version of a function that delays its execution
 * until after a specified wait time has elapsed since the last time it was invoked.
 * This helps prevent excessive form submissions during rapid user input.
 * @function
 * @param {Function} func - The function to debounce
 * @param {number} wait - The number of milliseconds to delay (300ms default for search)
 * @returns {Function} A debounced version of the provided function
 */
function debounce(func, wait) {
    let timeout;
    return function(...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, args), wait);
    };
}

/**
 * Initializes the contacts filter functionality when the DOM is loaded.
 * Sets up:
 * - Auto-submit on select changes
 * - Debounced search input with cursor position persistence
 * - Filter clearing functionality
 * @function
 */
document.addEventListener('DOMContentLoaded', function() {
    // Auto-submit the form on select change
    document.querySelectorAll('#filterForm select').forEach(function(el) {
        el.addEventListener('change', function() {
            document.getElementById('filterForm').submit();
        });
    });

    // Debounced submit for search input, keep cursor after reload
    const searchInput = document.querySelector('#filterForm input[name="search"]');
    if (searchInput) {
        searchInput.addEventListener('input', debounce(function() {
            // Save value and cursor position
            sessionStorage.setItem('searchFocus', '1');
            sessionStorage.setItem('searchValue', searchInput.value);
            sessionStorage.setItem('searchPos', searchInput.selectionStart);
            document.getElementById('filterForm').submit();
        }, 300));

        // On page load, restore focus and cursor position if needed
        if (sessionStorage.getItem('searchFocus') === '1') {
            searchInput.focus();
            const val = sessionStorage.getItem('searchValue') || '';
            const pos = parseInt(sessionStorage.getItem('searchPos')) || val.length;
            searchInput.value = val;
            searchInput.setSelectionRange(pos, pos);
            // Clean up
            sessionStorage.removeItem('searchFocus');
            sessionStorage.removeItem('searchValue');
            sessionStorage.removeItem('searchPos');
        }
    }

    /**
     * Handles the clear filters button click.
     * Resets all filter inputs and submits the form.
     * @event
     */
    document.getElementById('clearFilters').addEventListener('click', function() {
        document.querySelector('#filterForm input[name="search"]').value = '';
        document.querySelector('#filterForm select[name="role"]').selectedIndex = 0;
        document.getElementById('filterForm').submit();
    });
}); 