(function() {
    function showToast(message, type) {
        let toast = document.createElement('div');
        toast.className = 'toast-notification toast-notification--' + type;
        toast.textContent = message;
        document.body.appendChild(toast);
        requestAnimationFrame(function() { toast.classList.add('show'); });
        setTimeout(function() {
            toast.classList.remove('show');
            setTimeout(function() { toast.remove(); }, 300);
        }, 4000);
    }

    let filter = document.getElementById('categoryFilter');
    let table = document.getElementById('blocksTable');
    let countEl = document.getElementById('blockCount');
    if (!table) return;

    let tbody = table.querySelector('tbody');
    let rows = Array.from(tbody.querySelectorAll('tr'));
    let totalCount = rows.length;

    // --- Category Filtering ---
    filter.addEventListener('change', function() {
        let value = this.value;
        let visible = 0;
        rows.forEach(function(row) {
            if (!value || row.getAttribute('data-category') === value) {
                row.classList.remove('hidden-row');
                visible++;
            } else {
                row.classList.add('hidden-row');
            }
        });
        countEl.textContent = visible + ' of ' + totalCount + ' blocks';
        if (!value) {
            countEl.textContent = totalCount + ' blocks';
        }
    });

    // --- Status Toggle ---
    document.querySelectorAll('.toggleStatusBtn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            let blockId = this.getAttribute('data-block-id');
            let currentActive = this.getAttribute('data-active') === '1';
            let newActive = !currentActive;
            let button = this;

            fetch('/admin/blocks/ajax/toggle-active', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({ id: parseInt(blockId), is_active: newActive })
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                if (data.success) {
                    button.setAttribute('data-active', data.is_active ? '1' : '0');
                    if (data.is_active) {
                        button.textContent = 'Active';
                        button.className = 'toggleStatusBtn toggleStatusBtn--active';
                        showToast('Block is now active and available in the block picker.', 'success');
                    } else {
                        button.textContent = 'Inactive';
                        button.className = 'toggleStatusBtn toggleStatusBtn--inactive';
                        showToast('Block is now inactive and hidden from the block picker. Existing instances are not affected.', 'info');
                    }
                } else {
                    alert('Failed to update status: ' + (data.error || 'Unknown error'));
                }
            })
            .catch(function(error) {
                console.error('Error toggling status:', error);
                alert('Failed to update status. Please try again.');
            });
        });
    });

    // --- Delete Block ---
    document.querySelectorAll('.deleteBlockBtn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            let blockId = this.getAttribute('data-block-id');
            let blockName = this.getAttribute('data-block-name');
            let button = this;

            if (!confirm('Delete "' + blockName + '"? This cannot be undone.')) {
                return;
            }

            fetch('/admin/blocks/' + blockId, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({ _method: 'DELETE' })
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                if (data.success) {
                    let row = button.closest('tr');
                    row.style.transition = 'opacity 0.3s';
                    row.style.opacity = '0';
                    setTimeout(function() {
                        row.remove();
                        // Update rows array and count
                        rows = rows.filter(function(r) { return r !== row; });
                        totalCount = rows.length;
                        countEl.textContent = totalCount + ' blocks';
                    }, 300);
                    showToast('Block "' + blockName + '" deleted successfully.', 'success');
                } else {
                    showToast(data.error || 'Failed to delete block.', 'error');
                }
            })
            .catch(function(error) {
                console.error('Error deleting block:', error);
                showToast('Failed to delete block. Please try again.', 'error');
            });
        });
    });

    // --- Column Sorting ---
    let sortHeaders = table.querySelectorAll('th.sortable');
    let currentSort = { key: null, dir: 'asc' };

    sortHeaders.forEach(function(th) {
        th.addEventListener('click', function() {
            let key = this.getAttribute('data-sort');
            let dir = 'asc';
            if (currentSort.key === key && currentSort.dir === 'asc') {
                dir = 'desc';
            }
            currentSort = { key: key, dir: dir };

            // Update header classes
            sortHeaders.forEach(function(h) {
                h.classList.remove('asc', 'desc');
            });
            this.classList.add(dir);

            // Sort rows
            let attr = key === 'name' ? 'data-name' : 'data-category-name';
            rows.sort(function(a, b) {
                let valA = a.getAttribute(attr) || '';
                let valB = b.getAttribute(attr) || '';
                let cmp = valA.localeCompare(valB);
                return dir === 'desc' ? -cmp : cmp;
            });

            // Re-append sorted rows
            rows.forEach(function(row) {
                tbody.appendChild(row);
            });
        });
    });
})();
