Julie (Johnston) Ertz is a bit excited about scoring the match winner in the 89th minute in San Diego. Megan Rapinoe had scored the equalizer four minutes earlier. (Mike Blake/Reuters)

Up until the dying moments of Sunday’s match, the Tournament of Nations had gone terribly wrong for the U.S. women’s national team. A defeat to Australia on Thursday ended a 27-game unbeaten streak against the Matildas, and on Sunday, the Americans trailed Brazil by two goals with about 10 minutes left.

But then Christen Press scored and then Megan Rapinoe nabbed the equalizer, and in the 89th minute before 21,096 at San Diego’s Qualcomm Stadium, Julie (Johnston) Ertz stabbed in a loose ball for an implausible 4-3 victory.

Australia, sitting on six points after a 4-2 triumph over Japan earlier in the day, remains in prime position to win the trophy Thursday in Carson, Calif. But the Americans (three points) will take heart from their biggest comeback victory since overcoming a two-goal deficit against France at the 2012 London Olympics (4-2 in the group opener in Glasgow).

Brazil went ahead 67 seconds into the match on goalkeeper Alyssa Naeher’s gaffe:

Samantha Mewis equalized in the 18th minute:

Brazil scored twice in a 15-minute span for a 3-1 lead:

But Press scored her 43rd international goal:

Rapinoe scored her first international goal since the 2015 World Cup opener:

And Ertz scored her first international goal that didn’t come off a set piece:

The Americans are 6-3-0 in 2017 and 27-3-5 in the all-time series against Brazil. The tournament concludes Thursday at StubHub Center with Australia facing Brazil (7:15 ET, WatchESPN, ESPN3.com) and the United States playing Japan (10 p.m., ESPN2, Univision Deportes, WatchESPN, ESPN3.com).

USA: Alyssa Naeher; Taylor Smith (Julie Ertz 57th), Abby Dahlkemper, Casey Short (Sydney Leroux 76th), Kelley O’Hara; Becky Sauerbrunn, Samantha Mewis (Allie Long 86th), Carli Lloyd; Crystal Dunn (Mallory Pugh 53rd), Alex Morgan (Christen Press 57th), Megan Rapinoe (Lynn Williams 90+).

Subs not used: Jane Campbell, Abby Smith, Morgan Brian, Lindsey Horan, Ali Krieger, Margaret Purce.