Purgatory is widely misunderstood as a middle destination between heaven and hell, or as a second chance for those who died badly. Catholic teaching is neither. Everyone in purgatory is already saved and will certainly reach heaven; what remains is purification.
The distinction underlying it is between guilt and consequence. Catholic theology holds that forgiveness of sin removes the guilt but not necessarily the disordered attachments and the temporal consequences the sin left behind. A person may die genuinely repentant and genuinely reconciled while still being, in the tradition's language, not yet fit for the vision of God. Purgatory is the completion of that fitting.
Scripturally the doctrine rests on a small base: a passage in Second Maccabees describing prayer and offering for the dead, which Protestants exclude from the canon; Paul's image of work tested by fire in the third chapter of First Corinthians, where the builder is saved but only as through fire; and the long practice of praying for the dead, attested in catacomb inscriptions and in the early liturgies. Catholic theology treats that practice as evidence, on the principle that how the church prays reveals what it believes: prayer for the dead makes sense only if their condition can be affected.
The councils of Lyons in 1274, Florence in 1439 and Trent in 1563 affirmed the state and the value of prayers, Masses and almsgiving offered for those in it. What the councils deliberately did not define is duration, location or the nature of the pain. Popular imagination supplied fire and a calendar, and medieval devotion quantified the arithmetic; official teaching never did, and modern Catholic accounts often speak of an encounter with divine love that is itself purgative rather than of punishment at all.