If Carlos II dies in 1665, that still leaves one of Philip IV's sons still alive. Albeit this one isn't legitimate
Don Juan was the head of the government of Spain in OTL during this period. With Carlos II dead, I'd imagine he'd use his influence to see to it that the Cortes acknowledged his father and mother's relationship as legitimate (which some argue it might have been) thereby making him the Legitimate king.
Crowned as King Juan I of Spain, he could very well be exactly the kind of Monarch Spain needs at the time. Strong willed, charismatic, intelligent, and with a degree of military skill, under his leadership Spain could very well begin to recover somewhat, although it would be a long road ahead.
As for further Spanish succession, I've yet to find sources on Don Juan's wife. I'd imagine he had one at any rate. And given the fact that he was not legitimate I'd say it's a fair chance that she wouldn't be related to him. If he wasn't married, I'd wager that Juan would seek to marry into a prominent noble family inorder to gain some allies. At any rate, pressure would be on for Juan to produce an heir. Seeing that, if he doesnt, Spain goes down the crapper, let's assume that he does let's call him Philip V.
Philip V is quite unlike any of the Spanish Hapsburgs that had proceeded him. Due to the illegitimacy of his father and the fact that his father chose to marry outside of the Hapsburg family, the genetic deficiencies inerherent within the Spanish Hapsburgs have been watered down to a tolerable level. In essence, the Spanish Hapsburgs have been given a second lease on life.
For argument's sake let's say that Philip V is born in 1666, a year after Juan is crowned.
Due to no conflicts with Carlos II's mother, Juan is healthier and let's say he lives another 10 years, dieing in 1689. Leaving Philip V, a man much like his father, at 23 to assume the throne and lead Spain throughout the tumultuous first half of the 18th century.