Near the peak of the American war in Afghanistan, in 2014, a former chief of neighbouring Pakistan’s military intelligence — an institution allied both to the U.S. military and to its Taliban adversaries — appeared on a talk show called “Joke Night.” He put a bold prediction on the record.

“When history is written,” declared Gen. Hamid Gul, who led the feared spy service known as the ISI during the last stretch of the Cold War in the 1980s, “it will be stated that the ISI defeated the Soviet Union in Afghanistan with the help of America.”

“Then there will be another sentence,” Gul added after a brief pause, delivering his punchline to loud applause. “The ISI, with the help of America, defeated America.”

In President Joe Biden’s decision to withdraw all U.S. forces from Afghanistan by September, Pakistan’s powerful military establishment finally gets its wish after decades of bloody intrigue: the exit of a disruptive superpower from a backyard where the ISI had established strong influence through a friendly Taliban regime before the U.S. invaded in 2001.

A return of the Taliban to some form of power would dial the clock back to a time when Pakistan’s military played gatekeeper to Afghanistan, perpetually working to block the influence of India.

But the Pakistani military’s sheltering of the Taliban insurgency over the past two decades — doggedly pursuing a narrowly defined geopolitical victory next door — risks another wave of disruption at home. Pakistan is a fragile, nuclear-armed state already reeling from a crashed economy, waves of social unrest, agitation by oppressed minorities and a percolating Islamic militancy of its own that it is struggling to contain.

If Afghanistan descends into chaos, Pakistanis are bound to feel the burden again just as they did after Afghanistan disintegrated in the 1990s following the Soviet withdrawal. Millions of Afghan refugees crossed the porous border to seek relative safety in Pakistan’s cities and towns. And more: A Taliban return to power, either through a civil war or through a peace deal that gives them a share of power, would embolden the extremist movements in Pakistan that share the same source of ideological mentorship in the thousands of religious seminaries spread across Pakistan. Those groups have shown no hesitation in antagonising the country’s government.

While Pakistan’s military played a dangerous game of supporting militants abroad and containing extremists at home, the country’s Islamic movements found a rallying cause in the presence of an invading foreign force next door, openly fundraising for and cheering on their Afghan classmates. New extremist groups kept shrinking the civil society space in Pakistan — often targeting intellectuals and professionals for abuse or attack — and even found sympathisers in the ranks of Pakistan’s security forces.

Pakistani generals have resorted to a mix of force and appeasement in tackling the country’s own growing militancy problem, said Dr. Ayesha Siddiqa, a research associate at the School of Oriental and African Studies in London. But a strategy for countering the spread of extremism has been elusive.

“It scares me, it scares me,” Siddiqa said. “Once the Taliban come back, that should trouble the Pakistani government, or any government. It will be inspiring for all the other groups.”

Said Nazir, a retired brigadier and defence analyst in Islamabad, said Pakistan had “learned some lessons” from the blowback of past support to jihadi groups. The country would need to tread more cautiously in the endgame of the Afghan war.

“Victory will not be claimed by Pakistan, but tacitly the Taliban will owe it to Pakistan,” Nazir said. “Pakistan does fear the replay of past events and fears a bloody civil war and violence if hasty withdrawal and no political solution occur simultaneously.”

Seth Jones of the Centre for Strategic and International Studies in Washington said that although Pakistan’s military and intelligence establishment are “undoubtedly celebrating” the Biden announcement, greater control in Afghanistan is far from assured.

“It will be difficult, if not impossible, for Pakistan to control the Taliban and other militant groups in Afghanistan as the country spirals into a civil war,” he said. “Al-Qaida, the Islamic State, and other groups are already operating in Afghanistan. There is no way Pakistan can control this hodgepodge of groups, which have different interests, leaders, and goals.”

From the moment of its birth as a country in 1947, Pakistan found itself surrounded by enemies. The new borders drawn up by British officials instantly mired Pakistan in a host of territorial disputes, including a serious one with Afghanistan, which still lays claim to what most of the world sees as Pakistan’s north-western regions. It was at the peak of the Cold War in the 1970s, as the Soviet Union pushed to expand its influence in South and Central Asia, that Pakistani leaders found a formula of deploying Islamic proxies they have stuck to ever since. The United States armed and financed the training of the mujahideen insurgency that would defeat the Soviet army in Afghanistan and topple the government it propped up. Pakistan’s army, particularly its intelligence wing, would serve as the handler, host and trainer.

Through the ensuing civil war in the 1990s, Pakistani generals helped a younger group of fundamentalist Afghan fighters known as the Taliban sweep the fighting factions and establish a government with control over more than 90% of Afghanistan. But when the United States invaded in 2001 to chase Osama bin Laden and al-Qaida after their terrorist attacks on American soil, the Americans also turned their sights on Pakistan’s allies in Afghanistan, the ruling Taliban. Pakistan found itself in a difficult position. In the face of President George W. Bush’s “with us or against us” ultimatum, Pakistan’s military ruler, Gen. Pervez Musharraf, reluctantly went along.

The decision had an immediate blowback: Pakistan began facing attacks from the Pakistani Taliban for siding with the U.S. military campaign against their ideological brothers in Afghanistan. It took years of military operations that cost the lives of thousands of Pakistani forces, and displaced countless people in Pakistan’s northwest, to quell the group.

At the same time, Pakistan’s military kept working to help the Afghan Taliban regroup as an insurgency to keep the United States in check. Even as U.S. officials relied on Pakistani help to conduct the war and intelligence operations, some were bitter about the double role played by the ISI. The killing of bin Laden in Pakistan by U.S. forces in 2011 was one rare moment when those tensions played out in public.

But Pakistan’s generals were also successful in making themselves indispensable to the United States — offering a nuclear-armed ally in a region where China, Russia and Islamic militants all had interests. Effectively, it meant that the United States chose to turn a blind eye as its Pakistani allies helped the Taliban wear down U.S. and allied forces in Afghanistan.

Afghan government officials, meanwhile, were becoming increasingly distraught that their American allies were not coming down harder on Pakistan.

On one trip to Afghanistan soon after being elected vice president in 2008, Biden was urged by President Hamid Karzai to pressure Pakistan into rooting out Taliban sanctuaries on its soil. Biden was reported to respond by saying that Pakistan was 50 times more important to the United States than Afghanistan was. In recent years, as U.S. officials sought a way to leave Afghanistan, they again had to turn to Pakistan — to pressure the Taliban to come to peace talks, and to lend help when the United States needed to move against al-Qaida or the Islamic State group affiliate in the region.

With the U.S. intention to leave publicly declared, Pakistan did away with any semblance of denial that the Taliban leadership was sheltering there. Taliban leaders flew from Pakistani cities to engage in peace talks in Qatar. When negotiations reached delicate moments that required consultations with field commanders, they flew back to Pakistan.

When the United States finally signed a withdrawal agreement with the Taliban in February last year, the mood in some circles in Pakistan was one of open celebration. Pakistan’s former defence minister, Khawaja Muhammad Asif, who had repeatedly visited the halls of power in Washington as a U.S. ally, tweeted a photo of U.S. Secretary of State Mike Pompeo meeting Mullah Abdul Ghani Baradar, the Taliban deputy at the talks in Qatar.

“You might have might on your side, but God is with us,” Asif said in the tweet, ending with a cry of victory. “Allah u Akbar!”

But there are signs that extremist groups within Pakistan have already felt emboldened by the Taliban’s perceived victory, giving a glimpse of the trouble likely to be in store for Pakistani officials.

The once-defeated Pakistani Taliban have increased their activities in tribal areas bordering Afghanistan. Ambushes against security forces have become more frequent. Just how wide the problem of extremism might stretch has been on display in recent days on the streets of two of Pakistan’s main cities, Lahore and Karachi.

Supporters of Tehreek-e-Labbaik Pakistan, a movement that sees itself as protecting Islam against blasphemy, thrashed uniformed members of Pakistani forces and took dozens hostage for hours. Videos emerged of Pakistani army officers trying to reason with the violent protesters. Officials said two policemen had been killed and 300 wounded. The showdown continues, as the government moved to ban the group as a terrorist outfit.

“The state was not able to control the stick-wielding and stone-hurling members of the TLP that paralysed most parts of the country for two days,” said Afrasiab Khattak, a former chair of Pakistan’s human rights commission. “How will they handle trained, guns-carrying Taliban militants?”