Trying to generate unique match pairing for each team similar to 2024/25 UEFA Champion League Swiss system format

I’m trying to make a tournament pairing similar to the new UEFA Champion League format. There are 36 teams competing in the league phase. They are divided into 4 pots. Each team will play 8 matches (2 opponents from each pot). That adds up to 144 matches in total. I have a hard time coming up a function with good backtracking logic. Here is my failed code:

https://jsfiddle.net/4cgm1Lo8/5/

const pots = [
    ["A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8"],
    ["B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8"],
    ["C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8"],
    ["D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8"],
];

const MATCH_COUNT = 144;
const MAX_ROUNDS = 8

function run() {
    const teamIds = _.flatten(pots)
    return teamIds.reduce((matches,thisTeamId) => {
        for (let round = 0; round < MAX_ROUNDS; round++) {
            const thisTeamMatches = matches.filter(match => match.includes(thisTeamId))
            if (thisTeamMatches.length >= MAX_ROUNDS) {
                break;
            }
            const pool = teamIds.filter(poolTeamId => {
                const encounteredBefore = thisTeamMatches.find(match => match.includes(poolTeamId))
                const potEncounterCount = thisTeamMatches.filter(match => {
                    const opponentId = match.find(m => m != thisTeamId)
                    return getTeamPot(opponentId, pots) === getTeamPot(poolTeamId, pots)
                })
                const poolTeamIdMatches = matches.filter(match => match.includes(poolTeamId))
                return poolTeamId != thisTeamId && !encounteredBefore && potEncounterCount.length < 2 && poolTeamIdMatches.length < MAX_ROUNDS
            })
            matches.push([thisTeamId, _.sample(pool)])
        }
        return matches
    }, [] as string[][])
}



function getTeamPot(teamId: string, pots: string[][]) {
    return pots.findIndex((pot) =>
        pot.find((potTeamId) => potTeamId === teamId),
    );
}

function getOpponent(yourTeamId: string, match: string[][]){
    return match.find(m => m != thisTeamId)                 
}

console.log(run())

This function is unable to create 144 matches. Some of the matches created have undefined opponents. The code really doesn’t account for situations where it is unable to find a valid opponent for a team.

How would you make a backtracking method so that it can fill up some of the matchups that contains undefined opponent?