Turkish president Recep Tayyip Erdoğan’s grip on the country has been challenged by a resurgent opposition in local elections, with his ruling Justice and Development party (AKP) losing control of Ankara and on track to lose Istanbul, according to unofficial local election results.

Voting in 30 cities, 51 municipal capitals and 922 districts across the country on Sunday has been viewed widely as a referendum on the president’s handling of Turkey’s economic crisis as the nation of 81 million people faces a recession for the first time since Erdoğan entered office 16 years ago.

It is also a litmus test for whether the Turkish leader is willing to use his newly expanded presidential powers and increasing appetite for authoritarian measures to secure AKP dominance in the country’s two major cities.

Voters in Ankara, the capital, delivered a definitive blow to the government coalition on Sunday, wrenching the city out of the control of Islamist parties for the first time in 25 years. Erdoğan’s beloved Istanbul, his hometown and where he began his political career as mayor in 1994, looks set to follow.

The AKP loss in Ankara to the secular Republican People’s party (CHP) mayoral candidate, Mansur Yavaş, sent shockwaves through the rest of the country. The AKP said it would appeal.

In Istanbul on Monday, an agonising wait for the first results in the city’s mayoral race is still not over. At one point the AKP candidate, former prime minister Binali Yıldırım, and the opposition candidate Ekrem İmamoğlu, tied at 48.7% of the vote each with 98.8% of the ballots counted, before İmamoğlu inched ahead with a lead of 0.28 percentage points.

Erdoğan flew back to Istanbul from Ankara on Monday evening, where he is believed to be meeting with Yıldırım, the city’s governor and the head of Istanbul’s police force.

On Monday morning, posters of the president alongside Yıldırım thanking Istanbullus for their votes had already been plastered on billboards around the city, but an initial declaration of victory the night before was premature.

A woman walks past AKP billboards in Istanbul thanking voters and featuring Erdoğan and mayoral candidate Binali Yıldırım on Monday. Photograph: Murad Sezer/Reuters

İmamoğlu, the CHP coalition candidate, also declared himself mayor of Istanbul on Monday, as Yıldırım refused to concede, citing 300,000 invalid votes for the CHP, a margin that could give AKP victory. The official results may not arrive for days.

The opposition’s predicted gains come despite enormous obstacles: an almost completely pro-government media bias, allegations of AKP vote-rigging and a wave of arrests of opposition candidates in the majority Kurdish south-east of the country on terror charges ahead of polling day.

“The people have voted in favour of democracy, they have chosen democracy,” said the CHP leader, Kemal Kılıçdaroğlu.

The results – if they are not contested or opposition winners removed from their posts and caretaker officials installed – would mark the first lasting check on Erdoğan’s consolidation of power since he became prime minister in 2003.

Liberal neighbourhoods of Istanbul were tense but jubilant on Monday, with people in cafes glued to live election results on television.

“I see İmamoğlu becoming the head of the CHP and then prime minister of this country,” said Murat Sun, 38. “He will have to fight hard because the government still holds the power and they will create problems for him. But I am still very hopeful.”

Local elections do not normally deliver such watershed moments, but the catalyst for Sunday’s unexpected results has been Turkey’s faltering economy.

Erdoğan had framed the elections as a matter of ‘national survival’. Photograph: Bülent Kılıç/AFP/Getty Images

Unemployment is rising and with inflation at 20% the cost of living has soared. Last month Turkey officially entered a recession, ending years of strong economic growth that has helped Erdoğan stay in office.

In an attempt to curry favour with his base of working-class voters, the president opened cut-price “people’s vegetables” stalls a few weeks before the elections. He has been on the campaign trail for weeks, sometimes speaking eight times a day to rallies of more than 1 million people, framing the local elections as a matter of “national survival” and accusing opposition parties of links to terrorism.

But with no general election scheduled until 2023, the decisions on mayors, municipal assembly leaders and neighbourhood administrators around Turkey on Sunday also became a vote on his leadership.

Turkey’s voter turnout is among the highest in the world, and stood at 87% in last year’s general election. Opposition hopes that dissatisfaction with the government’s handling of Turkey’s economy since last year’s currency crash would prevent AKP voters from turning up at polling stations appeared to be well-founded.

“In Turkey, people support political parties like they’re football teams. But we still have a conscience. The fire has spread from the kitchen now. People see the queues for onions,” said Oznur Turunk, 66. “Every authoritarian government only lasts for a certain time period, so this was coming.”

Sunday’s election has also rocked Istanbul’s conservative working-class neighbourhoods – traditionally, AKP strongholds. Men sitting outside an AKP building in Tophane next to the Bosphorus on Monday afternoon shook their heads as they read newspapers and discussed the mayoral race.

“Turkey has a robust and deep belief in democratic structures and civil society is very resilient. Despite the last 16 years, that is still there,” said Lisel Hintz, a professor at Johns Hopkins University’s European and Eurasian studies department.

“The question is: how many people are tired of Erdoĝan’s message at this juncture?”

Despite the seismic results in Turkey’s major urban centres, the ruling AKP and an allied nationalist party still won more than half of the votes across Turkey as a whole.

The pro-Kurdish People’s Democratic party (HDP) regained several seats across the mainly Kurdish south-east, where the government has replaced elected mayors with government-appointed trustees in the past after alleging the ousted officials had links to the outlawed militant Kurdistan Workers’ party (PKK), but also lost two south-eastern towns to AKP control.

The high stakes were reflected by reports that four people had been killed in election-related violence.

For many people, memories of alleged results massaging and government tampering with the electoral roll in 2015’s general election are still fresh. It is feared Istanbul’s race may not be declared until the AKP feels it can justifiably eke out a victory.

As they stand, the reported results will also cause a headache for Erdoĝan inside his party, fuelling rumours of a breakaway party split within the AKP. They will also frustrate international businesses and diplomatic partners who assumed Ankara would be able to refocus on issues such as rebuilding international investor confidence and the next steps in Syria’s civil war once the campaign was over.

“In 2015, Erdogan called a new round of snap elections and restarted the war with the PKK to stoke national insecurity and get the general election result he wanted,” said Kimberly Guiler, a research fellow at the Harvard Kennedy School of Government’s Middle East Initiative.

“He has shown that he is not above minimising or negating opposition wins somehow. This is a checkmate. Let’s see what he does next.”