TEHRAN, Iran -- Iran's former President Akbar Hashemi Rafsanjani died Sunday after a decades-long career in the ruling elite, where his moderate views were not always welcome but his cunning guided him through revolution, war and the country's turbulent politics.

The political survivor's life spanned the trials of Iran's modern history, from serving as a close aide to Ayatollah Ruhollah Khomeini during the 1979 Islamic Revolution to acting as a go-between in the Iran-Contra deal. He helped found Iran's contested nuclear program, but later backed the accord with world powers to limit it in exchange for sanctions relief.

Rafsanjani, who showed ruthlessness while in power but later pushed for reforms, died Sunday after suffering a heart attack, state media reported. He was 82.

Iranian media said he was hospitalized north of Tehran earlier Sunday, where doctors performed CPR in vain for nearly an hour and a half before declaring him dead.

A female state newscaster's voice quivered as she read the news. Rafsanjani, "after a life full of restless efforts in the path of Islam and revolution, had departed for lofty heaven," she said.

Supreme Leader Ayatollah Ali Khamenei called Rafsanjani an "old friend and comrade" and said his loss is "difficult and life-decreasing." The government announced three days of mourning, and a funeral was expected to be held on Tuesday.

Rafsanjani served as president from 1989 to 1997, during a period of significant changes in Iran. At the time, the country was struggling to rebuild its economy after a devastating 1980s war with Iraq, while also cautiously allowing some wider freedoms, as seen in Iran's highly regarded film and media industry.

He also oversaw key developments in Iran's nuclear program by negotiating deals with Russia to build an energy-producing reactor in Bushehr, which finally went into service in 2011 after long delays. Behind the scenes, he directed the secret purchase of technology and equipment from Pakistan and elsewhere.

In an interview published in October, Rafsanjani acknowledged the 1980-1988 war with Iraq, which killed some 1 million people, led Iran to consider seeking nuclear weapons.

"Our basic doctrine was always for a peaceful nuclear application, but it never left our mind that if one day we should be threatened and it was imperative, we should be able to go down the other path," he said. "But we never went."

The cleric managed to remain within Iran's ruling theocracy after leaving office, but an attempt to return to the presidency in 2005 was dashed by the electoral victory of the more hard-line Mahmoud Ahmadinejad. Rafsanjani was later branded a dissenter by many conservatives for his harsh criticism of the crackdown that followed Ahmadinejad's re-election in 2009.

But after years of waning influence, Rafsanjani was handed an unexpected political resurgence with the 2013 victory of a fellow moderate, Hassan Rouhani, giving him an insider role in efforts that would culminate in the 2015 nuclear agreement.

Some analysts believe Rafsanjani was kept within the ruling fold as a potential mediator with America and its allies in the standoff over Iran's nuclear program. His past stature as a trusted Khomeini ally also offered him political protection. Rafsanjani was a top commander in the war with Iraq and played a key role in convincing Khomeini to accept a cease-fire after years of crippling stalemate.

His image, however, also had darker undertones. He was named by prosecutors in Argentina among Iranian officials suspected of links to a 1994 bombing of a Jewish centre in Buenos Aires that killed 85 people. Some Iranian reformers accused him of involvement in the slaying of liberals and dissidents during his presidency -- charges that he denied and that were never pursued by Iranian authorities.

"The title of Islamic Republic is not just a formality," he said in 2009 in the chaos after Ahmadinejad's re-election.

"Rest assured, if one of those two aspects is damaged we will lose our revolution. If it loses its Islamic aspect, we will go astray. If it loses its republican aspect, (the Islamic Republic) will not be realized. Based on the reasons that I have offered, without people and their vote there would be no Islamic system."

Rafsanjani -- a portly man with only sparse and wispy chin hairs in contrast to the full beards worn by most Islamic clerics in Iran -- first met Khomeini in the Shiite seminaries of Qom in the 1950s and later became a key figure in the Islamic uprising that toppled the U.S.-backed Shah Mohammad Reza Pahlavi in 1979.

He was elected as head of Iran's parliament in 1980 and served until 1989, when he was elected for the first of two four-year terms as president.

Here, Rafsanjani began to build his multilayered -- and sometimes contradictory -- political nature: A supporter of free enterprise, a relative pragmatist toward foreign affairs and an unforgiving leader who showed no mercy to any challenges to his authority.

Rafsanjani took a dim view of state control of the economy, even in the turbulent years after the Islamic Revolution, and he encouraged private businesses, development of Tehran's stock market and ways to boost Iranian exports.

He built roads and connected villages to electrical, telephone and water networks for the first time, earning the title of Commander of Reconstruction by his supporters.

There were certain self-interests at play as well.

Rafsanjani was assumed to be the head of a family-run pistachio business, which grew to become one of Iran's largest exporters and provided the financial foundation for a business empire that would eventually include construction companies, an auto assembly plant, vast real estate holdings and a private airline. In 2003, he was listed among Iran's "millionaire mullahs" by Forbes magazine.

His economic policies won him praise from Iran's elite and merchant classes, but brought bitterness from struggling workers seeking greater state handouts. Rafsanjani also faced warnings from the ruling theocracy about pushing too far. None of his reforms dared to undercut the vast power of the Revolutionary Guard -- which Rafsanjani briefly commanded, and which controls every key defence and strategic program.

Rafsanjani's complex legacy also was shaped by the times.

He took over the presidency in a critical time of transition just after the death of Khomeini. He tried to make overtures for better ties with the U.S. after the American-led invasion of Kuwait in 1991 to drive out Iraqi forces, arguing that Iran paid too high a price for its diplomatic freeze with Washington.

But he could not overcome opposition from Iranian hard-liners and failed to win the backing of Khomeini's successor as supreme leader, Ayatollah Ali Khamenei, for bold foreign policy moves. He also angered the West by strengthening Iran's ties to armed groups such as Lebanon's Hezbollah.

"One of the wrong things we did, in the revolutionary atmosphere, was constantly to make enemies," he said in a 1987 interview. "We pushed those who could have been neutral into hostility."

Rafsanjani was born in 1934 in the village of Bahraman in southeastern Iran's pistachio-growing region of Rafsanjan.

He was jailed for several years under the shah. He then helped organize the network of mullahs that became Khomeini's revolutionary underground. In 1965, he is reputed to have provided the handgun for the assassination of Iran's prime minister, Hassan Ali Mansoor.

Only months after the revolution, Rafsanjani was shot once in the stomach by gunmen from one of the groups vying for power amid the political turmoil. He was not seriously wounded -- and neither was his wife, who jumped in front to shield him from the attack.

"Great men of history do not die," Khomeini said in announcing that Rafsanjani had survived.

During the 1980s, he used his links with Lebanese Shiite extremists to help secure the release of Western hostages in Lebanon and was a key middleman -- identified as "Raf" in Pentagon documents -- in the secret Iran-Contra dealings to funnel U.S. arms to Iran in exchange for money used to fund Nicaraguan rebels.

Although Rafsanjani was seen by Washington as a potential ice breaker, his views were far from solidly pro-Western and displayed conflicted positions.

Shortly after becoming president in 1989, he hinted that Palestinians should kill Westerners to retaliate for Israeli actions in the occupied territories.

"It is not hard to kill Americans or Frenchmen," he said.

In February 1994, Rafsanjani survived a second assassination attempt. A lone gunman fired at him as he was speaking to mark the 15th anniversary of the revolution. Unhurt and unshaken, Rafsanjani calmed a crowd of thousands and continued his speech.

The Iran-Contra fallout is an often-told tale about the dangers of crossing Rafsanjani.

After word was leaked to a Beirut magazine about Rafsanjani's involvement, he ordered the arrest of the source, a senior adviser to the ruling clerics named Mehdi Hashemi, for treason and other charges. Hashemi and others were executed in September 1987.

Later, however, he was dismayed at the brutal crackdown against opposition groups and others claiming Ahmadinejad won re-election in June 2009 through vote rigging sanctioned by the ruling theocracy.

Khamenei decided to throw his backing behind Ahmadinejad, effectively snubbing Rafsanjani and his complaints. Later, Rafsanjani fell short on efforts to mobilize enough moderate clerics in the Assembly of Experts -- the only group with the power to dismiss the supreme leader -- to force possible concessions from Khamenei on the postelection clampdowns.

Rafsanjani was forced out of the post in 2011, but remained as head of the Expediency Council, an advisory body that mediates disputes between the parliament and the Guardian Council, a watchdog group controlled by hard-line clerics.

However, his family did not escape so easily. In January 2012, a court sentenced Rafsanjani's daughter, Faezeh Hashemi, to six months in prison on charges of criticizing the ruling system. A court in 2015 sentenced his younger son, Mahdi, to a 10-year prison term over embezzlement and security charges.

Rafsanjani is survived by his wife, Effat Marashi, and five children.

On Sunday night, Rouhani and others visited the hospital to see Rafsanjani one final time before his body was taken to a mosque ahead of burial.