const $ = s => document.querySelector(s);
const $$ = s => [...document.querySelectorAll(s)];
const rand = (a,b) => Math.floor(Math.random()*(b-a+1))+a;
const clamp = (n,a,b) => Math.max(a,Math.min(b,n));
const money = n => new Intl.NumberFormat('de-DE',{style:'currency',currency:'EUR',maximumFractionDigits:0}).format(n);

let state = null;
let view = 'dashboard';
let liveMatch = null;
let liveTimer = null;

function clubStrength(name, idx){
  const elite = ['Real Madrid','Manchester City','Bayern München','Liverpool','Arsenal','FC Barcelona','Inter Mailand','Paris Saint-Germain'];
  const strong = ['Borussia Dortmund','Bayer Leverkusen','Atlético Madrid','Juventus','AC Mailand','Napoli','Benfica','FC Porto','Sporting CP','Ajax','PSV Eindhoven','Feyenoord','Red Bull Salzburg','Sturm Graz'];
  if(elite.includes(name)) return rand(86,92);
  if(strong.includes(name)) return rand(80,86);
  return clamp(78-idx*2+rand(-2,3),66,82);
}
function makePlayer(clubRating, position, i){
  const age = rand(18,34);
  const potentialBonus = age < 22 ? rand(2,9) : rand(0,3);
  const rating = clamp(clubRating + rand(-8,5),55,94);
  return { id: crypto.randomUUID(), name: `${FIRST_NAMES[rand(0,FIRST_NAMES.length-1)]} ${LAST_NAMES[rand(0,LAST_NAMES.length-1)]}`, position, age, rating, potential: clamp(rating+potentialBonus, rating, 96), value: Math.round((rating**3)*55*(35-age)/20), wage: Math.round(rating*rating*18), fitness: rand(82,100), morale: rand(65,95), contract: rand(1,5), goals:0, assists:0, apps:0 };
}
function makeClub(name, idx){
  const rating = clubStrength(name,idx);
  const squad = [];
  const roles = [...POSITIONS,'TW','IV','RV','LV','DM','ZM','RA','LA','ST','ST','ZM','IV'];
  roles.forEach((p,i)=>squad.push(makePlayer(rating,p,i)));
  const stadiumName=STADIUMS[name]||`${name} Arena`; return { id: crypto.randomUUID(), name, rating, squad, budget: rand(12,90)*1e6, balance: rand(30,180)*1e6, stadium:{name:stadiumName, originalName:stadiumName, capacity: rand(17000,65000), condition:rand(70,95), ticketPrice:rand(22,58)}, fans:rand(180000,1800000), played:0,wins:0,draws:0,losses:0,gf:0,ga:0,points:0, form:[] };
}
function buildLeague(countryIndex,leagueIndex){
  const c=COUNTRIES[countryIndex], l=c.leagues[leagueIndex];
  return {country:c.name,name:l.name,clubs:l.clubs.map(makeClub),round:0,fixtures:[],results:[]};
}
function roundRobin(clubs){
  const ids=clubs.map(c=>c.id); if(ids.length%2) ids.push(null); const firstLeg=[]; const 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}); }
    firstLeg.push(games); a.splice(1,0,a.pop());
  }
  const secondLeg=firstLeg.map(g=>g.map(x=>({home:x.away,away:x.home,played:false})));
  const firstHalf=[...firstLeg,...secondLeg];
  const secondHalf=firstHalf.map(g=>g.map(x=>({home:x.home,away:x.away,played:false})));
  return [...firstHalf,...secondHalf];
}
function ensure36GameSeason(){
  if(!state?.league?.fixtures)return;
  const clubCount=state.league.clubs.length;
  const expectedRounds=36;
  if(clubCount===10&&state.league.fixtures.length===18){
    const extra=state.league.fixtures.map(round=>round.map(f=>({home:f.home,away:f.away,played:false})));
    state.league.fixtures.push(...extra);
  }
  if(clubCount===10&&state.league.fixtures.length!==expectedRounds){
    console.warn(`Unerwartete Saisonlaenge: ${state.league.fixtures.length} statt ${expectedRounds} Spieltage.`);
  }
}
function newGame(ci,li,clubName){
  const league=buildLeague(ci,li); league.fixtures=roundRobin(league.clubs);
  const userClub=league.clubs.find(c=>c.name===clubName);
  state={version:4,season:'2026/27',week:1,league,userClubId:userClub.id,selectedXI:userClub.squad.sort((a,b)=>b.rating-a.rating).slice(0,11).map(p=>p.id),news:[`Du wurdest als Manager von ${clubName} vorgestellt.`],international:{qualified:false,groupPoints:0,played:0},transferList:generateTransferList(league.clubs),outgoingOffers:[],lastMatch:null,matchFinanceHistory:[]};
  ensureSponsorState(); generateSponsorOffers(true); save(); render();
}
function generateTransferList(clubs){
  const base=[]; clubs.forEach(c=>c.squad.slice(14).forEach(p=>{if(Math.random()<.45)base.push({...p,fromClub:c.name,asking:Math.round(p.value*rand(90,125)/100)});}));
  return base.slice(0,35);
}
function getUserClub(){return state.league.clubs.find(c=>c.id===state.userClubId)}


const SPONSOR_COMPANIES=['AlpenMobil','NovaTech','KronenBank','RapidNet','VitaPlus','Nordstern Energie','BluePeak','Arena Bau','EuroDrive','GreenGrid','Sportiva','CityConnect','ProWerk','AeroLine','Goldquell','FutureByte','Bergland','PrimeLogistik','UrbanFox','Solaris','Titan Tools','Pulse Media','Globus Reisen','FreshOne','Mondo Foods','Helix Pharma','Vector Systems','RoyalBet','Maxx Telecom','Optima Versicherung'];
const SPONSOR_LABELS={shirt:'Trikotsponsor',board:'Stadionbande',stadium:'Stadionname',merch:'Merchandisingpartner'};
function ensureSponsorState(){
  const c=getUserClub();
  if(!c.stadium.originalName)c.stadium.originalName=c.stadium.name;
  if(!c.fans)c.fans=rand(180000,1800000);
  if(!state.sponsors)state.sponsors={shirt:null,stadium:null,merch:null,boards:Array(20).fill(null),offers:[],history:[],lastIncome:0,lastMerchSales:0};
  if(!Array.isArray(state.sponsors.boards))state.sponsors.boards=Array(20).fill(null);
  while(state.sponsors.boards.length<20)state.sponsors.boards.push(null);
  state.sponsors.boards=state.sponsors.boards.slice(0,20);
  if(!Array.isArray(state.sponsors.offers))state.sponsors.offers=[];
  if(!Array.isArray(state.sponsors.history))state.sponsors.history=[];
}
function clubSuccessScore(){
  const c=getUserClub(),table=sortedTable(),pos=Math.max(1,table.findIndex(x=>x.id===c.id)+1),n=table.length;
  const tableScore=(n-pos)/(Math.max(1,n-1));
  const formScore=c.form.length?c.form.reduce((a,x)=>a+(x==='S'?1:x==='U'?.45:0),0)/c.form.length:.5;
  const strengthScore=clamp((c.rating-65)/28,0,1);
  const internationalBonus=state.international?.qualified?.12:0;
  return clamp(.2+tableScore*.35+formScore*.2+strengthScore*.25+internationalBonus,0,1.15);
}
function sponsorSlotAvailable(type){
  ensureSponsorState();
  if(type==='board')return state.sponsors.boards.some(x=>!x);
  return !state.sponsors[type];
}
function generateSponsorOffers(force=false){
  ensureSponsorState();
  if(!force&&state.week%4!==0)return;
  const score=clubSuccessScore(),c=getUserClub();
  const desired=force?10:rand(3,6);
  const existing=new Set(state.sponsors.offers.map(o=>o.company+o.type));
  const types=['shirt','board','board','board','stadium','merch'];
  for(let i=0;i<desired;i++){
    const type=types[rand(0,types.length-1)];
    if(type!=='board'&&!sponsorSlotAvailable(type))continue;
    const company=SPONSOR_COMPANIES[rand(0,SPONSOR_COMPANIES.length-1)];
    if(existing.has(company+type))continue;
    const scale=.65+score*1.15+(c.fans/1800000)*.3;
    const base={shirt:210000,board:18000,stadium:170000,merch:70000}[type];
    const weekly=Math.round(base*scale*(.8+Math.random()*.45)/1000)*1000;
    const duration=rand(type==='board'?18:36,type==='board'?54:108);
    const signing=Math.round(weekly*rand(3,10)/10000)*10000;
    const royalty=type==='merch'?rand(8,18):0;
    const nameProposal=type==='stadium'?`${company} ${c.stadium.originalName.replace(/^(.*?\s)?(Arena|Stadion)$/i,'Arena')}`:null;
    state.sponsors.offers.push({id:crypto.randomUUID(),company,type,weekly,duration,signing,royalty,nameProposal,createdWeek:state.week});
    existing.add(company+type);
  }
  state.sponsors.offers=state.sponsors.offers.slice(-24);
}
function acceptSponsorOffer(id){
  ensureSponsorState();const idx=state.sponsors.offers.findIndex(o=>o.id===id);if(idx<0)return;
  const o=state.sponsors.offers[idx],c=getUserClub();let contract={...o,weeksLeft:o.duration,startWeek:state.week};delete contract.id;
  if(o.type==='board'){
    const slot=state.sponsors.boards.findIndex(x=>!x);if(slot<0)return alert('Alle 20 Werbebanden sind bereits vergeben.');
    contract.slot=slot+1;state.sponsors.boards[slot]=contract;
  }else{
    if(state.sponsors[o.type])return alert('Dieser Sponsorenplatz ist bereits belegt.');
    state.sponsors[o.type]=contract;
    if(o.type==='stadium')c.stadium.name=o.nameProposal;
  }
  c.balance+=o.signing;state.sponsors.history.unshift(`${o.company}: ${SPONSOR_LABELS[o.type]} abgeschlossen (${o.duration} Wochen).`);
  state.news.unshift(`${o.company} wird ${SPONSOR_LABELS[o.type]}. Unterschriftsbonus: ${money(o.signing)}.`);
  state.sponsors.offers.splice(idx,1);save();render();
}
function rejectSponsorOffer(id){ensureSponsorState();const o=state.sponsors.offers.find(x=>x.id===id);state.sponsors.offers=state.sponsors.offers.filter(x=>x.id!==id);if(o)state.news.unshift(`Das Sponsorenangebot von ${o.company} wurde abgelehnt.`);save();render();}
function weeklySponsorIncome(){
  ensureSponsorState();const c=getUserClub(),sp=state.sponsors;let fixed=0;
  const contracts=[sp.shirt,sp.stadium,sp.merch,...sp.boards.filter(Boolean)];contracts.forEach(x=>fixed+=x.weekly||0);
  c.balance+=fixed;sp.lastIncome=fixed;
  if(fixed>0)state.news.unshift(`Sponsoren: ${money(fixed)} feste Einnahmen in dieser Woche.`);
  function tick(key){const x=sp[key];if(!x)return;if(--x.weeksLeft<=0){state.news.unshift(`${x.company}: Vertrag als ${SPONSOR_LABELS[key]} ist ausgelaufen.`);sp[key]=null;if(key==='stadium')c.stadium.name=c.stadium.originalName;}}
  tick('shirt');tick('stadium');tick('merch');
  sp.boards=sp.boards.map(x=>{if(!x)return null;x.weeksLeft--;if(x.weeksLeft<=0){state.news.unshift(`${x.company}: Vertrag für Werbebande ${x.slot} ist ausgelaufen.`);return null;}return x;});
  generateSponsorOffers(false);
}


function ensureMatchFinanceState(){
  if(!Array.isArray(state.matchFinanceHistory))state.matchFinanceHistory=[];
  if(state.lastMatch&&state.lastMatch.attendance===undefined){state.lastMatch.attendance=0;state.lastMatch.ticketIncome=0;state.lastMatch.merchSales=0;state.lastMatch.merchIncome=0;}
}
function estimateAttendance(home,away){
  const table=sortedTable(),pos=Math.max(1,table.findIndex(x=>x.id===home.id)+1),success=1-(pos-1)/Math.max(1,table.length-1);
  const appeal=clamp(.52+success*.22+(away.rating-65)/120+(home.fans/1800000)*.12-(home.stadium.ticketPrice-35)/220,.35,.98);
  return Math.min(home.stadium.capacity,Math.max(1000,Math.round(home.stadium.capacity*appeal*(.9+Math.random()*.16))));
}
function calculateUserMatchFinance(h,a){
  ensureSponsorState();ensureMatchFinanceState();const user=getUserClub(),isHome=h.id===user.id,attendance=estimateAttendance(h,a);
  const ticketIncome=isHome?Math.round(attendance*user.stadium.ticketPrice):0;
  const score=clubSuccessScore(),resultFactor=.9+Math.random()*.25,venueFactor=isHome?1:.58;
  const merchSales=Math.round(user.fans*(.018+score*.018)*venueFactor*resultFactor);
  const merchRate=state.sponsors.merch?state.sponsors.merch.royalty/100:.30;
  const merchIncome=Math.round(merchSales*merchRate);
  return {attendance,ticketIncome,merchSales,merchIncome,isHome};
}

function ensureTransferState(){
  if(!state.outgoingOffers)state.outgoingOffers=[];
  getUserClub().squad.forEach(p=>{
    if(p.transferListed===undefined)p.transferListed=false;
    if(p.askingPrice===undefined)p.askingPrice=Math.round(p.value*1.05);
    if(p.listedWeek===undefined)p.listedWeek=null;
  });
}
function listedPlayers(){ensureTransferState();return getUserClub().squad.filter(p=>p.transferListed);}
function activeOfferFor(playerId){ensureTransferState();return state.outgoingOffers.find(o=>o.playerId===playerId&&o.status==='pending');}
function toggleTransferList(playerId){
  ensureTransferState(); const p=getUserClub().squad.find(x=>x.id===playerId); if(!p)return;
  if(p.transferListed){
    p.transferListed=false;p.listedWeek=null;
    state.outgoingOffers=state.outgoingOffers.filter(o=>o.playerId!==playerId||o.status!=='pending');
    state.news.unshift(`${p.name} wurde von der Transferliste genommen.`);
  }else{
    p.transferListed=true;p.listedWeek=state.week;p.askingPrice=Math.max(p.value,Math.round(p.value*1.08));
    state.news.unshift(`${p.name} wurde auf die Transferliste gesetzt.`);
  }
  save();render();
}
function updateAskingPrice(playerId,value){
  const p=getUserClub().squad.find(x=>x.id===playerId);if(!p)return;
  p.askingPrice=clamp(Math.round(Number(value)||p.value),Math.round(p.value*.5),Math.round(p.value*2.5));save();render();
}
function buyerNeedScore(club,player){
  const same=club.squad.filter(p=>p.position===player.position);
  const avg=same.reduce((s,p)=>s+p.rating,0)/(same.length||1);
  return clamp((player.rating-avg+10)/22,.12,.88);
}
function processOutgoingTransferOffers(){
  ensureTransferState(); const user=getUserClub();
  for(const p of listedPlayers()){
    if(activeOfferFor(p.id))continue;
    const weeksListed=Math.max(0,state.week-(p.listedWeek||state.week));
    const candidates=state.league.clubs.filter(c=>c.id!==user.id&&c.budget>p.value*.65)
      .map(c=>({club:c,score:buyerNeedScore(c,p)*(0.65+Math.random()*.7)}))
      .filter(x=>x.score>.18).sort((a,b)=>b.score-a.score);
    const chance=clamp(.16+weeksListed*.06+(p.rating-70)*.008,.12,.72);
    if(!candidates.length||Math.random()>chance)continue;
    const buyer=candidates[rand(0,Math.min(3,candidates.length-1))].club;
    const ageFactor=p.age<24?1.12:p.age>31?.78:1;
    const contractFactor=.88+Math.min(5,p.contract||2)*.035;
    let amount=Math.round(p.value*ageFactor*contractFactor*(.82+Math.random()*.35));
    amount=Math.min(amount,Math.round(buyer.budget*.72));
    if(amount<Math.round(p.value*.55))continue;
    state.outgoingOffers.push({id:crypto.randomUUID(),playerId:p.id,bidderId:buyer.id,amount,week:state.week,status:'pending'});
    state.news.unshift(`${buyer.name} bietet ${money(amount)} für ${p.name}. Deine Entscheidung ist erforderlich.`);
  }
}
function acceptOutgoingOffer(offerId){
  ensureTransferState(); const offer=state.outgoingOffers.find(o=>o.id===offerId&&o.status==='pending');if(!offer)return;
  const user=getUserClub(),buyer=getClub(offer.bidderId),idx=user.squad.findIndex(p=>p.id===offer.playerId);if(idx<0||!buyer)return;
  const player=user.squad[idx];
  if(!confirm(`${buyer.name} bietet ${money(offer.amount)} für ${player.name}. Angebot annehmen?`))return;
  user.squad.splice(idx,1);buyer.squad.push({...player,transferListed:false,listedWeek:null,askingPrice:undefined});
  buyer.budget=Math.max(0,buyer.budget-offer.amount);buyer.balance-=offer.amount;user.balance+=offer.amount;user.budget+=offer.amount;
  offer.status='accepted';state.outgoingOffers.forEach(o=>{if(o.playerId===player.id&&o.id!==offer.id&&o.status==='pending')o.status='expired';});
  state.selectedXI=state.selectedXI.filter(id=>id!==player.id);
  const replacements=[...user.squad].sort((a,b)=>b.rating-a.rating).filter(p=>!state.selectedXI.includes(p.id));
  while(state.selectedXI.length<11&&replacements.length)state.selectedXI.push(replacements.shift().id);
  state.news.unshift(`${player.name} wechselt für ${money(offer.amount)} zu ${buyer.name}.`);save();render();
}
function rejectOutgoingOffer(offerId){
  ensureTransferState();const offer=state.outgoingOffers.find(o=>o.id===offerId&&o.status==='pending');if(!offer)return;
  const p=getUserClub().squad.find(x=>x.id===offer.playerId),buyer=getClub(offer.bidderId);offer.status='rejected';
  if(p&&buyer)state.news.unshift(`Das Angebot von ${buyer.name} über ${money(offer.amount)} für ${p.name} wurde abgelehnt. Er bleibt auf der Transferliste.`);
  save();render();
}

function getClub(id){return state.league.clubs.find(c=>c.id===id)}
function teamPower(club){
  const ids=club.id===state.userClubId?state.selectedXI:club.squad.sort((a,b)=>b.rating-a.rating).slice(0,11).map(p=>p.id);
  const players=ids.map(id=>club.squad.find(p=>p.id===id)).filter(Boolean);
  return players.reduce((s,p)=>s+p.rating*(p.fitness/100)*(0.85+p.morale/500),0)/(players.length||1);
}
function goalsFor(power,opp,home){
  let x=1.2+(power-opp)/16+(home?.25:0)+Math.random()*1.3;
  return clamp(Math.round(x+rand(-1,1)),0,7);
}
function applyMatchResult(f,hg,ag){
  const h=getClub(f.home),a=getClub(f.away);
  [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); f.played=true;f.score=[hg,ag];
  if(h.id===state.userClubId||a.id===state.userClubId){
    const user=h.id===state.userClubId?h:a, isHome=h.id===state.userClubId, ug=isHome?hg:ag, og=isHome?ag:hg;
    const finance=(liveMatch&&liveMatch.fixture===f&&liveMatch.finance)?liveMatch.finance:calculateUserMatchFinance(h,a);
    user.balance += finance.ticketIncome+finance.merchIncome;
    state.sponsors.lastMerchSales=finance.merchSales;
    state.lastMatch={home:h.name,away:a.name,score:`${hg}:${ag}`,attendance:finance.attendance,ticketIncome:finance.ticketIncome,merchSales:finance.merchSales,merchIncome:finance.merchIncome,isHome};
    state.matchFinanceHistory.unshift({week:state.week,season:state.season,home:h.name,away:a.name,score:`${hg}:${ag}`,...finance});
    state.matchFinanceHistory=state.matchFinanceHistory.slice(0,20);
    const picked=state.selectedXI.map(id=>user.squad.find(p=>p.id===id)).filter(Boolean); picked.forEach(p=>{p.apps++;p.fitness=clamp(p.fitness-rand(4,12),45,100);p.morale=clamp(p.morale+(ug>og?rand(2,5):ug<og?-rand(2,5):0),30,100)});
    state.news.unshift(`${h.name} ${hg}:${ag} ${a.name}`);
  }
}
function simulateMatch(f){
  const h=getClub(f.home),a=getClub(f.away); const hp=teamPower(h),ap=teamPower(a);
  applyMatchResult(f,goalsFor(hp,ap,true),goalsFor(ap,hp,false));
}
function commentary(type,team,player){
  const lines={
    kickoff:['Der Ball rollt. Beide Teams beginnen konzentriert.'],
    chance:[`${team} kombiniert sich gefährlich nach vorne.`,`${player} kommt zum Abschluss – knapp vorbei!`,`Große Möglichkeit für ${team}, doch der Torwart ist zur Stelle.`],
    goal:[`TOR für ${team}! ${player} trifft nach einem schnellen Angriff.`,`TOOOR! ${player} lässt dem Keeper keine Chance.`,`Der Ball ist drin! ${team} jubelt, Torschütze: ${player}.`],
    card:[`Gelbe Karte für ${player} nach einem taktischen Foul.`,`Der Schiedsrichter verwarnt ${player}.`],
    save:[`Starke Parade! Der Torwart verhindert den Treffer.`,`Glanzreaktion des Keepers – weiter kein Tor.`],
    corner:[`Ecke für ${team}. Der Ball segelt gefährlich in den Strafraum.`,`Druckphase von ${team}: nächster Eckball.`],
    halftime:['Halbzeitpause. Die Trainer geben neue Anweisungen.'],
    final:['Schlusspfiff! Die Partie ist beendet.']
  };
  const arr=lines[type]||lines.chance; return arr[rand(0,arr.length-1)];
}
function randomPlayer(club,attacking=false){
  const pool=club.squad.filter(p=>attacking?['ST','RA','LA','OM','ZM'].includes(p.position):true);
  const use=pool.length?pool:club.squad; return use[rand(0,use.length-1)].name;
}
function startLiveMatch(f,round){
  if(liveMatch)return;
  const h=getClub(f.home),a=getClub(f.away);
  const finance=calculateUserMatchFinance(h,a);
  liveMatch={fixture:f,home:h,away:a,minute:0,homeGoals:0,awayGoals:0,events:[],paused:false,speed:1,finished:false,homePower:teamPower(h)+2,awayPower:teamPower(a),otherFixtures:round.filter(x=>x!==f),finance};
  view='live'; $$('.nav').forEach(x=>x.classList.remove('active')); render();
  addLiveEvent(0,'kickoff',commentary('kickoff')); runLiveTimer();
}
function addLiveEvent(minute,type,text){
  if(!liveMatch)return; liveMatch.events.unshift({minute,type,text});
  const feed=$('#liveFeed'); if(feed){feed.innerHTML=liveFeedHtml();feed.scrollTop=0;}
}
function liveFeedHtml(){return liveMatch.events.map(e=>`<div class="live-line ${e.type}"><span class="live-minute">${e.minute}'</span><span>${esc(e.text)}</span></div>`).join('');}
function runLiveTimer(){
  clearInterval(liveTimer);
  liveTimer=setInterval(()=>{
    if(!liveMatch||liveMatch.paused||liveMatch.finished)return;
    liveMatch.minute++; processLiveMinute(); updateLiveDisplay();
    if(liveMatch.minute>=90)finishLiveMatch();
  },500/Math.max(1,liveMatch?.speed||1));
}
function processLiveMinute(){
  const m=liveMatch.minute;
  if(m===45){addLiveEvent(m,'halftime',commentary('halftime'));return;}
  const total=Math.max(1,liveMatch.homePower+liveMatch.awayPower), homeAttack=Math.random()<liveMatch.homePower/total;
  const team=homeAttack?liveMatch.home:liveMatch.away, player=randomPlayer(team,true), roll=Math.random();
  if(roll<0.028){
    const attack=homeAttack?liveMatch.homePower:liveMatch.awayPower, defence=homeAttack?liveMatch.awayPower:liveMatch.homePower;
    if(Math.random()<clamp(.30+(attack-defence)/120,.18,.48)){
      if(homeAttack)liveMatch.homeGoals++;else liveMatch.awayGoals++;
      const p=team.squad.find(x=>x.name===player);if(p)p.goals++;
      addLiveEvent(m,'goal',commentary('goal',team.name,player));
    }else addLiveEvent(m,'save',commentary('save',team.name,player));
  }else if(roll<0.075)addLiveEvent(m,'chance',commentary('chance',team.name,player));
  else if(roll<0.095)addLiveEvent(m,'corner',commentary('corner',team.name,player));
  else if(roll<0.108)addLiveEvent(m,'yellow',commentary('card',team.name,randomPlayer(team)));
}
function updateLiveDisplay(){
  if(!liveMatch)return;
  const minute=$('#liveMinute'),score=$('#liveScore'),bar=$('#liveProgress');
  if(minute)minute.textContent=liveMatch.minute>=90?'90+':`${liveMatch.minute}'`;
  if(score)score.textContent=`${liveMatch.homeGoals} : ${liveMatch.awayGoals}`;
  if(bar)bar.style.width=`${Math.min(100,liveMatch.minute/90*100)}%`;
}
function finishLiveMatch(){
  if(!liveMatch||liveMatch.finished)return;
  liveMatch.finished=true;clearInterval(liveTimer);addLiveEvent(90,'final',commentary('final'));
  applyMatchResult(liveMatch.fixture,liveMatch.homeGoals,liveMatch.awayGoals);liveMatch.otherFixtures.forEach(simulateMatch);
  state.league.round++;state.week++;
  const user=getUserClub();user.squad.forEach(p=>p.fitness=clamp(p.fitness+rand(2,7),45,100));
  user.balance-=user.squad.reduce((sum,p)=>sum+p.wage,0);if(state.week%4===0)user.balance-=rand(250000,700000);
  processOutgoingTransferOffers();weeklySponsorIncome();save();updateLiveDisplay();render();
}
function nextWeek(){
  if(liveMatch&&liveMatch.finished){clearInterval(liveTimer);liveMatch=null;view='dashboard';}
  if(liveMatch)return;
  const round=state.league.fixtures[state.league.round];if(!round){endSeason();return;}
  const userFixture=round.find(f=>f.home===state.userClubId||f.away===state.userClubId);
  if(userFixture)startLiveMatch(userFixture,round);else{round.forEach(simulateMatch);state.league.round++;state.week++;processOutgoingTransferOffers();weeklySponsorIncome();save();render();}
}
function endSeason(){
  const table=sortedTable(); const pos=table.findIndex(c=>c.id===state.userClubId)+1;
  const user=getUserClub(); user.balance += Math.max(1,table.length-pos+1)*2e6; state.international.qualified=pos<=3;
  state.news.unshift(`Saison beendet: Platz ${pos}. Eine neue Saison wurde gestartet.`);
  state.season=(parseInt(state.season)+1)+'/'+String(parseInt(state.season)+2).slice(-2); state.week=1; state.league.round=0;
  state.league.clubs.forEach(c=>Object.assign(c,{played:0,wins:0,draws:0,losses:0,gf:0,ga:0,points:0,form:[]}));
  state.league.fixtures=roundRobin(state.league.clubs); ensure36GameSeason(); generateSponsorOffers(true); save();render();
}
function sortedTable(){return [...state.league.clubs].sort((a,b)=>b.points-a.points||(b.gf-b.ga)-(a.gf-a.ga)||b.gf-a.gf)}
function save(){localStorage.setItem('fmretro-save',JSON.stringify(state));}
function load(){const raw=localStorage.getItem('fmretro-save');if(raw){state=JSON.parse(raw);liveMatch=null;clearInterval(liveTimer);ensureTransferState();ensure36GameSeason();ensureSponsorState();ensureMatchFinanceState();if(!state.sponsors.offers.length)generateSponsorOffers(true);save();$('#startScreen').style.display='none';render();}else alert('Kein Spielstand vorhanden.');}
function esc(s){return String(s).replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]))}

function dashboard(){const c=getUserClub(); const table=sortedTable(); const pos=table.findIndex(x=>x.id===c.id)+1; const next=state.league.fixtures[state.league.round]?.find(f=>f.home===c.id||f.away===c.id);
return `<div class="grid cols-3"><div class="card"><div class="muted">Verein</div><div class="stat">${esc(c.name)}</div><div>${esc(state.league.name)}</div></div><div class="card"><div class="muted">Tabellenplatz</div><div class="stat">${pos}.</div><div>${c.points} Punkte</div></div><div class="card"><div class="muted">Kontostand</div><div class="stat ${c.balance<0?'bad':'good'}">${money(c.balance)}</div><div>Transferbudget: ${money(c.budget)}</div></div></div>
<div class="card" style="margin-top:16px"><div class="icon-title"><img src="assets/trophy-icon.jpg" alt="Pokal"><h2>Spieltag im Retro-Stil</h2></div><img class="hero-image" src="assets/matchday.jpg" alt="Pixel-Art Fußballspiel im Stadion"><p class="visual-caption">Grafische Spieltagsansicht – Ergebnisse werden weiterhin durch die Simulation berechnet.</p></div>
<div class="grid cols-2" style="margin-top:16px"><div class="card"><h2>Nächstes Spiel</h2>${next?`<div class="stat">${esc(getClub(next.home).name)} – ${esc(getClub(next.away).name)}</div><p class="muted">Spieltag ${state.league.round+1}</p>`:'<p>Saison beendet.</p>'}${state.lastMatch?`<h3>Letztes Ergebnis</h3><p>${esc(state.lastMatch.home)} <b>${state.lastMatch.score}</b> ${esc(state.lastMatch.away)}</p><div class="last-match-finance"><span>👥 ${Number(state.lastMatch.attendance||0).toLocaleString('de-DE')} Zuschauer</span><span>🎟 ${money(state.lastMatch.ticketIncome||0)} Tickets</span><span>🛍 ${money(state.lastMatch.merchSales||0)} Fanartikelverkauf</span><span>💶 ${money(state.lastMatch.merchIncome||0)} Vereinserlös Fanartikel</span></div>`:''}</div><div class="card"><h2>Manager-News</h2>${state.news.slice(0,6).map(n=>`<div class="fixture">${esc(n)}</div>`).join('')}</div></div>
<div class="card sponsor-quick-card" style="margin-top:16px"><div><h2>★ Sponsoren & Vermarktung</h2><p>Trikotsponsor, 20 Werbebanden, Stadionnamensrechte und Fanartikelverkauf verwalten.</p></div><button id="openSponsors" class="primary">Sponsoren öffnen</button></div>
<div class="grid cols-2 retro-gallery"><div class="card"><h3>Trikots</h3><img class="retro-strip" src="assets/kits.jpg" alt="Retro-Trikots"></div><div class="card"><h3>Status & Wetter</h3><img class="retro-strip" src="assets/status-bars.jpg" alt="Fitness- und Formanzeigen"><img class="retro-strip" style="margin-top:8px" src="assets/weather.jpg" alt="Wettersymbole"></div></div>`}
function squad(){ensureTransferState();const c=getUserClub(); return `<div class="card"><h2>Kader – ${esc(c.name)}</h2><p class="muted">Spieler können hier auf die Transferliste gesetzt oder wieder entfernt werden.</p><div class="player-row transfer-header"><span>Pos</span><span>Name</span><span>Alter</span><span>Stärke</span><span>Fitness</span><span>Wert</span><span>Status</span><span>Aktion</span></div>${[...c.squad].sort((a,b)=>b.rating-a.rating).map(p=>`<div class="player-row transfer-row"><span class="badge">${p.position}</span><span>${esc(p.name)}</span><span>${p.age}</span><b>${p.rating}</b><span>${p.fitness}%</span><span>${money(p.value)}</span><span>${p.transferListed?'<span class="listed-label">Transferliste</span>':'—'}</span><span><button data-list-player="${p.id}" class="${p.transferListed?'danger':''}">${p.transferListed?'Entfernen':'Anbieten'}</button></span></div>`).join('')}</div>`}
function lineup(){const c=getUserClub(); const slots=['TW','RV','IV','IV','LV','DM','ZM','ZM','RA','LA','ST']; return `<div class="card"><h2>Aufstellung</h2><p class="muted">Wähle elf Spieler. Fitness und Moral beeinflussen die Matchstärke.</p><div class="lineup-grid">${slots.map((pos,i)=>{const sel=state.selectedXI[i];return `<div class="lineup-slot"><b>${pos}</b><select data-lineup="${i}">${c.squad.map(p=>`<option value="${p.id}" ${p.id===sel?'selected':''}>${esc(p.name)} (${p.position}, ${p.rating})</option>`).join('')}</select></div>`}).join('')}</div></div>`}
function league(){return `<div class="card"><h2>${esc(state.league.name)} – Tabelle</h2><table><thead><tr><th>#</th><th>Verein</th><th>Sp</th><th>S</th><th>U</th><th>N</th><th>Tore</th><th>Diff</th><th>Pkt</th></tr></thead><tbody>${sortedTable().map((c,i)=>`<tr class="${c.id===state.userClubId?'user-team':''}"><td>${i+1}</td><td>${esc(c.name)}</td><td>${c.played}</td><td>${c.wins}</td><td>${c.draws}</td><td>${c.losses}</td><td>${c.gf}:${c.ga}</td><td>${c.gf-c.ga}</td><td><b>${c.points}</b></td></tr>`).join('')}</tbody></table></div>`}
function transfers(){
  ensureTransferState();const c=getUserClub(),pending=state.outgoingOffers.filter(o=>o.status==='pending');
  return `<div class="grid cols-2 transfer-summary"><div class="card"><h2>Einkäufe</h2><p>Transferbudget: <b>${money(c.budget)}</b></p><table><thead><tr><th>Spieler</th><th>Pos</th><th>Stärke</th><th>Verein</th><th>Preis</th><th></th></tr></thead><tbody>${state.transferList.slice(0,20).map((p,i)=>`<tr><td>${esc(p.name)}</td><td>${p.position}</td><td>${p.rating}</td><td>${esc(p.fromClub)}</td><td>${money(p.asking)}</td><td><button data-buy="${i}">Kaufen</button></td></tr>`).join('')}</tbody></table></div>
  <div class="card"><h2>Eingegangene Angebote</h2>${pending.length?pending.map(o=>{const p=c.squad.find(x=>x.id===o.playerId),b=getClub(o.bidderId);return p&&b?`<div class="offer-card"><div><b>${esc(b.name)}</b> bietet für <b>${esc(p.name)}</b></div><div class="offer-price">${money(o.amount)}</div><div class="muted">Marktwert ${money(p.value)} · Forderung ${money(p.askingPrice)}</div><div class="offer-actions"><button data-accept-offer="${o.id}" class="primary">Annehmen</button><button data-reject-offer="${o.id}" class="danger">Ablehnen</button></div></div>`:''}).join(''):'<p class="muted">Momentan liegen keine Angebote vor. Neue Gebote können beim Fortschreiten einer Woche eintreffen.</p>'}</div></div>
  <div class="card" style="margin-top:16px"><h2>Deine Transferliste</h2>${listedPlayers().length?`<table><thead><tr><th>Spieler</th><th>Pos</th><th>Stärke</th><th>Marktwert</th><th>Wunschpreis</th><th>Aktuelles Gebot</th><th></th></tr></thead><tbody>${listedPlayers().map(p=>{const o=activeOfferFor(p.id),b=o?getClub(o.bidderId):null;return `<tr><td>${esc(p.name)}</td><td>${p.position}</td><td>${p.rating}</td><td>${money(p.value)}</td><td><input class="price-input" data-asking-price="${p.id}" type="number" min="${Math.round(p.value*.5)}" max="${Math.round(p.value*2.5)}" step="100000" value="${p.askingPrice}"></td><td>${o&&b?`${esc(b.name)}: <b>${money(o.amount)}</b>`:'Noch keines'}</td><td><button data-list-player="${p.id}" class="danger">Entfernen</button></td></tr>`}).join('')}</tbody></table>`:'<p>Noch kein Spieler wurde auf die Transferliste gesetzt. Das kannst du im Menü „Kader“ erledigen.</p>'}</div>`;
}

function sponsors(){
  ensureSponsorState();const c=getUserClub(),sp=state.sponsors,score=Math.round(clubSuccessScore()*100);
  const activeCard=(title,x)=>`<div class="sponsor-contract"><h3>${title}</h3>${x?`<b>${esc(x.company)}</b><div>${money(x.weekly)}/Woche</div><small>${x.weeksLeft} Wochen verbleibend${x.royalty?` · ${x.royalty}% Umsatzbeteiligung`:''}</small>`:'<span class="muted">Noch frei</span>'}</div>`;
  return `<div class="grid cols-3 sponsor-metrics"><div class="card"><div class="muted">Vereinserfolg</div><div class="stat gold">${score}%</div><p>Tabellenplatz, Form, Stärke und internationale Teilnahme bestimmen die Qualität der Angebote.</p></div><div class="card"><div class="muted">Letzte Sponsoreneinnahmen</div><div class="stat good">${money(sp.lastIncome||0)}</div><p>inklusive Fanartikelbeteiligung</p></div><div class="card"><div class="muted">Fanbasis</div><div class="stat">${c.fans.toLocaleString('de-DE')}</div><p>Letzter Fanartikelumsatz: ${money(sp.lastMerchSales||0)}</p></div></div>
  <div class="grid cols-3" style="margin-top:16px">${activeCard('Trikotsponsor',sp.shirt)}${activeCard('Stadionnamensrechte',sp.stadium)}${activeCard('Merchandisingpartner',sp.merch)}</div>
  <div class="card" style="margin-top:16px"><h2>20 Stadion-Werbebanden</h2><div class="board-grid">${sp.boards.map((x,i)=>`<div class="ad-board ${x?'occupied':''}"><span>Bande ${i+1}</span><b>${x?esc(x.company):'FREI'}</b>${x?`<small>${money(x.weekly)}/W · ${x.weeksLeft} W.</small>`:''}</div>`).join('')}</div></div>
  <div class="card" style="margin-top:16px"><h2>Aktuelle Sponsorenangebote</h2>${sp.offers.length?`<table><thead><tr><th>Firma</th><th>Bereich</th><th>Wöchentlich</th><th>Bonus</th><th>Laufzeit</th><th>Details</th><th></th></tr></thead><tbody>${sp.offers.map(o=>`<tr><td><b>${esc(o.company)}</b></td><td>${SPONSOR_LABELS[o.type]}</td><td>${money(o.weekly)}</td><td>${money(o.signing)}</td><td>${o.duration} Wochen</td><td>${o.type==='merch'?`${o.royalty}% Fanartikel-Umsatz`:o.type==='stadium'?esc(o.nameProposal):o.type==='board'?'eine von 20 Banden':'Logo auf Heim- und Auswärtstrikot'}</td><td><div class="offer-actions"><button data-accept-sponsor="${o.id}" class="primary">Annehmen</button><button data-reject-sponsor="${o.id}" class="danger">Ablehnen</button></div></td></tr>`).join('')}</tbody></table>`:'<p class="muted">Momentan liegen keine Angebote vor. Neue Angebote erscheinen in regelmäßigen Abständen und nach Saisonerfolgen.</p>'}</div>`;
}

function finances(){ensureMatchFinanceState();const c=getUserClub(),w=c.squad.reduce((s,p)=>s+p.wage,0),hist=state.matchFinanceHistory.slice(0,10);return `<div class="grid cols-2"><div class="card"><div class="icon-title"><img src="assets/finance-icon.jpg" alt="Finanzen"><h2>Finanzen</h2></div><p>Kontostand</p><div class="stat ${c.balance<0?'bad':'good'}">${money(c.balance)}</div><hr><p>Wöchentliche Gehälter: <b>${money(w)}</b></p><p>Transferbudget: <b>${money(c.budget)}</b></p><p>Stadion-Einnahmen pro Heimspiel: ca. <b>${money(c.stadium.capacity*c.stadium.ticketPrice*.7)}</b></p></div><div class="card"><h2>Topverdiener</h2>${[...c.squad].sort((a,b)=>b.wage-a.wage).slice(0,8).map(p=>`<div class="fixture"><span>${esc(p.name)}</span><b>${money(p.wage)}/Woche</b></div>`).join('')}</div></div><div class="card" style="margin-top:16px"><h2>Spielabrechnungen</h2>${hist.length?`<table><thead><tr><th>Spiel</th><th>Zuschauer</th><th>Tickets</th><th>Fanartikelverkauf</th><th>Fanartikel-Erlös</th></tr></thead><tbody>${hist.map(x=>`<tr><td>${esc(x.home)} ${esc(x.score)} ${esc(x.away)}</td><td>${Number(x.attendance).toLocaleString('de-DE')}</td><td>${money(x.ticketIncome)}</td><td>${money(x.merchSales)}</td><td>${money(x.merchIncome)}</td></tr>`).join('')}</tbody></table>`:'<p class="muted">Noch keine Spielabrechnung vorhanden.</p>'}</div>`}
function stadium(){const c=getUserClub(),s=c.stadium;const stadiumImage=s.capacity<30000?'stadium-small.jpg':s.capacity<55000?'stadium-medium.jpg':'stadium-large.jpg';return `<div class="grid cols-2"><div class="card"><div class="icon-title"><img src="assets/stadium-icon.jpg" alt="Stadion"><h2>${esc(s.name)}</h2></div><img class="stadium-visual" src="assets/${stadiumImage}" alt="Retro-Stadionansicht"><div class="stat">${s.capacity.toLocaleString('de-DE')} Plätze</div><p>Zustand: ${s.condition}%</p><div class="progress"><span style="width:${s.condition}%"></span></div><p>Ticketpreis: ${money(s.ticketPrice)}</p></div><div class="card"><h2>Ausbau</h2><p>Erweitere um 5.000 Plätze.</p><p>Kosten: <b>${money(12e6)}</b></p><button id="upgradeStadium">Ausbauen</button><h3>Ticketpreis</h3><input id="ticketPrice" type="range" min="10" max="100" value="${s.ticketPrice}"><span id="ticketPriceLabel"> ${money(s.ticketPrice)}</span><h3 style="margin-top:22px">Stadionstufen</h3><div class="grid cols-3"><img class="retro-strip" src="assets/stadium-small.jpg" alt="Kleines Stadion"><img class="retro-strip" src="assets/stadium-medium.jpg" alt="Mittleres Stadion"><img class="retro-strip" src="assets/stadium-large.jpg" alt="Großes Stadion"></div></div></div>`}
function international(){const q=state.international.qualified;return `<div class="card"><h2>Internationaler Wettbewerb</h2>${q?`<p class="good"><b>Qualifiziert</b></p><p>Dein Verein nimmt in dieser Saison am International Champions Cup teil.</p>`:`<p>Die besten drei Teams der Liga qualifizieren sich für den internationalen Wettbewerb der nächsten Saison.</p>`}<h3>Europäische Topligen</h3><p class="muted">Das Spiel enthält bereits acht Nationalligen. Weitere Ligen lassen sich in <code>data.js</code> ergänzen.</p></div>`}
function liveView(){
  if(!liveMatch)return `<div class="card"><h2>Kein Live-Spiel aktiv</h2></div>`;
  const l=liveMatch;
  return `<div class="live-match card"><div class="live-top"><span class="viz-badge">LIVE</span><span id="liveMinute" class="live-clock">${l.minute}'</span></div><div class="live-scoreboard"><div><b>${esc(l.home.name)}</b><small>Heim</small></div><div id="liveScore" class="live-score">${l.homeGoals} : ${l.awayGoals}</div><div><b>${esc(l.away.name)}</b><small>Auswärts</small></div></div><div class="grid cols-3 match-finance-live"><div class="metric-box"><span>Zuschauer</span><b>${l.finance.attendance.toLocaleString('de-DE')}</b></div><div class="metric-box"><span>Ticketeinnahmen</span><b>${money(l.finance.ticketIncome)}</b></div><div class="metric-box"><span>Fanartikelverkauf</span><b>${money(l.finance.merchSales)}</b><small>Vereinseinnahme ${money(l.finance.merchIncome)}</small></div></div><div class="progress live-progress"><span id="liveProgress" style="width:${l.minute/90*100}%"></span></div><img class="hero-image live-pitch" src="assets/matchday.jpg" alt="Retro-Spieltagsansicht"><div class="grid cols-2 live-layout"><div class="card live-chat-card"><h2>Live-Ticker</h2><div id="liveFeed" class="live-feed" aria-live="polite">${liveFeedHtml()}</div></div><div class="card"><h2>Spielsteuerung</h2><div id="liveControls" class="live-controls">${l.finished?'<button id="continueAfterMatch" class="primary">Weiter zur Übersicht</button>':`<button id="pauseLive">${l.paused?'Fortsetzen':'Pause'}</button><button data-speed="1" class="${l.speed===1?'primary':''}">1×</button><button data-speed="2" class="${l.speed===2?'primary':''}">2×</button><button data-speed="4" class="${l.speed===4?'primary':''}">4×</button>`}</div><p class="muted">Eine Partie dauert bei 1× ungefähr 45 Sekunden. Der Ticker meldet Chancen, Tore, Karten, Ecken und Paraden.</p><div class="match-stats"><div><span>Heimstärke</span><b>${Math.round(l.homePower)}</b></div><div><span>Auswärtsstärke</span><b>${Math.round(l.awayPower)}</b></div></div></div></div></div>`;
}
function render(){if(!state)return; $('#seasonLabel').textContent=`Saison ${state.season} · Woche ${state.week} · ${state.league.country}`; const map={dashboard,squad,lineup,league,transfers,sponsors,finances,stadium,international,live:liveView}; $('#content').innerHTML=map[view](); bindDynamic();}
function bindDynamic(){
  const openSponsors=$('#openSponsors');if(openSponsors)openSponsors.onclick=()=>{$$('.nav').forEach(x=>x.classList.remove('active'));const n=$('.nav[data-view="sponsors"]');if(n)n.classList.add('active');view='sponsors';render();};
  const pause=$('#pauseLive');if(pause)pause.onclick=()=>{liveMatch.paused=!liveMatch.paused;pause.textContent=liveMatch.paused?'Fortsetzen':'Pause';};
  $$('[data-speed]').forEach(btn=>btn.onclick=()=>{liveMatch.speed=+btn.dataset.speed;runLiveTimer();render();});
  const cont=$('#continueAfterMatch');if(cont)cont.onclick=()=>{liveMatch=null;view='dashboard';$('.nav[data-view="dashboard"]').classList.add('active');render();};
 $$('[data-lineup]').forEach(sel=>sel.onchange=e=>{const i=+e.target.dataset.lineup; state.selectedXI[i]=e.target.value; save();}); $$('[data-buy]').forEach(btn=>btn.onclick=()=>buyPlayer(+btn.dataset.buy)); $$('[data-list-player]').forEach(btn=>btn.onclick=()=>toggleTransferList(btn.dataset.listPlayer)); $$('[data-accept-offer]').forEach(btn=>btn.onclick=()=>acceptOutgoingOffer(btn.dataset.acceptOffer)); $$('[data-reject-offer]').forEach(btn=>btn.onclick=()=>rejectOutgoingOffer(btn.dataset.rejectOffer)); $$('[data-asking-price]').forEach(inp=>inp.onchange=()=>updateAskingPrice(inp.dataset.askingPrice,inp.value)); $$('[data-accept-sponsor]').forEach(btn=>btn.onclick=()=>acceptSponsorOffer(btn.dataset.acceptSponsor)); $$('[data-reject-sponsor]').forEach(btn=>btn.onclick=()=>rejectSponsorOffer(btn.dataset.rejectSponsor)); const up=$('#upgradeStadium');if(up)up.onclick=()=>{const c=getUserClub();if(c.balance<12e6)return alert('Zu wenig Geld.');c.balance-=12e6;c.stadium.capacity+=5000;c.stadium.condition=100;save();render();}; const range=$('#ticketPrice');if(range)range.oninput=e=>{$('#ticketPriceLabel').textContent=' '+money(+e.target.value);getUserClub().stadium.ticketPrice=+e.target.value;save();};}
function buyPlayer(i){const p=state.transferList[i],c=getUserClub();if(!p)return;if(c.budget<p.asking)return alert('Transferbudget zu niedrig.');c.budget-=p.asking;c.balance-=p.asking;c.squad.push({...p,id:crypto.randomUUID()});state.transferList.splice(i,1);state.news.unshift(`${p.name} wurde für ${money(p.asking)} verpflichtet.`);save();render();}
function setupStart(){const cs=$('#countrySelect'),ls=$('#leagueSelect'),clubs=$('#clubSelect');COUNTRIES.forEach((c,i)=>cs.add(new Option(c.name,i)));function leagues(){ls.innerHTML='';COUNTRIES[+cs.value].leagues.forEach((l,i)=>ls.add(new Option(l.name,i)));teams();}function teams(){clubs.innerHTML='';COUNTRIES[+cs.value].leagues[+ls.value].clubs.forEach(n=>clubs.add(new Option(n,n)));}cs.onchange=leagues;ls.onchange=teams;leagues();$('#startBtn').onclick=()=>{$('#startScreen').style.display='none';newGame(+cs.value,+ls.value,clubs.value)};}
$$('.nav').forEach(b=>b.onclick=()=>{$$('.nav').forEach(x=>x.classList.remove('active'));b.classList.add('active');view=b.dataset.view;render();});
$('#nextWeekBtn').onclick=nextWeek;$('#saveBtn').onclick=()=>{save();alert('Spiel gespeichert.');};$('#loadBtn').onclick=load;$('#newBtn').onclick=()=>{if(confirm('Wirklich ein neues Spiel starten?')){$('#startScreen').style.display='grid';setupStart();}};
setupStart();if(localStorage.getItem('fmretro-save'))load();

/* Version 1.3 – Formationen, Sortierung, Live-Taktik, Karten und Sperren */
const FORMATIONS={
  '4-4-2':['TW','RV','IV','IV','LV','RM','ZM','ZM','LM','ST','ST'],
  '5-3-2':['TW','RV','IV','IV','IV','LV','ZM','ZM','ZM','ST','ST'],
  '4-3-3':['TW','RV','IV','IV','LV','ZM','ZM','ZM','RA','ST','LA']
};
const POSITION_ORDER={TW:0,RV:1,IV:2,LV:3,DM:4,RM:5,ZM:6,LM:7,OM:8,RA:9,LA:10,ST:11};
let squadSort='position';
let transferSort='position';

function ensureGameSystems(){
  if(!state)return;
  if(!FORMATIONS[state.formation])state.formation='4-4-2';
  if(!state.matchSettings)state.matchSettings={tactic:'balanced',aggression:'fair'};
  state.league.clubs.forEach(c=>c.squad.forEach(p=>{
    if(p.yellowCards===undefined)p.yellowCards=0;
    if(p.redCards===undefined)p.redCards=0;
    if(p.suspensionGames===undefined)p.suspensionGames=0;
  }));
  normalizeLineup();
}
function sortPlayers(list,mode){
  return [...list].sort((a,b)=>mode==='rating'?(b.rating-a.rating)||((POSITION_ORDER[a.position]??99)-(POSITION_ORDER[b.position]??99)):((POSITION_ORDER[a.position]??99)-(POSITION_ORDER[b.position]??99))||(b.rating-a.rating));
}
function normalizeLineup(){
  if(!state)return;
  const c=getUserClub(),slots=FORMATIONS[state.formation]||FORMATIONS['4-4-2'];
  const validIds=new Set(c.squad.map(p=>p.id));
  const picked=[];
  (state.selectedXI||[]).forEach(id=>{const p=c.squad.find(x=>x.id===id);if(validIds.has(id)&&p&&p.suspensionGames<=0&&!picked.includes(id)&&picked.length<slots.length)picked.push(id);});
  const available=sortPlayers(c.squad.filter(p=>!picked.includes(p.id)&&p.suspensionGames<=0),'rating');
  while(picked.length<slots.length&&available.length)picked.push(available.shift().id);
  state.selectedXI=picked.slice(0,slots.length);
}
function lineupGroupAverages(){
  const c=getUserClub(),slots=FORMATIONS[state.formation]||FORMATIONS['4-4-2'];
  const groups={TW:[],ABW:[],MIT:[],ST:[]};
  slots.forEach((slot,i)=>{const p=c.squad.find(x=>x.id===state.selectedXI[i]);if(!p)return;const g=slot==='TW'?'TW':['RV','IV','LV'].includes(slot)?'ABW':['ST','RA','LA'].includes(slot)?'ST':'MIT';groups[g].push(p.rating);});
  const avg=a=>a.length?(a.reduce((s,n)=>s+n,0)/a.length).toFixed(1):'–';
  return {TW:avg(groups.TW),ABW:avg(groups.ABW),MIT:avg(groups.MIT),ST:avg(groups.ST)};
}
function playerOption(p,sel,index){
  const used=(state.selectedXI||[]).some((id,i)=>i!==index&&id===p.id);
  const suspended=p.suspensionGames>0;
  return `<option value="${p.id}" ${p.id===sel?'selected':''} ${(used||suspended)&&p.id!==sel?'disabled':''}>${esc(p.name)} (${p.position}, ${p.rating}${suspended?`, gesperrt ${p.suspensionGames}`:''})</option>`;
}
function lineup(){
  ensureGameSystems();const c=getUserClub(),slots=FORMATIONS[state.formation];
  return `<div class="card"><h2>Aufstellung</h2><div class="lineup-toolbar"><label>Formation<select id="formationSelect"><option value="4-4-2" ${state.formation==='4-4-2'?'selected':''}>4-4-2</option><option value="5-3-2" ${state.formation==='5-3-2'?'selected':''}>5-3-2</option><option value="4-3-3" ${state.formation==='4-3-3'?'selected':''}>4-3-3</option></select></label><span class="muted">Bereits aufgestellte und gesperrte Spieler können nicht doppelt gewählt werden.</span></div><div class="lineup-grid formation-${state.formation.replaceAll('-','')}">${slots.map((pos,i)=>{const sel=state.selectedXI[i];return `<div class="lineup-slot"><b>${pos}</b><select data-lineup="${i}">${sortPlayers(c.squad,'position').map(p=>playerOption(p,sel,i)).join('')}</select></div>`}).join('')}</div></div>`;
}
function squad(){
  ensureTransferState();ensureGameSystems();const c=getUserClub(),players=sortPlayers(c.squad,squadSort);
  return `<div class="card"><div class="section-toolbar"><div><h2>Kader – ${esc(c.name)}</h2><p class="muted">Spieler verwalten, sortieren und auf die Transferliste setzen.</p></div><label>Sortierung<select id="squadSort"><option value="position" ${squadSort==='position'?'selected':''}>Position</option><option value="rating" ${squadSort==='rating'?'selected':''}>Stärke</option></select></label></div><div class="player-row transfer-header"><span>Pos</span><span>Name</span><span>Alter</span><span>Stärke</span><span>Fitness</span><span>Wert</span><span>Status</span><span>Aktion</span></div>${players.map(p=>`<div class="player-row transfer-row"><span class="badge">${p.position}</span><span>${esc(p.name)}${p.suspensionGames>0?` <span class="suspension-label">Gesperrt ${p.suspensionGames}</span>`:''}</span><span>${p.age}</span><b>${p.rating}</b><span>${p.fitness}%</span><span>${money(p.value)}</span><span>${p.transferListed?'<span class="listed-label">Transferliste</span>':'—'}${p.yellowCards?`<small class="card-count"> ${p.yellowCards} Gelbe</small>`:''}</span><span><button data-list-player="${p.id}" class="${p.transferListed?'danger':''}">${p.transferListed?'Entfernen':'Anbieten'}</button></span></div>`).join('')}</div>`;
}
function transfers(){
  ensureTransferState();ensureGameSystems();const c=getUserClub(),pending=state.outgoingOffers.filter(o=>o.status==='pending'),market=sortPlayers(state.transferList,transferSort).slice(0,20),listed=sortPlayers(listedPlayers(),transferSort);
  return `<div class="card transfer-sortbar"><label>Transferlisten sortieren<select id="transferSort"><option value="position" ${transferSort==='position'?'selected':''}>Position</option><option value="rating" ${transferSort==='rating'?'selected':''}>Stärke</option></select></label></div><div class="grid cols-2 transfer-summary"><div class="card"><h2>Einkäufe</h2><p>Transferbudget: <b>${money(c.budget)}</b></p><table><thead><tr><th>Spieler</th><th>Alter</th><th>Pos</th><th>Stärke</th><th>Verein</th><th>Preis</th><th></th></tr></thead><tbody>${market.map(p=>{const realIndex=state.transferList.findIndex(x=>x.id===p.id);return `<tr><td>${esc(p.name)}</td><td>${p.age}</td><td>${p.position}</td><td>${p.rating}</td><td>${esc(p.fromClub)}</td><td>${money(p.asking)}</td><td><button data-buy="${realIndex}">Kaufen</button></td></tr>`}).join('')}</tbody></table></div><div class="card"><h2>Eingegangene Angebote</h2>${pending.length?pending.map(o=>{const p=c.squad.find(x=>x.id===o.playerId),b=getClub(o.bidderId);return p&&b?`<div class="offer-card"><div><b>${esc(b.name)}</b> bietet für <b>${esc(p.name)}</b> (${p.age})</div><div class="offer-price">${money(o.amount)}</div><div class="muted">Marktwert ${money(p.value)} · Forderung ${money(p.askingPrice)}</div><div class="offer-actions"><button data-accept-offer="${o.id}" class="primary">Annehmen</button><button data-reject-offer="${o.id}" class="danger">Ablehnen</button></div></div>`:''}).join(''):'<p class="muted">Momentan liegen keine Angebote vor.</p>'}</div></div><div class="card" style="margin-top:16px"><h2>Deine Transferliste</h2>${listed.length?`<table><thead><tr><th>Spieler</th><th>Alter</th><th>Pos</th><th>Stärke</th><th>Marktwert</th><th>Wunschpreis</th><th>Aktuelles Gebot</th><th></th></tr></thead><tbody>${listed.map(p=>{const o=activeOfferFor(p.id),b=o?getClub(o.bidderId):null;return `<tr><td>${esc(p.name)}</td><td>${p.age}</td><td>${p.position}</td><td>${p.rating}</td><td>${money(p.value)}</td><td><input class="price-input" data-asking-price="${p.id}" type="number" min="${Math.round(p.value*.5)}" max="${Math.round(p.value*2.5)}" step="100000" value="${p.askingPrice}"></td><td>${o&&b?`${esc(b.name)}: <b>${money(o.amount)}</b>`:'Noch keines'}</td><td><button data-list-player="${p.id}" class="danger">Entfernen</button></td></tr>`}).join('')}</tbody></table>`:'<p>Noch kein Spieler wurde auf die Transferliste gesetzt.</p>'}</div>`;
}
function dashboard(){
  ensureGameSystems();const c=getUserClub(),table=sortedTable(),pos=table.findIndex(x=>x.id===c.id)+1,next=state.league.fixtures[state.league.round]?.find(f=>f.home===c.id||f.away===c.id),a=lineupGroupAverages();
  return `<div class="grid cols-3"><div class="card"><div class="muted">Verein</div><div class="stat">${esc(c.name)}</div><div>${esc(state.league.name)}</div></div><div class="card"><div class="muted">Tabellenplatz</div><div class="stat">${pos}.</div><div>${c.points} Punkte</div></div><div class="card"><div class="muted">Kontostand</div><div class="stat ${c.balance<0?'bad':'good'}">${money(c.balance)}</div><div>Transferbudget: ${money(c.budget)}</div></div></div><div class="card lineup-averages"><h2>Durchschnittsstärke der Aufstellung · ${state.formation}</h2><div class="grid cols-4"><div class="metric-box"><span>TW</span><b>${a.TW}</b></div><div class="metric-box"><span>ABW</span><b>${a.ABW}</b></div><div class="metric-box"><span>MIT</span><b>${a.MIT}</b></div><div class="metric-box"><span>ST</span><b>${a.ST}</b></div></div></div><div class="card" style="margin-top:16px"><div class="icon-title"><img src="assets/trophy-icon.jpg" alt="Pokal"><h2>Spieltag im Retro-Stil</h2></div><img class="hero-image" src="assets/matchday.jpg" alt="Pixel-Art Fußballspiel im Stadion"></div><div class="grid cols-2" style="margin-top:16px"><div class="card"><h2>Nächstes Spiel</h2>${next?`<div class="stat">${esc(getClub(next.home).name)} – ${esc(getClub(next.away).name)}</div><p class="muted">Spieltag ${state.league.round+1}</p>`:'<p>Saison beendet.</p>'}${state.lastMatch?`<h3>Letztes Ergebnis</h3><p>${esc(state.lastMatch.home)} <b>${state.lastMatch.score}</b> ${esc(state.lastMatch.away)}</p><div class="last-match-finance"><span>👥 ${Number(state.lastMatch.attendance||0).toLocaleString('de-DE')} Zuschauer</span><span>🎟 ${money(state.lastMatch.ticketIncome||0)} Tickets</span><span>🛍 ${money(state.lastMatch.merchSales||0)} Fanartikelverkauf</span><span>💶 ${money(state.lastMatch.merchIncome||0)} Vereinserlös Fanartikel</span></div>`:''}</div><div class="card"><h2>Manager-News</h2>${state.news.slice(0,6).map(n=>`<div class="fixture">${esc(n)}</div>`).join('')}</div></div><div class="card sponsor-quick-card" style="margin-top:16px"><div><h2>★ Sponsoren & Vermarktung</h2><p>Trikotsponsor, Werbebanden, Stadionname und Fanartikel verwalten.</p></div><button id="openSponsors" class="primary">Sponsoren öffnen</button></div>`;
}
function effectiveUserPower(base){
  const t=liveMatch?.tactic||state.matchSettings.tactic;
  return base*(t==='offensive'?1.07:t==='defensive'?.96:1);
}
function startLiveMatch(f,round){
  if(liveMatch)return;ensureGameSystems();normalizeLineup();
  const h=getClub(f.home),a=getClub(f.away),finance=calculateUserMatchFinance(h,a),userHome=h.id===state.userClubId;
  let hp=teamPower(h)+2,ap=teamPower(a);
  if(userHome)hp=effectiveUserPower(hp);else ap=effectiveUserPower(ap);
  liveMatch={fixture:f,home:h,away:a,minute:0,homeGoals:0,awayGoals:0,events:[],paused:false,speed:1,finished:false,homePower:hp,awayPower:ap,otherFixtures:round.filter(x=>x!==f),finance,tactic:state.matchSettings.tactic,aggression:state.matchSettings.aggression,userHome,yellowHome:0,yellowAway:0,redHome:0,redAway:0};
  document.body.classList.add('match-running');view='live';$$('.nav').forEach(x=>x.classList.remove('active'));render();addLiveEvent(0,'kickoff',commentary('kickoff'));runLiveTimer();
}
function cardPlayer(team,type){
  const eligible=team.squad.filter(p=>p.suspensionGames<=0);if(!eligible.length)return null;const p=eligible[rand(0,eligible.length-1)];
  if(type==='yellow'){p.yellowCards++;if(p.yellowCards>=4){p.yellowCards=0;p.suspensionGames=Math.max(p.suspensionGames,1);state.news.unshift(`${p.name} ist nach vier Gelben Karten für ein Spiel gesperrt.`);}}
  else{p.redCards++;p.suspensionGames=Math.max(p.suspensionGames,1);state.news.unshift(`${p.name} ist nach einer Roten Karte für ein Spiel gesperrt.`);}
  return p;
}
function processLiveMinute(){
  const m=liveMatch.minute;if(m===45){addLiveEvent(m,'halftime',commentary('halftime'));return;}
  const total=Math.max(1,liveMatch.homePower+liveMatch.awayPower),homeAttack=Math.random()<liveMatch.homePower/total,team=homeAttack?liveMatch.home:liveMatch.away,player=randomPlayer(team,true),roll=Math.random();
  const isUser=team.id===state.userClubId,tactic=isUser?liveMatch.tactic:'balanced',agg=isUser?liveMatch.aggression:'fair';
  const goalThreshold=tactic==='offensive'?.034:tactic==='defensive'?.023:.028;
  const chanceThreshold=goalThreshold+(tactic==='offensive'?.057:tactic==='defensive'?.038:.047);
  const cardRate=agg==='hard'?.030:.010,redChance=agg==='hard'?.18:.06;
  if(roll<goalThreshold){const attack=homeAttack?liveMatch.homePower:liveMatch.awayPower,defence=homeAttack?liveMatch.awayPower:liveMatch.homePower;if(Math.random()<clamp(.30+(attack-defence)/120,.18,.48)){if(homeAttack)liveMatch.homeGoals++;else liveMatch.awayGoals++;const p=team.squad.find(x=>x.name===player);if(p)p.goals++;addLiveEvent(m,'goal',commentary('goal',team.name,player));}else addLiveEvent(m,'save',commentary('save',team.name,player));}
  else if(roll<chanceThreshold)addLiveEvent(m,'chance',commentary('chance',team.name,player));
  else if(roll<chanceThreshold+.02)addLiveEvent(m,'corner',commentary('corner',team.name,player));
  else if(roll<chanceThreshold+.02+cardRate){const type=Math.random()<redChance?'red':'yellow',p=cardPlayer(team,type);if(p){if(homeAttack){if(type==='red')liveMatch.redHome++;else liveMatch.yellowHome++;}else{if(type==='red')liveMatch.redAway++;else liveMatch.yellowAway++;}addLiveEvent(m,type,type==='red'?`Rote Karte für ${p.name} (${team.name})!` : commentary('card',team.name,p.name));}}
}
function liveView(){
  if(!liveMatch)return `<div class="card"><h2>Kein Live-Spiel aktiv</h2></div>`;const l=liveMatch;
  return `<div class="live-match card"><div class="live-top"><span class="viz-badge">LIVE</span><span id="liveMinute" class="live-clock">${l.minute}'</span></div><div class="live-scoreboard"><div><b>${esc(l.home.name)}</b><small>Heim · 🟨 ${l.yellowHome} 🟥 ${l.redHome}</small></div><div id="liveScore" class="live-score">${l.homeGoals} : ${l.awayGoals}</div><div><b>${esc(l.away.name)}</b><small>Auswärts · 🟨 ${l.yellowAway} 🟥 ${l.redAway}</small></div></div><div class="grid cols-3 match-finance-live"><div class="metric-box"><span>Zuschauer</span><b>${l.finance.attendance.toLocaleString('de-DE')}</b></div><div class="metric-box"><span>Ticketeinnahmen</span><b>${money(l.finance.ticketIncome)}</b></div><div class="metric-box"><span>Fanartikelverkauf</span><b>${money(l.finance.merchSales)}</b><small>Vereinseinnahme ${money(l.finance.merchIncome)}</small></div></div><div class="progress live-progress"><span id="liveProgress" style="width:${l.minute/90*100}%"></span></div><img class="hero-image live-pitch" src="assets/matchday.jpg" alt="Retro-Spieltagsansicht"><div class="grid cols-2 live-layout"><div class="card live-chat-card"><h2>Live-Ticker</h2><div id="liveFeed" class="live-feed" aria-live="polite">${liveFeedHtml()}</div></div><div class="card"><h2>Spielsteuerung</h2><div id="liveControls" class="live-controls">${l.finished?'<button id="continueAfterMatch" class="primary">Weiter zur Übersicht</button>':`<button id="pauseLive">${l.paused?'Fortsetzen':'Pause'}</button><button data-speed="1" class="${l.speed===1?'primary':''}">1×</button><button data-speed="2" class="${l.speed===2?'primary':''}">2×</button><button data-speed="4" class="${l.speed===4?'primary':''}">4×</button>`}</div>${!l.finished?`<div class="live-tactics"><label>Taktik<select id="liveTactic"><option value="offensive" ${l.tactic==='offensive'?'selected':''}>Offensiv</option><option value="balanced" ${l.tactic==='balanced'?'selected':''}>Ausgeglichen</option><option value="defensive" ${l.tactic==='defensive'?'selected':''}>Defensiv</option></select></label><label>Zweikampf<select id="liveAggression"><option value="fair" ${l.aggression==='fair'?'selected':''}>Fair</option><option value="hard" ${l.aggression==='hard'?'selected':''}>Hart</option></select></label></div>`:''}<p class="muted">Offensiv erhöht Chancen und Risiko. Hartes Spiel erzeugt mehr Karten und mögliche Sperren.</p><div class="match-stats"><div><span>Heimstärke</span><b>${Math.round(l.homePower)}</b></div><div><span>Auswärtsstärke</span><b>${Math.round(l.awayPower)}</b></div></div></div></div></div>`;
}
function finishLiveMatch(){
  if(!liveMatch||liveMatch.finished)return;liveMatch.finished=true;clearInterval(liveTimer);addLiveEvent(90,'final',commentary('final'));applyMatchResult(liveMatch.fixture,liveMatch.homeGoals,liveMatch.awayGoals);liveMatch.otherFixtures.forEach(simulateMatch);state.league.round++;state.week++;
  const user=getUserClub();user.squad.forEach(p=>{p.fitness=clamp(p.fitness+rand(2,7),45,100);if(p.suspensionGames>0&&!state.selectedXI.includes(p.id))p.suspensionGames=Math.max(0,p.suspensionGames-1);});
  user.balance-=user.squad.reduce((sum,p)=>sum+p.wage,0);if(state.week%4===0)user.balance-=rand(250000,700000);processOutgoingTransferOffers();weeklySponsorIncome();save();document.body.classList.remove('match-running');updateLiveDisplay();render();
}
function render(){
  if(!state)return;ensureGameSystems();document.body.classList.toggle('match-running',!!liveMatch&&!liveMatch.finished);$('#seasonLabel').textContent=`Saison ${state.season} · Woche ${state.week} · ${state.league.country} · Version 1.3`;const map={dashboard,squad,lineup,league,transfers,sponsors,finances,stadium,international,live:liveView};$('#content').innerHTML=map[view]();bindDynamic();
}
function bindDynamic(){
  const openSponsors=$('#openSponsors');if(openSponsors)openSponsors.onclick=()=>{$$('.nav').forEach(x=>x.classList.remove('active'));const n=$('.nav[data-view="sponsors"]');if(n)n.classList.add('active');view='sponsors';render();};
  const pause=$('#pauseLive');if(pause)pause.onclick=()=>{liveMatch.paused=!liveMatch.paused;pause.textContent=liveMatch.paused?'Fortsetzen':'Pause';};
  $$('[data-speed]').forEach(btn=>btn.onclick=()=>{liveMatch.speed=+btn.dataset.speed;runLiveTimer();render();});
  const cont=$('#continueAfterMatch');if(cont)cont.onclick=()=>{liveMatch=null;document.body.classList.remove('match-running');view='dashboard';$$('.nav').forEach(x=>x.classList.remove('active'));$('.nav[data-view="dashboard"]')?.classList.add('active');render();};
  const formation=$('#formationSelect');if(formation)formation.onchange=e=>{state.formation=e.target.value;normalizeLineup();save();render();};
  const sqSort=$('#squadSort');if(sqSort)sqSort.onchange=e=>{squadSort=e.target.value;render();};
  const trSort=$('#transferSort');if(trSort)trSort.onchange=e=>{transferSort=e.target.value;render();};
  const tactic=$('#liveTactic');if(tactic)tactic.onchange=e=>{liveMatch.tactic=e.target.value;state.matchSettings.tactic=e.target.value;const base=teamPower(liveMatch.userHome?liveMatch.home:liveMatch.away);const adjusted=effectiveUserPower(base);if(liveMatch.userHome)liveMatch.homePower=adjusted+2;else liveMatch.awayPower=adjusted;save();};
  const aggression=$('#liveAggression');if(aggression)aggression.onchange=e=>{liveMatch.aggression=e.target.value;state.matchSettings.aggression=e.target.value;save();};
  $$('[data-lineup]').forEach(sel=>sel.onchange=e=>{const i=+e.target.dataset.lineup,newId=e.target.value;if(state.selectedXI.some((id,j)=>j!==i&&id===newId)){alert('Dieser Spieler ist bereits auf einer anderen Position aufgestellt.');render();return;}const p=getUserClub().squad.find(x=>x.id===newId);if(p?.suspensionGames>0){alert('Dieser Spieler ist gesperrt.');render();return;}state.selectedXI[i]=newId;save();render();});
  $$('[data-buy]').forEach(btn=>btn.onclick=()=>buyPlayer(+btn.dataset.buy));$$('[data-list-player]').forEach(btn=>btn.onclick=()=>toggleTransferList(btn.dataset.listPlayer));$$('[data-accept-offer]').forEach(btn=>btn.onclick=()=>acceptOutgoingOffer(btn.dataset.acceptOffer));$$('[data-reject-offer]').forEach(btn=>btn.onclick=()=>rejectOutgoingOffer(btn.dataset.rejectOffer));$$('[data-asking-price]').forEach(inp=>inp.onchange=()=>updateAskingPrice(inp.dataset.askingPrice,inp.value));$$('[data-accept-sponsor]').forEach(btn=>btn.onclick=()=>acceptSponsorOffer(btn.dataset.acceptSponsor));$$('[data-reject-sponsor]').forEach(btn=>btn.onclick=()=>rejectSponsorOffer(btn.dataset.rejectSponsor));
  const up=$('#upgradeStadium');if(up)up.onclick=()=>{const c=getUserClub();if(c.balance<12e6)return alert('Zu wenig Geld.');c.balance-=12e6;c.stadium.capacity+=5000;c.stadium.condition=100;save();render();};const range=$('#ticketPrice');if(range)range.oninput=e=>{$('#ticketPriceLabel').textContent=' '+money(+e.target.value);getUserClub().stadium.ticketPrice=+e.target.value;save();};
}
function load(){const raw=localStorage.getItem('fmretro-save');if(raw){state=JSON.parse(raw);liveMatch=null;clearInterval(liveTimer);ensureTransferState();ensure36GameSeason();ensureSponsorState();ensureMatchFinanceState();ensureGameSystems();if(!state.sponsors.offers.length)generateSponsorOffers(true);save();$('#startScreen').style.display='none';render();}else alert('Kein Spielstand vorhanden.');}

$$('.nav').forEach(b=>b.onclick=()=>{if(liveMatch&&!liveMatch.finished)return;$$('.nav').forEach(x=>x.classList.remove('active'));b.classList.add('active');view=b.dataset.view;render();});
$('#nextWeekBtn').onclick=nextWeek;
