As Western forces exit Afghanistan, Iran is watching with alarm. The resolution of one long-standing aim, the withdrawal of U.S. troops, is unleashing a separate challenge: what to do about the Taliban, another longtime problem for Iran, swiftly regaining power and territory next door.

The Afghan government said Friday that the Taliban had captured a key border crossing between Iran and Afghanistan.

Iran, ruled by Shiite clerics, and the Taliban, a radical Sunni movement, are at fundamental odds, and Iran has long bristled at the Taliban’s treatment of non-Sunni minorities.

Tehran fears both Taliban rule and Afghanistan returning to civil war, a destabilizing prospect likely to imperil the country’s ethnic Persian and Shiite communities, send more waves of Afghan refugees across the border and empower Sunni militancy in the region.

Seeking an upper hand, Iran has cultivated ties with some Taliban factions and softened its tone toward the extremist group, which it sees as all but certain to remain in power.

That gamble has elicited fierce debate in Iran, where the repressive Taliban is viewed unfavorably and skepticism of U.S. intentions runs high, even as the Biden administration makes slow headway in talks to return to the 2015 nuclear deal, from which then-President Donald Trump withdrew.

“Iran is going to be harmed immensely by chaos and civil war in Afghanistan,” said Fatemeh Aman, a nonresident senior fellow at the Middle East Institute, citing in particular Tehran’s fear of the Islamic State’s Afghanistan affiliate gaining ground. “They see partial rule as the best-case scenario, with the Taliban in power.”

But Iran’s increasingly public overtures to the Taliban “could be a miscalculation,” said Aman, as “Iran believes they are using the Taliban, but some could argue that the Taliban is using Iran to present themselves as more powerful, worthy of ruling a country.”

Iran was excluded from U.S.-Taliban talks in Doha, Qatar, which last year led to a troop withdrawal deal to end two decades of U.S. military operations in Afghanistan. Biden set a Sept. 11 deadline, but the U.S. military said this week that the exit was more than 90 percent complete.

The Taliban, thought to control around a third of Afghanistan, has so far largely gained ground without full-scale fighting and has instead relied on cutting deals with local leaders.

Still, more than 1,500 Afghan soldiers fled across the border to neighboring Tajikistan in recent weeks to escape Taliban advances, while some 200,000 Afghans have fled their homes this year.

The Taliban’s fast-paced advances have left Tehran fearing the possibility that the Taliban could retake Kabul — but even more so the specter of widespread violence increasing the flow of extremists, narcotics and weapons, said Aman.

In recent weeks, some Iranian hard-liners — aligned with Iran’s supreme leader, Ayatollah Ali Khamenei, and President-elect Ebrahim Raisi — have gone on the offensive and publicly painted a rose-tinted picture of a changed Taliban.

The United States military conducted airstrikes on what they said were facilities used by “Iran-backed militia groups” near the Iraq-Syria border on June 27. (DVIDS via Storyful)

In late June, the ultraconservative Kayhan newspaper, tied to the supreme leader, declared, “The Taliban today is different from the Taliban that beheaded people.”

Kayhan argued that the Taliban’s recent gains have not involved “horrible crimes similar to those of the Islamic State in Iraq,” and noted that the Taliban has even said it has no issues with Shiites.

Similar statements followed. Hessam Razavi, the foreign news editor at the hard-line Tasnim News Agency, which is close to the Revolutionary Guard Corps, told an Iranian TV program last month that there has been “no war between Shiites and the Taliban in Afghanistan.”

Some hard-liners rejected this conciliatory take. Last week, the front page of conservative newspaper Jomhouri Eslami criticized Iranian leaders for playing down the threat of “Taliban terrorists” along Iran’s border.

On Persian-language social media in Iran and Afghanistan, others condemned Iran’s leaders over perceived efforts to whitewash the Taliban’s bloody history of attacking Hazaras, a Shiite minority, and repressing women and personal freedoms.

In one incident seared in Iranian memory, Taliban insurgents in 1998 attacked the Iranian Consulate in Mazar-e Sharif in northern Afghanistan and killed nine Iranians. The two sides nearly went to war.

The outgoing government of centrist Iranian President Hassan Rouhani, meanwhile, has been more circumspect regarding the whiplash developments across the border.

“We are seriously considering the issue of Afghanistan and talking to all Afghan groups,” Saeed Khatibzadeh, a spokesman for the Foreign Ministry, said late last month, the Aftab Yazd newspaper reported. “A genuine dialogue between Afghans is the only lasting solution,” he said. “We are ready to facilitate talks. ”

While “the Iranians do care about Afghanistan … there is no clear strategy for how they are going to handle it,” said Vali Nasr of the Johns Hopkins School of Advanced International Studies.

Some in Iran celebrated the withdrawal as “a U.S. failure,” said Nasr. But others have argued that the “United States welcomes Afghanistan becoming a quagmire for Iran,” and that withdrawal “is priming Afghanistan for sectarian rule,” he said.

Even before the Doha deal, Iran cultivated ties with Tehran-friendly Taliban factions, as Afghanistan’s other neighbors, especially Pakistan, have done for decades.

Forging such ties was encouraged by the rise of the Islamic State’s Khorasan offshoot in Afghanistan in 2015. Iran began to see it as a bigger threat than the Taliban, which also opposes the ultraviolent group.

Afghan officials have confirmed the death of Taliban leader Mullah Akhtar Mansour in a U.S. drone strike, but many details remain unexplained. (Reuters)

Iran’s long-simmering Taliban ties have become increasingly public. In 2016, a U.S. drone strike killed Taliban leader Mullah Akhtar Mohammad Mansour as he returned to Pakistan after a stay in Iran. In the most high-level meeting between the parties, senior Iranian officials hosted a Taliban delegation in Tehran in late January.

The new head of Iran’s Quds Force in the powerful Islamic Revolutionary Guard Corps (IRGC), Ismail Qaani, also has extensive ties and experience in Afghanistan.

Iran and the United States, however, have in the past found common ground around fighting the Taliban.

As the United States prepared to invade Afghanistan in 2001, Iran, then led by reformist President Mohammad Khatami, provided intelligence. Then-Quds Force commander Qasem Soleimani reportedly oversaw the contact.

After the Taliban fell, Iran continued to help build a new Afghan government and mediate among warlords filling the security void.

But that cooperation ended in January 2002, when President George W. Bush named Iran, North Korea and Iraq an “axis of evil,” offending Tehran.

Now, Aman said, Washington and Tehran have a small window of time to cooperate again in Afghanistan’s interest.

“I hope they don’t wait for a civil war to sit down and talk as much as they can over Afghanistan,” said Aman. “Afghanistan has suffered so much from the differences and animosity between Iran and the U.S., and Iran and Saudi [Arabia] and Arab neighbors.”