/* Version 4.7.3 – stabile Transferansicht ohne rekursive Wrapper */
(function(){
  'use strict';
  const filters={scope:'market',name:'',position:'ALL',minRating:0,maxRating:100,minAge:15,maxAge:45,minFitness:0,maxPrice:0,contract:'ALL',listedOnly:false,sort:'rating_desc'};
  const safe=v=>Array.isArray(v)?v:[];
  const num=(v,d=0)=>Number.isFinite(Number(v))?Number(v):d;
  function ensure(){
    if(typeof state==='undefined'||!state)return;
    state.v46=(state.v46&&typeof state.v46==='object')?state.v46:{searchHistory:[],shortlist:[]};
    state.v46.searchHistory=safe(state.v46.searchHistory);
    state.v46.shortlist=safe(state.v46.shortlist);
    state.transferList=safe(state.transferList);
    state.outgoingOffers=safe(state.outgoingOffers);
  }
  function allLeagues(){
    ensure();
    const leagues=[];
    if(state?.league)leagues.push(state.league);
    safe(state?.v22?.worldLeagues).forEach(l=>{if(l&&!leagues.includes(l))leagues.push(l);});
    return leagues;
  }
  function allClubs(){
    const out=[];
    allLeagues().forEach(league=>safe(league?.clubs).forEach(club=>{if(club)out.push({league,club});}));
    return out;
  }
  function priceFor(player,club){
    const value=Math.max(50000,num(player?.value,Math.round(Math.pow(num(player?.rating,50),3)*45)));
    const age=num(player?.age,25),contract=num(player?.contract,1);
    const ageFactor=age<=22?1.35:age>=32?0.82:1;
    const contractFactor=contract>=3?1.28:contract<=1?0.92:1.08;
    const listed=player?.transferListed||player?.onAiMarket;
    const importance=safe(club?.squad).filter(x=>x.position===player?.position).sort((a,b)=>num(b.rating)-num(a.rating)).slice(0,2).some(x=>x.id===player?.id)?1.18:1;
    return Math.max(50000,Math.round(value*ageFactor*contractFactor*importance*(listed?0.92:1.12)/50000)*50000);
  }
  function pool(){
    ensure();
    if(filters.scope==='market'){
      return safe(state.transferList).map((p,index)=>({player:p,index,market:true,club:null,league:null,price:num(p.asking,num(p.askingPrice,num(p.value)))}));
    }
    const user=typeof getUserClub==='function'?getUserClub():null;
    const out=[];
    allClubs().forEach(({league,club})=>{
      if(!club||club.id===user?.id)return;
      safe(club.squad).forEach(player=>out.push({player,club,league,market:false,price:priceFor(player,club)}));
    });
    return out;
  }
  function matches(rec){
    const p=rec.player||{};
    const rating=num(p.rating),age=num(p.age),fitness=num(p.fitness,100),contract=num(p.contract);
    if(filters.name&&!String(p.name||'').toLowerCase().includes(filters.name.toLowerCase()))return false;
    if(filters.position!=='ALL'&&p.position!==filters.position)return false;
    if(rating<filters.minRating||rating>filters.maxRating)return false;
    if(age<filters.minAge||age>filters.maxAge)return false;
    if(fitness<filters.minFitness)return false;
    if(filters.maxPrice&&rec.price>filters.maxPrice)return false;
    if(filters.contract==='EXPIRING'&&contract>1)return false;
    if(filters.contract==='FREE'&&contract>0)return false;
    if(filters.listedOnly&&!rec.market&&!p.transferListed&&!p.onAiMarket)return false;
    return true;
  }
  function results(){
    const [key,dir]=filters.sort.split('_');const mult=dir==='asc'?1:-1;
    return pool().filter(matches).sort((a,b)=>{
      const pa=a.player||{},pb=b.player||{};
      if(key==='name')return String(pa.name||'').localeCompare(String(pb.name||''),'de')*mult;
      if(key==='age')return (num(pa.age)-num(pb.age))*mult;
      if(key==='price')return (num(a.price)-num(b.price))*mult;
      if(key==='fitness')return (num(pa.fitness)-num(pb.fitness))*mult;
      return (num(pa.rating)-num(pb.rating))*mult;
    }).slice(0,200);
  }
  function options(items,current){return items.map(([v,l])=>`<option value="${v}" ${v===current?'selected':''}>${l}</option>`).join('');}
  function ownSquadForSale(){
    const club=typeof getUserClub==='function'?getUserClub():null;if(!club)return'';
    const squad=safe(club.squad).slice().sort((a,b)=>num(b.rating)-num(a.rating));
    return `<div class="card"><h2>Eigene Spieler anbieten</h2><p class="muted">Hier kannst du Spieler direkt auf die Transferliste setzen oder wieder herunternehmen.</p>${squad.length?`<div class="table-scroll"><table><thead><tr><th>Spieler</th><th>Alter</th><th>Pos</th><th>Stärke</th><th>Fitness</th><th>Marktwert</th><th>Status</th><th>Aktion</th></tr></thead><tbody>${squad.map(p=>`<tr><td><b>${esc(p.name)}</b></td><td>${num(p.age)}</td><td>${esc(p.position||'–')}</td><td>${num(p.rating)}</td><td>${num(p.fitness,100)}%</td><td>${money(num(p.value))}</td><td>${p.transferListed?'<span class="listed-label">Transferliste</span>':'–'}</td><td><button data-list-player="${p.id}" class="${p.transferListed?'danger':'primary'}">${p.transferListed?'Herunternehmen':'Auf Transferliste'}</button></td></tr>`).join('')}</tbody></table></div>`:'<p class="muted">Kein Kader vorhanden.</p>'}</div>`;
  }
  function ownTransferList(){
    const club=typeof getUserClub==='function'?getUserClub():null;if(!club)return'';
    const listed=safe(club.squad).filter(p=>p.transferListed);
    const pending=safe(state.outgoingOffers).filter(o=>o.status==='pending');
    return `<div class="grid cols-2"><div class="card"><h2>Deine Transferliste</h2>${listed.length?`<div class="table-scroll"><table><thead><tr><th>Spieler</th><th>Alter</th><th>Pos</th><th>Stärke</th><th>Wunschpreis</th><th></th></tr></thead><tbody>${listed.map(p=>`<tr><td>${esc(p.name)}</td><td>${num(p.age)}</td><td>${esc(p.position||'–')}</td><td>${num(p.rating)}</td><td>${money(num(p.askingPrice,num(p.value)))}</td><td><button data-list-player="${p.id}" class="danger">Entfernen</button></td></tr>`).join('')}</tbody></table></div>`:'<p class="muted">Noch kein Spieler wurde angeboten.</p>'}</div><div class="card"><h2>Eingegangene Angebote</h2>${pending.length?pending.map(o=>{const p=safe(club.squad).find(x=>x.id===o.playerId);const bidder=typeof getClub==='function'?getClub(o.bidderId):null;return p?`<div class="offer-card"><div><b>${esc(p.name)}</b>${bidder?` · ${esc(bidder.name)}`:''}</div><div class="offer-price">${money(num(o.amount))}</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>`;
  }
  function renderTransfers(){
    ensure();
    const user=typeof getUserClub==='function'?getUserClub():null;
    if(!user)return '<div class="card"><h2>Transfers</h2><p>Bitte zuerst eine Karriere starten.</p></div>';
    const list=results();
    return `<div class="card"><div class="section-toolbar"><div><h2>Spielersuche & Transferfilter</h2><p class="muted">Transfermarkt oder alle simulierten Vereine durchsuchen.</p></div><div class="transfer-budget-chip">Budget <b>${money(num(user.budget))}</b><br><small>Kontostand ${money(num(user.balance))}</small></div></div><div class="search-filter-grid"><label>Bereich<select id="psScope">${options([['market','Transfermarkt'],['world','Alle Vereine']],filters.scope)}</select></label><label>Name<input id="psName" type="search" value="${esc(filters.name)}"></label><label>Position<select id="psPosition">${options([['ALL','Alle'],['TW','Torwart'],['ABW','Abwehr'],['IV','Innenverteidiger'],['RV','Rechtsverteidiger'],['LV','Linksverteidiger'],['MIT','Mittelfeld'],['DM','Defensives Mittelfeld'],['ZM','Zentrales Mittelfeld'],['RA','Rechtsaußen'],['LA','Linksaußen'],['ST','Stürmer']],filters.position)}</select></label><label>Mindeststärke<input id="psMinRating" type="number" min="0" max="100" value="${filters.minRating}"></label><label>Maximalstärke<input id="psMaxRating" type="number" min="0" max="100" value="${filters.maxRating}"></label><label>Mindestalter<input id="psMinAge" type="number" min="15" max="45" value="${filters.minAge}"></label><label>Maximalalter<input id="psMaxAge" type="number" min="15" max="45" value="${filters.maxAge}"></label><label>Mindestfitness<input id="psMinFitness" type="number" min="0" max="100" value="${filters.minFitness}"></label><label>Maximalpreis (Mio. €)<input id="psMaxPrice" type="number" min="0" step="0.1" value="${filters.maxPrice?filters.maxPrice/1e6:''}"></label><label>Vertrag<select id="psContract">${options([['ALL','Alle'],['EXPIRING','max. 1 Jahr'],['FREE','vertragslos']],filters.contract)}</select></label><label>Sortierung<select id="psSort">${options([['rating_desc','Stärke absteigend'],['rating_asc','Stärke aufsteigend'],['price_asc','Preis aufsteigend'],['price_desc','Preis absteigend'],['age_asc','Alter aufsteigend'],['fitness_desc','Fitness absteigend'],['name_asc','Name A–Z']],filters.sort)}</select></label><label><input id="psListedOnly" type="checkbox" ${filters.listedOnly?'checked':''}> Nur angebotene Spieler</label></div><div class="search-actions"><button id="applyPlayerSearch" class="primary">Filter anwenden</button><button id="resetPlayerSearch">Zurücksetzen</button></div></div><div class="card"><h2>Suchergebnisse <span class="viz-badge">${list.length}</span></h2>${list.length?`<div class="table-scroll"><table><thead><tr><th>Spieler</th><th>Verein</th><th>Pos</th><th>Alter</th><th>Stärke</th><th>Fitness</th><th>Vertrag</th><th>Preis</th><th></th></tr></thead><tbody>${list.map((r,i)=>`<tr><td><b>${esc(r.player?.name||'Unbekannt')}</b></td><td>${esc(r.club?.name||r.player?.fromClub||'Transfermarkt')}</td><td>${esc(r.player?.position||'–')}</td><td>${num(r.player?.age)}</td><td><b>${num(r.player?.rating)}</b></td><td>${num(r.player?.fitness,100)}%</td><td>${num(r.player?.contract).toFixed(1)} J.</td><td>${money(num(r.price))}</td><td><button data-v473-result="${i}">${r.market?'Kaufen':'Angebot'}</button></td></tr>`).join('')}</tbody></table></div>`:'<p class="muted">Keine passenden Spieler gefunden.</p>'}</div>${ownSquadForSale()}${ownTransferList()}`;
  }
  function readFilters(){
    filters.scope=$('#psScope')?.value||'market';filters.name=$('#psName')?.value?.trim()||'';filters.position=$('#psPosition')?.value||'ALL';
    filters.minRating=Math.max(0,Math.min(100,num($('#psMinRating')?.value)));filters.maxRating=Math.max(0,Math.min(100,num($('#psMaxRating')?.value,100)));
    filters.minAge=Math.max(15,Math.min(45,num($('#psMinAge')?.value,15)));filters.maxAge=Math.max(15,Math.min(45,num($('#psMaxAge')?.value,45)));
    filters.minFitness=Math.max(0,Math.min(100,num($('#psMinFitness')?.value)));filters.maxPrice=Math.max(0,num($('#psMaxPrice')?.value)*1e6);
    filters.contract=$('#psContract')?.value||'ALL';filters.sort=$('#psSort')?.value||'rating_desc';filters.listedOnly=!!$('#psListedOnly')?.checked;
  }
  function makeOffer(rec){
    const user=typeof getUserClub==='function'?getUserClub():null;if(!rec||!user)return;
    if(rec.market){if(typeof buyPlayer==='function')buyPlayer(rec.index);return;}
    const club=rec.club,p=rec.player,price=num(rec.price);if(!club||!p)return;
    const raw=prompt(`${club.name} fordert ungefähr ${money(price)} für ${p.name}.\nDein Angebot in Euro:`,String(price));if(raw===null)return;
    const amount=Math.round(num(raw)/50000)*50000;if(amount<=0)return alert('Ungültiger Betrag.');
    if(num(user.budget)<amount||num(user.balance)<amount)return alert('Transferbudget oder Kontostand reichen nicht aus.');
    const score=amount/Math.max(1,price)+(p.transferListed?0.18:0)+(num(p.contract)<=1?0.08:0)+Math.random()*0.12;
    const accepted=score>=0.98;state.v46.searchHistory.unshift({week:state.week,player:p.name,club:club.name,offer:amount,status:accepted?'angenommen':'abgelehnt'});
    if(!accepted){state.news=safe(state.news);state.news.unshift(`${club.name} lehnt dein Angebot für ${p.name} ab.`);save();render();return;}
    club.squad=safe(club.squad).filter(x=>x.id!==p.id);user.squad=safe(user.squad);user.squad.push(p);user.balance=num(user.balance)-amount;user.budget=num(user.budget)-amount;club.balance=num(club.balance)+amount;
    state.news=safe(state.news);state.news.unshift(`${p.name} wechselt für ${money(amount)} zu ${user.name}.`);save();render();
  }
  transfers=renderTransfers;
  const previousBind=bindDynamic;
  bindDynamic=function(){
    if(typeof previousBind==='function')previousBind();
    const apply=$('#applyPlayerSearch');if(apply)apply.onclick=()=>{readFilters();render();};
    const reset=$('#resetPlayerSearch');if(reset)reset.onclick=()=>{Object.assign(filters,{scope:'market',name:'',position:'ALL',minRating:0,maxRating:100,minAge:15,maxAge:45,minFitness:0,maxPrice:0,contract:'ALL',listedOnly:false,sort:'rating_desc'});render();};
    const current=results();$$('[data-v473-result]').forEach(b=>b.onclick=()=>makeOffer(current[num(b.dataset.v473Result)]));
  };
  window.PlayerSearchV46={ensure,renderTransfers,results};
})();
