Hafsid gold coin
In the early 1200s AD, the Almohad empire fell apart into Marinid, Christian, and Hafsid kingdoms. The middle of North Africa (modern Tunisia, western Libya, and eastern Algeria) broke away from the Almohad dynasty in 1229 AD under the leadership of Abu Zakariya. People called his descendants the Hafsids, because they belonged to the powerful Banu Hafs family.
The Hafsid kingdom, already wealthy, soon became even more wealthy because many Islamic and Jewish refugees who had fled from the Christians invading Spain came to the Hafsid kingdom to live. (Among these was the family of Ibn Khaldun, for example.) These refugees brought with them money and education and a lot of energy, which they put to work building 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, 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, and 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, particularly 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 began to attack European ships in the Mediterranean Sea. 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.