In your modified code (inside your elseif) you have $thumb = the_post_thumbnail( 'medium' );
.
the_post_thumbnail function is not returning a URL, but the entire image.
When you just need to output the source of the image, you should use the_post_thumbnail_url
.