(()=>{
'use strict';
const $=s=>document.querySelector(s);
let mode=localStorage.getItem('zoo_auth_mode')||'';
let token=localStorage.getItem('zoo_token')||'';

function headers(json=false){
  const h={};
  if(json)h['Content-Type']='application/json';
  if(mode==='guest')h['X-Guest-Session']=token;
  else if(token)h.Authorization='Bearer '+token;
  return h;
}
function toast(t,error=false){
  const x=$('#toast');x.textContent=t;x.classList.toggle('error',error);x.classList.add('show');
  clearTimeout(toast.t);toast.t=setTimeout(()=>x.classList.remove('show'),2200);
}
async function call(url,opt={}){
  const r=await fetch(url,{cache:'no-store',...opt});
  const j=await r.json();
  if(!r.ok||!j.ok)throw new Error(j.error||'Request failed');
  return j;
}
function playable(w){
  return Number(w?.cash_balance||0)+Number(w?.bonus_balance||0);
}
function render(j){
  const s=j.status||{};
  $('#rate').textContent=Number(s.reward_per_minute||1).toFixed(2);
  $('#minutes').textContent=Number(s.pending_minutes||0);
  $('#pending').textContent=Number(s.pending_amount||0).toFixed(2);
  $('#totalMinutes').textContent=Number(s.total_minutes||0);
  $('#totalEarned').textContent=Number(s.total_earned||0).toFixed(2);
  if(j.wallet)$('#balance').textContent=playable(j.wallet).toFixed(2);

  $('#state').textContent=s.pending_minutes>0?'Gift ready':'Tracking';
  $('#claim').disabled=!s.enabled||Number(s.pending_minutes||0)<1;
  $('#claim').textContent=s.enabled?(s.pending_minutes>0?'CLAIM VIP GIFT':'NO GIFT TO CLAIM'):'VIP GIFT UNAVAILABLE';

  const mins=j.recent_minutes||[];
  $('#minuteHistory').innerHTML=mins.length?mins.map(r=>`
    <div class="row">
      <div><b>${r.minute_key}</b><small>${r.bet_count} real bet${r.bet_count===1?'':'s'} • PKR ${Number(r.bet_amount).toFixed(2)} bet</small></div>
      <strong>+${Number(r.reward_amount).toFixed(2)}<em>${r.claimed?'claimed':'pending'}</em></strong>
    </div>`).join(''):'<div class="empty">Place a real bet during a completed minute to earn VIP Gift.</div>';

  const claims=s.claims||[];
  $('#claimHistory').innerHTML=claims.length?claims.map(c=>`
    <div class="row">
      <div><b>${c.created_at}</b><small>${c.minute_count} active minute${c.minute_count===1?'':'s'}</small></div>
      <strong>+${Number(c.amount).toFixed(2)}</strong>
    </div>`).join(''):'<div class="empty">No VIP claims yet.</div>';
}
async function refresh(){
  if(!token){location.href='/lobby/';return}
  try{
    const j=await call('/api/vip_minute_status.php',{headers:headers()});
    render(j);
  }catch(e){toast(e.message,true)}
}
$('#back').onclick=()=>location.href='/lobby/';
$('#claim').onclick=async()=>{
  $('#claim').disabled=true;
  try{
    const j=await call('/api/vip_minute_claim.php',{
      method:'POST',headers:headers(true),body:'{}'
    });
    render(j);
    if(j.result?.wallet)$('#balance').textContent=playable(j.result.wallet).toFixed(2);
    toast(j.result?.claimed
      ? `${j.result.minute_count} active minute${j.result.minute_count===1?'':'s'} • +${Number(j.result.amount).toFixed(2)} credited`
      : 'No completed active betting minutes to claim');
  }catch(e){toast(e.message,true);await refresh()}
};
refresh();
setInterval(refresh,15000);
})();