(()=>{'use strict';
const $=s=>document.querySelector(s),$$=s=>[...document.querySelectorAll(s)];
const token=localStorage.getItem('zoo_token')||'',mode=localStorage.getItem('zoo_auth_mode')||'';
let methods=[],selected=null,current=null,pollTimer=null;

function headers(json=false){
 const h={};if(json)h['Content-Type']='application/json';
 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 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'),2200)}
async function call(url,opt={}){
 const r=await fetch(url,{cache:'no-store',...opt});const j=await r.json();
 if(!r.ok||!j.ok)throw new Error(j.error||'Request failed');return j;
}
function methodIcon(m){
 if(m.code==='jazzcash')return '📱';
 if(m.code==='easypaisa')return '💳';
 if(m.type==='crypto')return '₮';
 if(m.type==='bank')return '🏦';
 return '＋';
}
function renderMethods(){
 const box=$('#methods');
 if(!methods.length){
   box.innerHTML='<div class="empty">No deposit method is enabled yet. The administrator must configure a payment destination/merchant method first.</div>';
   selected=null;$('#create').disabled=true;$('#amountRule').textContent='No payment method is currently available.';
   return;
 }
 box.innerHTML=methods.map((m,i)=>`<button type="button" class="method ${i===0?'active':''}" data-code="${m.code}">
   <span class="mi">${methodIcon(m)}</span>
   <span><b>${m.name}</b><small>${m.currency}${m.network?' • '+m.network:''}</small></span>
   <em>›</em>
 </button>`).join('');
 selected=methods[0];
 updateRule();
 $$('.method').forEach(b=>b.onclick=()=>{
   selected=methods.find(x=>x.code===b.dataset.code)||null;
   $$('.method').forEach(x=>x.classList.toggle('active',x===b));
   updateRule();
 });
}
function updateRule(){
 if(!selected){$('#amountRule').textContent='Select a payment method first.';$('#create').disabled=true;return}
 const min=Number(selected.min_amount||0),max=Number(selected.max_amount||0);
 $('#amount').min=String(min);$('#amount').max=String(max);
 $('#amountRule').textContent=`Allowed amount: ${selected.currency} ${money(min)} – ${money(max)}.`;
 validate();
}
function validate(){
 const n=Number($('#amount').value||0);
 const min=Number(selected?.min_amount||0),max=Number(selected?.max_amount||0);
 $('#create').disabled=!selected||!Number.isFinite(n)||n<min||n>max;
}
function setWallet(w){
 $('#playable').textContent=money(Number(w?.cash_balance||0)+Number(w?.bonus_balance||0));
 $('#cash').textContent=money(w?.cash_balance);$('#bonus').textContent=money(w?.bonus_balance);
}
function showPayment(d){
 current=d;const m=d.method_details||{};
 $('#payMethod').textContent=m.method_name||d.method;
 $('#payAmount').textContent=money(d.amount);$('#lzRef').textContent=d.reference||'—';
 $('#destLabel').textContent=m.destination_label||'PAYMENT DESTINATION';
 $('#destination').textContent=m.destination_value||'—';
 $('#instructions').textContent=m.instructions||'';
 $('#paymentCard').classList.remove('hide');
 $('#paymentCard').scrollIntoView({behavior:'smooth',block:'start'});
}
function showPending(d){
 current=d;$('#pendingId').textContent=d.id||'—';
 $('#pendingStatus').textContent=String(d.status||'pending').toUpperCase();
 $('#paymentCard').classList.add('hide');$('#pendingCard').classList.remove('hide');
 startPolling();
}
function stopPolling(){if(pollTimer){clearInterval(pollTimer);pollTimer=null}}
function startPolling(){
 stopPolling();if(!current?.id)return;
 pollTimer=setInterval(()=>checkStatus(false),5000);
}
async function checkStatus(showToast=true){
 if(!current?.id)return;
 try{
   const j=await call('/api/deposit_status.php?id='+encodeURIComponent(current.id)+'&ts='+Date.now(),{headers:headers()});
   current=j.deposit;const st=String(current.status||'pending');
   $('#pendingStatus').textContent=st.toUpperCase();
   if(st==='confirmed'){
     stopPolling();$('#pendingCard').classList.add('hide');
     const parts=[];
     if(Number(current.deposit_bonus||0)>0)parts.push(`5% bonus PKR ${money(current.deposit_bonus)}`);
     if(Number(current.welcome_bonus||0)>0)parts.push(`first deposit PKR ${money(current.welcome_bonus)}`);
     toast(`Deposit confirmed. Total PKR ${money(current.total_credit)} credited${parts.length?' • '+parts.join(' • '):''}.`);
     await Promise.all([loadWallet(),loadHistory()]);
   }else if(st!=='pending'){
     stopPolling();toast(`Deposit status: ${st}`,true);await loadHistory();
   }else if(showToast)toast('Still waiting for confirmation.');
 }catch(e){if(showToast)toast(e.message,true)}
}
async function loadWallet(){
 try{const j=await call('/api/wallet.php?ts='+Date.now(),{headers:headers()});if(j.wallet)setWallet(j.wallet)}catch(e){}
}
async function loadHistory(){
 try{
  const j=await call('/api/deposit_history.php?ts='+Date.now(),{headers:headers()});
  const rows=j.deposits||[],box=$('#history');
  if(!rows.length){box.innerHTML='<div class="empty">No deposits yet.</div>';return}
  box.innerHTML=rows.map(r=>{
   const st=String(r.status||'pending').toLowerCase(),credit=Number(r.total_credit||0);
   const rewards=st==='confirmed'
     ? `<small class="reward-detail">Principal ${money(r.principal_credit)}${Number(r.deposit_bonus||0)>0?' • 5% +'+money(r.deposit_bonus):''}${Number(r.welcome_bonus||0)>0?' • Welcome +'+money(r.welcome_bonus):''}</small>`
     : '';
   return `<div class="row"><div><b>${String(r.method||'Deposit')} • #${r.id}</b><small>${r.reference||''} • ${r.created_at||''}${r.payer_reference?' • Ref: '+r.payer_reference:''}</small>${rewards}</div><strong class="${st==='confirmed'?'credit':''}">${st==='confirmed'?'+ PKR '+money(credit):'PKR '+money(r.amount)}<small class="status ${st}">${st}</small></strong></div>`;
  }).join('');
 }catch(e){toast(e.message,true)}
}
async function load(){
 if(!token){location.href='/lobby/';return}
 try{
   const [m]=await Promise.all([
     call('/api/deposit_methods.php?ts='+Date.now(),{headers:headers()}),
     loadWallet(),loadHistory()
   ]);
   methods=m.methods||[];renderMethods();
 }catch(e){toast(e.message,true)}
}

$('#amount').oninput=validate;
$$('[data-amount]').forEach(b=>b.onclick=()=>{$('#amount').value=b.dataset.amount;validate()});
$('#create').onclick=async()=>{
 if(!selected)return;
 try{
  $('#create').disabled=true;
  const j=await call('/api/deposit_create.php',{
    method:'POST',headers:headers(true),
    body:JSON.stringify({method:selected.code,amount:Number($('#amount').value)})
  });
  showPayment(j.deposit);
 }catch(e){toast(e.message,true);validate()}
};
$('#copyDestination').onclick=async()=>{
 const v=$('#destination').textContent.trim();if(!v||v==='—')return;
 try{await navigator.clipboard.writeText(v);toast('Payment destination copied.')}catch(e){toast('Copy failed. Please copy it manually.',true)}
};
$('#submitRef').onclick=async()=>{
 if(!current?.id)return toast('Create a deposit first.',true);
 const ref=$('#payerRef').value.trim();if(!ref)return toast('Enter the transaction/reference ID.',true);
 $('#submitRef').disabled=true;
 try{
  const j=await call('/api/deposit_submit_reference.php',{
    method:'POST',headers:headers(true),
    body:JSON.stringify({deposit_id:Number(current.id),payer_reference:ref})
  });
  toast('Payment reference submitted.');
  showPending(j.deposit);
  await loadHistory();
 }catch(e){toast(e.message,true)}
 finally{$('#submitRef').disabled=false}
};
$('#checkStatus').onclick=()=>checkStatus(true);
$('#historyRefresh').onclick=loadHistory;
$('#refresh').onclick=()=>Promise.all([loadWallet(),loadHistory(),checkStatus(false)]);
$('#back').onclick=()=>location.href='/lobby/';
window.addEventListener('beforeunload',stopPolling);
load();
})();