window.addEventListener('DOMContentLoaded', () => {
    const selectAll = document.getElementById('select-all');
    const checks = () => Array.from(document.querySelectorAll('.row-check'));
    const counter = document.getElementById('selection-counter');
    const bulkBtn = document.getElementById('delete-selected');

    function refreshState() {
        const picked = checks().filter(c => c.checked);
        counter.textContent = `${picked.length} zaznaczonych`;
        bulkBtn.disabled = picked.length === 0;
    }

    if (selectAll) {
        selectAll.addEventListener('change', () => {
            checks().forEach(c => { c.checked = selectAll.checked; });
            refreshState();
        });
    }
    checks().forEach(c => c.addEventListener('change', refreshState));
    refreshState();

    const delAll = document.getElementById('delete-all-btn');
    if (delAll) {
        delAll.addEventListener('click', async () => {
            if (!confirm('Na pewno usunąć WSZYSTKIE bany?')) return;
            try {
                const res = await fetch(window.DELETE_ALL_BANS_URL, { method: 'DELETE' });
                const data = await res.json();
                if (data.status === 'all_bans_removed') {
                    window.location.reload();
                } else {
                    window.showToast?.({ text: 'Błąd podczas usuwania', variant: 'danger' });
                }
            } catch (e) {
                window.showToast?.({ text: 'Błąd sieci', variant: 'danger' });
            }
        });
    }
});