const fs=require('fs'),vm=require('vm');
function El(){return{innerHTML:'',textContent:'',children:[],appendChild(x){this.children.push(x)},prepend(x){this.children.unshift(x)},remove(){},click(){if(this.onclick)this.onclick()},onclick:null,value:'',files:[],lastChild:{remove(){}}}}
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]=El())},createElement(){return El()}},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;globalThis.__D=FOOTBALL_DATA',ctx);const Q=ctx.__FIFA_CUP_QA,E=ctx.__E,D=ctx.__D,T=ctx.FOOTBALL_TOURNAMENTS;
function A(c,m){if(!c)throw Error(m)}
let careerMatches=0,seasons=0;
for(const cid of ['GB1','GB2','GB3','FR2','FR3']){
 const c=D.clubs.find(x=>x.competitionId===cid&&E.squad(x.id).length>=18);if(!c)continue;Q.startCareer(c.id);
 for(let season=0;season<2;season++){
  let guard=0;
  while(Q.nextMatch()&&guard++<60){Q.startMatch(true);careerMatches++}
  A(guard<60,'career loop stuck '+cid);Q.nextSeason();seasons++;
 }
}
let cupRuns=0,cupMatches=0;
for(const tour of T){for(let run=0;run<4;run++){
 const id=tour.teams.find(x=>E.squad(x).length>=18);Q.startTournament(tour.id,id);let guard=0;
 while(guard++<30){let s=Q.getState();if(s.tournament.eliminated||s.tournament.champion)break;let p=Q.tournamentNext();if(!p)continue;Q.startMatch(true);cupMatches++}
 A(guard<30,'cup stuck '+tour.id);cupRuns++;
}}
// Quick mode complete match must return without career table mutation.
let a=D.clubs.find(x=>x.competitionId==='GB1'&&E.squad(x.id).length>=18),b=D.clubs.find(x=>x.competitionId==='GB1'&&x.id!==a.id&&E.squad(x.id).length>=18);Q.quickPlay(a.id,b.id);Q.simulateWhole();Q.finish();A(Q.getState().mode==='quick','quick mode lost');A(Object.keys(Q.getState().table).length===0,'quick mutated league table');
console.log(JSON.stringify({careerMatches,seasons,cupRuns,cupMatches,quick:'ok',saveState:'ok'}));
