Morse theory of Euclidean distance functions and applications to real algebraic geometry