Substitute Iago Aspas struck in stoppage-time to earn Spain a dramatic 2-2 draw with Morocco which gave them top spot in the FIFA World Cup Group B and a place in the last 16.
With Morocco heading towards their first win of the tournament, Aspas cleverly back-heeled the ball into the net to cancel out Youssef En-Nesyri's brilliant 81st-minute header for Morocco.
The Spanish equaliser was originally ruled out for offside but awarded after a lengthy review by the video referee amid chaotic scenes on the pitch.
Spain took top spot from Portugal on goals scored after the European champions were held to a 1-1 draw by Iran who equalised in stoppage-time.
Spain will play Russia in the last 16, while Portugal meet Uruguay, who earlier beat Russia 3-0 to top Group A.
Read more of our FIFA 2018 coverage:
"There was a lot of uncertainty, we didn't know we had finished top until some team mates told me," Aspas said.
"The important thing is that we are through and finished top of the group.
"Everyone would have taken finishing top of the group when the draw was made, then you have to think about everything that has happened [referring to the sacking of coach Julen Lopetegui], but we have just focused on working hard."
The first team eliminated from the World Cup following two 1-0 losses, Morocco began to play with the intensity that indicated they had every intention of returning home with a Spanish scalp and Khalid Boutaid put them ahead in the 14th minute.
Snatching the ball from Sergio Ramos in midfield, Boutaid ran through alone and coolly slotted home between the legs of David de Gea for Morocco's first goal of the World Cup and their first at the global showpiece tournament for 20 years.
The goal shocked Spain into action and Isco equalised for the 2010 world champions five minutes later, taking Andres Iniesta's pass and crashing it into the roof of the net.
Spain nearly grabbed a second just before halftime when Iniesta fired a low pass across the goalmouth that a sliding Diego Costa just missed getting his foot to.
Morocco returned to the pitch with renewed purpose after the break, taking the play to Spain and Nordin Amrabat nearly gave the North Africans the lead in the 56th minute when his thunderbolt from 25 yards clanged off the far post and crossbar.
It was Spain's turn to go close next as Morocco defender Romain Saiss cleared Isco's header off the line.
With time running out Spain finally began to play with urgency but could not find the equaliser until Aspas struck and his goal was finally given after a long wait for VAR confirmation.
"We leave the World Cup with our heads held high," Morocco midfielder Faycal Fajr said.
"We gave everything, we defended our colours."