ISTANBUL — As he stood on the top of his campaign bus before a sea of supporters on election night, Ekrem Imamoglu, Istanbul’s mayor-elect — the man who beat President Recep Tayyip Erdogan and his all-powerful party machine twice — hugged a teenager who had by chance helped him win over the city.
Running alongside the bus of then-candidate, now mayor-elect, Ekrem Imamoglu in March, the boy, Berkay Gezgin, had shouted to him: “Don’t worry, brother Ekrem, everything will be fine.”
It became the campaign’s slogan, because it captured exactly the spirit that Mr. Imamoglu, a virtually unknown district mayor, was trying to evoke as he took on one of the heavyweights of the ruling party — not to speak of Mr. Erdogan himself.
Mr. Imamoglu, 49, beat Mr. Erdogan and his party first in March and again in a rerun this Sunday. His winning formula was a message of optimism and love that sought to appeal to the religious conservatives who formed the base of Mr. Erdogan’s support, as well as nationalists and the important Kurdish minority.
“We had two simple rules: Ignore Erdogan and love those who love Erdogan,” said Ates Ilyas Bassoy, the national campaign manager for the Republican People’s Party, or C.H.P., which led the opposition alliance. “The whole strategy depended on this.”
Two years of inflation, flagging growth and a currency collapse, much of it easily traceable to the economic policies of the Erdogan government, certainly soured the atmosphere around the election.
But campaign officials on both sides said Mr. Imamoglu’s success in the rerun was also as much the result of missteps by the ruling party and bad decisions by Mr. Erdogan — including pushing for the do-over election — as anything the candidate had done.
Mr. Bassoy said he reversed the opposition’s focus on criticizing Mr. Erdogan, citing as an example how Robert De Niro’s insult to President Trump at the Tony Awards last year served only to motivate Trump supporters who were insulted by the slur.
Mr. Bassoy published a booklet on how to woo voters with “radical love,” urging opposition candidates to get out and talk to people but to avoid arrogance, sarcasm and high-level politics.
Mr. Imamoglu, he said, was a natural.
In fact, he was the product of careful profiling by an outside team for the opposition’s Istanbul branch, which found he had the right mix of attributes and minimal political baggage to appeal to a broad cross section of Istanbul voters.
As for Mr. Imamoglu’s opponent — Binali Yildirim, 63, a former prime minister and close ally of Mr. Erdogan — Mr. Bassoy said he wondered why the president “chose a very weak guy.”
“Yildirim is 16 years older than Imamoglu and his image is old,” Mr. Bassoy added.
Mr. Yildirim played up his experience of 25 years in government, but to many that epitomized the cronyism that critics say has ruined the image of the ruling Justice and Development Party, or A.K.P.
While Mr. Yildirim’s businessmen sons have been accused of corrupt dealings, he batted away a question about them in a TV debate, saying that they had won several lawsuits and that others were still underway.
The choice of Mr. Yildirim, political insiders say, follows a trend of Mr. Erdogan relying increasingly on people for their loyalty, rather than their ability. Former members of the ruling party say that is a long way from the early years, when the party was a great amalgamation of ideas, a place where people with different talents and backgrounds, whether businesspeople or intellectuals, came together.
The damage began five years ago when divisions first appeared inside the party over how to handle popular protests in Istanbul’s central park in 2013, said Kemal Ozturk, a senior columnist and ruling party member who has written critically of the decline of the party.
“It started to fall away from its founding principles and philosophy,” he said. “It lost its ability to convince people.”
The departure of one of the party’s ideologues, Ahmet Davutoglu, who resigned as prime minister in 2016, was seen as a critical juncture. Mr. Erdogan then moved to create a presidential system and amass more power for himself, driving away the main intellectuals of the party.
The failed coup that occurred a few months later came to shape the thinking that eventually brought failure at the polls, said Atilgan Bayar, a former strategic campaign adviser to the ruling party, who joined the opposition campaign this year.
He said Mr. Erdogan was right to move against the followers of the Islamist preacher, Fehtullah Gulen, who had infiltrated government institutions and were trying for a power grab, but that he took it too far. Tens of thousands were detained.
In time, he said, the ruling party’s belligerent rhetoric came to infect the entire national discourse.
As Mr. Erdogan steadily gained control over the main news media companies, closing many outlets and forcing owners to sell out to businessmen close to his party, pro-government propaganda replaced independent reporting, especially on TV.
Over time, the relentless attacks on opponents and critics in the pro-government news media and on television chat shows, as well as the sheer thuggishness of the presenters, wore thin.
So, too, did Mr. Erdogan’s fighting talk. His campaign message in March that the local election was a matter of “national survival” largely failed.
“The A.K.P. electorate is also frustrated and weary of seeing the world explained with conspiracy theories and religion,” Mr. Bayar said.
Analysts across the political spectrum are describing the Istanbul vote as a tectonic shift in Turkish society. Although the A.K.P. won a majority of Istanbul’s 39 municipal districts in the March election, voters switched their allegiance in droves in the rerun.
Twelve districts that voted for Mr. Yildirim in March swung behind Mr. Imamoglu in June, including some of the most conservative ones, seen as strongholds of the ruling party — the religious center of Fatih; Tuzla, the home district of Mr. Yildirim; and Uskudar, where Mr. Erdogan lives.
Analysts attributed part of the shift to public resentment over the cancellation of the March mayoral vote, which Mr. Imamoglu won by 13,000 votes.
A focus group run by the opposition in April showed that ruling party voters were not against a recount, but strongly opposed a repeat election, said Gulfem Saydan Sanver, a political consultant who advised the opposition campaign.
“That was one of the main points that the A.K.P. missed,” she said.
“On March 31, educated conservatives came to us,” said Yuksel Taskin, a professor of political science and a prominent member of the opposition. “On June 23, we saw working class conservatives turn towards the C.H.P.”
One of the most important swings occurred among women, in particular those from lower and middle-income conservative families who had helped power the rise of Mr. Erdogan’s ruling party.
While his party had long campaigned against, and eventually removed, a ban on headscarves in public institutions and public universities, those same headscarf-wearing women turned against the party.
“Their goal was to be emancipated,” Mr. Bayar, the campaign strategist, said. “But, right now, these women with headscarves cannot find a place for themselves in a party that increasingly uses authoritarian language, because they are much more freedom oriented and they want to be in social life much more.”
He added: “Because they have experienced it themselves, they cannot tolerate injustice.”
In the end the ruling party underestimated its opponent, Mr. Imamoglu. The A.K.P. used to be very good at polling its constituents and gathering feedback from communities, said Ms. Sanver, but communication within the party has broken down and it has lost touch with its own supporters.
“I studied most of the A.K.P. campaigns since 2007,” she said. “I can easily tell you that this has been the worst political campaign they have ever done.”