Nial Ferguson in the Ascent of Money cites Spain as the canonical case of a state that just doesn't get economics.
Philip II of Spain defaulted on debt four times - in 1557, 1560, 1575 and 1596 - becoming the first nation in history to declare sovereign default due to rising military costs and the declining value of gold, as it had become increasingly dependent on the revenues flowing in from its mercantile empire in the Americas.
Let me emphasize "the declining value of gold" - gold has very little intrinsic value. When gold is used as a medium of exchange, the value is set by the market, and adding more gold will only generate inflation. Inflation encourages borrowing and discourages lending; the tension between those two hampers the ability of the economy to invest, or even to spend money wisely. (I lack the background in Spanish history to draw the relationship between the effects of inflation and the expulsion of the Jews, but it seems to me that there may be an interesting story there.) (There is also probably an interesting paper on macroeconomic errors of a mercantile economy, but I have neither the skill, nor the time, nor the space, to write that paper.)
Adding specie to an economy doesn't enable the country to spend the money wisely. To defeat the Barbary pirates, Spain would have had to construct a superior fleet. Fleet building is a long term investment - even if you can produce the ships quickly, you need to produce professional sailors, admirals and tactics, and you have to ensure that the fleet is supported by solid logistics. That kind of investment is difficult to make in times of high inflation. In an environment where the throne regularly defaults, I would suggest that it is imprudent to participate in such a long term investment.
I think it would also be interesting to examine the actual inflow of specie compared to the expected inflow of specie. I think that the Spanish Throne and the Spanish economy probably reasoned as you do that they had access to the "wealth of a continent". In truth they had a capital inflow - large, but limited. In order to make use of the wealth of the continent, they would have to borrow against future inflows, and lending to the Spanish throne was not a good idea. Furthermore I'm not sure that they accounted for the rising cost of obtaining and defending that capital inflow.
Complex question, and I'm sure that there are many book-length answers.