(()=>{'use strict';

const $=s=>document.querySelector(s);
const $$=s=>[...document.querySelectorAll(s)];

const token=localStorage.getItem('zoo_token')||'';
const mode=localStorage.getItem('zoo_auth_mode')||'';
let selectedMethod='jazzcash';
let payoutRoute='direct';
let activeAccount=null;
let eligibility=null;
let wallet=null;
let settings={};
let submitting=false;

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 niceMethod(m){
  if(m==='jazzcash')return 'JazzCash';
  if(m==='easypaisa')return 'Easypaisa';
  if(m==='usdt_trc20')return 'USDT TRC20';
  if(m==='manual')return 'Manual';
  return m||'Payment account';
}

function date(v){
  if(!v)return '—';
  const d=new Date(String(v).replace(' ','T'));
  return Number.isNaN(d.getTime())?String(v):d.toLocaleString();
}

function toast(msg,error=false){
  const el=$('#toast');
  if(!el)return;
  el.textContent=msg;
  el.classList.toggle('error',!!error);
  el.classList.add('show');
  clearTimeout(toast._t);
  toast._t=setTimeout(()=>el.classList.remove('show'),2200);
}

async function jsonFetch(url,opts={}){
  opts.headers=Object.assign(headers(!!opts.body),opts.headers||{});
  opts.cache='no-store';
  const r=await fetch(url,opts);
  let j={};
  try{j=await r.json();}catch(e){}
  if(!r.ok||j.ok===false)throw new Error(j.error||'Request failed');
  return j;
}

function setState(text){
  const el=$('#state');
  if(el)el.textContent=text;
}

function conditionLabel(key){
  return ({
    registered:'Registered account',
    phone_verified:'Verified mobile',
    withdrawal_account_bound:'Withdrawal account bound',
    minimum_withdrawable_reached:'Minimum withdrawal reached'
  })[key]||key.replaceAll('_',' ');
}

function renderEligibility(){
  const e=eligibility||{};
  const c=e.conditions||{};
  const box=$('#conditions');
  if(box){
    box.innerHTML='';
    Object.entries(c).forEach(([key,ok])=>{
      const row=document.createElement('div');
      row.className='condition '+(ok?'good':'bad');
      row.innerHTML=`<i>${ok?'✓':'!'}</i><span>${conditionLabel(key)}</span><b>${ok?'READY':'REQUIRED'}</b>`;
      box.appendChild(row);
    });
    if(!Object.keys(c).length){
      box.innerHTML='<div class="condition bad"><i>!</i><span>Eligibility unavailable</span><b>CHECK</b></div>';
    }
  }

  const req=e.wager_requirement||null;
  const remaining=Number(req?.remaining_amount ?? e.wager_remaining ?? wallet?.wager_remaining ?? 0);
  const initial=Number(req?.initial_amount||remaining||0);
  $('#wagerRemaining').textContent=money(remaining);
  const wagerBox=$('#wagerBox');
  if(remaining>0){
    wagerBox.classList.remove('hide');
    const done=initial>0?Math.max(0,Math.min(100,100-(remaining/initial*100))):0;
    $('#wagerBar').style.width=done+'%';
  }else{
    wagerBox.classList.add('hide');
    $('#wagerBar').style.width='100%';
  }

  const can=!!e.eligible && !!activeAccount && Number(wallet?.withdrawable_balance||0)>0;
  $('#withdrawBtn').disabled=!can;
  setState(e.eligible?'Eligible':'Requirements');
}

function renderWallet(){
  const w=wallet||{};
  $('#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);
}

function renderAccount(){
  if(activeAccount){
    $('#bindCard').classList.add('hide');
    $('#boundCard').classList.remove('hide');
    $('#boundMethod').textContent=niceMethod(activeAccount.method);
    $('#boundDestination').textContent=activeAccount.destination_masked||'Bound';
    $('#boundName').textContent=activeAccount.account_name||'';
  }else{
    $('#boundCard').classList.add('hide');
    $('#bindCard').classList.remove('hide');
  }
}

function renderHours(){
  const open=settings.withdrawal_open_time||'00:00';
  const close=settings.withdrawal_close_time||'23:59';
  const tz=settings.withdrawal_timezone||'UTC';
  $('#hours').textContent=`Available ${open}–${close} (${tz})`;
}

function renderHistory(rows){
  const box=$('#history');
  if(!rows?.length){
    box.innerHTML='<div class="empty">No withdrawal requests yet.</div>';
    return;
  }
  box.innerHTML='';
  rows.forEach(r=>{
    const el=document.createElement('div');
    const status=String(r.status||'requested').toLowerCase();
    el.className='row';
    el.innerHTML=`
      <div>
        <b>${r.payout_route==='raast_agent'?'Raast Agent → '+niceMethod(r.method):niceMethod(r.method)} • #${r.id}</b>
        <small>${date(r.created_at)}${r.provider_txn_id?' • '+r.provider_txn_id:''}</small>
        ${r.agent_code?`<small>Agent ID: ${r.agent_code} • Verify: ${r.verification_code||'—'} • ${r.agent_status||''}</small>`:''}
        ${r.admin_note?`<small>${String(r.admin_note)}</small>`:''}
      </div>
      <div>
        <strong>PKR ${money(r.amount)}</strong>
        <small class="status ${status}">${status.replaceAll('_',' ')}</small>
      </div>`;
    box.appendChild(el);
  });
}

async function load(){
  if(!token){
    location.href='/lobby/';
    return;
  }
  setState('Loading…');

  try{
    const [acc,elig,hist]=await Promise.all([
      jsonFetch('/api/withdrawal_accounts.php?ts='+Date.now()),
      jsonFetch('/api/withdrawal_eligibility.php?ts='+Date.now()),
      jsonFetch('/api/withdrawals.php?ts='+Date.now())
    ]);

    activeAccount=(acc.accounts||[]).find(a=>Number(a.is_active)!==0)||(acc.accounts||[])[0]||null;
    eligibility=elig.eligibility||{};
    wallet=elig.wallet||{};
    settings=hist.settings||{};
    renderAccount();
    renderWallet();
    renderEligibility();
    renderHours();
    renderHistory(hist.withdrawals||[]);
  }catch(e){
    setState('Unavailable');
    toast(e.message,true);
  }
}

async function bind(){
  if(submitting)return;
  const destination=$('#destination').value.trim();
  const accountName=$('#accountName').value.trim();

  if(!destination){
    toast('Enter the withdrawal account number',true);
    return;
  }

  submitting=true;
  $('#bindBtn').disabled=true;
  try{
    const j=await jsonFetch('/api/withdrawal_account_bind.php',{
      method:'POST',
      body:JSON.stringify({
        method:selectedMethod,
        destination,
        account_name:accountName||null
      })
    });
    toast('Withdrawal account bound');
    activeAccount=j.account||null;
    await load();
  }catch(e){
    toast(e.message,true);
  }finally{
    submitting=false;
    $('#bindBtn').disabled=false;
  }
}

function requestedAmount(){
  return Number($('#amount').value||0);
}

async function submitWithdrawal(){
  if(submitting||!activeAccount)return;
  const amount=requestedAmount();
  if(payoutRoute==='raast_agent'){
    if(!$('#agentCodeInput').value.trim()){
      toast('Enter the Raast Agent ID received from your agent',true);
      return;
    }
    if(!$('#agentConfirmationInput').value.trim()){
      toast('Enter the confirmation code received from your agent',true);
      return;
    }
  }
  if(!Number.isFinite(amount)||amount<=0){
    toast('Enter a valid withdrawal amount',true);
    return;
  }

  submitting=true;
  $('#confirmWithdraw').disabled=true;
  try{
    const j=await jsonFetch('/api/withdrawal_request.php',{
      method:'POST',
      body:JSON.stringify({
        withdrawal_account_id:Number(activeAccount.id),
        amount,
        payout_route:payoutRoute,
        agent_code:payoutRoute==='raast_agent' ? $('#agentCodeInput').value.trim() : null,
        confirmation_code:payoutRoute==='raast_agent' ? $('#agentConfirmationInput').value.trim() : null
      })
    });
    $('#confirm').classList.add('hide');
    $('#amount').value='';    toast('Withdrawal requested');
    await load();
  }catch(e){
    toast(e.message,true);
  }finally{
    submitting=false;
    $('#confirmWithdraw').disabled=false;
  }
}

$$('.method').forEach(btn=>{
  btn.onclick=()=>{
    selectedMethod=btn.dataset.method||'jazzcash';
    $$('.method').forEach(x=>x.classList.toggle('active',x===btn));
    $('#destinationLabel').textContent='Account mobile number';
    $('#destination').placeholder='03XXXXXXXXX';
    $('#destination').inputMode='numeric';
  };
});
$$('.route').forEach(btn=>{
  btn.onclick=()=>{
    payoutRoute=btn.dataset.route||'direct';
    $$('.route').forEach(x=>x.classList.toggle('active',x===btn));
    const isAgent=payoutRoute==='raast_agent';
    $('#agentHint').classList.toggle('hide',!isAgent);
    $('#agentFields').classList.toggle('hide',!isAgent);
  };
});

$$('.quick [data-pct]').forEach(btn=>{
  btn.onclick=()=>{
    const pct=Number(btn.dataset.pct||0);
    const max=Number(wallet?.withdrawable_balance||0);
    $('#amount').value=Math.floor((max*pct/100)*100)/100;
  };
});

$('#bindBtn').onclick=bind;
$('#refresh').onclick=load;
$('#back').onclick=()=>location.href='/lobby/';

$('#withdrawBtn').onclick=()=>{
  const amount=requestedAmount();
  if(!Number.isFinite(amount)||amount<=0){
    toast('Enter a valid withdrawal amount',true);
    return;
  }
  $('#confirmAmount').textContent=money(amount);
  $('#confirmMethod').textContent=payoutRoute==='raast_agent'
    ? 'Raast Agent → '+niceMethod(activeAccount?.method)
    : niceMethod(activeAccount?.method);
  $('#confirm').classList.remove('hide');
};

$('#cancelConfirm').onclick=()=>$('#confirm').classList.add('hide');
$('#confirmWithdraw').onclick=submitWithdrawal;

load();
})();