document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.subtask-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', function () {
            const gid = this.dataset.gid;
            const completed = this.checked;

            fetch('/wp-admin/admin-ajax.php', {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    action: 'afb_toggle_subtask',
                    gid: gid,
                    completed: completed ? 'true' : 'false',
                    security: afb_toggle_subtask_vars.nonce
                })
            })
            .then(res => res.json())
            .then(data => {
                console.log('Toggle response:', data);
                if (!data.success) {
                    if (data.message && data.message.includes('logged in with Asana')) {
                        alert('⚠ You must log in with Asana to complete this task.');
                    } else if (data.message) {
                        alert('❌ Could not update subtask: ' + data.message);
                    } else {
                        alert('❌ Could not update subtask. No detailed error returned.');
                    }
                    this.checked = !completed;
                } else {
                    const parent = this.closest('.flex.items-center');
                    const label = parent.querySelector('a.text-blue-600');
                    if (label) {
                        if (completed) {
                            label.classList.add('line-through', 'text-gray-400');
                        } else {
                            label.classList.remove('line-through', 'text-gray-400');
                        }
                    }
                    const section = this.closest('.mb-4');
                    const checkboxes = section.querySelectorAll('.subtask-checkbox');
                    const total = checkboxes.length;
                    const done = Array.from(checkboxes).filter(cb => cb.checked).length;
                    const percent = Math.round((done / total) * 100);

                    const bar = section.previousElementSibling.querySelector('.bg-blue-500');
                    const labelText = section.previousElementSibling.querySelector('.text-xs.text-gray-500');
                    if (bar) bar.style.width = percent + '%';
                    if (labelText) labelText.textContent = `${done}/${total} complete (${percent}%)`;
                }
            })
            .catch(err => {
                console.error('Fetch error:', err);
                alert('❌ Network or server error. Please try again.');
                this.checked = !completed;
            });
        });
    });
});
