So evolution is an optimization process. On a constantly changing landscape.
And this is getting away from the central point, but there's also much debate (at least at the level I'm reading; maybe it's solved by now for those in the field) about how traits can support a community at the expense of the individual - like with old humans losing the ability to procreate.
https://en.wikipedia.org/wiki/Kin_selection
tl;dr: those in the community have almost the same genes as you, so helping them is almost as beneficial as helping yourself.
The only thing evolution does is favor one adaptation over another. At that point in time, a particular mutation/adaptation may work out better (though frequently due to pure chance), so it survives and gains inertia. Inertia is a very powerful thing; it's why we have a lot of big companies that don't seem to do that well, laws that don't make much sense, etc. Once something is in place, it's hard to change it. The same thing is true of evolution. It does not always result in the most optimal configuration, or even frequently.
There's plenty of examples of things in the human anatomy which are actually terrible "design" choices, but when viewed through the lens of evolution, make sense. A famous example is some nerve (I forget the name now) that takes a ridiculous and non-sensical route, but when you look at the history of how we evolved, it makes sense that it got stuck there because of what came before. It's like that with a lot of human technology too; train tracks, for instance, weren't spaced at their current spacing (gauge) because it was the optimal design choice (esp. not now with modern trains and cargo sizes), they did it because technologies and tooling and infrastructure that came before made it easier to use that gauge than to switch to something different. If we could change things, it'd make more sense to increase the standard gauge on most railways, but there's too much inertia and it'd cost too much.