(()=>{
'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 wallet(w){
  $('#cash').textContent=Number(w?.cash_balance||0).toFixed(2);
  $('#bonus').textContent=Number(w?.bonus_balance||0).toFixed(2);
  $('#withdrawable').textContent=Number(w?.withdrawable_balance||0).toFixed(2);
}
function history(rows){
  const box=$('#history');
  if(!rows?.length){box.innerHTML='<div class="empty">No check-ins yet.</div>';return}
  box.innerHTML=rows.map(r=>`
    <div class="history-row">
      <div><b>${r.claim_date}</b><small>${r.created_at||''}</small></div>
      <strong>+${Number(r.reward_amount).toFixed(2)}</strong>
    </div>`).join('');
}
function status(s){
  $('#rewardRange').textContent=`${Number(s.reward_min).toFixed(2)} – ${Number(s.reward_max).toFixed(2)}`;
  $('#state').textContent=s.claimed?'Claimed':'Available';
  $('#todayStatus').textContent=s.claimed?'Reward claimed':'Ready to claim';
  $('#todayAmount').textContent=s.claimed?`+${Number(s.reward_amount).toFixed(2)}`:'';
  $('#claim').disabled=!!s.claimed||!s.enabled;
  $('#claim').textContent=s.claimed?'CLAIMED TODAY':(s.enabled?"CLAIM TODAY'S REWARD":'CHECK-IN UNAVAILABLE');
  $('#nextText').textContent=s.claimed?`Next claim after ${s.next_claim_at} (${s.timezone})`:`Available today • ${s.timezone}`;
}
async function refresh(){
  if(!token){location.href='/lobby/';return}
  try{
    const j=await call('/api/daily_checkin_status.php',{headers:headers()});
    status(j.status);wallet(j.wallet);history(j.recent);
  }catch(e){toast(e.message,true)}
}
$('#back').onclick=()=>location.href='/lobby/';
$('#claim').onclick=async()=>{
  $('#claim').disabled=true;
  try{
    const j=await call('/api/daily_checkin_claim.php',{
      method:'POST',headers:headers(true),body:'{}'
    });
    status(j.status);history(j.recent);
    if(j.result?.wallet)wallet(j.result.wallet);
    toast(j.result?.already_claimed?'Today’s reward was already claimed':`Daily reward +${Number(j.result.amount||0).toFixed(2)} credited`);
  }catch(e){toast(e.message,true);await refresh()}
};
refresh();
})();