301 lines
13 KiB
JavaScript
301 lines
13 KiB
JavaScript
/* 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=`<img src="/uploads/avatars/${encodeURIComponent(avatarFile)}?v=${Date.now()}" style="width:100%;height:100%;object-fit:cover;border-radius:inherit" alt="${esc(username)}">`;
|
||
} 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 <button type="button" style="background:#fff;color:#a86f00;border:none;border-radius:6px;padding:5px 12px;font-weight:700;cursor:pointer">Zurück zum Admin</button>';
|
||
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='<p class="empty">Noch keine Spielrunden.</p>';
|
||
$('pageBtns').classList.add('hidden');
|
||
return;
|
||
}
|
||
|
||
const icon=r=>{
|
||
if(!r.outcome)return'<div class="hist-icon open">⏳</div>';
|
||
const won=(r.was_imposter&&!r.voted_out&&r.outcome==='imposters_win')
|
||
||(!r.was_imposter&&r.outcome==='innocents_win');
|
||
return`<div class="hist-icon ${won?'win':'loss'}">${won?'🏆':'💀'}</div>`;
|
||
};
|
||
const badge=r=>{
|
||
if(!r.outcome)return'<span class="outcome-badge open">Offen</span>';
|
||
const won=(parseInt(r.was_imposter)&&r.outcome==='imposters_win'&&!parseInt(r.voted_out))
|
||
||(!parseInt(r.was_imposter)&&r.outcome==='innocents_win');
|
||
return`<span class="outcome-badge ${won?'win':'loss'}">${won?'Gewonnen ✓':'Verloren'}</span>`;
|
||
};
|
||
|
||
wrap.innerHTML='<div class="hist-list">'+data.rounds.map(r=>`
|
||
<div class="hist-card">
|
||
${icon(r)}
|
||
<div class="hist-main">
|
||
<div class="hist-room">${esc(r.room_code)} <span style="color:var(--muted);font-weight:400;font-size:12px">Runde #${r.round_num}</span></div>
|
||
<div class="hist-sub">
|
||
${parseInt(r.was_imposter)?'<span class="imp-tag">Imposter</span>':'<span style="color:var(--muted)">Innocent</span>'}
|
||
<span>${new Date(r.played_at*1000).toLocaleDateString('de-DE',{day:'2-digit',month:'2-digit',year:'numeric'})}</span>
|
||
</div>
|
||
</div>
|
||
<div class="hist-right">${badge(r)}</div>
|
||
</div>`).join('')+'</div>';
|
||
|
||
const totalPages=Math.ceil(_total/20);
|
||
if(totalPages>1){
|
||
$('pageBtns').classList.remove('hidden');
|
||
$('pageInfo').textContent='Seite '+page+' / '+totalPages;
|
||
$('prevBtn').disabled=page<=1;
|
||
$('nextBtn').disabled=page>=totalPages;
|
||
} else {
|
||
$('pageBtns').classList.add('hidden');
|
||
}
|
||
}
|
||
|
||
async function doUpload(file){
|
||
if(!file)return;
|
||
if(file.size>2*1024*1024){msg('err','Bild zu groß (max 2 MB).');return;}
|
||
const reader=new FileReader();
|
||
reader.onload=async e=>{
|
||
try{
|
||
const res=await fetch('/api/auth/upload_avatar',{
|
||
method:'POST',headers:{'Content-Type':'application/json'},
|
||
body:JSON.stringify({imageBase64:e.target.result})
|
||
});
|
||
const data=await res.json();
|
||
if(!res.ok||data.error){msg('err',data.error||'Upload fehlgeschlagen.');return;}
|
||
msg('ok','Profilbild gespeichert!');
|
||
$('dropZone').classList.remove('over');
|
||
await loadProfile();
|
||
}catch(ex){msg('err','Upload-Fehler.');}
|
||
};
|
||
reader.readAsDataURL(file);
|
||
}
|
||
|
||
function uploadAvatar(input){doUpload(input.files[0]);input.value='';}
|
||
function handleDrop(e){
|
||
e.preventDefault();
|
||
$('dropZone').classList.remove('over');
|
||
doUpload(e.dataTransfer.files[0]);
|
||
}
|
||
|
||
async function doStickerUpload(file){
|
||
if(!file)return;
|
||
if(!/^image\/(png|gif)$/.test(file.type)){msg('err','Nur PNG oder GIF erlaubt.');return;}
|
||
if(file.size>500*1024){msg('err','Sticker zu groß (max 500 KB).');return;}
|
||
const reader=new FileReader();
|
||
reader.onload=async e=>{
|
||
try{
|
||
const res=await fetch('/api/auth/upload_sticker',{
|
||
method:'POST',headers:{'Content-Type':'application/json'},
|
||
body:JSON.stringify({imageBase64:e.target.result})
|
||
});
|
||
const data=await res.json();
|
||
if(!res.ok||data.error){msg('err',data.error||'Upload fehlgeschlagen.');return;}
|
||
msg('ok','Sticker gespeichert!');
|
||
$('stickerDropZone').classList.remove('over');
|
||
await loadProfile();
|
||
}catch(ex){msg('err','Upload-Fehler.');}
|
||
};
|
||
reader.readAsDataURL(file);
|
||
}
|
||
function uploadSticker(input){doStickerUpload(input.files[0]);input.value='';}
|
||
function handleStickerDrop(e){
|
||
e.preventDefault();
|
||
$('stickerDropZone').classList.remove('over');
|
||
doStickerUpload(e.dataTransfer.files[0]);
|
||
}
|
||
|
||
async function changeCred(){
|
||
const old=$('oldCred').value, nw=$('newCred').value;
|
||
if(!old||!nw){msg('err','Alle Felder ausfüllen.');return;}
|
||
try{
|
||
const res=await fetch('/api/auth/change_credential',{
|
||
method:'POST',headers:{'Content-Type':'application/json'},
|
||
body:JSON.stringify({old,new:nw})
|
||
});
|
||
const data=await res.json();
|
||
if(!res.ok||data.error){msg('err',data.error||'Fehler');return;}
|
||
msg('ok',_isAdmin?'Passwort geändert!':'PIN geändert!');
|
||
$('oldCred').value=$('newCred').value='';
|
||
}catch(e){msg('err','Fehler.');}
|
||
}
|
||
|
||
async function saveColor(){
|
||
const color=$('colorPicker').value;
|
||
try{
|
||
const res=await fetch('/api/auth/save_color',{
|
||
method:'POST',headers:{'Content-Type':'application/json'},
|
||
body:JSON.stringify({color})
|
||
});
|
||
const data=await res.json();
|
||
if(!res.ok||data.error){msg('err',data.error||'Fehler');return;}
|
||
msg('ok','Farbe gespeichert!');
|
||
}catch(e){msg('err','Fehler.');}
|
||
}
|
||
|
||
async function logout(){
|
||
await fetch('/api/auth/logout',{method:'POST'});
|
||
window.location.href='/login';
|
||
}
|
||
|
||
init();
|
||
async function changeName(){
|
||
const v=$('newName').value.trim();
|
||
if(!v){ msg('err','Gib einen Namen ein.'); return; }
|
||
try{
|
||
const res=await fetch('/api/auth/change_username',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:v})});
|
||
const d=await res.json();
|
||
if(!res.ok||d.error){ msg('err',d.error||'Name konnte nicht geändert werden.'); return; }
|
||
msg('ok','Name geändert!'); await loadProfile();
|
||
}catch(e){ msg('err','Fehler.'); }
|
||
}
|
||
|
||
return{loadHistory,uploadAvatar,handleDrop,uploadSticker,handleStickerDrop,changeCred,changeName,saveColor,saveNameStyle,logout,get page(){return _page;}};
|
||
})();
|