/* Version 2.2 – globale Ligen, Spieltagsresultate, Trainingstransparenz */
(() => {
  const positionOrder = {TW:0,RV:1,IV:2,LV:3,DM:4,ZM:5,RA:6,LA:7,ST:8};
  let selectedWorldLeague = '';
  let selectedWorldClub = '';

  function leagueKey(country, name){ return `${country}|||${name}`; }
  function safeDate(){
    const start = new Date(2026, 7, 1, 12, 0, 0);
    start.setDate(start.getDate() + Math.max(0, (Number(state?.week)||1)-1) * 7);
    return start.toLocaleDateString('de-DE',{weekday:'short',day:'2-digit',month:'2-digit',year:'numeric'});
  }
  function createSchedule(clubs){
    if (typeof createLeagueSchedule === 'function') return createLeagueSchedule(clubs);
    const ids=clubs.map(c=>c.id); if(ids.length%2)ids.push(null); const rounds=[],a=[...ids];
    for(let r=0;r<a.length-1;r++){const games=[];for(let i=0;i<a.length/2;i++){const h=a[i],aw=a[a.length-1-i];if(h&&aw)games.push({home:h,away:aw,played:false});}rounds.push(games);a.splice(1,0,a.pop());}
    return [...rounds,...rounds.map(g=>g.map(x=>({home:x.away,away:x.home,played:false})))];
  }
  function resetStats(club){ Object.assign(club,{played:0,wins:0,draws:0,losses:0,gf:0,ga:0,points:0,form:[]}); }
  function worldApply(league, fixture, hg, ag){
    const h=league.clubs.find(c=>c.id===fixture.home),a=league.clubs.find(c=>c.id===fixture.away); if(!h||!a)return;
    [h,a].forEach(c=>c.played++);h.gf+=hg;h.ga+=ag;a.gf+=ag;a.ga+=hg;
    if(hg>ag){h.wins++;h.points+=3;a.losses++;h.form.unshift('S');a.form.unshift('N');}
    else if(hg<ag){a.wins++;a.points+=3;h.losses++;h.form.unshift('N');a.form.unshift('S');}
    else{h.draws++;a.draws++;h.points++;a.points++;h.form.unshift('U');a.form.unshift('U');}
    h.form=h.form.slice(0,5);a.form=a.form.slice(0,5);fixture.played=true;fixture.score=[hg,ag];
  }
  function worldPower(club){
    return [...club.squad].sort((a,b)=>b.rating-a.rating).slice(0,11).reduce((s,p)=>s+p.rating*(p.fitness||90)/100,0)/11;
  }
  function simulateWorldRound(league){
    if(!league?.fixtures?.length)return;
    if(league.round>=league.fixtures.length){league.round=0;league.clubs.forEach(resetStats);league.fixtures=createSchedule(league.clubs);}
    const round=league.fixtures[league.round]||[];
    round.forEach(f=>{if(f.played)return;const h=league.clubs.find(c=>c.id===f.home),a=league.clubs.find(c=>c.id===f.away);const hp=worldPower(h),ap=worldPower(a);worldApply(league,f,goalsFor(hp,ap,true),goalsFor(ap,hp,false));});
    league.lastRoundResults=round.map(f=>({home:f.home,away:f.away,score:f.score}));league.round++;
  }
  function ensureV22State(){
    if(!state)return;
    ensureV20State(); ensureV15State();
    state.v22 ||= {worldLeagues:[],lastRoundResults:[],trainingImprovements:[],campImprovements:[],version:22};
    const activeKey=leagueKey(state.league.country,state.league.name);
    const known=new Set(state.v22.worldLeagues.map(l=>leagueKey(l.country,l.name)));
    COUNTRIES.forEach((country,ci)=>country.leagues.forEach((def,li)=>{
      const key=leagueKey(country.name,def.name); if(key===activeKey||known.has(key))return;
      const l=buildLeague(ci,li);l.fixtures=createSchedule(l.clubs);l.clubs.forEach(c=>c.squad.forEach(p=>{p.value ||= Math.round(p.rating**3*45);p.fitness ||= rand(75,100);}));state.v22.worldLeagues.push(l);known.add(key);
    }));
    state.v22.worldLeagues=state.v22.worldLeagues.filter(l=>leagueKey(l.country,l.name)!==activeKey);
    if(!selectedWorldLeague){const first=state.v22.worldLeagues[0];selectedWorldLeague=first?leagueKey(first.country,first.name):'';selectedWorldClub=first?.clubs[0]?.id||'';}
  }
  function sortedLeagueTable(league){return [...league.clubs].sort((a,b)=>b.points-a.points||(b.gf-b.ga)-(a.gf-a.ga)||b.gf-a.gf);}
  function allLeagueOptions(){
    const active={country:state.league.country,name:state.league.name,active:true};
    return [active,...state.v22.worldLeagues].map(l=>`<option value="${esc(leagueKey(l.country,l.name))}" ${selectedWorldLeague===leagueKey(l.country,l.name)?'selected':''}>${esc(l.country)} · ${esc(l.name)}${l.active?' (deine Liga)':''}</option>`).join('');
  }
  function selectedLeagueObject(){
    if(selectedWorldLeague===leagueKey(state.league.country,state.league.name))return state.league;
    return state.v22.worldLeagues.find(l=>leagueKey(l.country,l.name)===selectedWorldLeague)||state.v22.worldLeagues[0]||state.league;
  }
  function leagueClub(league,id){return league.clubs.find(c=>c.id===id);}
  function buyWorldPlayer(leagueKeyValue,clubId,playerId){
    ensureV22State();const league=leagueKeyValue===leagueKey(state.league.country,state.league.name)?state.league:state.v22.worldLeagues.find(l=>leagueKey(l.country,l.name)===leagueKeyValue);
    const seller=league?.clubs.find(c=>c.id===clubId),p=seller?.squad.find(x=>x.id===playerId),buyer=getUserClub();if(!p||seller.id===buyer.id)return;
    const price=Math.round(Math.max(p.value||0,p.rating**3*42)*1.22/10000)*10000;
    if(buyer.budget<price)return alert(`Transferbudget reicht nicht. Benötigt: ${money(price)}`);
    if(!confirm(`${p.name} für ${money(price)} verpflichten?`))return;
    seller.squad=seller.squad.filter(x=>x.id!==p.id);buyer.squad.push(p);buyer.budget-=price;buyer.balance-=price;seller.budget+=price;seller.balance+=price;state.news.unshift(`${p.name} wechselt für ${money(price)} von ${seller.name} zu ${buyer.name}.`);save();render();
  }
  function leaguesView(){
    ensureV22State();const l=selectedLeagueObject();if(!selectedWorldClub||!l.clubs.some(c=>c.id===selectedWorldClub))selectedWorldClub=l.clubs[0]?.id||'';const club=leagueClub(l,selectedWorldClub);const table=sortedLeagueTable(l);const results=l.lastRoundResults||[];
    return `<div class="card"><h2>Ligen & Mannschaften</h2><div class="grid cols-2"><label>Liga<select id="worldLeagueSelect">${allLeagueOptions()}</select></label><label>Mannschaft<select id="worldClubSelect">${l.clubs.map(c=>`<option value="${c.id}" ${c.id===selectedWorldClub?'selected':''}>${esc(c.name)}</option>`).join('')}</select></label></div></div>
    <div class="grid cols-2" style="margin-top:16px"><div class="card"><h2>Tabelle · ${esc(l.country)} ${esc(l.name)}</h2><div class="table-scroll"><table><thead><tr><th>#</th><th>Verein</th><th>Sp</th><th>Tore</th><th>Pkt.</th></tr></thead><tbody>${table.map((c,i)=>`<tr><td>${i+1}</td><td>${clubNameWithCrest(c,'tiny')}</td><td>${c.played}</td><td>${c.gf}:${c.ga}</td><td><b>${c.points}</b></td></tr>`).join('')}</tbody></table></div>${results.length?`<h3>Letzter Spieltag</h3>${results.map(r=>{const h=leagueClub(l,r.home),a=leagueClub(l,r.away);return `<div class="fixture"><span>${esc(h?.name||'')}</span><b>${r.score?.join(' : ')||'–'}</b><span>${esc(a?.name||'')}</span></div>`}).join('')}`:''}</div>
    <div class="card"><h2>Kader · ${esc(club?.name||'')}</h2>${club?`<div class="table-scroll"><table><thead><tr><th>Pos</th><th>Spieler</th><th>Alter</th><th>Stärke</th><th>Fitness</th><th>Preis</th><th></th></tr></thead><tbody>${[...club.squad].sort((a,b)=>(positionOrder[a.position]??99)-(positionOrder[b.position]??99)||b.rating-a.rating).map(p=>{const price=Math.round(Math.max(p.value||0,p.rating**3*42)*1.22/10000)*10000;return `<tr><td>${p.position}</td><td>${esc(p.name)}</td><td>${p.age}</td><td><b>${p.rating}</b></td><td>${p.fitness}%</td><td>${money(price)}</td><td>${club.id===state.userClubId?'Eigener Spieler':`<button data-world-buy="${p.id}" data-world-club="${club.id}" data-world-league="${esc(leagueKey(l.country,l.name))}">Kaufen</button>`}</td></tr>`}).join('')}</tbody></table></div>`:'<p>Kein Verein ausgewählt.</p>'}</div></div>`;
  }
  function resultListHtml(results){
    if(!results?.length)return '<p class="muted">Keine weiteren Ergebnisse vorhanden.</p>';
    return `<div class="all-results-list">${results.map(r=>`<div class="fixture crest-fixture"><span>${clubNameWithCrest(getClub(r.home),'tiny')}</span><b>${r.score?.join(' : ')||'–'}</b><span>${clubNameWithCrest(getClub(r.away),'tiny')}</span></div>`).join('')}</div>`;
  }
  function improvementTable(items,title){
    if(!items?.length)return `<div class="card"><h2>${title}</h2><p class="muted">Keine Stärkeverbesserung in dieser Einheit.</p></div>`;
    return `<div class="card"><h2>${title}</h2><table><thead><tr><th>Spieler</th><th>Position</th><th>Vorher</th><th>Jetzt</th><th>Fortschritt</th></tr></thead><tbody>${items.map(x=>`<tr><td>${esc(x.name)}</td><td>${x.position}</td><td>${x.before}</td><td><b>${x.after}</b></td><td class="good">+${x.after-x.before}</td></tr>`).join('')}</tbody></table></div>`;
  }

  const oldRunWeeklyTraining=runWeeklyTraining;
  runWeeklyTraining=function(){
    ensureV22State();const before=new Map(getUserClub().squad.map(p=>[p.id,p.rating]));oldRunWeeklyTraining();state.v22.trainingImprovements=getUserClub().squad.filter(p=>p.rating>(before.get(p.id)||p.rating)).map(p=>({id:p.id,name:p.name,position:p.position,before:before.get(p.id),after:p.rating,week:state.week}));
    if(state.v22.trainingImprovements.length)state.news.unshift(`Training: ${state.v22.trainingImprovements.map(x=>`${x.name} ${x.before}→${x.after}`).join(', ')}`);
  };
  const oldStartTrainingCamp=startTrainingCamp;
  startTrainingCamp=function(){
    ensureV22State();const before=new Map(getUserClub().squad.map(p=>[p.id,p.rating]));oldStartTrainingCamp();state.v22.campImprovements=getUserClub().squad.filter(p=>p.rating>(before.get(p.id)||p.rating)).map(p=>({id:p.id,name:p.name,position:p.position,before:before.get(p.id),after:p.rating,week:state.week}));save();render();
  };
  const oldTraining=training;
  training=function(){ensureV22State();return oldTraining()+`<div class="grid cols-2" style="margin-top:16px">${improvementTable(state.v22.trainingImprovements,'Verbesserungen im letzten normalen Training')}${improvementTable(state.v22.campImprovements,'Verbesserungen im letzten Trainingslager')}</div>`;};

  const oldAcademy=academy;
  academy=function(){ensureV22State();let html=oldAcademy();state.v20.scoutReports.forEach(p=>{const price=Math.round(p.rating**3*45);html=html.replace(`<button data-sign-scout="${p.id}">Verpflichten</button>`,`<b>${money(price)}</b><br><button data-sign-scout="${p.id}">Verpflichten</button>`);});return html;};

  const oldPlayerOption=playerOption;
  playerOption=function(p,sel,index){
    const used=(state.selectedXI||[]).some((id,i)=>i!==index&&id===p.id),blocked=!isPlayerAvailable(p);
    const status=p.injuryGames?`, verletzt ${p.injuryGames}`:p.suspensionGames?`, gesperrt ${p.suspensionGames}`:'';
    return `<option value="${p.id}" ${p.id===sel?'selected':''} ${(used||blocked)&&p.id!==sel?'disabled':''}>${esc(p.name)} (${p.position}, St ${p.rating}, Fit ${p.fitness}%${status})</option>`;
  };
  const oldLineup=lineup;
  lineup=function(){ensureV22State();return oldLineup();};

  const oldFinish=finishLiveMatch;
  finishLiveMatch=function(){
    if(!state)return oldFinish();ensureV22State();const roundIndex=state.league.round;const beforeWeek=state.week;oldFinish();
    if(state&&state.week>beforeWeek){const round=state.league.fixtures[roundIndex]||[];state.v22.lastRoundResults=round.map(f=>({home:f.home,away:f.away,score:f.score}));state.v22.worldLeagues.forEach(simulateWorldRound);save();render();}
  };
  const oldNext=nextWeek;
  nextWeek=function(){
    if(!state)return oldNext();ensureV22State();const roundIndex=state.league.round,beforeWeek=state.week;oldNext();
    if(state&&state.week>beforeWeek&&!liveMatch){const round=state.league.fixtures[roundIndex]||[];state.v22.lastRoundResults=round.map(f=>({home:f.home,away:f.away,score:f.score}));state.v22.worldLeagues.forEach(simulateWorldRound);save();render();}
  };

  const oldLiveView=liveView;
  liveView=function(){
    const html=oldLiveView();if(liveMatch?.finished&&liveMatch.completedReport){ensureV22State();
      const globalResults=state.v22.worldLeagues.map(l=>{const rs=l.lastRoundResults||[];if(!rs.length)return '';return `<details><summary>${esc(l.country)} · ${esc(l.name)} · Spieltag ${l.round}</summary>${rs.map(r=>{const h=leagueClub(l,r.home),a=leagueClub(l,r.away);return `<div class="fixture"><span>${esc(h?.name||'')}</span><b>${r.score?.join(' : ')||'–'}</b><span>${esc(a?.name||'')}</span></div>`}).join('')}</details>`;}).join('');
      return html+`<div class="card" style="margin-top:16px"><h2>Alle Ergebnisse · ${esc(state.league.name)} · Spieltag ${Math.max(1,state.league.round)}</h2>${resultListHtml(state.v22.lastRoundResults)}</div>${improvementTable(state.v22.trainingImprovements,'Spielerverbesserungen dieser Woche')}<div class="card" style="margin-top:16px"><h2>Ergebnisse der internationalen Ligen</h2>${globalResults||'<p class="muted">Noch keine Ergebnisse.</p>'}</div>`;}return html;
  };

  const oldBind=bindDynamic;
  bindDynamic=function(){
    oldBind();const ls=$('#worldLeagueSelect');if(ls)ls.onchange=e=>{selectedWorldLeague=e.target.value;selectedWorldClub='';render();};const cs=$('#worldClubSelect');if(cs)cs.onchange=e=>{selectedWorldClub=e.target.value;render();};$$('[data-world-buy]').forEach(b=>b.onclick=()=>buyWorldPlayer(b.dataset.worldLeague,b.dataset.worldClub,b.dataset.worldBuy));
  };
  const oldNew=newGame;
  newGame=function(ci,li,clubName){oldNew(ci,li,clubName);ensureV22State();save();render();};
  const oldLoad=load;
  load=function(){oldLoad();if(state){ensureV22State();save();render();}};
  const oldRender=render;
  render=function(){
    if(!state)return;ensureV22State();oldRender();
    const label=$('#seasonLabel');if(label)label.textContent=`${safeDate()} · Spieltag ${Math.min(state.league.round+1,state.league.fixtures.length)} / ${state.league.fixtures.length} · Saison ${state.season} · ${state.league.country} ${state.league.name} · V2.2`;
    if(view==='leagues'){ $('#content').innerHTML=leaguesView();bindDynamic(); }
  };
})();
