Spanish Prime Minister Pedro Sánchez’s Socialists posted unexpected gains in a regional ballot that halted what had seemed to be an unstoppable rise for the far right.