/* Football Manager Retro V3.2 - Vereinshistorie und Langzeitkarriere */
(() => {
  'use strict';

  let historyTab = 'seasons';
  const TABS = [
    ['seasons','Saisonen'],['titles','Titel'],['europe','Europa'],['records','Rekorde'],
    ['legends','Legenden'],['players','Spieler'],['transfers','Transfers'],['stadium','Stadion'],
    ['finances','Finanzen'],['chronicle','Chronik'],['newspapers','Saisonzeitungen']
  ];

  function nowDate(){
    const start = new Date(2026, 6, 1);
    start.setDate(start.getDate() + Math.max(0, ((state?.week || 1)-1) * 7));
    return start.toLocaleDateString('de-AT');
  }
  function histId(prefix, parts){return `${prefix}:${parts.map(x=>String(x??'')).join('|')}`;}
  function addUnique(list, item){if(!list.some(x=>x.id===item.id))list.unshift(item);}
  function userClubSafe(){try{return getUserClub();}catch{return null;}}
  function totalSquadValue(c){return (c?.squad||[]).reduce((s,p)=>s+(Number(p.value)||0),0);}
  function currentPosition(){try{return sortedTable().findIndex(c=>c.id===state.userClubId)+1;}catch{return 0;}}
  function goalDiff(c){return (c?.gf||0)-(c?.ga||0);}

  function ensureHistory(){
    if(!state)return;
    state.v32 ||= {
      version:32,
      managerName:'Manager',
      startedSeason:state.season,
      seasons:[], titles:[], europe:[], records:{}, legends:[], playerCareers:{}, transfers:[],
      stadium:[], finances:[], chronicle:[], newspapers:[], syncedTransfers:0, syncedReports:0,
      lastFacilityLevels:{}, lastCapacity:0, cumulative:{matches:0,wins:0,draws:0,losses:0,gf:0,ga:0,attendance:0,revenue:0,costs:0}
    };
    const h=state.v32,c=userClubSafe();
    h.seasons ||= [];h.titles ||= [];h.europe ||= [];h.records ||= {};h.legends ||= [];h.playerCareers ||= {};
    h.transfers ||= [];h.stadium ||= [];h.finances ||= [];h.chronicle ||= [];h.newspapers ||= [];
    h.cumulative ||= {matches:0,wins:0,draws:0,losses:0,gf:0,ga:0,attendance:0,revenue:0,costs:0};
    h.lastFacilityLevels ||= {};
    if(c && !h.clubFounded){
      h.clubFounded={club:c.name,league:state.league.name,country:state.league.country,season:state.season};
      h.lastCapacity=c.stadium?.capacity||0;
      addUnique(h.chronicle,{id:histId('start',[state.season,c.name]),season:state.season,week:1,date:nowDate(),type:'Karrierestart',text:`Karriere bei ${c.name} begonnen.`});
    }
    if(state.v20?.facilities) Object.entries(state.v20.facilities).forEach(([k,v])=>{if(h.lastFacilityLevels[k]===undefined)h.lastFacilityLevels[k]=v;});
    syncTransfers(); syncReports(); syncCompetitions(); syncRecords();
  }

  function careerFor(p){
    const h=state.v32;
    h.playerCareers[p.id] ||= {id:p.id,name:p.name,position:p.position,firstSeason:state.season,lastSeason:state.season,apps:0,starts:0,minutes:0,goals:0,yellow:0,red:0,ratingTotal:0,ratingCount:0,titles:[],clubs:[userClubSafe()?.name].filter(Boolean),active:true};
    const x=h.playerCareers[p.id];x.name=p.name;x.position=p.position;x.lastSeason=state.season;x.active=true;return x;
  }

  function syncReports(){
    const h=state.v32,reports=state.matchReports||[];
    reports.slice().reverse().forEach(r=>{
      const id=histId('match',[r.id||'',r.season,r.week,r.home,r.away,r.score]);
      if(h.chronicle.some(x=>x.id===id))return;
      const [hg,ag]=String(r.score||'0:0').split(':').map(Number),home=r.homeId===state.userClubId||r.home===userClubSafe()?.name;
      const ug=home?hg:ag,og=home?ag:hg;
      h.cumulative.matches++;h.cumulative.gf+=ug;h.cumulative.ga+=og;
      if(ug>og)h.cumulative.wins++;else if(ug===og)h.cumulative.draws++;else h.cumulative.losses++;
      h.cumulative.attendance+=Number(r.finance?.attendance||0);h.cumulative.revenue+=Number(r.finance?.totalIncome||r.finance?.totalRevenue||0);h.cumulative.costs+=Number(r.finance?.matchCosts||0);
      (r.players||[]).forEach(pr=>{
        const clubPlayer=userClubSafe()?.squad.find(p=>p.id===pr.id)||pr;
        const c=careerFor(clubPlayer);c.apps++;if(!pr.substitute)c.starts++;c.minutes+=Number(pr.minutes||0);c.goals+=Number(pr.goals||0);c.ratingTotal+=Number(pr.rating||0);c.ratingCount++;if(pr.cards>=2)c.red++;else if(pr.cards===1)c.yellow++;
      });
      addUnique(h.chronicle,{id,season:r.season,week:r.week,date:nowDate(),type:'Spiel',text:`${r.home} ${r.score} ${r.away}${r.manOfMatch?` · Spieler des Spiels: ${r.manOfMatch.name} (${Number(r.manOfMatch.rating).toFixed(1)})`:''}`});
    });
    h.syncedReports=reports.length;
  }

  function syncTransfers(){
    const h=state.v32,arr=state.transferHistory||[];
    arr.slice().reverse().forEach((t,i)=>{
      const id=histId('transfer',[t.season||state.season,t.week,t.player,t.from,t.to,t.amount,i]);
      if(h.transfers.some(x=>x.id===id))return;
      const item={id,season:t.season||state.season,week:t.week||state.week,date:nowDate(),player:t.player,from:t.from,to:t.to,amount:Number(t.amount)||0,direction:t.to===userClubSafe()?.name?'Zugang':'Abgang'};
      h.transfers.unshift(item);
      addUnique(h.chronicle,{id:`chron-${id}`,season:item.season,week:item.week,date:item.date,type:'Transfer',text:`${item.player}: ${item.from} → ${item.to} für ${money(item.amount)}.`});
      const rec=h.records;
      if(item.direction==='Zugang'&&item.amount>(rec.recordPurchase?.amount||0))rec.recordPurchase={player:item.player,amount:item.amount,season:item.season,club:item.from};
      if(item.direction==='Abgang'&&item.amount>(rec.recordSale?.amount||0))rec.recordSale={player:item.player,amount:item.amount,season:item.season,club:item.to};
    });
    h.syncedTransfers=arr.length;
  }

  function syncCompetitions(){
    const h=state.v32,user=userClubSafe()?.name;if(!user)return;
    const comps=[state.v23?.cup,...Object.values(state.v23?.uefa||{})].filter(Boolean);
    comps.forEach(comp=>{
      const key=histId('competition',[comp.name,comp.season]);
      const existing=h.europe.find(x=>x.id===key);
      const rounds=(comp.rounds||[]).map((round,i)=>({name:comp.roundNames?.[i]||`Runde ${i+1}`,matches:round.filter(f=>f.home===user||f.away===user).map(f=>({home:f.home,away:f.away,score:f.played?`${f.hg}:${f.ag}`:'–',winner:f.winner}))})).filter(x=>x.matches.length);
      const entry={id:key,season:comp.season,name:comp.name,stage:comp.finished?(comp.champion===user?'Sieger':'Beendet'):(comp.roundNames?.[comp.roundIndex]||'Laufend'),champion:comp.champion,rounds};
      if(existing)Object.assign(existing,entry);else h.europe.unshift(entry);
      if(comp.finished&&comp.champion===user){
        addTitle(comp.name,comp.season,'', '', comp.rounds?.at(-1)?.[0]);
      }
    });
  }

  function addTitle(name,season,opponent='',score='',match=null){
    const h=state.v32,id=histId('title',[name,season]);
    if(h.titles.some(x=>x.id===id))return;
    if(match){opponent=match.home===userClubSafe()?.name?match.away:match.home;score=match.played?`${match.hg}:${match.ag}`:'';}
    const item={id,name,season,opponent,score,date:nowDate()};h.titles.unshift(item);
    addUnique(h.chronicle,{id:`chron-${id}`,season,week:state.week,date:nowDate(),type:'Titel',text:`🏆 ${name} gewonnen${opponent?` gegen ${opponent}`:''}${score?` (${score})`:''}.`});
    (userClubSafe()?.squad||[]).forEach(p=>{const c=careerFor(p);if(!c.titles.includes(`${name} ${season}`))c.titles.push(`${name} ${season}`);});
  }

  function syncStadiumChanges(){
    const h=state.v32,c=userClubSafe();if(!c)return;
    if(c.stadium?.capacity>h.lastCapacity){
      const before=h.lastCapacity,after=c.stadium.capacity,cost=12000000;
      const id=histId('stadium-capacity',[state.season,state.week,before,after]);
      addUnique(h.stadium,{id,season:state.season,week:state.week,date:nowDate(),name:'Stadionkapazität',before,after,cost});
      addUnique(h.chronicle,{id:`chron-${id}`,season:state.season,week:state.week,date:nowDate(),type:'Stadion',text:`Stadion von ${before.toLocaleString('de-DE')} auf ${after.toLocaleString('de-DE')} Plätze erweitert.`});
      h.lastCapacity=after;
    }
    Object.entries(state.v20?.facilities||{}).forEach(([key,level])=>{
      const prev=h.lastFacilityLevels[key]??level;
      if(level>prev){
        const name=(typeof V20_FACILITIES!=='undefined'&&V20_FACILITIES[key])||key,cost=level*1500000,id=histId('facility',[state.season,state.week,key,level]);
        addUnique(h.stadium,{id,season:state.season,week:state.week,date:nowDate(),name,level,cost});
        addUnique(h.chronicle,{id:`chron-${id}`,season:state.season,week:state.week,date:nowDate(),type:'Infrastruktur',text:`${name} auf Stufe ${level} ausgebaut (${money(cost)}).`});
      }
      h.lastFacilityLevels[key]=level;
    });
  }

  function syncRecords(){
    const h=state.v32,c=userClubSafe();if(!c)return;const rec=h.records;
    rec.totalMatches=h.cumulative.matches;rec.totalWins=h.cumulative.wins;rec.totalDraws=h.cumulative.draws;rec.totalLosses=h.cumulative.losses;rec.totalGoals=h.cumulative.gf;rec.totalAgainst=h.cumulative.ga;
    rec.totalAttendance=h.cumulative.attendance;rec.totalRevenue=h.cumulative.revenue;rec.totalCosts=h.cumulative.costs;
    rec.mostApps=Object.values(h.playerCareers).sort((a,b)=>b.apps-a.apps)[0]||null;
    rec.topScorer=Object.values(h.playerCareers).sort((a,b)=>b.goals-a.goals)[0]||null;
    rec.bestAverage=Object.values(h.playerCareers).filter(x=>x.ratingCount>=5).sort((a,b)=>(b.ratingTotal/b.ratingCount)-(a.ratingTotal/a.ratingCount))[0]||null;
    const reports=state.matchReports||[];
    reports.forEach(r=>{
      const [hg,ag]=String(r.score||'0:0').split(':').map(Number),home=r.home===c.name,ug=home?hg:ag,og=home?ag:hg,diff=ug-og;
      if(diff>(rec.biggestWin?.diff??-999))rec.biggestWin={match:`${r.home} ${r.score} ${r.away}`,diff,season:r.season};
      if(diff<(rec.biggestLoss?.diff??999))rec.biggestLoss={match:`${r.home} ${r.score} ${r.away}`,diff,season:r.season};
      const att=Number(r.finance?.attendance||0);if(att>(rec.attendanceRecord?.attendance||0))rec.attendanceRecord={attendance:att,match:`${r.home} – ${r.away}`,season:r.season};
    });
  }

  function seasonFinancials(season){
    const rows=(state.matchFinanceHistory||[]).filter(x=>x.season===season);
    return rows.reduce((a,x)=>{a.revenue+=Number(x.totalIncome||x.totalRevenue||x.ticketIncome||0);a.costs+=Number(x.matchCosts||0);a.attendance+=Number(x.attendance||0);a.matches++;return a;},{revenue:0,costs:0,attendance:0,matches:0});
  }

  function closeSeasonSnapshot(){
    ensureHistory();const h=state.v32,c=userClubSafe(),table=sortedTable(),pos=table.findIndex(x=>x.id===state.userClubId)+1,fin=seasonFinancials(state.season);
    const champion=table[0]?.name||'–',top=[...(c?.squad||[])].sort((a,b)=>(b.goals||0)-(a.goals||0))[0];
    const snap={id:histId('season',[state.season,c?.name]),season:state.season,league:state.league.name,country:state.league.country,position:pos,points:c?.points||0,wins:c?.wins||0,draws:c?.draws||0,losses:c?.losses||0,gf:c?.gf||0,ga:c?.ga||0,goalDiff:goalDiff(c),promoted:state.league.name.includes('2.')&&pos===1,relegated:state.league.name.includes('Bundesliga')&&pos===table.length,manager:h.managerName,clubValue:totalSquadValue(c),balance:c?.balance||0,transferBudget:c?.budget||0,attendance:fin.attendance,revenue:fin.revenue,costs:fin.costs,profit:fin.revenue-fin.costs,topScorer:top?.name||'–',topGoals:top?.goals||0};
    if(!h.seasons.some(x=>x.id===snap.id))h.seasons.unshift(snap);
    if(pos===1)addTitle(`${state.league.name} Meister`,state.season);
    if(snap.promoted)addUnique(h.chronicle,{id:histId('promotion',[state.season]),season:state.season,week:state.week,date:nowDate(),type:'Aufstieg',text:`⬆ Aufstieg aus der ${state.league.name}.`});
    if(snap.relegated)addUnique(h.chronicle,{id:histId('relegation',[state.season]),season:state.season,week:state.week,date:nowDate(),type:'Abstieg',text:`⬇ Abstieg aus der ${state.league.name}.`});
    if(!h.finances.some(x=>x.season===state.season))h.finances.unshift({id:histId('finance',[state.season]),season:state.season,...fin,profit:fin.revenue-fin.costs,balance:c?.balance||0,sponsorIncome:state.sponsors?.lastIncome||0,transferBalance:h.transfers.filter(x=>x.season===state.season).reduce((s,x)=>s+(x.direction==='Abgang'?x.amount:-x.amount),0)});
    const titleNames=h.titles.filter(x=>x.season===state.season).map(x=>x.name);
    const euroWinners=Object.values(state.v23?.uefa||{}).map(x=>({name:x.name,winner:x.champion}));
    const news={id:histId('newspaper',[state.season]),season:state.season,title:`Saisonrückblick ${state.season}`,date:nowDate(),champion,clubPosition:pos,club:c?.name,league:state.league.name,titles:titleNames,topScorer:top?.name||'–',topGoals:top?.goals||0,cupWinner:state.v23?.cup?.champion||'–',europeWinners:euroWinners,biggestTransfer:[...h.transfers].filter(x=>x.season===state.season).sort((a,b)=>b.amount-a.amount)[0]||null,profit:fin.revenue-fin.costs};
    if(!h.newspapers.some(x=>x.id===news.id))h.newspapers.unshift(news);
    addUnique(h.chronicle,{id:histId('seasonend',[state.season]),season:state.season,week:state.week,date:nowDate(),type:'Saisonende',text:`Saison ${state.season}: Platz ${pos}, ${c?.points||0} Punkte, ${c?.gf||0}:${c?.ga||0} Tore${titleNames.length?` · Titel: ${titleNames.join(', ')}`:''}.`});
    if(top&&top.goals>=15){const car=careerFor(top),id=histId('legend',[top.id,state.season]);addUnique(h.legends,{id,playerId:top.id,name:top.name,position:top.position,reason:`${top.goals} Tore in ${state.season}`,apps:car.apps,goals:car.goals,average:car.ratingCount?car.ratingTotal/car.ratingCount:0,titles:[...car.titles]});}
    syncRecords();
  }

  function tabsHtml(){return `<div class="history-tabs">${TABS.map(([id,label])=>`<button class="${historyTab===id?'active':''}" data-history-tab="${id}">${label}</button>`).join('')}</div>`;}
  function empty(text='Noch keine Einträge vorhanden.'){return `<p class="muted">${text}</p>`;}
  function seasonsHtml(h){return h.seasons.length?`<div class="table-scroll"><table><thead><tr><th>Saison</th><th>Liga</th><th>Platz</th><th>Pkt.</th><th>S/U/N</th><th>Tore</th><th>Kontostand</th><th>Kaderwert</th></tr></thead><tbody>${h.seasons.map(s=>`<tr><td><b>${s.season}</b></td><td>${esc(s.country)} · ${esc(s.league)}</td><td>${s.position}.</td><td>${s.points}</td><td>${s.wins}/${s.draws}/${s.losses}</td><td>${s.gf}:${s.ga}</td><td>${money(s.balance)}</td><td>${money(s.clubValue)}</td></tr>`).join('')}</tbody></table></div>`:empty('Die erste Saison ist noch nicht abgeschlossen.');}
  function titlesHtml(h){return h.titles.length?`<div class="history-trophy-grid">${h.titles.map(t=>`<article class="card history-trophy"><div class="history-cup">🏆</div><h3>${esc(t.name)}</h3><b>${esc(t.season)}</b>${t.opponent?`<p>Finalgegner: ${esc(t.opponent)} ${esc(t.score)}</p>`:''}</article>`).join('')}</div>`:empty('Noch kein Titel gewonnen.');}
  function europeHtml(h){return h.europe.length?h.europe.map(e=>`<div class="card history-comp"><h3>${esc(e.name)} · ${esc(e.season)}</h3><p><b>${esc(e.stage)}</b>${e.champion?` · Sieger: ${esc(e.champion)}`:''}</p>${e.rounds.map(r=>`<details><summary>${esc(r.name)}</summary>${r.matches.map(m=>`<div class="fixture"><span>${esc(m.home)}</span><b>${esc(m.score)}</b><span>${esc(m.away)}</span></div>`).join('')}</details>`).join('')}</div>`).join(''):empty('Noch keine internationalen Teilnahmen gespeichert.');}
  function recordsHtml(h){const r=h.records;const stat=(l,v,s='')=>`<div class="metric-card"><span>${l}</span><div class="viz-stat-value">${v}</div>${s?`<small>${s}</small>`:''}</div>`;return `<div class="grid cols-4">${stat('Pflichtspiele',r.totalMatches||0)}${stat('Siege',r.totalWins||0)}${stat('Gesamttore',r.totalGoals||0)}${stat('Zuschauer gesamt',Number(r.totalAttendance||0).toLocaleString('de-DE'))}</div><div class="grid cols-2" style="margin-top:16px"><div class="card"><h3>Spielrekorde</h3><p>Höchster Sieg: <b>${esc(r.biggestWin?.match||'–')}</b></p><p>Höchste Niederlage: <b>${esc(r.biggestLoss?.match||'–')}</b></p><p>Zuschauerrekord: <b>${Number(r.attendanceRecord?.attendance||0).toLocaleString('de-DE')}</b> ${esc(r.attendanceRecord?.match||'')}</p></div><div class="card"><h3>Spielerrekorde</h3><p>Meiste Spiele: <b>${esc(r.mostApps?.name||'–')}</b> (${r.mostApps?.apps||0})</p><p>Meiste Tore: <b>${esc(r.topScorer?.name||'–')}</b> (${r.topScorer?.goals||0})</p><p>Beste Durchschnittsnote: <b>${esc(r.bestAverage?.name||'–')}</b> (${r.bestAverage?.ratingCount?(r.bestAverage.ratingTotal/r.bestAverage.ratingCount).toFixed(2):'–'})</p><p>Rekordeinkauf: <b>${esc(r.recordPurchase?.player||'–')}</b> ${r.recordPurchase?money(r.recordPurchase.amount):''}</p><p>Rekordverkauf: <b>${esc(r.recordSale?.player||'–')}</b> ${r.recordSale?money(r.recordSale.amount):''}</p></div></div>`;}
  function legendsHtml(h){return h.legends.length?`<div class="history-trophy-grid">${h.legends.map(x=>`<article class="card"><div class="history-legend-icon">⭐</div><h3>${esc(x.name)}</h3><p>${esc(x.position)} · ${esc(x.reason)}</p><p>${x.apps} Spiele · ${x.goals} Tore · Ø ${Number(x.average||0).toFixed(2)}</p><small>${x.titles.map(esc).join(' · ')||'Vereinslegende'}</small></article>`).join('')}</div>`:empty('Noch keine Spieler in der Hall of Fame.');}
  function playersHtml(h){const arr=Object.values(h.playerCareers).sort((a,b)=>b.apps-a.apps||b.goals-a.goals);return arr.length?`<div class="table-scroll"><table><thead><tr><th>Spieler</th><th>Pos.</th><th>Zeitraum</th><th>Spiele</th><th>Startelf</th><th>Minuten</th><th>Tore</th><th>Ø Note</th><th>Titel</th></tr></thead><tbody>${arr.map(x=>`<tr><td><b>${esc(x.name)}</b></td><td>${esc(x.position)}</td><td>${esc(x.firstSeason)}–${x.active?'heute':esc(x.lastSeason)}</td><td>${x.apps}</td><td>${x.starts}</td><td>${x.minutes}</td><td>${x.goals}</td><td>${x.ratingCount?(x.ratingTotal/x.ratingCount).toFixed(2):'–'}</td><td>${x.titles.length}</td></tr>`).join('')}</tbody></table></div>`:empty('Spielerstatistiken entstehen nach absolvierten Spielen.');}
  function transfersHtml(h){return h.transfers.length?`<div class="table-scroll"><table><thead><tr><th>Saison</th><th>Spieler</th><th>Von</th><th>Nach</th><th>Richtung</th><th>Ablöse</th></tr></thead><tbody>${h.transfers.map(x=>`<tr><td>${esc(x.season)}</td><td><b>${esc(x.player)}</b></td><td>${esc(x.from)}</td><td>${esc(x.to)}</td><td>${x.direction}</td><td>${money(x.amount)}</td></tr>`).join('')}</tbody></table></div>`:empty('Noch keine Transfers gespeichert.');}
  function stadiumHtml(h){return h.stadium.length?`<div class="history-timeline">${h.stadium.map(x=>`<article><div class="timeline-dot"></div><small>${esc(x.season)} · Woche ${x.week}</small><h3>${esc(x.name)}</h3><p>${x.level?`Ausbaustufe ${x.level}`:`${Number(x.before).toLocaleString('de-DE')} → ${Number(x.after).toLocaleString('de-DE')} Plätze`} · Kosten ${money(x.cost||0)}</p></article>`).join('')}</div>`:empty('Noch keine Stadion- oder Infrastrukturmaßnahmen gespeichert.');}
  function financesHtml(h){return h.finances.length?`<div class="table-scroll"><table><thead><tr><th>Saison</th><th>Einnahmen</th><th>Kosten</th><th>Gewinn/Verlust</th><th>Transferbilanz</th><th>Zuschauer</th><th>Endbestand</th></tr></thead><tbody>${h.finances.map(x=>`<tr><td><b>${x.season}</b></td><td class="good">${money(x.revenue)}</td><td class="bad">${money(x.costs)}</td><td class="${x.profit>=0?'good':'bad'}"><b>${money(x.profit)}</b></td><td class="${x.transferBalance>=0?'good':'bad'}">${money(x.transferBalance)}</td><td>${Number(x.attendance).toLocaleString('de-DE')}</td><td>${money(x.balance)}</td></tr>`).join('')}</tbody></table></div>`:empty('Die Finanzhistorie wird am Saisonende abgeschlossen.');}
  function chronicleHtml(h){return h.chronicle.length?`<div class="history-timeline">${h.chronicle.slice(0,250).map(x=>`<article><div class="timeline-dot"></div><small>${esc(x.season)} · Woche ${x.week||'–'} · ${esc(x.type)}</small><p>${esc(x.text)}</p></article>`).join('')}</div>`:empty();}
  function newspapersHtml(h){return h.newspapers.length?h.newspapers.map(n=>`<article class="card season-newspaper"><header><span>SPORTAKTUELL</span><b>${esc(n.season)}</b></header><h2>${esc(n.title)}</h2><div class="grid cols-3"><div><small>Meister</small><b>${esc(n.champion)}</b></div><div><small>Eigener Verein</small><b>${esc(n.club)} · Platz ${n.clubPosition}</b></div><div><small>ÖFB-Cup</small><b>${esc(n.cupWinner)}</b></div></div><hr><p><b>Torschützenkönig des Vereins:</b> ${esc(n.topScorer)} (${n.topGoals} Tore)</p><p><b>Eigene Titel:</b> ${n.titles.map(esc).join(', ')||'keine'}</p><p><b>Saisonergebnis:</b> ${money(n.profit)}</p>${n.biggestTransfer?`<p><b>Teuerster Transfer:</b> ${esc(n.biggestTransfer.player)} für ${money(n.biggestTransfer.amount)}</p>`:''}<p><b>UEFA-Sieger:</b> ${n.europeWinners.map(x=>`${esc(x.name)}: ${esc(x.winner||'noch offen')}`).join(' · ')}</p></article>`).join(''):empty('Die erste Saisonzeitung erscheint nach Saisonende.');}

  function historyView(){
    ensureHistory();syncStadiumChanges();const h=state.v32;
    const content={seasons:seasonsHtml,titles:titlesHtml,europe:europeHtml,records:recordsHtml,legends:legendsHtml,players:playersHtml,transfers:transfersHtml,stadium:stadiumHtml,finances:financesHtml,chronicle:chronicleHtml,newspapers:newspapersHtml}[historyTab](h);
    return `<section class="history-page"><div class="card history-header"><div><span class="viz-badge">VERSION 3.2</span><h2>Vereinshistorie · ${esc(userClubSafe()?.name||'')}</h2><p>Alle Erfolge, Saisonen, Rekorde und prägenden Momente deiner Karriere.</p></div><div class="history-header-stat"><b>${h.seasons.length}</b><span>abgeschlossene Saisonen</span></div><div class="history-header-stat"><b>${h.titles.length}</b><span>Titel</span></div></div>${tabsHtml()}<div class="card history-content">${content}</div></section>`;
  }

  const oldEndSeason=endSeason;
  endSeason=function(){if(state){closeSeasonSnapshot();save();}oldEndSeason();if(state){ensureHistory();state.v32.playerCareers&&Object.values(state.v32.playerCareers).forEach(x=>x.active=false);(userClubSafe()?.squad||[]).forEach(p=>careerFor(p));save();}};

  const oldFinish=finishLiveMatch;
  finishLiveMatch=function(){oldFinish();if(state){ensureHistory();syncStadiumChanges();save();}};
  const oldNext=nextWeek;
  nextWeek=function(){oldNext();if(state){ensureHistory();syncStadiumChanges();save();}};

  const oldBind=bindDynamic;
  bindDynamic=function(){oldBind();$$('[data-history-tab]').forEach(b=>b.onclick=()=>{historyTab=b.dataset.historyTab;render();});};

  const oldRender=render;
  render=function(){
    if(!state)return;ensureHistory();syncStadiumChanges();oldRender();
    if(view==='history'){$('#content').innerHTML=historyView();bindDynamic();}
    const label=$('#seasonLabel');if(label)label.textContent=`${nowDate()} · Spieltag ${Math.min((state.league.round||0)+1,state.league.fixtures?.length||1)} / ${state.league.fixtures?.length||1} · Saison ${state.season} · ${state.league.country} ${state.league.name} · V3.2`;
  };

  const oldNew=newGame;
  newGame=function(...args){oldNew(...args);if(state){state.v32=null;ensureHistory();save();render();}};
  const oldLoad=load;
  load=function(){oldLoad();if(state){ensureHistory();save();render();}};

  window.FMHistory32={ensure:ensureHistory,view:historyView,closeSeason:closeSeasonSnapshot};
})();
