All are "correct" but have different meanings.
The word "just" here is an adverb meaning "exactly" or "precisely". In the first example "just when the sun was setting." tells us the exact time when he reached the village.
In the second example "just the sun was setting" the word "just" means "only". So this means that "only the sun and nothing else was setting". That is an odd idea, and probably not intended.
The third and fourth are also correct. But now we have "just reached the village". So here "just" has the sense of "closely" or "by a narrow margin". You might say "I just reached the village as the sun was setting, so I was safe from the zombies that attack at night"
This example shows how the word "Just" can have different meanings according to context. It can mean "exactly", "only" or "closely". We know which meaning is correct from the context. "Just when..." means exactly. "Just the sun..." means "only". And "just reached" means "by a narrow margin".