/* LuckZoo PRIZING Payout Flight v1
 * Additive visual-only settlement notification.
 * Does not modify board geometry, winner logic, bets, payout math or timing.
 */
(()=>{
'use strict';

let busy=false;
let lastShown=Number(sessionStorage.getItem('lz_last_payout_round')||0);

function authHeaders(){
  const token=localStorage.getItem('zoo_token')||'';
  const mode=localStorage.getItem('zoo_auth_mode')||'';
  const h={'Accept':'application/json'};
  if(mode==='guest')h['X-Guest-Session']=token;
  else if(token)h['Authorization']='Bearer '+token;
  return h;
}

function phase(){
  return String(document.getElementById('phase')?.textContent||'').trim().toUpperCase();
}

function playable(w){
  return Number(w?.cash_balance||0)+Number(w?.bonus_balance||0);
}

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

function sourceRect(){
  const winner=document.getElementById('winner');
  if(winner && !winner.classList.contains('hide')){
    const r=winner.getBoundingClientRect();
    if(r.width&&r.height)return r;
  }

  // Exact existing central Total Bet / winner zone fallback.
  const center=document.querySelector('.center-bets,.battle-card,.total-bet');
  return center?.getBoundingClientRect()||null;
}

function targetRect(){
  // Header balance was removed from the game UI.
  // Always target the visible bottom-left player balance first.
  const bal=document.getElementById('bal')||document.getElementById('topBal');
  return bal?.getBoundingClientRect()||null;
}

function animateCredit(amount,newBalance){
  const from=sourceRect(),to=targetRect();
  if(!from||!to){
    setBalance(newBalance);
    return;
  }

  let layer=document.getElementById('lz-payout-fx');
  if(!layer){
    layer=document.createElement('div');
    layer.id='lz-payout-fx';
    layer.style.cssText='position:fixed;inset:0;pointer-events:none;z-index:2147483640;overflow:visible';
    document.body.appendChild(layer);
  }

  const credit=document.createElement('div');
  credit.className='lz-payout-credit';
  credit.textContent='+'+Number(amount).toLocaleString(undefined,{maximumFractionDigits:2});
  credit.style.cssText=
    'position:fixed;display:flex;align-items:center;justify-content:center;'+
    'min-width:78px;height:42px;padding:0 14px;border-radius:22px;'+
    'background:linear-gradient(180deg,#fff48a,#e8ad19);'+
    'border:2px solid #fff0a0;color:#173a13;font:1000 20px Arial,sans-serif;'+
    'text-shadow:0 1px 0 #fff8;box-shadow:0 0 20px #ffd33c,0 7px 18px #000a;'+
    'will-change:transform,opacity;z-index:2';

  const x1=from.left+from.width/2;
  const y1=from.top+from.height/2;
  const x2=to.left+to.width/2;
  const y2=to.top+to.height/2;

  credit.style.left=x1+'px';
  credit.style.top=y1+'px';
  credit.style.transform='translate(-50%,-50%) scale(.85)';
  layer.appendChild(credit);

  // Brief readable hold beside winner, then fly to balance.
  setTimeout(()=>{
    credit.style.transition='transform .82s cubic-bezier(.18,.74,.22,1),opacity .82s ease';
    credit.style.transform=`translate(calc(-50% + ${x2-x1}px),calc(-50% + ${y2-y1}px)) scale(.58)`;
  },280);

  setTimeout(()=>{
    credit.remove();
    setBalance(newBalance);

    const target=document.getElementById('bal')||document.getElementById('topBal');
    if(target){
      target.classList.add('lz-balance-credit-pop');
      setTimeout(()=>target.classList.remove('lz-balance-credit-pop'),500);
    }
  },1150);
}

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

  // The message belongs ONLY to PRIZING.
  if(!phase().startsWith('PRIZING'))return;

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

  busy=true;
  try{
    const r=await fetch('/api/recent_player_settlement.php?_='+Date.now(),{
      headers:authHeaders(),
      cache:'no-store'
    });
    const j=await r.json();
    if(!r.ok||!j.ok||!j.settlement)return;

    const s=j.settlement;
    const rid=Number(s.round_id||0);
    const payout=Number(s.payout||0);

    if(!rid||rid===lastShown)return;

    /*
     * Mark this settlement handled even when payout is zero.
     * This prevents a stale previous win from being shown during a later round.
     */
    lastShown=rid;
    sessionStorage.setItem('lz_last_payout_round',String(rid));

    if(payout<=0)return;

    animateCredit(payout,playable(j.wallet));
  }catch(e){
    console.warn('LuckZoo payout flight:',e);
  }finally{
    busy=false;
  }
}

setInterval(poll,350);
document.addEventListener('visibilitychange',()=>{if(!document.hidden)poll()});
})();
