Turkish President Recep Tayyip Erdoğan and his political party, the AKP, will be in a period of transition after having suffered an electoral defeat at the hands of opposition figure Ekrem Imamoğlu for control of Istanbul after a re-run of the city’s mayoral election.

Erdogan had previously said that “whoever wins Istanbul, wins Turkey” and with nearly all ballots counted, Imamoğlu had captured 54% of the vote, far ahead of his to his opponent, former Prime Minister Binali Yildirim, who received 45% of the ballots cast.

Imamoğlu’s margin of victory was a huge increase on what he achieved in an earlier election held in March that was later annulled after the AKP accused the opposition of voting irregularities.

The decision to re-run the vote was heavily criticised by Turkey’s Western allies and caused an uproar among domestic opponents who said that democracy in Turkey was under threat.

The latest results, however, appear to have been a boon for the overall health of the democratic process in an overwhelmingly Muslim nation of more than 80 million people.

Imamoğlu, of the secularist Republican People’s Party (CHP), won broad support in Istanbul, by far Turkey’s largest city as well as its cultural capital that was once the seat of government during the 500-year Ottoman Empire.

Unlike in previous elections, the CHP did well in traditionally conservative parts of the city where the Islamist-rooted AKP had reigned supreme for the better part of the last 25 years.

“In this city today, you have fixed democracy. Thank you Istanbul,” Imamoğlu told supporters. “We came to embrace everyone,” he said. “We will build democracy in this city, we will build justice. In this beautiful city, I promise, we will build the future.”

Erdogan congratulated Imamoğlu for the victory and later wished him luck as mayor.

A Council of Europe delegation said, despite some reported incidents of aggressive encounters with party supporters, noted that “the citizens of Istanbul elected a new mayor in a well-organised and transparent vote, albeit intense circumstances,” according to the delegation’s head, Andrew Dawson.

The AKP’s support among pious and religiously conservative Turks helped it oversee a decade and a half of construction-fuelled economic growth which helped Erdoğan win an unprecedented number of national and local elections by wide margins.

The ongoing economic recession and a financial crisis have eroded that has seen the national currency, the lira, lose much of its value over the last year saw support for Erdoğan dry up as voters appear to have also grown concerned about his ever-tighter control over the government.