Democracy picks the leader who is best at getting elected, not necessarily the best at leading the country. The ability to become a leader differs from the ability to lead. For example, populism and overconfidence in oneself may help one’s election prospects but harm performance at governing.
Even if there was some very accurate way to select the best leader (e.g. test their honesty, intelligence, work ethic, in addition to electability), it may be not be feasible in practice to make this person govern for long. The reason is the political economy constraint that someone better at obtaining power can depose the best leader (one whose government would maximise social welfare, however defined). The disruption resulting from the coup may even harm society more than the difference between being governed by the best leader as opposed to the best power-grabber. In this case, the leadership of the most electable person may maximise welfare, subject to assumptions like „the best power-grabber is also good enough at retaining power, preventing coups once in government”.
The skills of getting elected and organising a revolution probably differ, so an elected government has some of the same vulnerability as the best leader. The political economy constraint of preventing a coup may then favour making the strongest dictator or the most dangerous revolutionary lead the country. However, this may not be the best system for selecting leaders due to a tradeoff between the ability to govern and the ability to overthrow a government. The welfare-maximising selection system subject to the political economy constraint would pick the person who is best at governing among those who can successfully resist a coup. Democracy may be such a compromise, choosing reasonably popular leaders who have a low probability of being overthrown and are adequate at governing. On the one hand, democracy may avoid a ruthless dictator whose rule is very stable, but harmful, and on the other hand a saintly leader who would be deposed quickly.