It doesn't always target the closest unit. For example, a spell-casting unit might attack a unit that's 1 tile away, rather than one standing right next to it.
I tested it and concluded that it depends on in-game delays, because when repeating the same battle multiple times, the spell-casting units attacked different stacks. It's possible that other conditions exist (e.g., with an 80% probability for the upper stack, 20% for the lower stack), but it definitely depends on the delays.
So, if there's a chance to attack one of two or more stacks, it's impossible to predict with 100% certainty which one will be targeted. It might be possible to predict with some degree of probability, but that would require a deep dive into the game's mechanics (which AlexSpl is capable of).
Charity suffereth long, and is kind; charity envieth not; charity vaunteth not itself, is not puffed up,
Doth not behave itself unseemly, seeketh not her own, is not easily provoked, thinketh no evil;
Rejoiceth not in iniquity, but rejoiceth in the truth;
Beareth all things, believeth all things, hopeth all things, endureth all things. Charity never faileth...