For more than a decade, Spain seemed immune to the steady eruptions of Islamist violence that rocked other European countries where radicalized young men, often from poor immigrant backgrounds, carried out devastating bomb, gun or vehicular attacks.

Spain’s security forces carved out a reputation as some of Europe’s most dogged counterterrorism operators, fighting an intense battle beneath a deceptively placid surface in a country whose long Mediterranean coastline, just across from Morocco, makes it an inviting entry point into Europe for jihadists.

But the illusion of a Spanish haven was shattered Thursday when a van swerved down Las Ramblas, Barcelona’s famous pedestrian boulevard, leaving behind a trail of bodies including 13 dead and about 100 injured. Another person was killed in a second attack at a nearby seaside resort that ended when the police shot dead five suspected assailants.

Now, the authorities are rushing to answer how a group that included teenagers was able to carry out a well-planned and coordinated attack in a country that has parried danger for so long, despite being such a tempting and symbolic target for Islamists.