(()=>{
'use strict';

const $=s=>document.querySelector(s);
const cover=$('#sessionCover');
const toast=$('#toast');
let sessionLoadTimer=null;
let sessionLoadProgress=0;
let sessionNavigating=false;

function sessionLoadCopy(p){
  if(p<18)return ['Starting LuckZoo…','Loading resources…'];
  if(p<42)return ['Checking player session…','Connecting securely…'];
  if(p<68)return ['Syncing player data…','Restoring account and wallet…'];
  if(p<88)return ['Preparing lobby…','Loading lobby resources…'];
  return ['Almost ready…','Finalizing LuckZoo…'];
}
function paintSessionLoad(p,status='',detail=''){
  sessionLoadProgress=Math.max(0,Math.min(100,Math.round(p)));
  const bar=$('#sessionLoadBar'),pct=$('#sessionLoadPercent'),st=$('#sessionLoadStatus'),dt=$('#sessionLoadDetail');
  if(bar)bar.style.width=sessionLoadProgress+'%';
  if(pct)pct.textContent=sessionLoadProgress+'%';
  const c=sessionLoadCopy(sessionLoadProgress);
  if(st)st.textContent=status||c[0];
  if(dt)dt.textContent=detail||c[1];
}
function startSessionLoad(){
  clearInterval(sessionLoadTimer);
  sessionNavigating=false;
  sessionLoadProgress=0;
  paintSessionLoad(0,'Starting LuckZoo…','Loading resources…');
  sessionLoadTimer=setInterval(()=>{
    if(sessionLoadProgress>=92)return;
    const step=sessionLoadProgress<30?3:sessionLoadProgress<65?2:1;
    paintSessionLoad(Math.min(92,sessionLoadProgress+step));
  },120);
}
function stageSessionLoad(p,status,detail=''){
  paintSessionLoad(Math.max(sessionLoadProgress,p),status,detail);
}
function completeSessionLoad(status='Ready',detail='LuckZoo is ready'){
  clearInterval(sessionLoadTimer);
  sessionLoadTimer=null;
  paintSessionLoad(100,status,detail);
}


function note(t){
  toast.textContent=t;
  toast.classList.add('show');
  clearTimeout(note.t);
  note.t=setTimeout(()=>toast.classList.remove('show'),1800);
}
function setReady(ok,text){
  $('#sessionStatus').textContent=text;
  document.querySelector('.status-pill').classList.toggle('ready',!!ok);
  $('#playZoo').disabled=!ok;
  $('#playHint').textContent=ok?'Session ready':'Preparing session…';
}
function saveSession(token,mode){
  localStorage.setItem('zoo_token',token);
  localStorage.setItem('zoo_auth_mode',mode);
  if(mode==='guest' && token){
    localStorage.setItem('zoo_device_guest_token',token);
  }
}
function clearSession(removeDeviceGuest=false){
  localStorage.removeItem('zoo_token');
  localStorage.removeItem('zoo_auth_mode');
  if(removeDeviceGuest){
    localStorage.removeItem('zoo_device_guest_token');
  }
}
function playerHeaders(json=false){
  const token=localStorage.getItem('zoo_token')||'';
  const mode=localStorage.getItem('zoo_auth_mode')||'';
  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;
}
async function attachReferralFromUrl(){
  const ref=new URLSearchParams(location.search).get('ref');
  if(!ref||!localStorage.getItem('zoo_token'))return;
  try{
    const r=await fetch('/api/referral_attach.php',{
      method:'POST',headers:playerHeaders(true),
      body:JSON.stringify({referral_code:ref}),cache:'no-store'
    });
    const j=await r.json();
    if(r.ok&&j.ok&&j.referral?.attached)note('Referral connected');
  }catch(e){}
  const u=new URL(location.href);u.searchParams.delete('ref');
  history.replaceState({},'',u.pathname+(u.searchParams.toString()?'?'+u.searchParams:''));
}
function setWallet(wallet){
  // Lobby must show the same PLAYABLE balance as the game:
  // cash_balance + bonus_balance.
  const cash=Number(wallet?.cash_balance ?? 0);
  const bonus=Number(wallet?.bonus_balance ?? 0);
  const fallback=Number(wallet?.balance ?? 0);
  const playable=(cash||bonus)?(cash+bonus):fallback;
  $('#balance').textContent=Number(playable||0).toFixed(2);
}
function setGuest(guest){
  const id=guest?.user_id ?? guest?.id;
  const custom=String(guest?.display_name||localStorage.getItem('lz_display_name')||'').trim();
  if(custom)localStorage.setItem('lz_display_name',custom);
  $('#playerName').textContent=custom||(id?`Guest${id}`:'Guest');
  $('#accountType').textContent='';
  $('#profileBtn').classList.add('guest-name-only');
}
function setRegistered(user){
  $('#profileBtn').classList.remove('guest-name-only');
  const cached=String(localStorage.getItem('lz_display_name')||'').trim();
  $('#playerName').textContent=cached||user?.display_name||user?.name||user?.username||user?.phone_local||'Player';
  $('#accountType').textContent='Bound Account';
}

async function createGuest(){
  const r=await fetch('/api/guest_create.php',{
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:'{}',
    cache:'no-store'
  });
  const j=await r.json();
  if(!r.ok||!j.ok||!j.guest?.session_token)throw new Error(j.error||'Guest session failed');
  saveSession(j.guest.session_token,'guest');
  setGuest(j.guest);
  setWallet(j.wallet);
  return true;
}

async function resumeGuest(token){
  const r=await fetch('/api/guest_resume.php',{
    method:'POST',
    headers:{'Content-Type':'application/json','X-Guest-Session':token},
    body:JSON.stringify({session_token:token}),
    cache:'no-store'
  });

  let j={};
  try{ j=await r.json(); }catch(e){}

  if(!r.ok||!j.ok){
    const err=new Error(j.error||'Guest resume failed');
    err.status=r.status;
    throw err;
  }

  // Keep the same guest on this browser/device across reloads.
  saveSession(token,'guest');
  setGuest(j.guest);
  setWallet(j.wallet);
  return true;
}


async function resumeGuestSafely(primaryToken){
  const deviceToken=localStorage.getItem('zoo_device_guest_token')||'';
  const candidates=[...new Set([primaryToken,deviceToken].filter(Boolean))];
  let lastError=null;

  for(const token of candidates){
    for(let attempt=0;attempt<2;attempt++){
      try{
        await resumeGuest(token);
        return true;
      }catch(e){
        lastError=e;

        // 401 means this particular token is really invalid; do not retry it.
        if(Number(e.status)===401)break;

        // Network/temporary server issue: brief retry before giving up.
        if(attempt===0){
          await new Promise(resolve=>setTimeout(resolve,350));
        }
      }
    }
  }

  throw lastError||new Error('Guest session could not be resumed');
}

async function resumeRegistered(token){
  const r=await fetch('/api/account_me.php',{
    headers:{'Authorization':'Bearer '+token},
    cache:'no-store'
  });
  const j=await r.json();
  if(!r.ok||!j.ok)throw new Error(j.error||'Account resume failed');
  setRegistered(j.user);
  setWallet(j.wallet);
  return true;
}


async function syncLobbyIdentity(){
  const token=localStorage.getItem('zoo_token')||'';
  const mode=localStorage.getItem('zoo_auth_mode')||'';
  if(!token)return;

  try{
    const r=await fetch('/api/account_center.php?ts='+Date.now(),{
      headers:playerHeaders(),
      cache:'no-store'
    });
    const j=await r.json();
    if(!r.ok||!j.ok)return;

    const a=j.account||{};
    const uid=Number(a.user_id||0);

    if(a.auth_mode==='guest' || a.registered===false){
      const custom=String(a.display_name||localStorage.getItem('lz_display_name')||'').trim();
      if(custom)localStorage.setItem('lz_display_name',custom);
      $('#playerName').textContent=custom||(uid?`Guest${uid}`:'Guest');
      $('#accountType').textContent='';
      $('#profileBtn').classList.add('guest-name-only');
    }else{
      $('#profileBtn').classList.remove('guest-name-only');
      const custom=String(a.display_name||'').trim();
      if(custom)localStorage.setItem('lz_display_name',custom);
      const internal=String(a.internal_login_id||'').trim();

      $('#playerName').textContent=
        custom ||
        (internal?`ID ${internal}`:'') ||
        (uid?`Player #${uid}`:'Player');

      $('#accountType').textContent=internal?`ID:${internal}`:(uid?`ID:${uid}`:'Bound Account');
    }

    if(j.wallet)setWallet(j.wallet);
  }catch(e){}
}

async function bindStatus(){
  const token=localStorage.getItem('zoo_token')||'';
  const mode=localStorage.getItem('zoo_auth_mode')||'';
  if(!token)return;
  const h={};
  if(mode==='guest')h['X-Guest-Session']=token;
  else h['Authorization']='Bearer '+token;

  try{
    const r=await fetch('/api/account_bind_status.php',{headers:h,cache:'no-store'});
    const j=await r.json();
    if(j.ok&&j.binding){
      const bound=!!(j.binding.phone_e164||j.binding.phone_verified_at||j.binding.internal_login_id);
      const bt=$('#bindText'); if(bt)bt.textContent=bound?'Account already secured':'Secure your player ID';
    }
  }catch(e){}
}







/* Native compact Withdraw panel ----------------------------------------- */
function wdMoney(v){return Number(v||0).toFixed(2)}

async function refreshWithdrawPanel(){
  try{
    const r=await fetch('/api/account_center.php?ts='+Date.now(),{
      headers:playerHeaders(),cache:'no-store'
    });
    const j=await r.json();
    if(!r.ok||!j.ok)throw new Error(j.error||'Could not load withdrawal status');

    const a=j.account||{}, w=j.wallet||{};
    $('#wdWithdrawable').textContent=wdMoney(w.withdrawable_balance);
    $('#wdWager').textContent=wdMoney(w.wager_remaining);

    $('#wdGuestState').classList.add('hide');
    $('#wdNoAccountState').classList.add('hide');
    $('#wdReadyState').classList.add('hide');

    // Guest sessions cannot use the registered-session withdrawal endpoint.
    // Show the proper action instead of exposing "Missing session token".
    if(!a.registered){
      $('#wdGuestState').classList.remove('hide');
      return;
    }

    if(!a.withdrawal_bound){
      $('#wdNoAccountState').classList.remove('hide');
      return;
    }

    const wa=a.withdrawal_account||{};
    const method=wa.method==='jazzcash'?'JazzCash':wa.method==='easypaisa'?'Easypaisa':'Payment account';
    $('#wdDestination').textContent=method+' • '+(wa.destination_masked||'Bound');
    $('#wdReadyState').classList.remove('hide');
  }catch(e){
    note(e.message||'Could not load withdrawal status');
  }
}
function openWithdrawPanel(){
  const p=$('#withdrawPanel');
  p.classList.remove('hide');
  p.setAttribute('aria-hidden','false');
  refreshWithdrawPanel();
}
function closeWithdrawPanel(){
  const p=$('#withdrawPanel');
  p.classList.add('hide');
  p.setAttribute('aria-hidden','true');
}
$('#withdrawPanelClose').onclick=closeWithdrawPanel;
$('#withdrawPanel').addEventListener('click',e=>{if(e.target===$('#withdrawPanel'))closeWithdrawPanel();});
$('#wdOpenBind').onclick=()=>{closeWithdrawPanel();openBindPanel();};
$('#wdOpenFull').onclick=()=>{closeWithdrawPanel();openFullPage('withdraw');};
$('#wdContinue').onclick=()=>{closeWithdrawPanel();openFullPage('withdraw');};
/* End native compact Withdraw panel ------------------------------------- */


/* Native compact Bonuses panel ----------------------------------------- */
function bnMoney(v){return Number(v||0).toFixed(2)}

async function refreshBonusPanel(){
  try{
    const r=await fetch('/api/account_center.php?ts='+Date.now(),{
      headers:playerHeaders(),
      cache:'no-store'
    });
    const j=await r.json();
    if(!r.ok||!j.ok)throw new Error(j.error||'Could not load bonuses');

    const a=j.account||{};
    const w=j.wallet||{};
    const playable=Number(w.cash_balance||0)+Number(w.bonus_balance||0);

    $('#bnPlayable').textContent=bnMoney(playable);
    $('#bnBonus').textContent=bnMoney(w.bonus_balance);
    $('#bnWithdrawable').textContent=bnMoney(w.withdrawable_balance);

    const hasDeposit=!!a.has_successful_deposit;
    $('#bnWelcomeState').textContent=hasDeposit?'Welcome bonus already credited':'First confirmed deposit';
    $('#bnWelcomeBadge').textContent=hasDeposit?'CLAIMED':'AVAILABLE';
    $('#bnWelcomeBadge').classList.toggle('claimed',hasDeposit);

    const bound=!!(a.phone_verified||a.internal_login_bound);
    $('#bnBindState').textContent=bound?'Binding completed':'Verify and bind your mobile';
    $('#bnBindBadge').textContent=bound?'CLAIMED':'AVAILABLE';
    $('#bnBindBadge').classList.toggle('claimed',bound);
  }catch(e){
    note(e.message||'Could not load bonus status');
  }
}

function openBonusPanel(){
  const panel=$('#bonusPanel');
  panel.classList.remove('hide');
  panel.setAttribute('aria-hidden','false');
  refreshBonusPanel();
}
function closeBonusPanel(){
  const panel=$('#bonusPanel');
  panel.classList.add('hide');
  panel.setAttribute('aria-hidden','true');
}
$('#bonusPanelClose').onclick=closeBonusPanel;
$('#bonusPanel').addEventListener('click',e=>{if(e.target===$('#bonusPanel'))closeBonusPanel();});

document.querySelectorAll('[data-bonus-action]').forEach(btn=>{
  btn.onclick=()=>{
    const action=btn.dataset.bonusAction;
    closeBonusPanel();
    if(action==='bind'){openBindPanel();return}
    if(action==='deposit'){openFullPage('deposit');return}
    if(action==='checkin'){openFullPage('checkin');return}
    if(action==='vip'){openFullPage('vip');return}
  };
});
/* End native compact Bonuses panel ------------------------------------- */


/* Generic compact module panel ------------------------------------------ */
const moduleMap={
  deposit:{title:'Deposit',kicker:'ADD FUNDS',icon:'💳',url:'/account/manual-deposit.html'},
  withdraw:{title:'Withdraw',kicker:'CASH OUT',icon:'⇩',url:'/account/withdraw.html'},
  bind:{title:'Bind Account',kicker:'ACCOUNT SECURITY',icon:'🔗',url:'/account/bind.html'},
  checkin:{title:'Daily Check-In',kicker:'DAILY REWARD',icon:'📅',url:'/account/checkin.html'},
  vip:{title:'VIP Minute',kicker:'ACTIVE REWARDS',icon:'👑',url:'/account/vip.html'},
  history:{title:'Transactions',kicker:'HISTORY & RECORDS',icon:'◷',url:'/account/transactions.html'},
  bonus:{title:'Bonuses & Rewards',kicker:'OFFERS',icon:'🎁',url:'/account/bonuses.html'},
  refer:{title:'Refer & Earn',kicker:'INVITE FRIENDS',icon:'👥',url:'/account/refer.html'},
  account:{title:'Account & Security',kicker:'PLAYER ACCOUNT',icon:'👤',url:'/account/'},
  settings:{title:'Settings',kicker:'ACCOUNT SETTINGS',icon:'⚙',url:'/account/settings.html'}
};

let moduleCurrent='';

function openFullPage(kind){
  const cfg=moduleMap[kind];
  if(!cfg)return;
  location.href=cfg.url;
}

function openModulePanel(kind){
  const cfg=moduleMap[kind];
  if(!cfg)return;

  moduleCurrent=kind;
  $('#modulePanelTitle').textContent=cfg.title;
  $('#modulePanelKicker').textContent=cfg.kicker;
  $('#modulePanelIcon').textContent=cfg.icon;
  $('#moduleLoading').classList.remove('hide');

  const panel=$('#modulePanel');
  const card=panel.querySelector('.module-card');
  const frame=$('#moduleFrame');

  // Only Deposit needs a taller compact window so amount presets,
  // create-deposit button and lower controls stay visible.
  card.classList.toggle('module-card-deposit',kind==='deposit');
  card.classList.toggle('module-card-refer',kind==='refer');

  panel.classList.remove('hide');
  panel.setAttribute('aria-hidden','false');

  const sep=cfg.url.includes('?')?'&':'?';
  frame.src=cfg.url+sep+'embed=1&ts='+Date.now();
}

function closeModulePanel(){
  const panel=$('#modulePanel');
  const frame=$('#moduleFrame');
  const card=panel.querySelector('.module-card');
  panel.classList.add('hide');
  panel.setAttribute('aria-hidden','true');
  card.classList.remove('module-card-deposit');
  card.classList.remove('module-card-refer');
  frame.src='about:blank';
  moduleCurrent='';
  syncLobbyIdentity();
  bindStatus();
}

$('#modulePanelClose').onclick=closeModulePanel;
$('#modulePanel').addEventListener('click',e=>{if(e.target===$('#modulePanel'))closeModulePanel();});

function prepareEmbeddedModule(){
  try{
    const frame=$('#moduleFrame');
    const doc=frame.contentDocument;
    const win=frame.contentWindow;
    if(!doc||!win)return;

    const path=win.location.pathname;
    if(path==='/lobby/' || path==='/lobby'){
      closeModulePanel();
      return;
    }

    let style=doc.getElementById('luckzoo-embed-style');
    if(!style){
      style=doc.createElement('style');
      style.id='luckzoo-embed-style';
      style.textContent=`
        html,body{
          min-height:0!important;
          width:100%!important;
          max-width:none!important;
          margin:0!important;
          background:#041c12!important;
          overflow:hidden!important;
          scrollbar-width:none!important;
        }
        html::-webkit-scrollbar,body::-webkit-scrollbar{display:none!important}

        /* The outer LuckZoo mini panel supplies its own title/close button. */
        body>header,.page>header,.topbar{display:none!important}

        /* Prevent desktop page wrappers from becoming a narrow column after scaling. */
        .page,.wrap,.wrapper,.container,.shell,main{
          width:100%!important;
          max-width:none!important;
          margin-left:0!important;
          margin-right:0!important;
          box-sizing:border-box!important;
        }

        .done[href="/lobby/"],a[href="/lobby/"].done{display:none!important}

        /* Compact overlay mode: keep primary actions, hide secondary long logs/footer areas. */
        body.luckzoo-compact .history,
        body.luckzoo-compact .recent,
        body.luckzoo-compact .activity,
        body.luckzoo-compact .account-meta,
        body.luckzoo-compact footer{display:none!important}
      `;
      doc.head.appendChild(style);
    }

    // Refer page needs a tighter embedded layout than the full account page.
    if(path.includes('/account/refer')){
      let rs=doc.getElementById('luckzoo-refer-compact-style');
      if(!rs){
        rs=doc.createElement('style');
        rs.id='luckzoo-refer-compact-style';
        rs.textContent=`
          html,body,.page,.wrap,.wrapper,.container,.shell,main{
            min-height:0!important; height:auto!important;
          }
          body{padding-bottom:0!important}
          main,.page,.wrap,.wrapper,.container,.shell{padding-bottom:0!important}
          footer{display:none!important}
        `;
        doc.head.appendChild(rs);
      }
    }

    doc.body.classList.add('luckzoo-compact');

    doc.querySelectorAll('a[href="/lobby/"],a[href="/lobby"]').forEach(a=>{
      a.addEventListener('click',ev=>{
        ev.preventDefault();
        closeModulePanel();
      });
    });
  }catch(e){}
}

function fitEmbeddedModule(){
  try{
    const frame=$('#moduleFrame');
    const doc=frame.contentDocument;
    if(!doc||!doc.body)return;

    const body=doc.body;
    const root=doc.documentElement;

    // Reset previous fit before measuring.
    body.style.zoom='1';
    body.style.width='100%';
    root.style.width='100%';
    root.style.overflow='hidden';
    body.style.overflow='hidden';

    const availableH=Math.max(1,frame.clientHeight-4);
    const naturalH=Math.max(body.scrollHeight,root.scrollHeight);

    // Vertical fit only. Do NOT enlarge the document width; that was the cause
    // of the narrow/right-shifted pages in V2.
    let scale=Math.min(1,availableH/Math.max(1,naturalH));
    scale=Math.max(.78,scale);

    body.style.zoom=String(scale);

    // Compensate zoom so the usable visual width remains the iframe width.
    // The page wrappers themselves are forced to 100%, preventing side drift.
    body.style.width=(100/scale)+'%';

    // Anchor content to the left edge after compensation; no auto-centering.
    body.style.marginLeft='0';
    body.style.marginRight='0';
    root.style.overflow='hidden';
    body.style.overflow='hidden';
  }catch(e){}
}

$('#moduleFrame').addEventListener('load',()=>{
  $('#moduleLoading').classList.add('hide');

  try{
    const frame=$('#moduleFrame');
    const doc=frame.contentDocument;
    const win=frame.contentWindow;
    if(!doc||!win)return;

    prepareEmbeddedModule();

    // Fit after initial paint and after API-driven content arrives.
    requestAnimationFrame(fitEmbeddedModule);
    setTimeout(fitEmbeddedModule,120);
    setTimeout(fitEmbeddedModule,420);
    setTimeout(fitEmbeddedModule,900);

    if(win.__luckzooFitObserver)win.__luckzooFitObserver.disconnect();
    let fitTimer=0;
    win.__luckzooFitObserver=new MutationObserver(()=>{
      clearTimeout(fitTimer);
      fitTimer=setTimeout(()=>{
        prepareEmbeddedModule();
        fitEmbeddedModule();
      },100);
    });
    win.__luckzooFitObserver.observe(doc.body,{
      childList:true,subtree:true,characterData:true,attributes:true
    });
  }catch(e){}
});

window.addEventListener('resize',()=>{
  if(!$('#modulePanel').classList.contains('hide')){
    prepareEmbeddedModule();
    fitEmbeddedModule();
  }
});

/* End generic compact module panel -------------------------------------- */


/* Compact Bind panel ------------------------------------------------------ */
let bpVerificationId=0;

function bpSetStatus(text,type=''){
  const el=$('#bpStatus');
  if(!el)return;
  el.textContent=text;
  el.classList.toggle('ok',type==='ok');
  el.classList.toggle('error',type==='error');
}

async function bpCall(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 bpRender(binding={}){
  const phoneBound=!!binding.phone_verified_at;
  const currentMode=localStorage.getItem('zoo_auth_mode')||'';
  const registered=currentMode==='registered';

  $('#bpPhoneBound').classList.toggle('hide',!phoneBound);
  if(phoneBound){
    $('#bpBoundPhone').textContent=binding.phone_local||binding.phone_e164||binding.phone_national||'Verified';
  }

  if(registered && phoneBound){
    $('#bpPhoneForm').classList.add('hide');
    $('#bpPasswordForm').classList.add('hide');
    $('#bpRegistered').classList.remove('hide');
    bpSetStatus('Account already secured','ok');
    return;
  }

  $('#bpRegistered').classList.add('hide');

  if(phoneBound){
    $('#bpPhoneForm').classList.add('hide');
    $('#bpPasswordForm').classList.toggle('hide',registered);
    bpSetStatus(registered?'Account is secured':'Mobile verified — create your login password','ok');
  }else{
    $('#bpPhoneForm').classList.remove('hide');
    $('#bpPasswordForm').classList.add('hide');
    bpSetStatus('Verify your mobile number to secure this Player ID');
  }
}

async function bpRefresh(){
  try{
    bpSetStatus('Checking account…');
    const j=await bpCall('/api/account_bind_status.php',{headers:playerHeaders()});
    bpRender(j.binding||{});
  }catch(e){
    bpSetStatus(e.message||'Could not load binding status','error');
  }
}

function openBindPanel(){
  const panel=$('#bindPanel');
  if(!panel)return;
  bpVerificationId=0;
  $('#bpOtp').value='';
  $('#bpPassword').value='';
  $('#bpPassword2').value='';
  $('#bpOtpRow').classList.add('hide');
  panel.classList.remove('hide');
  panel.setAttribute('aria-hidden','false');
  bpRefresh();
}

function closeBindPanel(){
  const panel=$('#bindPanel');
  if(!panel)return;
  panel.classList.add('hide');
  panel.setAttribute('aria-hidden','true');
  bindStatus();
  syncLobbyIdentity();
  setTimeout(()=>refreshStartupPopups(),180);
}

$('#bindPanelClose').onclick=closeBindPanel;
$('#bindPanel').addEventListener('click',e=>{if(e.target===$('#bindPanel'))closeBindPanel();});

$('#bpRequestOtp').onclick=async()=>{
  const phone=$('#bpPhone').value.trim();
  if(!phone){bpSetStatus('Enter your mobile number','error');return}
  try{
    bpSetStatus('Creating verification request…');
    const j=await bpCall('/api/request_phone_verification.php',{
      method:'POST',headers:playerHeaders(true),body:JSON.stringify({phone})
    });
    bpVerificationId=Number(j.verification?.verification_id||0);
    if(!bpVerificationId)throw new Error('Verification request was not created');
    $('#bpOtpRow').classList.remove('hide');
    bpSetStatus('OTP sent — enter the 6-digit code.','ok');
    $('#bpOtp').focus();
  }catch(e){bpSetStatus(e.message||'OTP request failed','error')}
};

$('#bpVerifyOtp').onclick=async()=>{
  const code=$('#bpOtp').value.trim();
  if(!bpVerificationId||!code){bpSetStatus('Request and enter the OTP first','error');return}
  try{
    bpSetStatus('Verifying mobile…');
    const j=await bpCall('/api/verify_bind_phone.php',{
      method:'POST',headers:playerHeaders(true),
      body:JSON.stringify({verification_id:bpVerificationId,code})
    });
    bpRender(j.binding||{});
    $('#bpPhoneForm').classList.add('hide');
    $('#bpPasswordForm').classList.remove('hide');
    bpSetStatus('Mobile verified — create your login password','ok');
  }catch(e){bpSetStatus(e.message||'Verification failed','error')}
};

$('#bpSecureAccount').onclick=async()=>{
  const currentMode=localStorage.getItem('zoo_auth_mode')||'';
  if(currentMode!=='guest'){
    bpSetStatus('Account is already registered','ok');
    return;
  }
  const p=$('#bpPassword').value;
  const p2=$('#bpPassword2').value;
  if(p.length<8){bpSetStatus('Password must be at least 8 characters','error');return}
  if(p!==p2){bpSetStatus('Passwords do not match','error');return}
  try{
    bpSetStatus('Securing account…');
    const j=await bpCall('/api/complete_account_registration.php',{
      method:'POST',headers:playerHeaders(true),body:JSON.stringify({password:p})
    });
    if(j.user?.session_token){
      localStorage.setItem('zoo_token',j.user.session_token);
      localStorage.setItem('zoo_auth_mode','registered');
    }
    bpRender(j.binding||{});
    $('#bpPasswordForm').classList.add('hide');
    $('#bpRegistered').classList.remove('hide');
    bpSetStatus('Account secured. Balance and history preserved.','ok');
    await syncLobbyIdentity();
    await bindStatus();
  }catch(e){bpSetStatus(e.message||'Could not secure account','error')}
};
/* End compact Bind panel -------------------------------------------------- */

let startupQueue=[];
let startupCurrent=null;
let startupRefreshTimer=null;
let startupRunning=false;

function showNextStartup(){
  if(!startupQueue.length){
    startupCurrent=null;
    $('#startupModal').classList.add('hide');
    $('#startupModal').setAttribute('aria-hidden','true');
    return;
  }

  startupCurrent=startupQueue.shift();
  const kind=startupCurrent.kind;
  const art=$('#startupArtwork');
  const img=$('#startupImage');

  art.classList.toggle('popup-bind',kind==='bind');
  art.classList.toggle('popup-deposit',kind==='deposit');

  img.src=kind==='bind'
    ? '/assets/popup-bind.webp?v=2'
    : '/assets/popup-deposit.webp?v=2';

  img.alt=kind==='bind' ? 'Bind your LuckZoo account' : 'Make a LuckZoo deposit';

  // The deposit artwork has no "Maybe later" label, so only the X closes it.
  $('#startupLater').style.display=kind==='bind' ? 'block' : 'none';

  $('#startupModal').classList.remove('hide');
  $('#startupModal').setAttribute('aria-hidden','false');
}

function dismissStartup(){
  $('#startupModal').classList.add('hide');
  $('#startupModal').setAttribute('aria-hidden','true');
  setTimeout(showNextStartup,120);
}

async function refreshStartupPopups(){
  if(startupRunning)return;
  startupRunning=true;

  try{
    const r=await fetch('/api/account_center.php?ts='+Date.now(),{
      headers:playerHeaders(),
      cache:'no-store'
    });
    const j=await r.json();
    if(!r.ok||!j.ok)return;

    const a=j.account||{};

    // Binding is complete when the verified mobile or permanent internal login
    // binding exists. Once complete, the Bind popup never enters the queue again.
    const bound=!!(a.phone_verified||a.internal_login_bound);

    // First Deposit stops only after the backend reports a successful/credited deposit.
    const hasDeposit=!!a.has_successful_deposit;

    startupQueue=[];

    if(!bound){
      startupQueue.push({
        kind:'bind',
        icon:'🔗',
        kicker:'SECURE YOUR PLAYER ID',
        title:'Bind Your Account',
        text:'Bind your mobile account to protect your LuckZoo Player ID.<div class="startup-reward"><small>BINDING REWARD</small><strong>PKR 10</strong></div>',
        action:'BIND ACCOUNT',
        url:'/account/bind.html'
      });
    }

    if(!hasDeposit){
      startupQueue.push({
        kind:'deposit',
        icon:'🎁',
        kicker:'WELCOME OFFER',
        title:'First Deposit Bonus',
        text:'Make your first deposit with JazzCash or Easypaisa.<div class="startup-reward"><small>FIRST DEPOSIT BONUS</small><strong>PKR 65</strong><em>+ 5% on every deposit</em></div>',
        action:'DEPOSIT NOW',
        url:'/account/manual-deposit.html'
      });
    }

    // Do not interrupt an already-open popup. The next one-minute check will
    // refresh the conditions again.
    if($('#startupModal').classList.contains('hide')){
      showNextStartup();
    }
  }catch(e){
    // Lobby remains usable if the promotional check temporarily fails.
  }finally{
    startupRunning=false;
  }
}

function startStartupReminderLoop(){
  clearInterval(startupRefreshTimer);

  // Immediate sequence after lobby login.
  setTimeout(()=>refreshStartupPopups(),420);

  // Then re-check every 60 seconds for as long as player remains in lobby.
  startupRefreshTimer=setInterval(()=>{
    if(document.visibilityState==='visible'){
      refreshStartupPopups();
    }
  },60000);
}

$('#startupClose').onclick=dismissStartup;
$('#startupLater').onclick=dismissStartup;
$('#startupModal').addEventListener('click',e=>{if(e.target===$('#startupModal'))dismissStartup();});

$('#startupAction').onclick=()=>{
  if(!startupCurrent)return;
  if(startupCurrent.kind==='bind'){
    $('#startupModal').classList.add('hide');
    $('#startupModal').setAttribute('aria-hidden','true');
    startupCurrent=null;
    openBindPanel();
    return;
  }
  if(startupCurrent.kind==='deposit'){
    $('#startupModal').classList.add('hide');
    $('#startupModal').setAttribute('aria-hidden','true');
    startupCurrent=null;
    openModulePanel('deposit');
    return;
  }
  location.href=startupCurrent.url;
};

async function boot(){
  startSessionLoad();
  setReady(false,'Connecting');
  stageSessionLoad(10,'Loading resources…','Preparing lobby components…');

  let token=localStorage.getItem('zoo_token')||'';
  let mode=localStorage.getItem('zoo_auth_mode')||'';
  stageSessionLoad(24,'Checking player session…','Connecting securely…');

  try{
    if(token&&mode==='guest'){
      try{
        await resumeGuestSafely(token);
      }catch(e){
        // Only a confirmed invalid/expired guest session should send the player
        // back to auth. A temporary network/API error must not destroy the guest.
        if(Number(e.status)===401){
          clearSession(true);
          location.replace('/auth/');
          return;
        }
        setReady(false,'Retry');
        note('Could not reconnect guest session. Refresh to retry.');
        return;
      }
    }else if(token&&mode==='registered'){
      try{await resumeRegistered(token)}
      catch(e){clearSession();location.replace('/auth/');return}
    }else if(token||mode){
      const savedGuest=localStorage.getItem('zoo_device_guest_token')||'';
      if(savedGuest){
        try{
          await resumeGuestSafely(savedGuest);
          token=savedGuest;
          mode='guest';
        }catch(e){
          if(Number(e.status)===401) clearSession(true);
          else clearSession(false);
        }
      }else{
        clearSession(false);
        token='';
        mode='';
      }
    }

    if(!localStorage.getItem('zoo_token')){
      const savedGuest=localStorage.getItem('zoo_device_guest_token')||'';
      if(savedGuest){
        try{
          await resumeGuestSafely(savedGuest);
        }catch(e){
          if(Number(e.status)===401){
            clearSession(true);
            location.replace('/auth/');
            return;
          }
          setReady(false,'Retry');
          note('Could not reconnect guest session. Refresh to retry.');
          return;
        }
      }else{
        location.replace('/auth/');
        return;
      }
    }

    stageSessionLoad(70,'Syncing player data…','Restoring account and wallet…');
    setReady(true,'Online');
    await attachReferralFromUrl();
    await syncLobbyIdentity();
    await bindStatus();
    stageSessionLoad(92,'Preparing lobby…','Finalizing LuckZoo…');
    startStartupReminderLoop();
  }catch(e){
    setReady(false,'Retry');
    note(e.message||'Could not start player session');
  }finally{
    completeSessionLoad('Ready','Welcome to LuckZoo');
    setTimeout(()=>cover.classList.add('hide'),220);
  }
}

function play(){
  if(!localStorage.getItem('zoo_token')){
    note('Player session is not ready yet');
    return;
  }
  cover.classList.remove('hide');
  startSessionLoad();
  stageSessionLoad(18,'Opening Zoo Roulette…','Loading game resources…');
  sessionNavigating=true;
  location.href='/?from=lobby';
}

$('#playZoo').onclick=play;$('#profileBtn').onclick=()=>openFullPage('account');
const gameCard=$('#gameCard'); if(gameCard)gameCard.onclick=play;
const footerGame=$('#footerGame'); if(footerGame)footerGame.onclick=play;

document.querySelectorAll('[data-module]').forEach(el=>{
  el.onclick=()=>{
    const m=el.dataset.module;

    // Account/features now open as normal full pages.
    // This removes the iframe/mini-card restriction and lets each page
    // use its own natural height + vertical scrolling.
    if(moduleMap[m]){
      openFullPage(m);
      return;
    }

    note('This module is next.');
  };
});

window.addEventListener('focus',()=>{
  const token=localStorage.getItem('zoo_token')||'';
  const mode=localStorage.getItem('zoo_auth_mode')||'';
  if(!token)return;
  if(mode==='guest'){
    resumeGuestSafely(token).then(()=>syncLobbyIdentity()).catch(()=>{});
  }else if(mode==='registered'){
    resumeRegistered(token).then(()=>syncLobbyIdentity()).catch(()=>{});
  }
});

boot();
})();