document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', async (e) => {
            const input = e.target;

            const permissionUUID = input.dataset.permissionUuid;
            const userGroupUUID = input.dataset.userGroupUuid;
            const permissionValue = input.dataset.value;
            const apiUrl = input.dataset.apiUrl;

            // Revert the checkbox immediately; only mark it again on success
            input.checked = !input.checked;
            input.disabled = true;

            // Build URL-encoded form data
            const formData = new URLSearchParams();
            formData.append('permission_uuid', permissionUUID);
            formData.append('user_group_uuid', userGroupUUID);
            formData.append('permission_value', permissionValue);
            formData.append('X-HTTP-Method-Override', 'PUT')

            try {
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: formData.toString()
                });

                if (response.ok) {
                    // Uncheck all switches in the same group
                    const groupSelector = `input[data-permission-uuid="${permissionUUID}"][data-user-group-uuid="${userGroupUUID}"]`;
                    document.querySelectorAll(groupSelector).forEach(cb => cb.checked = false);

                    // Then check the selected one
                    input.checked = true;
                } else {
                    console.error('API error:', response.status);
                    // Leave checkbox state unchanged (reverted above)
                }
            } catch (err) {
                console.error('Network error:', err);
                // Leave checkbox state unchanged (reverted above)
            } finally {
                input.disabled = false;
            }
        });
    });
});