"何" is pronounced as "なん" before counter-words like in "何時{なんじ}", "何歳{なんさい}" etc; or before particles like in "何で", "何とか" etc.
However, it remains to be pronounced as "なに" in some words like "何事{なにごと}", "何色{なにいろ}", "何者{なにもの}" etc. It can also be pronounced both ways like in "何か".
What is the logic/origin behind this pronunciation difference?