Chris Brown won a big victory in custody court Friday, but it could get derailed because of an on-the-spot drug test.
TMZ broke the story, Chris got temporary joint custody of Royalty, where he and baby mama Nia Guzman rotate every 4 days.
Sources close to Nia tell TMZ, something else happened in court. Her lawyer asked the judge to force Chris to submit hair and urine samples for drug tests, and the judge ordered Chris to ante up on the spot.
The judge didn't say what he would do if the tests came back positive for drugs ... it would obviously depend in part what type of drugs, if any, were present in his system.
Our Nia sources also say Chris' custody win had strings attached ... his mom must be present when he has physical custody of his 1-year-old.
We're told in 12 days Chris and Nia must go into mediation to hopefully agree on a long-term custody and support agreement. If they can't, the 4-day rotation will continue and a full-blown trial will be scheduled.