(()=>{'use strict';
const $=s=>document.querySelector(s),$$=s=>[...document.querySelectorAll(s)];
const token=localStorage.getItem('zoo_token')||'',mode=localStorage.getItem('zoo_auth_mode')||'';
let summary=null,page=1,pages=1;
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'),1800)}
async function api(url,opt={}){opt.headers=Object.assign(headers(!!opt.body),opt.headers||{});opt.cache='no-store';const r=await fetch(url,opt);const j=await r.json().catch(()=>({}));if(!r.ok||!j.ok)throw new Error(j.error||'Request failed');return j}
function linkFor(code){return location.origin+'/lobby/?ref='+encodeURIComponent(code)}
async function loadSummary(){
 if(!token){location.href='/lobby/';return}
 const j=await api('/api/referral_summary.php?ts='+Date.now());summary=j.summary||{};
 const code=summary.referral_code||'';const link=linkFor(code);
 $('#code').textContent=code;$('#link').textContent=link;
 // QR is presentation-only; referral code/link remains fully functional even if this external image is blocked.
 $('#qr').src='https://api.qrserver.com/v1/create-qr-code/?size=220x220&margin=0&data='+encodeURIComponent(link);
 $('#yesterday').textContent=money(summary.yesterday_earnings);$('#direct').textContent=summary.direct_referrals||0;$('#team').textContent=summary.team_members||0;
 $('#directYesterday').textContent=money(summary.direct_earnings_yesterday);$('#teamYesterday').textContent=money(summary.team_earnings_yesterday);
 $('#unclaimed').textContent=money(summary.unclaimed);$('#claimed').textContent=money(summary.claimed);
 const r=summary.rules||{};$('#baseRate').textContent=Number(r.referral_contribution_percent||0)+'%';
 $('#l1').textContent=Number(r.referral_level1_percent||0)+'%';$('#l2').textContent=Number(r.referral_level2_percent||0)+'%';$('#l3').textContent=Number(r.referral_level3_percent||0)+'%';
 $('#receive').disabled=Number(summary.unclaimed||0)<=0;
}
function esc(v){return String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]))}
async function loadDownline(){
 const q=new URLSearchParams({search:$('#search').value.trim(),level:$('#level').value,page:String(page),limit:'20'});
 const j=await api('/api/referral_downline.php?'+q+'&ts='+Date.now());const d=j.downline||{};pages=d.pages||1;page=d.page||1;
 $('#downCount').textContent=(d.total||0)+' members';$('#pageInfo').textContent=page+' / '+pages;
 $('#downRows').innerHTML=(d.rows||[]).length?(d.rows||[]).map(r=>`<div class="down-row">
  <div><small>PLAYER ID</small><b>${esc(r.public_id||r.user_id)}</b><small class="level-badge">LEVEL ${r.level}</small></div>
  <div><small>YESTERDAY</small><b>PKR ${money(r.yesterday_contribution)}</b></div>
  <div><small>TEAM SIZE</small><b>${r.team_size||0}</b></div>
  <div class="extra"><small>TOTAL CONTRIBUTION</small><b>PKR ${money(r.total_contribution)}</b></div>
  <div class="extra"><small>RECHARGE</small><b>PKR ${money(r.recharge_amount)}</b></div>
 </div>`).join(''):'<div class="down-row"><div><b>No downline found.</b></div></div>';
}
$$('[data-tab]').forEach(b=>b.onclick=()=>{$$('[data-tab]').forEach(x=>x.classList.toggle('active',x===b));$('#promoPane').classList.toggle('hide',b.dataset.tab!=='promo');$('#downlinePane').classList.toggle('hide',b.dataset.tab!=='downline');if(b.dataset.tab==='downline')loadDownline().catch(e=>toast(e.message,true))});
$('#copyCode').onclick=()=>navigator.clipboard.writeText(summary?.referral_code||'').then(()=>toast('Promo code copied'));
$('#copyLink').onclick=()=>navigator.clipboard.writeText(linkFor(summary?.referral_code||'')).then(()=>toast('Promo link copied'));
$('#share').onclick=async()=>{const url=linkFor(summary?.referral_code||'');if(navigator.share)await navigator.share({title:'LuckZoo',text:'Join my LuckZoo team',url});else{await navigator.clipboard.writeText(url);toast('Promo link copied')}};
$('#receive').onclick=async()=>{try{const j=await api('/api/referral_claim.php',{method:'POST',body:'{}'});toast('Received PKR '+money(j.claim?.amount));await loadSummary()}catch(e){toast(e.message,true)}};
$('#searchBtn').onclick=()=>{page=1;loadDownline().catch(e=>toast(e.message,true))};$('#prev').onclick=()=>{if(page>1){page--;loadDownline()}};$('#next').onclick=()=>{if(page<pages){page++;loadDownline()}};
$('#back').onclick=()=>location.href='/lobby/';$('#refresh').onclick=()=>{loadSummary().catch(e=>toast(e.message,true));if(!$('#downlinePane').classList.contains('hide'))loadDownline()};
loadSummary().catch(e=>toast(e.message,true));
})();