/* Version 2.3 – ÖFB-Cup, UEFA-Wettbewerbe und Festgeld */
(() => {
  const UCL_TEAMS = ['Ajex','Arsenel','Atalantia','Athletic Clab','Atlético Madrin','Borusia Dortmunt','FC Barceluna','Bavern Münchenau','Benfika','Budø/Glimt','Chelsia','Club Brugga','FC Cupenhagen','Eintracht Frankfort','Galatasera','Interna Mailand','Juventia','Kairat Almety','Bayer Leverkuzen','Liverpol','Manchesta Citi','Marselle','AS Monako','Napola','Newcastle Union','Olympoacos','Pefos FC','Pari Saint-Germand','PSV Eindhovan','Qerabağ','Reel Madrin','Slavia Preg','Sporting CPA','Totenham','Union Seint-Gilloise','Villareal'];
  const UEL_TEAMS = ['Red Ball Salzberg','Sturm Greiz','Gink','Ladogorets','Dinamo Zegreb','Viktoria Polsen','Modtjylland','Aston Volla','Nottingham Furest','Lilea','Lyona','OGC Nica','VfB Stuttgard','SC Freiberg','Penathinaikos','PAOKA','Firencváros','Maccabi Til-Aviv','Bolonga','AS Rhome','Feyenord','Go Ahead Eegles','FC Utricht','Brenn','SC Brega','FC Porta','FCSBA','Celtika','Rangera','Roter Stern Bilgrad','Real Bitis','Celta Vogo','Malmö FFA','FC Basila','Young Boys Birn','Fenerbahcex'];
  const UECL_TEAMS = ['Nuah','SK Rapid Wieden','Zrinjski Mustar','HNK Rojeka','AEK Lernaca','Omonia Nokosia','Sigma Olmütze','Sparta Preg','Crystal Pelace','KuPS Kaopio','RC Strasbourgh','Mainz 06 05','Lincoln Red Impse','AEK Athin','Briiðablik','Florentina','Drota','Hamrun Spertans','AZ Alkmear','Shkëndoja','Jagiellonia Boałystok','Lech Puznań','Legia Werschau','Reków','Shamrock Ruvers','Shilbourne','Universitatea Creiova','Abirdeen','Slovan Bretislava','Cilje','Rayo Vellecano','Häckin','Leusanne-Sport','Semsunspor','Dynamo Kyov','Shakhtar Dunetsk'];
  const REGIONAL_AT = ['SV Liobendorf','FC Durnbirn 1913','SC Kelsdorf','Union Garten','Wiener Spurt-Club','ASV Soegendorf','SV Lefnitz','Triibach','SC Schwez','FC Pinzgau Sealfelden','WSC Hertha Wils','Diutschlandsberger SC','SV Kachl','FC Wulfurt','SC Imste','SV Wellern','Krimser SC','SC Neusiedl am Sie','ASK Vuitsberg','SV Woldon','FC Gliisdorf 09','SVG Riichenau','USV St. Anna am Aogen','SC Wiener Voktoria','FC Marchfeld Dunauauen','SV Siekirchen','SV Wels-Grünau','SC Röthos','Vöcklemarkter SC','SK Boschofshofen','SV Obirwart','SC Mennsdorf','Wiener Niustadt','FC Kafstein','SV Austria Salzberg','SC Wiiz'];

  function teamName(x){ return typeof x === 'string' ? x : x?.name || 'Unbekannt'; }
  function shuffle(a){ const x=[...a]; for(let i=x.length-1;i>0;i--){const j=Math.floor(Math.random()*(i+1));[x[i],x[j]]=[x[j],x[i]];} return x; }
  function findAnyClub(name){
    const norm=s=>String(s||'').toLowerCase().replace(/[^a-z0-9äöüß]/g,'');
    const target=norm(name); const pools=[...(state?.league?.clubs||[]),...((state?.v22?.worldLeagues||[]).flatMap(l=>l.clubs||[]))];
    return pools.find(c=>norm(c.name)===target || norm(c.name).includes(target) || target.includes(norm(c.name)));
  }
  function powerByName(name){ const c=findAnyClub(name); if(c?.squad?.length) return c.squad.sort((a,b)=>b.rating-a.rating).slice(0,11).reduce((s,p)=>s+p.rating,0)/11; let h=0; for(const ch of name)h=(h*31+ch.charCodeAt(0))%997; return 66+(h%23); }
  function simulateKnockout(home,away){
    const hp=powerByName(home)+2, ap=powerByName(away); let hg=goalsFor(hp,ap,true),ag=goalsFor(ap,hp,false); let pens=null;
    if(hg===ag){ if(Math.random()<.5)hg++; else ag++; pens=true; }
    return {home,away,hg,ag,winner:hg>ag?home:away,pens};
  }
  function makePairs(teams){ const s=shuffle(teams); const out=[]; for(let i=0;i<s.length;i+=2)out.push({home:s[i],away:s[i+1],played:false}); return out; }
  function competition(name,type,teams,roundNames){ return {id:uid(),name,type,season:state.season,roundIndex:0,roundNames,rounds:[makePairs(teams)],champion:null,finished:false,lastProcessedWeek:0}; }
  function ensureV23State(){
    if(!state)return; state.v23 ||= {version:23,lastProcessedWeek:0,cup:null,uefa:{},deposit:null,depositHistory:[],lastCupResults:[],lastUefaResults:[]};
    const c=getUserClub(); c.fixedDeposit ||= 0;
    if(!state.v23.cup || state.v23.cup.season!==state.season) initCup();
    if(!state.v23.uefa.ucl || state.v23.uefa.ucl.season!==state.season) initUefa();
  }
  function allAustrianManagedNames(){
    const pools=[state.league,...(state.v22?.worldLeagues||[])].filter(l=>l?.country==='Österreich');
    return [...new Set(pools.flatMap(l=>(l.clubs||[]).map(c=>c.name)))];
  }
  function initCup(){
    const managed=allAustrianManagedNames(); const user=getUserClub();
    if(state.league.country==='Österreich' && !managed.includes(user.name))managed.push(user.name);
    const teams=[...new Set([...managed,...REGIONAL_AT])].slice(0,64); while(teams.length<64)teams.push(`Landesliga-Auswahl ${teams.length+1}`);
    state.v23.cup=competition('ÖFB-Cup','knockout',teams,['1. Runde','2. Runde','Achtelfinale','Viertelfinale','Halbfinale','Finale']);
  }
  function initUefa(){
    state.v23.uefa={
      ucl:competition('UEFA Champions League','league-ko',UCL_TEAMS,['Ligaphase 1','Ligaphase 2','Ligaphase 3','Ligaphase 4','Achtelfinale','Viertelfinale','Halbfinale','Finale']),
      uel:competition('UEFA Europa League','league-ko',UEL_TEAMS,['Ligaphase 1','Ligaphase 2','Ligaphase 3','Ligaphase 4','Achtelfinale','Viertelfinale','Halbfinale','Finale']),
      uecl:competition('UEFA Conference League','league-ko',UECL_TEAMS,['Ligaphase 1','Ligaphase 2','Ligaphase 3','Ligaphase 4','Achtelfinale','Viertelfinale','Halbfinale','Finale'])
    };
  }
  function processCompetition(comp){
    if(!comp||comp.finished)return [];
    let round=comp.rounds[comp.roundIndex]; if(!round)return [];
    const results=round.map(f=>{ if(f.played)return f; const r=simulateKnockout(f.home,f.away);Object.assign(f,r,{played:true});return f; });
    const user=getUserClub(); const userResult=results.find(r=>r.home===user.name||r.away===user.name);
    if(userResult){ const won=userResult.winner===user.name; const prize=won?(comp.name==='ÖFB-Cup'?150000:comp.name.includes('Champions')?1200000:comp.name.includes('Europa League')?700000:400000):0; user.balance+=prize; if(prize)state.news.unshift(`${comp.name}: ${user.name} gewinnt ${userResult.hg}:${userResult.ag} und erhält ${money(prize)} Prämie.`); else state.news.unshift(`${comp.name}: ${user.name} scheidet mit ${userResult.hg}:${userResult.ag} gegen ${userResult.home===user.name?userResult.away:userResult.home} aus.`); }
    const winners=results.map(r=>r.winner); comp.roundIndex++;
    if(winners.length===1){comp.champion=winners[0];comp.finished=true;state.news.unshift(`${comp.name}: ${comp.champion} gewinnt den Wettbewerb.`);}
    else comp.rounds.push(makePairs(winners));
    return results;
  }
  const CUP_WEEKS=[2,6,11,18,27,35]; const UEFA_WEEKS=[3,5,8,10,17,23,30,36];
  function processTournamentsForWeek(){
    ensureV23State(); if(state.v23.lastProcessedWeek===state.week)return;
    state.v23.lastCupResults=[];state.v23.lastUefaResults=[];
    const ci=CUP_WEEKS.indexOf(state.week); if(ci>=0 && state.v23.cup.roundIndex===ci)state.v23.lastCupResults=processCompetition(state.v23.cup);
    UEFA_WEEKS.forEach((w,i)=>{if(state.week===w){Object.values(state.v23.uefa).forEach(comp=>{if(comp.roundIndex===i)state.v23.lastUefaResults.push({name:comp.name,results:processCompetition(comp)});});}});
    processDeposit(); state.v23.lastProcessedWeek=state.week; save();
  }
  function processDeposit(){
    const d=state.v23.deposit;if(!d)return;d.remainingWeeks--;
    if(d.remainingWeeks<=0){const c=getUserClub(),interest=Math.round(d.amount*d.rate*d.termWeeks/52),payout=d.amount+interest;c.balance+=payout;state.v23.depositHistory.unshift({...d,interest,payout,maturedWeek:state.week,maturedSeason:state.season});state.v23.deposit=null;state.news.unshift(`Festgeld fällig: ${money(payout)} wurden inklusive ${money(interest)} Zinsen gutgeschrieben.`);}
  }
  function startDeposit(){
    ensureV23State(); if(state.v23.deposit)return alert('Es besteht bereits eine Festgeldanlage.');
    const amount=Number($('#depositAmount')?.value||0),term=Number($('#depositTerm')?.value||12),c=getUserClub();
    const rates={8:.025,12:.032,24:.041,36:.048},rate=rates[term]||.032;
    if(amount<100000)return alert('Mindestanlage: 100.000 €'); if(amount>c.balance)return alert('Kontostand reicht nicht aus.');
    if(!confirm(`${money(amount)} für ${term} Wochen zu ${(rate*100).toFixed(1)} % p.a. anlegen?`))return;
    c.balance-=amount;state.v23.deposit={amount,termWeeks:term,remainingWeeks:term,rate,startWeek:state.week,startSeason:state.season};save();render();
  }
  function compHtml(comp){
    const round=comp.rounds[Math.min(comp.roundIndex,comp.rounds.length-1)]||[]; const title=comp.finished?`Sieger: ${comp.champion}`:`${comp.roundNames[comp.roundIndex]||'K.-o.-Runde'}`;
    return `<div class="card"><h2>${esc(comp.name)}</h2><p><b>${esc(title)}</b></p>${round.slice(0,18).map(f=>`<div class="fixture"><span>${esc(f.home)}</span><b>${f.played?`${f.hg}:${f.ag}`:'–'}</b><span>${esc(f.away)}</span></div>`).join('')}${round.length>18?`<details><summary>${round.length-18} weitere Spiele</summary>${round.slice(18).map(f=>`<div class="fixture"><span>${esc(f.home)}</span><b>${f.played?`${f.hg}:${f.ag}`:'–'}</b><span>${esc(f.away)}</span></div>`).join('')}</details>`:''}</div>`;
  }
  function cupsView(){ensureV23State();return `<div class="card"><h2>Pokalbewerbe</h2><p>Der ÖFB-Cup umfasst 64 Vereine aus Bundesliga, 2. Liga sowie nicht verwaltete Regional- und Landesligisten. Die UEFA-Bewerbe verwenden externe Teilnehmerpools und werden parallel zur Liga simuliert.</p></div><div class="grid cols-2" style="margin-top:16px">${compHtml(state.v23.cup)}${compHtml(state.v23.uefa.ucl)}${compHtml(state.v23.uefa.uel)}${compHtml(state.v23.uefa.uecl)}</div>`;}
  function depositHtml(){
    const d=state.v23.deposit; const rates=[['8 Wochen','2,5 % p.a.'],['12 Wochen','3,2 % p.a.'],['24 Wochen','4,1 % p.a.'],['36 Wochen','4,8 % p.a.']];
    const active = d ? `<div class="grid cols-4"><div class="metric-box"><span>Anlage</span><b>${money(d.amount)}</b></div><div class="metric-box"><span>Zinssatz</span><b>${(d.rate*100).toFixed(1)} % p.a.</b></div><div class="metric-box"><span>Restlaufzeit</span><b>${d.remainingWeeks} Wochen</b></div><div class="metric-box"><span>Erwartete Auszahlung</span><b>${money(d.amount+Math.round(d.amount*d.rate*d.termWeeks/52))}</b></div></div><p class="muted">Vorzeitige Auflösung ist nicht möglich.</p>` : `<div class="grid cols-2"><label>Anlagebetrag<input id="depositAmount" type="number" min="100000" step="100000" value="1000000"></label><label>Laufzeit<select id="depositTerm">${rates.map((x,i)=>`<option value="${[8,12,24,36][i]}">${x[0]} · ${x[1]}</option>`).join('')}</select></label></div><button id="startDeposit" class="primary">Festgeld anlegen</button>`;
    const history = state.v23.depositHistory.length ? `<h3>Abgeschlossene Anlagen</h3>${state.v23.depositHistory.slice(0,6).map(x=>`<div class="fixture"><span>${money(x.amount)} · ${x.termWeeks} Wochen</span><b class="good">+${money(x.interest)} Zinsen</b></div>`).join('')}` : '';
    return `<div class="card" style="margin-top:16px"><h2>Festgeldkonto</h2>${active}${history}</div>`;
  }

  const oldFinances=finances; finances=function(){ensureV23State();return oldFinances()+depositHtml();};
  const oldInternational=international; international=function(){ensureV23State();return cupsView();};
  const oldNext=nextWeek; nextWeek=function(){const before=state?.week||0;oldNext();if(state&&state.week>before)processTournamentsForWeek();};
  const oldFinish=finishLiveMatch; finishLiveMatch=function(){const before=state?.week||0;oldFinish();if(state&&state.week>before)processTournamentsForWeek();};
  const oldBind=bindDynamic; bindDynamic=function(){oldBind();const b=$('#startDeposit');if(b)b.onclick=startDeposit;};
  const oldRender=render; render=function(){if(state)ensureV23State();oldRender(); if(!state)return; if(view==='international'){$('#content').innerHTML=cupsView();bindDynamic();} if(view==='finances'){$('#content').innerHTML=finances();bindDynamic();} const label=$('#seasonLabel');if(label)label.textContent=label.textContent.replace(/V2\.2|Version 2\.2/g,'V2.3');};
  const oldNew=newGame;newGame=function(...args){oldNew(...args);ensureV23State();save();render();};
  const oldLoad=load;load=function(){oldLoad();if(state){ensureV23State();save();render();}};
})();
