(()=>{'use strict';
const $=s=>document.querySelector(s),$$=s=>[...document.querySelectorAll(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 date(v){if(!v)return '—';const d=new Date(String(v).replace(' ','T'));return Number.isNaN(d.getTime())?v:d.toLocaleString()}
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 method(m){return m==='jazzcash'?'JazzCash':m==='easypaisa'?'Easypaisa':m||'Payment account'}
async function load(){
 if(!token){location.href='/lobby/';return}
 try{
  const r=await fetch('/api/account_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 account');
  const a=j.account||{},w=j.wallet||{};
  $('#playerId').textContent=a.internal_login_id?`ID ${a.internal_login_id}`:`Player #${a.user_id||''}`;
  $('#accountState').textContent=a.registered?'Registered & secured':'Guest session';$('#displayName').value=a.display_name||'';
  $('#playable').textContent=money(Number(w.cash_balance||0)+Number(w.bonus_balance||0));
  $('#withdrawable').textContent=money(w.withdrawable_balance);$('#wager').textContent=money(w.wager_remaining);

  $('#phone').textContent=a.phone_verified?(a.phone_masked||'Verified'):'Not bound';
  $('#phoneInfo').textContent=a.phone_verified?'Verified mobile is permanently bound.':'Bind a mobile number to secure your account.';
  $('#phoneState').textContent=a.phone_verified?'✓':'!';$('#phoneState').classList.toggle('ok',!!a.phone_verified);

  $('#internal').textContent=a.internal_login_bound?(a.internal_login_id||'Bound'):'Not bound';
  $('#internalInfo').textContent=a.internal_login_bound?'Internal login ID is permanently bound.':'Optional LuckZoo login ID.';
  $('#internalState').textContent=a.internal_login_bound?'✓':'!';$('#internalState').classList.toggle('ok',!!a.internal_login_bound);

  const wa=a.withdrawal_account;
  $('#withdrawAccount').textContent=a.withdrawal_bound?`${method(wa?.method)} • ${wa?.destination_masked||'Bound'}`:'Not bound';
  $('#withdrawInfo').textContent=a.withdrawal_bound?'Withdrawal destination is locked from player-side changes.':'Bind JazzCash or Easypaisa before withdrawal.';
  $('#withdrawState').textContent=a.withdrawal_bound?'✓':'!';$('#withdrawState').classList.toggle('ok',!!a.withdrawal_bound);

  const allSecure=!!a.registered&&!!a.phone_verified&&!!a.withdrawal_bound;
  $('#secureBadge').textContent=allSecure?'SECURED':'ACTION NEEDED';$('#secureBadge').classList.toggle('ok',allSecure);
  $('#pendingDeposits').textContent=a.pending_deposits||0;$('#pendingWithdrawals').textContent=a.pending_withdrawals||0;
  $('#created').textContent=date(a.created_at);$('#lastLogin').textContent=date(a.last_login_at);
 }catch(e){
   $('#accountState').textContent='Could not load account';
   $('#secureBadge').textContent='DATA ERROR';
   toast(e.message,true);
 }
}
$('#saveName').onclick=async()=>{const name=$('#displayName').value.trim();if(name.length<2){toast('Enter at least 2 characters',true);return}try{const r=await fetch('/api/account_profile_update.php',{method:'POST',headers:{...headers(),'Content-Type':'application/json'},body:JSON.stringify({display_name:name}),cache:'no-store'});const j=await r.json();if(!r.ok||!j.ok)throw new Error(j.error||'Could not save name');const savedName=j.display_name||name;localStorage.setItem('lz_display_name',savedName);toast('Display name updated');$('#displayName').value=savedName}catch(e){toast(e.message,true)}};
$$('[data-go]').forEach(b=>b.onclick=()=>location.href=b.dataset.go);
$('#back').onclick=()=>location.href='/lobby/';$('#refresh').onclick=load;
$('#logout').onclick=()=>$('#confirm').classList.remove('hide');$('#cancel').onclick=()=>$('#confirm').classList.add('hide');
$('#confirmLogout').onclick=async()=>{
 const currentToken=localStorage.getItem('zoo_token')||'';
 const currentMode=localStorage.getItem('zoo_auth_mode')||'';
 try{
   if(currentToken&&currentMode==='registered'){
     await fetch('/api/logout.php',{method:'POST',headers:{Authorization:'Bearer '+currentToken},cache:'no-store'});
   }
 }catch(e){}
 localStorage.removeItem('zoo_token');
 localStorage.removeItem('zoo_auth_mode');

 // A guest logout ends the active session view but keeps the device guest
 // token so the next Guest Login can resume the same guest on this device.
 // Registered logout still clears guest-resume identity data.
 if(currentMode!=='guest'){
   localStorage.removeItem('zoo_device_guest_token');
   localStorage.removeItem('lz_display_name');
 }
 location.replace('/auth/?loggedout=1');
};
load();
})();