You use this when something happens that you did not expect. It is a surprise. You thought one thing, but the opposite happened.
に、で。
Just when I thought we had won the match, we suffered a comeback loss in the final few seconds.
、に。
Just when I thought it had finally cleared up, it started raining again right away.
、。
Just when I thought the project was complete, the client came back with additional requests.
、に。
Just when I thought nobody else was coming, Tanaka-san popped in right at the end of the party.
、。
In what turned out to be a tough fight contrary to expectations of an easy win, the team barely managed to secure victory.