/**
 * Sorting functionality for table columns
 * Handles toggling between ascending, descending, and no sort
 * Preserves other GET parameters and resets pagination
 */

/**
 * Updates the sort parameter in the URL and reloads the page
 * @param {string} field - The field name to sort by
 */
function updateSort(field) {
    // Get current URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    const currentSort = urlParams.get('sort');
    
    let newSort;
    
    // Toggle sort direction logic:
    // 1. If not sorted by this field -> sort ascending (field)
    // 2. If sorted ascending -> sort descending (-field)
    // 3. If sorted descending -> sort ascending (field)
    if (currentSort === field) {
        // Currently ascending, switch to descending
        newSort = '-' + field;
    } else if (currentSort === '-' + field) {
        // Currently descending, switch to ascending
        newSort = field;
    } else {
        // Not sorted by this field, start with ascending
        newSort = field;
    }
    
    // Update sort parameter
    urlParams.set('sort', newSort);
    
    // Reset to first page when sorting changes
    urlParams.delete('page');
    
    // Reload page with new parameters
    window.location.search = urlParams.toString();
}

/**
 * Gets the current sort field and direction
 * @returns {Object} Object with field and direction properties
 */
function getCurrentSort() {
    const urlParams = new URLSearchParams(window.location.search);
    const sort = urlParams.get('sort');
    
    if (!sort) {
        return { field: null, direction: null };
    }
    
    if (sort.startsWith('-')) {
        return {
            field: sort.substring(1),
            direction: 'desc'
        };
    }
    
    return {
        field: sort,
        direction: 'asc'
    };
}

/**
 * Initializes sort indicators on page load
 * Adds visual indicators to show current sort state
 */
function initializeSortIndicators() {
    const currentSort = getCurrentSort();
    
    if (!currentSort.field) {
        return;
    }
    
    // Find all sort headers and update their indicators
    const sortHeaders = document.querySelectorAll('[data-sort-field]');
    sortHeaders.forEach(header => {
        const field = header.getAttribute('data-sort-field');
        
        if (field === currentSort.field) {
            // Add active class or update icon
            header.classList.add('sort-active');
            
            // Update icon if present
            const icon = header.querySelector('.sort-icon');
            if (icon) {
                if (currentSort.direction === 'asc') {
                    icon.className = 'bi bi-arrow-up sort-icon';
                } else {
                    icon.className = 'bi bi-arrow-down sort-icon';
                }
            }
        }
    });
}

// Initialize sort indicators when DOM is ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeSortIndicators);
} else {
    initializeSortIndicators();
}
