/** AURA FARMING — Etapa 10: atualização do placar da batalha */
(() => {
  const root=document.querySelector('.battle-room');if(!root)return;
  const base=document.querySelector('meta[name="app-base-url"]')?.content||'';const id=Number(root.dataset.battleId||0);let stopped=false;
  const format=n=>Number(n||0).toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2});
  const statusLabel=s=>String(s||'').replaceAll('_',' ').toUpperCase();
  async function refresh(){
    try{const r=await fetch(`${base}/api/v1/battles/state.php?id=${id}`,{credentials:'same-origin'});const d=await r.json();if(!r.ok||!d.ok)return;const b=d.batalha;
      document.querySelector('[data-battle-status]').textContent=statusLabel(b.status);
      const timer=document.querySelector('[data-battle-timer]');if(timer){const sec=Math.max(0,Number(b.tempo_restante||0));timer.textContent=b.status==='em_andamento'?`${String(Math.floor(sec/60)).padStart(2,'0')}:${String(sec%60).padStart(2,'0')}`:'03:00';}
      (b.jogadores||[]).forEach(p=>{const score=document.querySelector(`[data-score-user="${p.usuario_id}"]`);const status=document.querySelector(`[data-status-user="${p.usuario_id}"]`);if(score)score.textContent=format(p.pontuacao);if(status)status.textContent=statusLabel(p.status);});
      if(['finalizada','cancelada','expirada'].includes(b.status)){stopped=true;window.setTimeout(()=>location.reload(),700);}
    }catch(_){ }
  }
  const loop=setInterval(()=>{if(!stopped)refresh();else clearInterval(loop);},1800);refresh();
})();
