Isn’t it unfair for God to damn someone for committing a last-minute mortal sin if he’s been righteous up till then?
You’re looking at this issue all wrong. It’s incorrect to think of sin and virtue as “outweighing” each other, at least in the case of someone who dies in either the state of grace or the state of mortal sin. At death your disposition toward God, whether friendship or rebellion, is fixed for eternity. You are unable thereafter to “change your mind.” That’s why the damned in hell cannot repent and become God’s friends. Likewise, the blessed in heaven are in no danger of rebelling against God and losing their salvation.
Second, the question of “fairness” is irrelevant to this issue. God is all just and all merciful. During our lives he extends his mercy to us, repeatedly allowing us to repent and turn from sin and thus shields us from the eternal consequences of our sins. But at death his justice demands that we be recompensed on the basis of our relationship to him.
The Lord explains that fairness is not the issue:
When a righteous man turns away from his righteousness and commits iniquity and does the same abominable things that the wicked man does, shall he live? None of the righteous deeds which he has done shall be remembered; for the treachery of which he is guilty and the sin he has committed, he shall die. Yet you say, “The way of the Lord is not just.” Hear now, O house of Israel: Is my way not just? Is it not your ways that are not just? When a righteous man turns away from his righteousness and commits iniquity, he shall die for it; for the iniquity which he has committed he shall die.
Again, when a wicked man turns away from the wickedness he has committed and does what is lawful and right, he shall save his life. Because he considered and turned away from all the transgressions which he had committed, he shall surely live, he shall not die. Yet the house of Israel says, “The way of the Lord is not just.” O house of Israel, are my ways not just? Is it not your ways that are not just? Therefore I will judge you, O house of Israel, every one according to his ways, says the Lord God. Repent and turn from all your transgressions, lest iniquity be your ruin. Cast away from you all the transgressions which you have committed against me, and get yourselves a new heart and a new spirit! Why will you die, O house of Israel? For I have no pleasure in the death of any one, says the Lord God; so turn, and live. (Ez 18:21-32; cf. Mt 20:1-15)
One needs to understand the gravity of mortal sin. By committing mortal sin a person implicitly rejects God and the entire life of holiness he has led up to that point. By spurning that life he spurns the reward he would have gotten as a result of it. It is his own fault if he dies in a state of alienation from God and his reward.