(()=>{'use strict';
const $=s=>document.querySelector(s);
const token=localStorage.getItem('zoo_token')||'',mode=localStorage.getItem('zoo_auth_mode')||'';
function headers(){const h={};if(mode==='guest')h['X-Guest-Session']=token;else if(token)h.Authorization='Bearer '+token;return h}
function money(v){return Number(v||0).toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2})}
function toast(t,e=false){const x=$('#toast');x.textContent=t;x.classList.toggle('error',e);x.classList.add('show');clearTimeout(toast.t);toast.t=setTimeout(()=>x.classList.remove('show'),1800)}
function label(r){const ref=String(r.reference_type||'');if(r.kind==='welcome_bonus'||ref==='welcome_bonus')return ['🎉','Welcome Bonus'];if(r.kind==='deposit_bonus'||ref==='deposit_bonus')return ['💰','Deposit Bonus'];if(ref==='phone_binding'||ref==='phone_binding_bonus')return ['🔗','Binding Bonus'];if(ref==='daily_checkin')return ['📅','Daily Check-In'];if(ref==='vip_minute_gift')return ['🎁','VIP Minute Gift'];return ['🎁',r.title||'Reward']}
async function load(){
 if(!token){location.href='/lobby/';return}
 try{
  const r=await fetch('/api/bonus_center.php?ts='+Date.now(),{headers:headers(),cache:'no-store'});
  const j=await r.json();if(!r.ok||!j.ok)throw new Error(j.error||'Could not load rewards');
  const w=j.wallet||{};$('#playable').textContent=money(Number(w.cash_balance||0)+Number(w.bonus_balance||0));$('#bonusBalance').textContent=money(w.bonus_balance);$('#earned').textContent=money(j.total_rewards);
  const ws=$('#welcomeState');ws.textContent=j.status?.welcome_claimed?'CREDITED':'AVAILABLE';ws.classList.toggle('claimed',!!j.status?.welcome_claimed);
  const bs=$('#bindingState');bs.textContent=j.status?.binding_claimed?'CREDITED':(j.status?.phone_verified?'READY':'NOT CLAIMED');bs.classList.toggle('claimed',!!j.status?.binding_claimed);
  const rows=j.rewards||[],box=$('#history');
  if(!rows.length){box.innerHTML='<div class="empty">No reward activity yet.</div>';return}
  box.innerHTML=rows.map(x=>{const [i,n]=label(x);return `<div class="row"><div class="ri">${i}</div><div><b>${n}</b><small>${x.created_at||''}</small></div><strong>+ PKR ${money(x.impact||x.amount)}</strong></div>`}).join('');
 }catch(e){toast(e.message,true)}
}
$('#back').onclick=()=>location.href='/lobby/';$('#refresh').onclick=load;$('#checkin').onclick=()=>location.href='/account/checkin.html';$('#vip').onclick=()=>location.href='/account/vip.html';load();
})();