
const fs=require("fs"),vm=require("vm");
function E(){return{innerHTML:"",textContent:"",children:[],appendChild(x){this.children.push(x)},prepend(x){this.children.unshift(x)},remove(){},lastChild:null,onclick:null,value:"",files:[]}}
const els={},store={};
const ctx={console,Math,Date,Blob:function(){},URL:{createObjectURL(){return"blob:x"}},FileReader:function(){},
localStorage:{setItem(k,v){store[k]=v},getItem(k){return store[k]??null}},
document:{getElementById(id){return els[id]||(els[id]=E())},createElement(){return E()}},window:{}};
ctx.window=ctx;vm.createContext(ctx);
for(const f of ["data.js","tournaments.js","engine.js","game.js"])vm.runInContext(fs.readFileSync(__dirname+"/"+f,"utf8"),ctx);vm.runInContext("globalThis.__E=Engine;",ctx);
const T=ctx.FOOTBALL_TOURNAMENTS,Q=ctx.__FIFA_CUP_QA;
function A(c,m){if(!c)throw Error(m)}
A(T.length===4,"4 tournaments");
const map=Object.fromEntries(T.map(x=>[x.id,x]));
A(map.ucl.teams.length===36,"ucl teams "+map.ucl.teams.length);
A(map.uecl.teams.length===36,"uecl teams "+map.uecl.teams.length);
A(map.euro.teams.length===24,"euro teams "+map.euro.teams.length);
A(map.worldcup.teams.length===48,"wc teams "+map.worldcup.teams.length);
for(const t of T)for(const id of t.teams)A(ctx.__E.club(id),`${t.id} club missing ${id}`);

// UCL: complete synthetic league table -> top 24 produce playoffs / R16.
Q.startTournament("ucl",map.ucl.teams[0]);
let s=Q.getState();let rank=0;for(const id of map.ucl.teams){let r=s.tournament.table[id];r.p=8;r.pts=100-rank;r.gf=50-rank;r.ga=rank;rank++}
Q.buildLeagueKnockout();s=Q.getState();
A(s.tournament.phase==="knockout","ucl knockout");
A(s.tournament.knockout[0].length===8,"ucl playoff 8 ties");

// EURO: complete six group tables -> 16 qualifiers.
Q.startTournament("euro",map.euro.teams[0]);s=Q.getState();
for(const tb of s.tournament.groupTables){let i=0;for(const id of Object.keys(tb)){tb[id].p=3;tb[id].pts=9-i*2;tb[id].gf=8-i;tb[id].ga=i;i++}}
Q.buildGroupKnockout();s=Q.getState();A(s.tournament.knockout[0].length===8,"Euro R16");

// World Cup: 12 groups -> 32 qualifiers -> 16 R32 ties.
Q.startTournament("worldcup",map.worldcup.teams[0]);s=Q.getState();
for(const tb of s.tournament.groupTables){let i=0;for(const id of Object.keys(tb)){tb[id].p=3;tb[id].pts=9-i*2;tb[id].gf=8-i;tb[id].ga=i;i++}}
Q.buildGroupKnockout();s=Q.getState();A(s.tournament.knockout[0].length===16,"WC R32");

// Save state serializability.
let raw=JSON.stringify(s);A(raw.length>1000,"serialize");
console.log(JSON.stringify({tournaments:T.map(x=>({id:x.id,teams:x.teams.length})),uclPlayoffTies:8,euroR16Ties:8,worldCupR32Ties:16,save:"serializable"}));
