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

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

    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') {
            table.querySelectorAll('.selected-row').forEach(selectedRow => {
                if (selectedRow !== row) {
                    selectedRow.classList.remove('selected-row');
                    selectedRow.querySelector('input[type="checkbox"]').checked = false;
                }
            });
        }
        row.classList.toggle('selected-row');
        checkbox.checked = !checkbox.checked;
        const selectedRows = table.querySelectorAll('.selected-row');

        document.querySelectorAll('[data-requires-selection]').forEach(button => {
            button.disabled = selectedRows.length === 0;
        });
    });

    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);
        });
        document.querySelectorAll('[data-requires-selection]').forEach(button => {
            button.disabled = !allSelected;
        });
        this.textContent = allSelected ? 'Unselect All' : 'Select All';
    });

    // Edit button click handler
    if (editBtn) {
        editBtn.addEventListener('click', function() {
            const selectedRow = table.querySelector('.selected-row');
            if (selectedRow) {
                const objectId = selectedRow.dataset.id;
                const editUrl = editBtn.dataset.url.replace('0', objectId);
                window.location.href = editUrl;
            }
        });
    }

    // Delete modal logic
    const deleteModal = document.getElementById('deleteModal');
    const cancelDelete = document.getElementById('cancelDelete');
    const confirmDelete = document.getElementById('confirmDelete');
    let selectedId = null;

    if (deleteBtn) {
        deleteBtn.addEventListener('click', function() {
            const selectedRow = table.querySelector('.selected-row');
            if (selectedRow) {
                selectedId = selectedRow.dataset.id;
                deleteModal.style.display = 'block';
            }
        });
    }

    cancelDelete.addEventListener('click', function() {
        deleteModal.style.display = 'none';
    });

    confirmDelete.addEventListener('click', function() {
        if (selectedId) {
            const deleteUrl = deleteBtn.dataset.url.replace('0', selectedId);

            fetch(deleteUrl, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': getCookie('csrftoken')
                },
            })
            .then(response => {
                if (response.ok) {
                    window.location.reload(); // This reloads the page after success
                } else {
                    alert('Error deleting item');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error deleting item');
            });
        }
        deleteModal.style.display = 'none';
    });

    window.addEventListener('click', function(event) {
        if (event.target === deleteModal) {
            deleteModal.style.display = 'none';
        }
    });

    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    const filterInput = document.getElementById('filterInput');
    const activeBtn = document.getElementById('activeBtn');
    const allBtn = document.getElementById('allBtn');
    const filterForm = document.getElementById('filterForm');

    if (activeBtn && allBtn && filterInput && filterForm) {
        // Read filter from cookie if present
        const filterCookie = getCookie('list_filter');
        if (filterCookie && !filterInput.value) {
            filterInput.value = filterCookie;
        }

        function updateButtons() {
            if (filterInput.value === 'all') {
                allBtn.classList.add('active');
                activeBtn.classList.remove('active');
            } else {
                activeBtn.classList.add('active');
                allBtn.classList.remove('active');
            }
        }

        updateButtons();

        activeBtn.addEventListener('click', function() {
            filterInput.value = 'active';
            document.cookie = 'list_filter=active;path=/';
            updateButtons();
            filterForm.submit();
        });

        allBtn.addEventListener('click', function() {
            filterInput.value = 'all';
            document.cookie = 'list_filter=all;path=/';
            updateButtons();
            filterForm.submit();
        });
    }
});