document.addEventListener('DOMContentLoaded', function() {
    const table = document.getElementById('objectTable');
    if (!table) return;

    const selectionMode = table.dataset.selectionMode || 'single';
    const toggleSelectAllBtn = document.getElementById('toggleSelectAllBtn');

    if (table.dataset.selectionMode === 'multiple') {
        toggleSelectAllBtn.style.display = 'inline-block';
    }

    table.addEventListener('click', function(e) {
        const row = e.target.closest('.selectable-row');
        if (!row) return;

        const checkbox = row.querySelector('input[type="checkbox"]');
        if (!checkbox) return;

        if (selectionMode === 'single') {
            // Deselect all other rows
            table.querySelectorAll('.selected-row').forEach(selectedRow => {
                if (selectedRow !== row) {
                    selectedRow.classList.remove('selected-row');
                    selectedRow.querySelector('input[type="checkbox"]').checked = false;
                }
            });
        }

        // Toggle current row
        row.classList.toggle('selected-row');
        checkbox.checked = !checkbox.checked;

        // Update buttons state
        const selectedRows = table.querySelectorAll('.selected-row');
        document.querySelectorAll('[data-requires-selection]').forEach(button => {
            button.disabled = selectedRows.length === 0;
        });

        // Handle edit/delete buttons from original crud-list.js
        const objectId = row.dataset.id;
        const editBtn = document.getElementById('editBtn');
        const deleteBtn = document.getElementById('deleteBtn');

        if (editBtn) {
            editBtn.removeAttribute('disabled');
            editBtn.href = editBtn.dataset.url?.replace('0', objectId);
        }
        if (deleteBtn) {
            deleteBtn.removeAttribute('disabled');
        }
    });

    let allSelected = false;
    toggleSelectAllBtn.addEventListener('click', function() {
        const rows = table.querySelectorAll('.selectable-row');
        allSelected = !allSelected;

        rows.forEach(row => {
            const checkbox = row.querySelector('input[type="checkbox"]');
            checkbox.checked = allSelected;
            row.classList.toggle('selected-row', allSelected);
        });

        // Update other buttons state
        document.querySelectorAll('[data-requires-selection]').forEach(button => {
            button.disabled = !allSelected;
        });

        // Update button text
        this.textContent = allSelected ? 'Unselect All' : 'Select All';
    });

});