WASHINGTON — Led by a chief justice who some conservatives immediately branded a turncoat, the Supreme Court upheld most of President Obama's healthcare law Thursday, resolving a high-stakes constitutional clash not seen in decades and handing Obama a victory that surprised many in Washington.

Chief Justice John G. RobertsJr.and the four liberal justices joined to uphold the Democrats' most ambitious social legislation in a generation.

The unpopular requirement that everyone buy health insurance or pay a penalty — likened by detractors to a rule that everyone purchase broccoli — was unconstitutional as a mandate, Roberts said, but valid as long as it was simply considered a tax.

"We do not consider whether the act embodies sound policies," wrote Roberts, a conservative appointed to the court by PresidentGeorge W. Bushin 2005. "That judgment is entrusted to the nation's elected leaders. We ask only whether Congress has the power under the Constitution to enact the challenged provisions."

Obama, who had staked the success of his presidency on passage of the law, initially thought he had lost when Fox News and CNN incorrectly reported the mandate had been struck down. But after he retreated to his offices to ponder his defeat, White House Counsel Kathryn Ruemmler walked in to give him the thumbs-up.

"First, there were dark clouds," one aide said, "and then there was joy."

Obama's first call was to Solicitor Gen. Donald B. Verrilli Jr., who had insisted on presenting the tax argument to the justices.

Later the president went before television cameras to pronounce the ruling "a victory for people all over this country whose lives will be more secure because of this law and the Supreme Court's decision to uphold it."

Republican presidential candidate Mitt Romney, who also awaited the court's decision in Washington, used the ruling as a call to arms.

"Our mission is clear. If we want to get rid of Obamacare, we are going to have to replace President Obama. My mission is to make sure we do exactly that," Romney said, standing behind a lectern decorated with a sign that said, "Repeal and Replace Obamacare."

But the decision was not a total victory for the administration. One part of the law would greatly expand Medicaid to cover an additional 17 million low-income people. Although Washington would pay nearly all the extra cost, states ultimately would pay a small portion of the bill.

Roberts said the required expansion of Medicaid would violate the rights of states by threatening them with the loss of all their Medicaid money if they refused.

"The states are given no choice in this case," Roberts wrote, likening the requirement to "a gun to the head."

Instead, Roberts wrote, states must be given the right to opt out of expanded coverage. That raises the likelihood of a wide gap in coverage between states with Democratic majorities, which are already eager to cover more residents under Medicaid, and conservative states, which are likely to say no, even if it means turning down large amounts of federal money. Already on Thursday, some Republican governors were saying they would opt out.

Overall, the new law, which already is being phased in, will require insurers to offer coverage to all, even those who have serious diseases. And it will require those who can afford it to carry "minimum" coverage. Republican state officials sued to strike down the law before it could take full effect, arguing this insurance "mandate" amounted to an unprecedented and unconstitutional overreach by the Democrats.

The chief justice, defying many predictions, found a way to uphold the law in an opinion that steered something of a middle course.

On the one hand, Roberts agreed with the law's conservative challengers who said Congress did not have the power to compel the purchase of a private product such as health insurance.

But in practice, the only penalty the law provides for not complying is an extra charge on income tax returns beginning in 2015 for those who choose not to have insurance coverage.

And that is constitutional, Roberts said.

"The federal government does not have the power to order people to buy health insurance," he wrote in the majority opinion. "The federal government does have the power to impose a tax on those without health insurance."

Justices Ruth Bader Ginsburg, Stephen G. Breyer, Sonia Sotomayor and Elena Kagan joined Roberts to form the majority, but they said the mandate was constitutional even without considering it a tax.

The tax would start at $95 in 2015 and increase to $695 by 2017 — far less than the cost of insurance. Even so, it is expected to raise about $4 billion a year to help pay for healthcare coverage.

During oral arguments in March, Roberts and his fellow conservatives made clear they were skeptical of the government's claim that it could require Americans to buy insurance. The taxing power was mentioned only briefly and hardly debated.

JusticeAnthony M. Kennedy, normally the court's swing vote, found himself in the unusual position of speaking for the four dissenters in a major case. They would have thrown out the entire law.

Speaking in harsh tones, Kennedy said the court majority "regards its statutory interpretation as modest. It is not. It amounts to a vast judicial overreaching. It creates a debilitated, inoperable version of healthcare regulation that Congress did not enact and the public does not expect." Justices Antonin Scalia, Clarence Thomas andSamuel A. Alito Jr. agreed in the joint dissent.

"The values that should have determined our course today are caution, minimalism, and the understanding that the federal government is one of limited powers," the dissenters said. "But the court's ruling undermines those values at every turn. In the name of restraint, it overreaches. In the name of constitutional avoidance, it creates new constitutional questions. In the name of cooperative federalism, it undermines state sovereignty."

Although some conservatives, clearly stung by a sense of betrayal, excoriated the chief justice, constitutional experts praised him for rising to the occasion in a momentous case. During his confirmation hearings in 2005, Roberts said he aspired to be a modest and restrained judge, one who would not casually second-guess elected officials.

"This was an impressive feat of statesmanship by the chief justice," said New York University law professor Richard Pildes. "Legal analysis, not politics, controlled the decision."

"When the chips were down, Roberts did exactly what he promised to do under oath," said Harvard law professor Noah Feldman. "He stayed the court's hand and rejected activism."

That opinion was anything but universal. Conservative legal activist Larry Klayman vowed to seek "an indictment" of the chief justice before "a citizens grand jury."

Jack Kingston, a Republican from Georgia, tweeted: "With ¿#Obamacare ruling, I feel like I just lost two great friends: America and Justice Roberts."

But other conservatives had a more measured response.

Randy Barnett, the Georgetown University law professor who led the legal challenge to the mandate, took comfort from the first part of Roberts' opinion limiting Congress' power to compel purchases. "By rewriting the law to make it a 'tax,' the court has now thrown Obamacare into the political process where the people will decide whether it will stand," he said.

House Republicans responded by scheduling another vote to repeal the law. Even if it passes the GOP-controlled House, however, it will almost certainly die in the Senate — as have previous attempts.

david.savage@latimes.com

Christi Parsons, Kathleen Hennessey, Lisa Mascaro, Noam N. Levey and Michael A. Memoli in the Washington bureau contributed to this report.