'use strict';
(function(){
const C=(n,a,b)=>Math.max(a,Math.min(b,n));
const personalities=['Profi','Führungsspieler','Wunderkind','Hitzkopf','Vereinsmensch','Söldner','Teamspieler','Individualist'];
const roles=['Talent','Ergänzungsspieler','Rotation','Stammspieler','Schlüsselspieler'];
function uid45(){return 'v45-'+Date.now().toString(36)+'-'+Math.random().toString(36).slice(2,8)}
function ensure(){
 if(typeof state==='undefined'||!state||!getUserClub())return;
 const c=getUserClub();
 state.v45 ||= {version:'4.5',lastWeek:-1,chemistry:68,captainId:null,viceCaptainId:null,manager:{name:'Manager',reputation:45,contractWeeks:104,wage:12000,careerGames:0,wins:0,titles:0,preferredFormation:state.formation||'4-4-2',status:'Im Amt'},jobOffers:[],stories:[],awards:[],aiTransfers:[],rivalries:{},seasonStartWeek:state.week};
 c.squad.forEach((p,i)=>{
   p.personality ||= personalities[Math.floor(Math.random()*personalities.length)];
   p.squadRole ||= i<4?'Schlüsselspieler':i<12?'Stammspieler':i<18?'Rotation':p.age<22?'Talent':'Ergänzungsspieler';
   p.promisedRole ||= p.squadRole;
   p.satisfaction = Number.isFinite(+p.satisfaction)?+p.satisfaction:C(62+(p.morale||70)/5-Math.random()*12,20,96);
   p.appearancesSeason ||= 0;p.startsSeason ||=0;p.minutesSeason ||=0;p.weeksUnused ||=0;p.relationships ||= {};
   p.retirementAge ||= 34+Math.floor(Math.random()*5);
 });
 if(!state.v45.captainId){const best=[...c.squad].sort((a,b)=>(b.leadership||b.mental||b.rating)-(a.leadership||a.mental||a.rating))[0];state.v45.captainId=best?.id||null;}
 if(!state.v45.viceCaptainId){state.v45.viceCaptainId=c.squad.find(p=>p.id!==state.v45.captainId)?.id||null;}
 updateChemistry(false);
}
function activeIds(){return new Set((state.selectedXI||state.lineup||[]).filter(Boolean));}
function updateChemistry(write=true){
 const c=getUserClub(),ids=activeIds();let total=0;
 c.squad.forEach(p=>{const used=ids.has(p.id);const expected={Schlüsselspieler:.8,Stammspieler:.65,Rotation:.4,Ergänzungsspieler:.18,Talent:.12}[p.promisedRole||p.squadRole]||.3;const actual=Math.min(1,(p.startsSeason||0)/Math.max(1,state.week));let delta=(actual-expected)*13+(p.morale-70)/12;
 if(p.personality==='Vereinsmensch'||p.personality==='Teamspieler')delta+=3;if(p.personality==='Söldner'&&p.wage<25000)delta-=3;if(p.weeksUnused>4)delta-=5;
 p.satisfaction=C(Math.round((p.satisfaction||65)*.86+(65+delta)*.14),5,100);total+=p.satisfaction;});
 const captain=c.squad.find(p=>p.id===state.v45.captainId);let chem=total/Math.max(1,c.squad.length);if(captain)chem+=(captain.leadership||captain.mental||captain.rating)/25;chem+=Math.min(8,(c.form||[]).filter(x=>x==='S').length*1.5);state.v45.chemistry=C(Math.round(chem),10,100);if(write&&state.v45.chemistry<42)state.news.unshift('Die Kabinenchemie ist angespannt. Gespräche mit Führungsspielern wären sinnvoll.');
}
function weekly(){ensure();if(state.v45.lastWeek===state.week)return;state.v45.lastWeek=state.week;const c=getUserClub(),ids=activeIds();state.v45.manager.contractWeeks=Math.max(0,state.v45.manager.contractWeeks-1);
 c.squad.forEach(p=>{if(ids.has(p.id)){p.appearancesSeason++;p.startsSeason++;p.minutesSeason+=90;p.weeksUnused=0;p.form=C((p.form||70)+Math.round(Math.random()*5)-1,30,99);}else{p.weeksUnused++;p.form=C((p.form||70)-Math.round(Math.random()*3),25,99);}});
 updateChemistry();aiWorld();seasonStories();jobMarket();save();
}
function aiWorld(){const clubs=state.league?.clubs||[];if(state.week%2!==0)return;for(const club of clubs){if(club.id===state.userClubId||!club.squad?.length)continue;club.ai ||= {philosophy:['Jugend','Ausgeglichen','Stars','Sparsam'][Math.floor(Math.random()*4)],formation:['4-4-2','4-3-3','5-3-2'][Math.floor(Math.random()*3)]};
 const needs=['TW','ABW','MIT','ST'].sort((a,b)=>club.squad.filter(p=>p.position===a).length-club.squad.filter(p=>p.position===b).length)[0];
 if(Math.random()<.08){const seller=clubs.filter(x=>x.id!==club.id&&x.squad?.some(p=>p.position===needs&&p.rating<88))[Math.floor(Math.random()*(clubs.length-1))];const target=seller?.squad?.filter(p=>p.position===needs).sort((a,b)=>b.rating-a.rating)[0];if(target&&club.balance>(target.value||1e6)*1.1){const price=Math.round((target.value||1e6)*(1+Math.random()*.25));seller.squad=seller.squad.filter(p=>p.id!==target.id);club.squad.push(target);club.balance-=price;seller.balance+=price;state.v45.aiTransfers.unshift({week:state.week,season:state.season,player:target.name,from:seller.name,to:club.name,price});state.v45.aiTransfers=state.v45.aiTransfers.slice(0,100);}}
 }}
function seasonStories(){const table=sortedTable();if(!table.length)return;const user=getUserClub(),pos=table.findIndex(x=>x.id===user.id)+1;const lead=table[0],second=table[1];let story='';if(state.league.round>5&&lead&&second&&lead.points-second.points<=3)story=`Meisterschaftsrennen: ${lead.name} und ${second.name} trennen nur ${lead.points-second.points} Punkte.`;if(user.form?.slice(-5).filter(x=>x==='S').length>=4)story=`Erfolgsserie: ${user.name} ist derzeit kaum zu stoppen.`;if(pos>=table.length-2)story=`Abstiegskampf: ${user.name} steht unter großem Ergebnisdruck.`;if(story&&state.v45.stories[0]?.text!==story)state.v45.stories.unshift({week:state.week,text:story});state.v45.stories=state.v45.stories.slice(0,40);}
function jobMarket(){const m=state.v45.manager;if(state.week%8===0&&m.reputation>48&&Math.random()<.35){const candidates=state.league.clubs.filter(c=>c.id!==state.userClubId);const club=candidates[Math.floor(Math.random()*candidates.length)];if(club&&!state.v45.jobOffers.some(o=>o.clubId===club.id)){state.v45.jobOffers.push({id:uid45(),clubId:club.id,clubName:club.name,weeks:104+Math.floor(Math.random()*80),wage:Math.round((m.wage*(1.15+Math.random()*.6))/1000)*1000,target:'Obere Tabellenhälfte'});state.news.unshift(`${club.name} möchte mit dir über den Trainerposten sprechen.`);}}
 const table=sortedTable(),pos=table.findIndex(x=>x.id===state.userClubId)+1;if(state.league.round>10&&pos>Math.ceil(table.length*.75)){m.reputation=C(m.reputation-1,1,100);if(m.reputation<18)m.status='Unter Druck';}
}
function switchClub(id){const club=state.league.clubs.find(c=>c.id===id);if(!club)return;state.userClubId=id;state.selectedXI=club.squad.slice().sort((a,b)=>b.rating-a.rating).slice(0,11).map(p=>p.id);state.lineup=[...state.selectedXI];state.v45.manager.status='Im Amt';state.v45.manager.contractWeeks=104;state.v45.jobOffers=[];state.news.unshift(`Du hast den Trainerposten bei ${club.name} übernommen.`);ensure();save();view='dashboard';render();}
function aging(){ensure();const clubs=state.league.clubs||[];for(const club of clubs){const retired=[];club.squad.forEach(p=>{p.age++;if(p.age>=30){p.speed=C((p.speed||p.pace||70)-Math.floor(Math.random()*3),20,99);p.condition=C((p.condition||70)-Math.floor(Math.random()*2),20,99);}if(p.age<25&&Math.random()<.55){p.rating=C(p.rating+(Math.random()<.4?1:0),35,p.potential||99);}if(p.age>=p.retirementAge&&Math.random()<.5)retired.push(p);});if(retired.length)club.squad=club.squad.filter(p=>!retired.includes(p));while(club.squad.length<23){const pos=['TW','ABW','MIT','ST'][Math.floor(Math.random()*4)],first=['Lakas','Nuah','Lion','Devid','Milana','Eloas','Junas'][Math.floor(Math.random()*7)],last=['Haber','Meyer','Gruber','Nuvak','Kovac','Schmodt','Beuer'][Math.floor(Math.random()*7)],rating=48+Math.floor(Math.random()*18);club.squad.push({id:uid45(),name:first+' '+last,age:16+Math.floor(Math.random()*3),position:pos,rating,potential:rating+12+Math.floor(Math.random()*22),fitness:92,morale:72,form:68,value:rating*rating*1500,wage:800+rating*35,contract:3,goals:0,personality:personalities[Math.floor(Math.random()*personalities.length)],squadRole:'Talent',promisedRole:'Talent',satisfaction:78,retirementAge:35+Math.floor(Math.random()*4)});}}
 state.v45.awards.unshift({season:state.season,name:'Nachwuchsjahrgang',detail:'Neue Talente sind in die Fußballwelt nachgerückt.'});
}
function chemistryView(){ensure();const c=getUserClub();if(!c||!state.v45)return '<div class="card"><h2>Kabine & Chemie</h2><p>Die Kabinendaten werden gerade vorbereitet.</p></div>';const rows=[...(c.squad||[])].sort((a,b)=>(Number(b.satisfaction)||0)-(Number(a.satisfaction)||0)).map(p=>`<tr><td>${esc(p.name)}</td><td>${esc(p.personality)}</td><td><select data-role="${p.id}">${roles.map(r=>`<option ${r===(p.promisedRole||p.squadRole)?'selected':''}>${r}</option>`).join('')}</select></td><td>${p.startsSeason||0}</td><td><b class="${p.satisfaction<45?'bad':p.satisfaction>75?'good':''}">${p.satisfaction}%</b></td><td>${p.weeksUnused||0} Wo.</td></tr>`).join('');return `<div class="grid cols-3"><div class="metric-card"><span>Teamchemie</span><div class="viz-stat-value">${state.v45.chemistry}/100</div></div><div class="metric-card"><span>Kapitän</span><div class="viz-stat-value small">${esc(c.squad.find(p=>p.id===state.v45.captainId)?.name||'–')}</div></div><div class="metric-card"><span>Unzufrieden</span><div class="viz-stat-value">${c.squad.filter(p=>p.satisfaction<45).length}</div></div></div><div class="card"><h2>Mannschaft & Kabine</h2><div class="grid cols-2"><label>Kapitän<select id="captainSelect">${c.squad.map(p=>`<option value="${p.id}" ${p.id===state.v45.captainId?'selected':''}>${esc(p.name)}</option>`).join('')}</select></label><label>Stellvertreter<select id="viceSelect">${c.squad.map(p=>`<option value="${p.id}" ${p.id===state.v45.viceCaptainId?'selected':''}>${esc(p.name)}</option>`).join('')}</select></label></div><div class="table-scroll"><table><thead><tr><th>Spieler</th><th>Persönlichkeit</th><th>Versprochene Rolle</th><th>Starts</th><th>Zufriedenheit</th><th>Ohne Einsatz</th></tr></thead><tbody>${rows}</tbody></table></div></div>`;}
function careerView(){ensure();const m=state.v45.manager;return `<div class="grid cols-3"><div class="metric-card"><span>Reputation</span><div class="viz-stat-value">${m.reputation}/100</div></div><div class="metric-card"><span>Vertrag</span><div class="viz-stat-value">${m.contractWeeks} Wo.</div></div><div class="metric-card"><span>Status</span><div class="viz-stat-value small">${m.status}</div></div></div><div class="card"><h2>Managerkarriere</h2><p>Verein: <b>${esc(getUserClub().name)}</b> · Gehalt ${money(m.wage)}/Woche · bevorzugt ${esc(m.preferredFormation)}</p><h3>Jobangebote</h3>${state.v45.jobOffers.length?state.v45.jobOffers.map(o=>`<div class="offer-card"><b>${esc(o.clubName)}</b><p>${o.target} · ${money(o.wage)}/Woche · ${o.weeks} Wochen</p><button data-job="${o.clubId}" class="primary">Annehmen</button></div>`).join(''):'<p class="muted">Derzeit keine Angebote.</p>'}<h3>Fußballwelt – letzte KI-Transfers</h3>${state.v45.aiTransfers.slice(0,12).map(t=>`<div class="fixture">${esc(t.player)}: ${esc(t.from)} → ${esc(t.to)} (${money(t.price)})</div>`).join('')||'<p class="muted">Noch keine KI-Transfers.</p>'}</div>`;}
function analysisView(){
  ensure();
  const c=getUserClub();
  if(!c||!state?.league)return '<div class="card"><h2>Gegneranalyse</h2><p>Bitte zuerst eine Karriere starten.</p></div>';
  const fixtures=Array.isArray(state.league.fixtures)?state.league.fixtures:[];
  let next=null;
  for(let r=Math.max(0,Number(state.league.round)||0);r<fixtures.length&&!next;r++){
    next=(Array.isArray(fixtures[r])?fixtures[r]:[]).find(f=>f&&(f.home===c.id||f.away===c.id));
  }
  if(!next)return '<div class="card"><h2>Gegneranalyse</h2><p>Kein kommendes Ligaspiel.</p></div>';
  const opp=getClub(next.home===c.id?next.away:next.home);
  if(!opp)return '<div class="card"><h2>Gegneranalyse</h2><p>Der nächste Gegner konnte nicht geladen werden.</p></div>';
  const squad=Array.isArray(opp.squad)?opp.squad:[];
  const avg=(key,fallback='rating')=>squad.length?Math.round(squad.reduce((sum,p)=>sum+(Number(p?.[key])||Number(p?.[fallback])||50),0)/squad.length):0;
  const pace=avg('speed'),head=avg('heading'),cond=avg('condition','fitness'),strength=avg('rating');
  const tips=[];
  if(pace<68)tips.push('Schnelle Angriffe und Konter gegen die langsame Defensive.');
  if(head>74)tips.push('Flanken vermeiden und Standards konzentriert verteidigen.');
  if(cond<68)tips.push('Hohes Tempo und Pressing können in der Schlussphase wirken.');
  if(!tips.length)tips.push('Ausgeglichen beginnen und das Momentum beobachten.');
  const stories=Array.isArray(state.v45?.stories)?state.v45.stories:[];
  return `<div class="card"><h2>Gegneranalyse: ${esc(opp.name)}</h2><div class="grid cols-3"><div class="metric-card"><span>Kaderstärke</span><div class="viz-stat-value">${strength}</div></div><div class="metric-card"><span>Tempo</span><div class="viz-stat-value">${pace}</div></div><div class="metric-card"><span>Kondition</span><div class="viz-stat-value">${cond}</div></div></div><h3>Scoutempfehlung</h3>${tips.map(t=>`<div class="viz-callout">${esc(t)}</div>`).join('')}<h3>Saison-Dramaturgie</h3>${stories.slice(0,8).map(x=>`<div class="fixture">Spieltag ${Number(x.week)||0}: ${esc(x.text||'')}</div>`).join('')||'<p class="muted">Die Saison nimmt gerade erst Fahrt auf.</p>'}</div>`;
}
const oldRender=render;render=function(){if(!state)return;ensure();oldRender();if(view==='chemistry'){$('#content').innerHTML=chemistryView();bind45();}if(view==='career'){$('#content').innerHTML=careerView();bind45();}if(view==='analysis'){$('#content').innerHTML=analysisView();bind45();}const l=$('#seasonLabel');if(l)l.textContent=l.textContent.replace(/Version 4\.4[^·]*/,'Version 4.5 · Karrierewelt');};
function bind45(){document.querySelectorAll('[data-role]').forEach(s=>s.onchange=()=>{const p=getUserClub().squad.find(x=>x.id===s.dataset.role);if(p){p.promisedRole=s.value;p.satisfaction=C(p.satisfaction+2,0,100);save();render();}});const cap=$('#captainSelect');if(cap)cap.onchange=()=>{state.v45.captainId=cap.value;updateChemistry();save();render();};const vice=$('#viceSelect');if(vice)vice.onchange=()=>{state.v45.viceCaptainId=vice.value;save();render();};document.querySelectorAll('[data-job]').forEach(b=>b.onclick=()=>switchClub(b.dataset.job));}
const oldBind=window.v20Bind;window.v20Bind=function(){if(oldBind)oldBind();bind45();};
const oldProc=window.v20ProcessWeek;window.v20ProcessWeek=function(){if(oldProc)oldProc();weekly();};
const oldEnd=window.endSeason;window.endSeason=function(){ensure();aging();state.v45.manager.reputation=C(state.v45.manager.reputation+2,1,100);state.v45.manager.contractWeeks+=52;oldEnd();};
const oldNew=window.newGame;window.newGame=function(){oldNew.apply(this,arguments);if(state){state.v45=null;ensure();save();}};
const oldLoad=window.load;window.load=function(){oldLoad.apply(this,arguments);if(state){ensure();save();}};
window.FMCareerWorld45={ensure,weekly,aging};if(window.state)ensure();
})();
