BARCELONA(NYTIMES) - For more than a decade, Spain seemed immune to the steady eruptions of violence by Islamic militants that rocked other European countries where radicalised 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 counter-terrorism 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 extremists.
But the illusion of a Spanish haven was shattered on 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 suspects.
Now, 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 Islamic militants.
"For the jihadis, Spain is still very much a front-line country," said Bruce Hoffman, a Georgetown University professor who has advised the U.S. government on terrorism.
Since 2004, when a series of bombs ripped through commuter trains in Madrid, killing 192 people, Spain has foiled a long list of plots by Islamic militants - not least in the coastal area around Barcelona where Thursday's attacks took place.
Over 700 suspected extremists have been arrested since 2004, according to the Interior Ministry. They include Pakistanis plotting suicide attacks on the Barcelona subway in 2008; a terrorist cell in Melilla, Spain's territory in North Africa; and nine, mostly Moroccan, men arrested in April in connection with the March 2016 attacks in Brussels that targeted the city's airport and a subway station.
Last year, the Spanish authorities quashed a possible plot to drive a truck through crowds, similar to earlier attacks in Berlin and in the French city of Nice, and they intercepted a shipment by sea of 20,000 uniforms being smuggled to militants in Syria and Iraq.
"The Spanish authorities are at the top of the game in Europe," said Matthew G. Olsen, a former director of the National Counter-terrorism Center. "My sense is they have been extremely successful in identifying and disrupting attacks." Galvanized by the 2004 Madrid attacks in the same way the Sept. 11, 2001, terrorist attacks served as a wake-up call for Americans, the Spaniards built on their decades of experience in fighting ETA, the Basque separatist movement, and introduced a raft of laws that helped to disrupt radical cells.
But counter-terrorism is partly a matter of luck, and on Thursday, Spain's ran out with a plot whose size and complexity offered a sobering reality check.
Some of the young men involved in the attacks in Barcelona and Cambrils were teenagers, and investigators believe they had lived double lives as they planned the attacks for a year at a house in Alcanar, a sleepy town 120 miles down the coast from Barcelona.
It offered a stark reminder of the challenge in Catalonia, a region with a reputation as a burgeoning hub of Islamic extremism.
The economic boom in Catalonia, home to just over a quarter of Spain's almost 2 million Muslim residents, attracted large numbers of Muslim migrants from Morocco, Algeria and South Asia. But many struggled to integrate and were drawn to clusters of radical Salafi mosques that sprang up around a handful of smaller towns.
In a diplomatic cable in 2007, State Department officials warned that the area, with its large population of disaffected, male and unmarried Muslim immigrants, had become "a magnet for terrorist recruiters." As far back as the Sept. 11, 2001, attacks, investigators found themselves scrutinising the area.
"There is a history there," said Lorenzo Vidino, the director of the George Washington University Program on Extremism. "If you look at Google maps, the next town over from Cambrils is Salou. You can literally walk it. And Salou is the town where Mohamed Atta had his last meeting in Europe before 9/11," he said, referring to the pilot of the first plane to fly into the World Trade Center, who is believed to have met with a Qaeda figure in Salou before the 2001 attack.
But Spain does not loom as a primary focus for Islamic militants. Although a staunch NATO ally, the country has been a marginal player in the United States' wars in Iraq and Afghanistan. Even as they aggressively intercepted terrorist cells, Spain's leaders have prided themselves on their efforts to integrate Muslims into mainstream society.
Despite an economic crash and high unemployment since the 2008 financial crisis, Spain has not seen the emergence of hard-line, anti-Muslim political movements as elsewhere in Europe.
Around 200 Spanish residents are believed to have travelled to Syria and Iraq to join the fighting there - a fraction of the hundreds who have gone from countries like Britain and France.
Yet Spain cannot escape its symbolic attraction for Islamic militants that is rooted deep in its history. Between the eighth and 15th centuries a large part of the Iberian Peninsula was ruled by Muslim caliphs, and extremist websites often speak fancifully about a return to the era of Al-Andalus, as medieval Spain was known.
And despite its efforts at integration, Spain has struggled with extremist currents inside its Moroccan communities, in much the same way as British officials deal with Pakistani communities and the French with residents of Tunisian or Algerian descent.
That problem is linked to Spain's close, if sometimes testy, historical relationship with Morocco, which accounts for much of the country's Muslim migration.
Almost all of the dozen suspects in Thursday's attacks have been identified as Moroccans or of Moroccan origin. That is the same background as the ringleader and the foot soldiers of the Paris attacks on Nov. 13, 2015, as well as of the men who rolled suitcase bombs into the Brussels airport on March 22, 2016.
In August 2015, Ayoub El-Khazzani, a Moroccan-born man who lived in the south of Spain, was overpowered by passengers on a high-speed train travelling between Amsterdam and Paris after he opened fire with a Kalashnikov rifle. Khazzani was said to have been radicalized in a mosque in Algeciras, Spain.
Over 1,600 Moroccans have joined the Islamic State in Syria and Libya, according to Morocco's Interior Ministry, and security experts believe there are hundreds of sympathizers inside the country.
"What's astounding is that an attack like this hasn't taken place inside Morocco," said Issandr El Amrani, an analyst with the International Crisis Group, which recently published a study of Islamic State activities in North Africa.
Spanish counterterrorism relies heavily on cooperation with the Moroccan security forces, who have successfully penetrated migrant communities across Europe through a strong network of informants, despite concerns from human rights groups about their methods, Amrani said.
But that assistance also depends on the political relationship between the countries, which has been dogged by tensions over Ceuta and Melilla, Spain's enclaves in North Africa, and a simmering dispute over the Western Sahara region.
While it has cut costs in other areas, the Spanish government raised both the staff numbers and the budget this year for its intelligence services. Toughened anti-terrorism legislation has allowed authorities to arrest suspects at an earlier stage of attack planning than in Britain and elsewhere.
Until this week's attacks, 54 people had been arrested this year on suspicion of terrorist activity in Spain, where the threat of returnees from Syria is deemed relatively small.
But like so many intelligence agencies in Europe, the Spanish are overwhelmed by the volume of potential terrorism plots they are trying to monitor, said Seth G. Jones, a terrorism specialist at the RAND Corp.
"They're totally swamped with leads," he said. "There is no way they can cover all their current open cases."