const fs=require('fs'),vm=require('vm');
function E(id=''){let html='';return{id,textContent:'',children:[],onclick:null,onchange:null,value:'',files:[],set innerHTML(v){html=v;if(v==='')this.children=[]},get innerHTML(){return html},appendChild(x){this.children.push(x);return x},prepend(x){this.children.unshift(x);return x},remove(){},lastChild:null,click(){if(this.onclick)return this.onclick()}}}
const els={},store={};['actions','screen','log','status','saveBtn','loadBtn','newBtn','exportBtn','importBtn','importFile'].forEach(id=>els[id]=E(id));
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(id))},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;globalThis.D=FOOTBALL_DATA;',ctx);
const Q=ctx.__FIFA_CUP_QA,E2=ctx.E;function A(c,m){if(!c)throw Error(m)}
const club=ctx.D.clubs.find(c=>E2.squad(c.id).length>=22 && !c.national);A(club,'club');
Q.startCareer(club.id);let s=Q.getState();const auto=[...s.xi],bench=E2.squad(club.id).filter(p=>!auto.includes(p.id)&&!p.injury&&!p.suspension).slice(0,3);A(bench.length>=2,'bench');
s.xi[1]=bench[0].id;s.xi[7]=bench[1].id;const manual=[...s.xi];Q.setState(s);
els.saveBtn.onclick();s=Q.getState();s.xi=[...auto];Q.setState(s);els.loadBtn.onclick();s=Q.getState();A(s.xi[1]===manual[1]&&s.xi[7]===manual[7],'save/load manual XI');
Q.startMatch(false);s=Q.getState();const matchXI=s.match.userHome?s.match.homeXI:s.match.awayXI;A(matchXI[1]===manual[1]&&matchXI[7]===manual[7],'manual XI lost at kickoff');
const beforeState=[...s.xi],xi=s.match.userHome?s.match.homeXI:s.match.awayXI,sub=E2.squad(club.id).find(p=>!xi.includes(p.id)&&!p.injury&&!p.suspension);A(sub,'sub');xi[0]=sub.id;A(s.xi[0]===beforeState[0],'match XI aliases saved XI');
console.log(JSON.stringify({club:club.name,manualSaved:true,kickoffPreserved:true,matchCopy:true}));
