Last summer, the YMCA quietly began making plans to to sell its hulking McBurney Y building on 23rd Street, and evict the few dozen tenants that were still living there. But Chelsea residents soon found out about the plan–and, in concert with local politicians and tenant advocates, raised a major ruckus over the sale.

Now, the Y has worked out an intricate deal that seems to make everyone happy. The housing nonprofit Common Ground and real estate developer Time Equities will purchase the old McBurney buildings for $17 million, splitting the space into a section for tony new lofts and second part with inexpensive housing with social services for poor and formerly homeless people. The 13 remaining tenants of the McBurney will be able to move back into the building once all the work is done.

Common Ground, which runs several other massive supportive housing developments in Manhattan, also will set up a unique residential program to help 18- to 25-year-olds who are aging out of foster care. About 40 apartments will be built especially for these young adults, who often must resort to sofa-hopping when they get too old to stay in group homes.

“It’s a complicated deal,” said Common Ground executive director Rosanne Haggerty. “But from early on, the Y saw that our proposal fit with their mission and their commitment to working with young people.”

For its part, the Y will build a new 67,000-square-foot center on 14th Street, complete with swimming pool and computer center. And local residents and merchants won’t have to fight off the Costco superstore that was originally planned for that 14th Street site.

The developments will be funded through the city’s housing department and child welfare department, with contributions from the borough president and local State Assembly and City Council members.