(()=>{
'use strict';
const $=s=>document.querySelector(s);
const $$=s=>[...document.querySelectorAll(s)];

let token=localStorage.getItem('zoo_token')||'';
let mode=localStorage.getItem('zoo_auth_mode')||'';
let rows=[];
let filter='all';

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 signed(v){
  const n=Number(v||0);
  return `${n>0?'+':''}${money(n)}`;
}
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'),2000);
}
function niceMethod(m){
  const s=String(m||'').toLowerCase();
  if(s==='jazzcash')return 'JazzCash';
  if(s==='easypaisa')return 'Easypaisa';
  if(s==='usdt_trc20')return 'USDT TRC20';
  return m||'';
}
function icon(r){
  if(r.category==='deposit')return '＋';
  if(r.category==='withdrawal')return '⇩';
  if(r.category==='reward')return '🎁';
  if(r.kind==='win')return '★';
  if(r.kind==='bet')return '●';
  if(r.kind==='refund')return '↩';
  return '◷';
}
function subtitle(r){
  const bits=[];
  if(r.method)bits.push(niceMethod(r.method));
  if(r.reference)bits.push(r.reference);
  if(r.reference_type && !['deposit','withdrawal'].includes(r.reference_type))bits.push(r.reference_type.replaceAll('_',' '));
  bits.push(r.created_at||'');
  return bits.filter(Boolean).join(' • ');
}
function details(r){
  const d=[];
  if(r.category==='deposit' && String(r.status)==='confirmed'){
    if(Number(r.principal_credit)>0)d.push(['Principal',money(r.principal_credit)]);
    if(Number(r.deposit_bonus)>0)d.push(['Deposit Bonus',money(r.deposit_bonus)]);
    if(Number(r.welcome_bonus)>0)d.push(['Welcome Bonus',money(r.welcome_bonus)]);
  }else if(r.category==='reward'){
    if(Number(r.cash_delta))d.push(['Cash',signed(r.cash_delta)]);
    if(Number(r.bonus_delta))d.push(['Bonus',signed(r.bonus_delta)]);
  }else if(r.category==='game'){
    if(Number(r.cash_delta))d.push(['Cash',signed(r.cash_delta)]);
    if(Number(r.bonus_delta))d.push(['Bonus',signed(r.bonus_delta)]);
    if(Number(r.withdrawable_delta))d.push(['Withdrawable',signed(r.withdrawable_delta)]);
  }
  if(!d.length)return '';
  return `<div class="detail">${d.map(x=>`<span>${x[0]}<b>${x[1]}</b></span>`).join('')}</div>`;
}
function impact(r){
  if(r.category==='deposit'){
    if(String(r.status)==='confirmed')return Number(r.total_credit||r.impact||0);
    return 0;
  }
  return Number(r.impact||0);
}
function render(){
  const box=$('#transactions');
  const show=filter==='all'?rows:rows.filter(r=>r.category===filter);
  $('#loading').style.display='none';

  if(!show.length){
    box.innerHTML=`<div class="empty">No ${filter==='all'?'transactions':filter+' transactions'} yet.</div>`;
    return;
  }

  box.innerHTML=show.map(r=>{
    const n=impact(r);
    const amountClass=n>0?'positive':n<0?'negative':'neutral';
    const status=String(r.status||'completed').toLowerCase();
    const displayAmount=r.category==='deposit' && status!=='confirmed'
      ? `PKR ${money(r.amount)}`
      : `PKR ${signed(n)}`;

    return `<article class="tx ${r.category}">
      <div class="icon">${icon(r)}</div>
      <div class="body">
        <b>${r.title||'Transaction'}</b>
        <small>${subtitle(r)}</small>
      </div>
      <div class="amount ${amountClass}">
        <strong>${displayAmount}</strong>
        <small class="status-${status}">${status}</small>
      </div>
      ${details(r)}
    </article>`;
  }).join('');
}
function wallet(w){
  $('#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);
}
async function load(){
  if(!token){location.href='/lobby/';return}
  $('#loading').style.display='block';
  try{
    const r=await fetch('/api/transaction_history.php?limit=120&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 transactions');

    rows=j.transactions||[];
    wallet(j.wallet||{});

    $('#countAll').textContent=j.summary?.all||0;
    $('#countDeposit').textContent=j.summary?.deposit||0;
    $('#countWithdrawal').textContent=j.summary?.withdrawal||0;
    $('#countReward').textContent=j.summary?.reward||0;
    $('#countGame').textContent=j.summary?.game||0;

    render();
  }catch(e){
    $('#loading').style.display='none';
    toast(e.message,true);
  }
}
$$('[data-filter]').forEach(b=>b.onclick=()=>{
  filter=b.dataset.filter;
  $$('[data-filter]').forEach(x=>x.classList.toggle('active',x===b));
  render();
});
$('#refresh').onclick=load;
$('#back').onclick=()=>location.href='/lobby/';
load();
})();