/* Black Sheep Bluff – profile.php – ausgelagertes JS */
const Profile = (() => {
const $ = id => document.getElementById(id);
let _page=1, _total=0, _isAdmin=false;
const COLORS=['#3ECC5C','#4A5BE8','#5DCAA5','#ffcf6e','#65DC7A','#85B7EB','#D4537E','#97C459'];
const colorFor=s=>{let h=0;for(const c of(s||''))h=(h*31+c.charCodeAt(0))>>>0;return COLORS[h%COLORS.length];};
const initials=s=>(s||'?').trim().split(/\s+/).map(w=>w[0]).join('').slice(0,2).toUpperCase();
const esc=s=>(s||'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const pct=(n,d)=>d?Math.round((n/d)*100):0;
function msg(type,text){
const el=$(type==='err'?'errBox':'okBox');
el.textContent=text; el.classList.remove('hidden');
setTimeout(()=>el.classList.add('hidden'),type==='err'?4500:3000);
}
function animCount(el,to){
const dur=600,start=Date.now(),from=0;
const step=()=>{
const t=Math.min(1,(Date.now()-start)/dur);
const ease=1-Math.pow(1-t,3);
el.textContent=Math.round(from+(to-from)*ease);
if(t<1)requestAnimationFrame(step);
};
requestAnimationFrame(step);
}
function setAvatar(username, avatarFile){
const el=$('heroAv');
if(avatarFile){
el.style='';
el.innerHTML=``;
} else {
el.style.background=colorFor(username);
el.textContent=initials(username);
}
}
function bsbImpBar(on){
if(!on || document.getElementById('imp-bar')) return;
const b=document.createElement('div'); b.id='imp-bar';
b.style.cssText='position:fixed;top:0;left:0;right:0;z-index:5000;background:#a86f00;color:#fff;font:600 13px/1.4 Inter,system-ui,sans-serif;padding:8px 14px;display:flex;align-items:center;justify-content:center;gap:12px;flex-wrap:wrap';
b.innerHTML='👁 Admin-Modus – du bist als anderer User angemeldet ';
b.querySelector('button').onclick=async()=>{ try{ await fetch('/api/auth/stop_impersonating',{method:'POST'}); }catch(e){} location.href='/admin'; };
document.body.appendChild(b); document.body.style.paddingTop=(b.offsetHeight||38)+'px';
}
const BSB_FONTS={inter:"Inter",sora:"Sora",pacifico:"Pacifico",lobster:"Lobster",bungee:"Bungee",bangers:"Bangers",orbitron:"Orbitron",pressstart:"'Press Start 2P'"};
function nameStyleObj(u){
u=u||{};
const c1=u.color||'var(--navy)';
const st=u.name_style||u.nameStyle||'solid';
const font=BSB_FONTS[u.name_font||u.nameFont]||'';
let style='',cls='';
if(st==='rainbow'){ cls='name-rainbow'; }
else if(st==='gradient'&&u.color2){ style=`background:linear-gradient(90deg,${c1},${u.color2});-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent;color:transparent`; }
else { style=`color:${c1}`; }
if(font) style+=`;font-family:${font}`;
return {style,cls};
}
function applyName(el, baseCls, baseStyle, u, text){
if(!el) return;
const ns=nameStyleObj(u);
el.className=(baseCls+(ns.cls?' '+ns.cls:'')).trim();
el.setAttribute('style', baseStyle+ns.style);
if(text!=null) el.textContent=text;
}
function currentStyle(){ return { color:$('colorPicker').value, color2:$('colorPicker2').value, name_style:$('nameStyleSel').value, name_font:$('nameFontSel').value }; }
function updatePreview(){
const grad=$('nameStyleSel').value==='gradient';
const c2=$('color2Wrap'); if(c2) c2.style.display=grad?'':'none';
applyName($('colorPreviewName'),'','font-weight:800;font-size:24px;',currentStyle());
}
async function saveNameStyle(){
try{
const res=await fetch('/api/auth/save_name_style',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(currentStyle())});
const d=await res.json();
if(!res.ok||d.error){ msg('err',d.error||'Fehler.'); return; }
msg('ok','Name-Stil gespeichert!'); await loadProfile();
}catch(e){ msg('err','Fehler.'); }
}
async function init(){
try{
const res=await fetch('/api/auth/me');
const data=await res.json();
if(!data.user){window.location.href='/login';return;}
_isAdmin=data.user.role==='admin';
bsbImpBar(data && data.impersonating);
if(_isAdmin){
$('adminLink').classList.remove('hidden');
$('oldCred').removeAttribute('inputmode');
$('newCred').removeAttribute('inputmode');
$('newCred').maxLength=255;
$('oldCredLabel').textContent='Aktuelles Passwort';
$('newCredLabel').textContent='Neues Passwort (min. 8 Zeichen)';
$('pinCardTitle').textContent='Passwort ändern';
$('newCred').placeholder='••••••••';
}
await loadProfile();
['nameStyleSel','colorPicker','colorPicker2','nameFontSel'].forEach(id=>{ const el=$(id); if(el) el.addEventListener('input',updatePreview); });
await loadHistory(1);
}catch(e){msg('err','Ladefehler.');}
}
async function loadProfile(){
const res=await fetch('/api/auth/get_profile');
const data=await res.json();
if(!data.profile)return;
const p=data.profile;
applyName($('profileName'),'hero-name','',p,p.username);
{ const _nn=$('newName'); if(_nn && document.activeElement!==_nn) _nn.value=p.username; }
$('profileRole').textContent=p.role;
$('profileRole').className='role-badge '+p.role;
const since=new Date((p.created_at||0)*1000);
$('profileSince').textContent='Dabei seit '+since.toLocaleDateString('de-DE',{year:'numeric',month:'long'});
setAvatar(p.username, p.avatar);
const sp=$('stickerPreview');
if(p.sticker){ sp.src='/uploads/sticker/'+encodeURIComponent(p.sticker)+'?v='+Date.now(); sp.classList.remove('hidden'); }
else { sp.classList.add('hidden'); }
const savedColor = p.color || colorFor(p.username);
$('colorPicker').value = savedColor;
$('colorPicker2').value = p.color2 || savedColor;
$('nameStyleSel').value = p.name_style || 'solid';
$('nameFontSel').value = p.name_font || '';
applyName($('colorPreviewName'),'','font-weight:800;font-size:24px;',p,p.username);
updatePreview();
const s=p;
animCount($('sPlayed'),parseInt(s.games_played)||0);
animCount($('sWon'),parseInt(s.games_won)||0);
animCount($('sLost'),parseInt(s.games_lost)||0);
animCount($('sImp'),parseInt(s.times_imposter)||0);
animCount($('sImpW'),parseInt(s.imposter_wins)||0);
animCount($('sInnoW'),parseInt(s.innocent_wins)||0);
const totalPct=pct(s.games_won,s.games_played);
const impPct=pct(s.imposter_wins,s.times_imposter);
const innoPct=pct(s.innocent_wins,(s.games_played||0)-(s.times_imposter||0));
setTimeout(()=>{
$('wrTotal').style.width=totalPct+'%'; $('wrTotalPct').textContent=totalPct+'%';
$('wrImp').style.width=impPct+'%'; $('wrImpPct').textContent=impPct+'%';
$('wrInno').style.width=innoPct+'%'; $('wrInnoPct').textContent=innoPct+'%';
},100);
}
async function loadHistory(page=1){
_page=page;
const res=await fetch('/api/auth/get_history?page='+page);
const data=await res.json();
if(!data.rounds)return;
_total=data.total;
const wrap=$('historyWrap');
if(!data.rounds.length){
wrap.innerHTML='
Noch keine Spielrunden.
'; $('pageBtns').classList.add('hidden'); return; } const icon=r=>{ if(!r.outcome)return''; const won=(r.was_imposter&&!r.voted_out&&r.outcome==='imposters_win') ||(!r.was_imposter&&r.outcome==='innocents_win'); return``; }; const badge=r=>{ if(!r.outcome)return'Offen'; const won=(parseInt(r.was_imposter)&&r.outcome==='imposters_win'&&!parseInt(r.voted_out)) ||(!parseInt(r.was_imposter)&&r.outcome==='innocents_win'); return`${won?'Gewonnen ✓':'Verloren'}`; }; wrap.innerHTML='