In the early 1200s AD, the Almohad empire fell apart into Marinid, Christian, and Hafsid kingdoms. The middle of North Africa broke away from the Almohad dynasty in 1229 AD. Modern Tunisia, western Libya, and eastern Algeria came under the leadership of Abu Zakariya. People called his descendants the Hafsids, because they belonged to the powerful Banu Hafs family.
The Hafsid kingdom was already wealthy. Soon they got even more wealthy because they took in many Islamic and Jewish refugees. These refugees were fleeing from the Christians invading Spain. The Hafsid kingdom welcomed them. Among these refugees was the family of Ibn Khaldun, for example. These refugees brought with them money and education and a lot of energy. They built new houses and new mosques all over the Hafsid kingdom, especially in Tunis. Many new buildings in Tunis had the horseshoe arches and tiles of medieval Spanish architecture. They helped to remind the refugees of the home they had lost.
The Hafsids were rich enough to pay the Holy Roman Emperor Friedrich II a lot of money every year (well, most years) to keep him from attacking them. The Hafsids also bought a lot of Sicilian wheat and barley. After Friedrich died in 1250 the Hafsid sultan Mustansir tried to stop the payments. But Louis IX and his youngest brother Charles attacked Tunis as the Eighth Crusade. That encouraged Mustansir to start paying protection money again.
During the 1300s the Hafsids were weaker and poorer. Many people living in the Hafsid kingdom (like Ibn Khaldun‘s parents) died of the Black Death. Between 1347 and 1357, the Marinids pretty much controlled the Hafsids. But thanks to the help of the Berber people, the Hafsids were able to fight off the Marinids and get their kingdom back. The Italian and Spanish rulers of the 1400s, especially Venice and Aragon, continued to attack the Hafsid kingdom to force them to pay tribute.
The Hafsids bought more and more manufactured goods like paper from Italy. To resist European power and make money, the Hafsids started to attack European ships in the Mediterranean Sea. That is, they became pirates. During the 1400s, the Hafsids also tried to diversify; they traded south across the Sahara with the people of West Africa, and east across the Sahara with the Mamluks in Egypt.
But by the 1500s the Hafsids were not really independent anymore. The Berber people, who were nomads, were independent. The Hafsids just bounced back and forth between being conquered by the Ottomans and being vassals of the Holy Roman Empire. In 1574, Nurbanu Sultan of the Ottoman Empire finally sent troops to conquer Tunis, killed the last Hafsid caliph, and ended the Hafsid kingdom.