This is one of the great unknowns that keeps me up at night pondering about how it all works.
It's one of those topics that becomes more mindblowing the more you know about it, or related topics such as AI/ML research.
Random examples:
How does sexual attraction get encoded in the brain? Think about how complex and subtle the selection criteria has to be to reliably[1] pick out "same species", but not "same sex of the same species". The distinguishing attributes are subtle, such as slight changes of the fat distribution of the face, and a couple of body ratios[2]. But to identify body ratios, you need to be able to identify bodies, ratios, and have that entire mapping from the visual cortex all the way through to the arousal centre of your brain be learned in a way that is consistent with something encoded in your genetics that was laid down in your neurons before birth, at a time when you had not yet seen anything, let alone male or female humans!
The other one that blows my mind is how terrestrial animals are afraid of heights. This has been studied at length, and despite this the exact mechanism is not perfectly understood. Even babies are afraid of crawling over a ledge. But think about it: what is a ledge? It's not just "an edge", it has to have a certain spatial orientation to be dangerous and scary! This instinct is baked into every brain, but its trigger is a complex combination of head angle, gaze angle, depth perception, and 3D geometry! Even animals that don't have stereoscopic vision are able to identify a dropoff and be afraid of it.
To me the most amazing is how all quadruped grazing animals are able to walk or even run from birth. That's a staggering level of neural training pre-baked before birth! Vision, proprioception, muscle control, everything pre-trained to the point of some animals able to outrun a cheetah on rough terrain mere days after plopping out of their mother! Go ask Boston Dynamics how hard a problem this is to solve...
[1] Actually, the failure modes are educational! Bestiality and furry tendencies indicate that this neural encoding is based on a shared set of traits with all mammals, but with species-specific aspects. Clearly the filters are good, but not perfect.
[2] Apparently just some specific curves suffice: https://www.etsy.com/au/listing/673314609/sexy-lovers-art-pr...