We need to appreciate the powerful effect of the identity-based populations that every person has. If a person identifies with some issue or cause, they become a member of a distributed population who also identify with that same issue. Each person is a member of literally thousands of these populations, and has their own priority for how they value these identities relative to each other.

The most important identities are those a person is willing to kill or die for. If I identify as a Sunni and prioritize identity I would reasonably see joining ISIS as a way to help preserve and advance issues critical to that identity. If I return home to perceived discrimination by my nation because i am a member of that Sunni population i have an internal crisis i must resolve. I will reasonably come to value my Sunni identity over my national identity (as most religious people of any ilk do).

This isn't voodoo magic or mass brainwashing - it is just common sense and human nature. None of that validates acts of terrorism, but when legal and less drastic approaches are either denied or ineffective in addressing the perceived grievances, people of every culture historically will ultimately act out.