/* LuckZoo Registered/Guest Playable Balance Fix v1
 * Additive only. Does NOT replace zoo.js or touch the locked UI.
 *
 * Cause fixed:
 * /api/wallet.php authenticates Guest sessions only.
 * After Bind Account converts a Guest to a Registered user, the game still
 * calls wallet.php, which returns 401 and zoo.js silently keeps 0.00.
 *
 * This small addon uses:
 *   guest      -> /api/wallet.php
 *   registered -> /api/account_me.php
 * and displays cash_balance + bonus_balance as playable game balance.
 */
(()=>{
'use strict';

let busy=false;

function setBalance(v){
  const n=Number(v||0).toFixed(2);
  const a=document.getElementById('bal');
  const b=document.getElementById('topBal');
  if(a)a.textContent=n;
  if(b)b.textContent=n;
}

async function refreshPlayableBalance(){
  if(busy)return;

  const token=localStorage.getItem('zoo_token')||'';
  const mode=localStorage.getItem('zoo_auth_mode')||'';
  if(!token)return;

  busy=true;
  try{
    let r;

    if(mode==='registered'){
      r=await fetch('/api/account_me.php?ts='+Date.now(),{
        headers:{'Authorization':'Bearer '+token,'Accept':'application/json'},
        cache:'no-store'
      });
    }else{
      r=await fetch('/api/wallet.php?session_token='+encodeURIComponent(token)+'&ts='+Date.now(),{
        headers:{'X-Guest-Session':token,'Accept':'application/json'},
        cache:'no-store'
      });
    }

    const j=await r.json();
    if(!r.ok||!j.ok||!j.wallet)return;

    const playable=
      Number(j.wallet.cash_balance||0)+
      Number(j.wallet.bonus_balance||0);

    setBalance(playable);

    window.LuckZooPlayableBalance={
      auth_mode:mode,
      cash:Number(j.wallet.cash_balance||0),
      bonus:Number(j.wallet.bonus_balance||0),
      playable
    };
  }catch(e){
    console.warn('LuckZoo playable balance refresh:',e);
  }finally{
    busy=false;
  }
}

function start(){
  refreshPlayableBalance();
  // Keep it synchronized after bets/rewards without changing game logic.
  setInterval(refreshPlayableBalance,1500);
  window.addEventListener('focus',refreshPlayableBalance);
}

if(document.readyState==='loading'){
  document.addEventListener('DOMContentLoaded',start,{once:true});
}else{
  start();
}
})();