Merkel and allies lose votes but hang on in German elections as AfD surges