ISTANBUL — Turkey’s electoral authorities on Monday ordered a rerun of the race for mayor of Istanbul, wiping away a crushing defeat for President Recep Tayyip Erdogan but heightening the prospect of social unrest and a new economic crisis.
The opposition party immediately condemned the decision as a blow to the democratic foundations of the country, which has seen an increasingly authoritarian drift under Mr. Erdogan’s 18 years in power.
The extraordinary battle over Istanbul, the country’s largest city and commercial capital, underscored just how deeply wounding the loss had been for Mr. Erdogan and his party.
Though Mr. Erdogan secured another five-year term as president with sweeping new powers last year, he was rendered suddenly vulnerable by his party’s poor showing in the March 31 elections as the economy has begun to falter.
Mr. Erdogan’s Justice and Development Party, the A.K.P., lost control of the capital, Ankara, as well as several important industrial towns in southern Turkey. But the defeat in Istanbul, which has remained his political base and private fief, as well as a source of great wealth and prestige for his family and inner circle, was an especially bitter pill to swallow.
The opposition Republican People’s Party had denounced demands for a new Istanbul election as a bid by Mr. Erdogan and his party to undo the will of the voters, who handed a narrow but bitterly contested victory to the opposition candidate, Ekrem Imamoglu.
Even after a recount of certain contested districts, Mr. Imamoglu was certified as the winner by electoral officials and took up office.
An opposition lawmaker, Mahmut Tanal, described the decision on Twitter as “the murder of law” and “a black stain.” Opposition party leaders gathered in an emergency meeting to weigh whether to boycott a new vote, scheduled for June 23.
“I think this is the greatest distortion of democratic elections in Turkey since the country’s first free and fair polls in 1950,” said Soner Cagaptay, director of the Turkish Research Program at the Washington Institute for Near East Policy.
“This is a sad day for Turkey,” he said. “Never before has the loser in Turkey refused to recognize the outcome of an election. This decision throws into doubt hard-earned consensus in Turkey built over decades that power and government changes hands through democratic elections.”
Turkish political analysts, speaking on condition that they not be named for fear of retribution from the palace, said Mr. Erdogan was furious at the loss of Istanbul.
By one account, he threw a tantrum on the night of the election, which was ultimately decided by a margin of 13,000 votes.
According to another account, the ruling party’s candidate, Binali Yildirim, a former prime minister and close ally of the president, was ready to cede the election but was stopped at the last minute and made to declare victory, most probably by Mr. Erdogan himself.
As electoral officials prepared to certify that Mr. Imamoglu had narrowly won, the president and his party alleged irregularities so broad that they took the extraordinary step of petitioning for the election to be held over.
Mr. Erdogan’s party made its last-ditch appeal on the grounds that banned officials and voters had taken part in the election and that thousands of names had been dropped unlawfully from the electoral rolls.
The proof they offered was far from overwhelming — mainly focused on allegations of a conspiracy — and many of those allegations were dismissed by the 11 judges of the High Election Council.
But Monday’s decision indicated that the judges had accepted the allegations that some polling station officials were not appointed from among public officials, as required under Turkish law.
The decision was 7 to 4 in a body whose independence has been questioned by the opposition since the judges’ terms were extended for another year at the end of 2018 in an amendment put forward by Mr. Erdogan’s party.
Recep Ozel, the A.K.P.’s representative to the election council, said that Mr. Imamoglu’s mandate was now canceled and that the Interior Ministry would appoint an interim mayor until the rerun.
“Everybody participated in the decision with their free will,” Mr. Ozel said. “We have exceeded the quorum. Both who voted in favor or against, made their decision according to their legal views.”
The decision was a blow to the opposition, which had proved itself seemingly well organized for the vote, stationing supporters to monitor the count in every polling station.
Once challenged, Mr. Imamoglu, the opposition candidate, insisted he was ahead and had the documentation to prove it.
There followed a flurry of conflicting messages and political maneuvering from Mr. Erdogan’s camp as the leadership played for time.
Mr. Erdogan himself at times seemed to be ready to concede, amid warnings in Turkey and abroad that, if he tried to cancel the election, the ensuing political turmoil would risk a deeper economic crisis.
The day after the High Election Council confirmed Mr. Imamoglu’s mandate as mayor, Mr. Erdogan gave a prepared speech signaling that he would accept defeat.
“The time is to cool the red-hot iron, to embrace each other and strengthen our unity,” he had said.
But ultimately, Mr. Erdogan joined the effort to fight the humiliating results.
Behind the scenes through the late hours of election night and the days that followed, a fierce power struggle was unfolding between a tight circle of ambitious, hawkish officials around the president who were determined to hold on to Istanbul, and a wider circle of older heads in the party who advised acknowledging defeat in the city.
“With the influence of those circles around him that I identified as a group, he made himself believe that he might get results with the appeal process,” said Abdulkadir Selvi, a columnist known for his close contacts in the government.
That group is believed to be led by Mr. Erdogan’s son-in-law, Berat Albayrak, 41, who was promoted to minister of finance and treasury last year. The interior minister, Suleyman Soylu, 49, has also emerged as an aggressive player.
Mr. Erdogan never went as far as claiming victory, but he did play for time, and he and his allies immediately began trying to reverse the outcome in Istanbul.
The morning after the election, the judge heading the High Election Council confirmed that Mr. Imamoglu was indeed ahead in the race, but the count dragged on and was only completed two days after the election.
Officials of the ruling party then issued a deluge of objections and appeals across Istanbul’s 39 districts to challenge the numbers. Recounts were ordered in five districts and invalid ballots examined and recounted across all districts.
Politicians, party supporters and analysts feverishly followed every recount, claim and counterclaim. The gap between the candidates narrowed bit by bit.
In its campaign, the A.K.P. had urged voters to ‘‘stamp the light bulb’’ — the party logo, which appears on the ballot sheet to aid those who have difficulty reading. Voters do not use a pen but mark their choice with an ink stamp in Turkish elections.
Some A.K.P. voters had stamped the light bulb logo on the ballot sheet, instead of placing the mark in the box provided, technically making the ballots invalid. But on re-examination of the spoiled ballots, officials allowed them to be counted. The A.K.P. slowly gained ground.
But it was still not enough to change the result.
The opposition-run district of Buyukcekmece became a focus. An A.K.P. official announced that two people from the district had been arrested. They including a municipal worker in the census office who had removed more than 3,000 people from the electoral rolls.
Altogether, the worker had made 7,000 irregular entries by registering people in nonexistent or half-built properties, or by adding them to buildings that were already occupied.
Mr. Imamoglu derided the claims, saying that in fact the A.K.P. had been found to be behind several efforts to register people illegally in the district. More than 700 people were removed from the electoral roll by election officials during the formal registration process earlier in the year, opposition officials said.
Attention then turned to another district, Maltepe, where both sides complained that the other was delaying the recount.
After a tense standoff over the ballot boxes, including a fistfight that injured a guard, the police evacuated the hall. The counting resumed.
Ten days into the process, with the numbers still not showing in his favor, Mr. Erdogan said that the irregularities had been organized and criminal and that the election should be canceled. Pro-government newspapers picked up the cry.
After that, Mr. Erdogan held a meeting of his party administration, which was leaning toward applying for cancellation, according to Mr. Selvi, the columnist.
Ali Ihsan Yavuz, deputy chairman of the A.K.P., delivered three suitcases of documents to the High Election Council and gave an hourslong briefing to reporters with a PowerPoint display.
There had been forgery, fraud and unlawfulness, he said.
Nine ballot-box officials had been purged from their public posts, so their appointment as election officials was unlawful, he said, adding that the government was deepening its investigation around the two people arrested in Buyukcekmece in connection with registration and census irregularities.
He suggested that officials purged in the extensive government crackdown since the failed coup of 2016 should not be allowed to vote. A further complaint claimed that 41,000 ineligible voters may have voted unlawfully.
“There is fraud here, corruption,” Mr. Erdogan told an assembly of businessmen on Saturday. “Removing this corruption, this fraud will exonerate the High Election Council, and also fill our nation’s heart with peace.”