Supporters of Iranian President Hassan Rouhani cheer during a campaign rally this week in the southwestern city of Ahvaz. (Behrouz Mehri/AFP/Getty Images)

Iranian officials began counting votes early Saturday after heavy turnout in a pivotal presidential election that could ­either boost Iran’s engagement with the world or possibly plunge the country back into greater diplomatic isolation.

Across the nation on Friday, ­voters filed into schools, mosques and other sites to cast ballots after a campaign offering starkly differing visions. Polling stations had long lines throughout the day, and voting was extended by several hours.

In the balance is Iran’s international outreach — as well as its national identity as a state either moving toward more social and political openness or turning inward to assuage Iranians troubled by reforms and economic stagnation.

Also at stake is the legacy of the incumbent, Hassan Rouhani, who ended more than a decade of U.N. sanctions as part of a 2015 nuclear deal with world powers, including the United States.

His top challenger was hard-line cleric Ebrahim Raisi, who views the West with suspicion and insists that the easing of sanctions under the nuclear pact has done little to help ordinary Iranians. Two other candidates remained in the race but were considered also-rans. If no one wins more than 50 percent of the vote, a runoff will be held in a week between the two leading candidates.

Iran’s top authorities — the supreme leader, Ayatollah Ali Khamenei, and his circle of ruling clerics — have endorsed the nuclear accord, which calls for limiting Tehran’s nuclear program in exchange for sanctions relief. Any possible changes to the pact would probably take time to evolve.

But the outcome of the election could have more immediate repercussions across the Middle East. Iran backs anti-Israel factions such as Lebanon’s Hezbollah and has close ties with Syria’s regime, which is opposed by the United States and its regional allies.

Just as Iran’s presidential vote took place, President Trump headed to Iran’s main regional rival, Saudi Arabia, to begin a trip that will include a stop in Israel. Iran is expected to be a major topic of Trump’s talks in both countries.

Officials cited high voter turnout in extending the voting for four hours, leaving open the ­option of a further extension. ­According to Iran’s electoral law, polls can stay open until midnight but must be closed after that.

Raisi complained of “widespread voting violations,” according to Iran’s semiofficial Fars News Agency and other reports. He was photographed arriving at the Interior Ministry in Tehran late Friday, but the nature of the claims was not immediately clear.

Rouhani has broad support among moderates and others seeking further openings in Iranian policies, while Raisi has powerful backers among Iran’s security establishment and its ruling clerics, led by Khamenei.

Iran’s president has important sway over domestic affairs and serves as the face of Iran to the world. But all key policies, such as diplomatic initiatives, must be cleared by Khamenei and his ­cadre of unelected theocrats.

No Iranian president since 1981 has failed to secure a second four-year term, yet Rouhani has faced sharp criticism over the poor economy and what Raisi described as his “weak” position when negotiating with the West.

The nuclear agreement was at the heart of Rouhani’s project to end the country’s pariah status and rejoin the global economy. If reelected, however, he will face a more confrontational Trump administration, which has taken a harsh line against Iran and placed the nuclear deal under review.

Despite increased tensions with the United States since Trump’s election, Rouhani sees Iran as benefiting from better ties with the West and from foreign investment. He has accused rivals of wanting to thwart progress.

The “era of violence and extremism is over,” Rouhani said at a rally this month.

Raisi seized on economic discontent to run a populist campaign, promising to increase cash handouts to the poor and create more than a million jobs during his first year in office. Iran’s unemployment rate has hovered around 12 percent.

Although Raisi pledged to uphold the nuclear deal, his links to the influential clergy and Revolutionary Guard Corps, a powerful military force with control over key sectors of the economy, suggested an aversion to diplomacy. Raisi remained vague on foreign policy, but his own domestic legacy includes participation in a 1988 “Death Commission” that oversaw the execution of thousands of political prisoners.

Raisi “has run a campaign ­focused on economic populist themes, but has not taken strong positions on many other issues,” said Farzan Sabet, a fellow at Stanford University and founder of IranPolitik, a blog on Iranian politics. This approach was apparently “intended to keep negative attention focused on his rival,” Sabet said.

On Friday, Raisi, Rouhani and Khamenei all cast ballots as the voting began nationwide, and the supreme leader urged Iranians to head to the polls.

“Iranian officials are obsessed with high turnout rates and have been encouraging popular participation in this election, from the campaign stump to the Friday prayer lectern,” said Behnam Ben Taleblu, Iran analyst at the Foundation for Defense of Democracies in Washington.

Iran’s popular foreign minister, Mohammad Javad Zarif, appeared amid a crowd of voters at his own polling station.

Elsewhere, people chanted as reformist former president Mohammad Khatami cast his ballot. Khatami served as president from 1997 to 2005 but was banned from speaking publicly after reformists joined widespread protests against disputed election results in 2009. Other opposition leaders — including Mir Hossein Mousavi, his wife, Zahra Rahnavard, and Mehdi Karroubi — remain under house arrest. All vowed to vote for Rouhani.

Although the supreme leader wields ultimate religious and political authority, and a group loyal to him called the Guardian Council vets candidates for office and often disqualifies reformists, Iranian elections remain highly charged and competitive, drawing thousands to rallies around the country.

More than 56 million Iranians are eligible to vote in the 63,000 polling stations set up nationwide.

After casting his ballot, Rouhani called on Iranians to unite behind whoever wins. “Any candidate who is elected should be helped to accomplish this heavy responsibility,” the Associated Press quoted him as saying.