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

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)}
function save(token,mode){
  localStorage.setItem('zoo_token',token);
  localStorage.setItem('zoo_auth_mode',mode);
  if(mode==='guest'){
    localStorage.setItem('zoo_device_guest_token',token);
  }else if(mode==='registered'){
    localStorage.removeItem('zoo_device_guest_token');
  }
}
function clear(){localStorage.removeItem('zoo_token');localStorage.removeItem('zoo_auth_mode')}
function phone(raw){let n=String(raw||'').replace(/\D/g,'');if(n.startsWith('92')&&n.length===12)return '+'+n;if(n.startsWith('0')&&n.length===11)return '+92'+n.slice(1);if(n.length===10&&n.startsWith('3'))return '+92'+n;return raw.trim()}
async function api(url,body){const r=await fetch(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body||{}),cache:'no-store'});const j=await r.json().catch(()=>({}));if(!r.ok||!j.ok)throw new Error(j.error||'Request failed');return j}
let loaderTimer=null;
let loaderProgress=0;
let loaderNavigating=false;

function loaderCopy(p){
  if(p<18)return ['Starting LuckZoo…','Loading resources…'];
  if(p<38)return ['Loading resources…','Preparing secure components…'];
  if(p<58)return ['Checking player session…','Connecting securely…'];
  if(p<78)return ['Syncing player data…','Restoring your LuckZoo session…'];
  return ['Preparing your lobby…','Almost ready…'];
}

function paintLoader(p,status='',detail=''){
  const l=$('#loader'); if(!l)return;
  loaderProgress=Math.max(0,Math.min(100,Math.round(p)));
  const bar=$('#loaderBar'),pct=$('#loaderPercent'),st=$('#loaderStatus'),dt=$('#loaderDetail');
  if(bar)bar.style.width=loaderProgress+'%';
  if(pct)pct.textContent=loaderProgress+'%';
  const copy=loaderCopy(loaderProgress);
  if(st)st.textContent=status||copy[0];
  if(dt)dt.textContent=detail||copy[1];
}

function startLoader(status='Starting LuckZoo…',detail='Loading resources…'){
  loaderNavigating=false;
  clearInterval(loaderTimer);
  const l=$('#loader'); if(l)l.classList.remove('hide');
  paintLoader(0,status,detail);
  loaderTimer=setInterval(()=>{
    if(loaderProgress>=92)return;
    let step=loaderProgress<30?3:loaderProgress<65?2:1;
    paintLoader(Math.min(92,loaderProgress+step));
  },120);
}

function setLoaderStage(p,status,detail=''){
  if(p>loaderProgress)paintLoader(p,status,detail);
  else paintLoader(loaderProgress,status,detail);
}

function hideLoader(){
  if(loaderNavigating)return;
  clearInterval(loaderTimer);
  loaderTimer=null;
  const l=$('#loader');
  if(l)l.classList.add('hide');
  document.body.classList.remove('auth-booting');
}

function completeLoader(status='Ready',detail='Opening LuckZoo…',done=null){
  clearInterval(loaderTimer);
  loaderTimer=null;
  paintLoader(100,status,detail);
  setTimeout(()=>{if(done)done();else hideLoader()},180);
}

function enter(){
  loaderNavigating=true;
  completeLoader('Ready','Opening your LuckZoo lobby…',()=>location.replace('/lobby/'));
}

async function withLoader(fn){
  startLoader('Connecting securely…','Verifying your request…');
  try{
    await fn();
  }finally{
    if(!loaderNavigating)hideLoader();
  }
}

async function resumeExisting(){
 startLoader('Starting LuckZoo…','Loading resources…');
 setLoaderStage(12,'Loading resources…','Preparing secure components…');

 const token=localStorage.getItem('zoo_token')||'',mode=localStorage.getItem('zoo_auth_mode')||'';

 // No active session: finish startup cleanly, then reveal the login/register page.
 if(!token||!mode){
   setLoaderStage(68,'Preparing login…','Finalizing interface…');
   setTimeout(()=>completeLoader('Ready','Welcome to LuckZoo'),260);
   return;
 }

 try{
   setLoaderStage(34,'Checking player session…','Connecting securely…');
   const h=mode==='guest'?{'X-Guest-Session':token}:{Authorization:'Bearer '+token};
   const url=mode==='guest'?'/api/guest_resume.php':'/api/account_me.php';
   const opt=mode==='guest'
     ? {method:'POST',headers:{...h,'Content-Type':'application/json'},body:JSON.stringify({session_token:token}),cache:'no-store'}
     : {headers:h,cache:'no-store'};

   const r=await fetch(url,opt);
   setLoaderStage(72,'Syncing player data…','Restoring your LuckZoo session…');
   const j=await r.json();

   if(r.ok&&j.ok){
     setLoaderStage(92,'Preparing your lobby…','Almost ready…');
     enter();
     return;
   }
   clear();
 }catch(e){
   clear();
 }

 setLoaderStage(76,'Preparing login…','Session check complete…');
 completeLoader('Ready','Welcome to LuckZoo');
}
$$('[data-tab]').forEach(b=>b.onclick=()=>{$$('[data-tab]').forEach(x=>x.classList.toggle('active',x===b));$('#loginPane').classList.toggle('hide',b.dataset.tab!=='login');$('#registerPane').classList.toggle('hide',b.dataset.tab!=='register')});
$$('[data-eye]').forEach(b=>b.onclick=()=>{const i=$('#'+b.dataset.eye);i.type=i.type==='password'?'text':'password'});
$('#loginBtn').onclick=()=>withLoader(async()=>{try{const j=await api('/api/login.php',{phone:phone($('#loginPhone').value),password:$('#loginPassword').value});save(j.user.session_token,'registered');enter()}catch(e){toast(e.message,true)}});
async function guest(){
  await withLoader(async()=>{
    try{
      const saved=localStorage.getItem('zoo_device_guest_token')||'';

      if(saved){
        try{
          const j=await api('/api/guest_resume.php',{session_token:saved});
          const token=j.guest?.session_token||saved;
          save(token,'guest');
          enter();
          return;
        }catch(e){
          // Keep the device guest token on temporary/network errors. A new guest is
          // created only when the saved guest is definitely unusable.
          if(Number(e.status)===401 || /invalid|expired|not found/i.test(String(e.message||''))){
            localStorage.removeItem('zoo_device_guest_token');
          }else{
            throw e;
          }
        }
      }

      const j=await api('/api/guest_create.php',{});
      save(j.guest.session_token,'guest');
      enter();
    }catch(e){
      toast(e.message,true);
    }
  });
}
$('#guestBtn').onclick=guest;$('#guestBtn2').onclick=guest;
$('#registerBtn').onclick=()=>withLoader(async()=>{
  try{
    if(!$('#agree').checked)throw new Error('Please agree to the account and game rules');
    if($('#regPassword').value!==$('#regConfirm').value)throw new Error('Passwords do not match');

    const body={
      phone:phone($('#regPhone').value),
      password:$('#regPassword').value
    };

    const mode=localStorage.getItem('zoo_auth_mode')||'';
    const guestToken=mode==='guest'
      ? (localStorage.getItem('zoo_token')||localStorage.getItem('zoo_device_guest_token')||'')
      : '';

    if(guestToken) body.guest_session_token=guestToken;

    const j=await api('/api/register.php',body);
    save(j.user.session_token,'registered');
    enter();
  }catch(e){
    toast(e.message,true);
  }
});
$('#forgotOpen').onclick=()=>$('#forgotModal').classList.remove('hide');$('#forgotClose').onclick=()=>$('#forgotModal').classList.add('hide');
$('#sendReset').onclick=async()=>{try{const j=await api('/api/password_reset_request.php',{phone:phone($('#forgotPhone').value)});resetId=Number(j.reset?.reset_id||0);$('#forgotStep1').classList.add('hide');$('#forgotStep2').classList.remove('hide');if(j.reset?.dev_otp){$('#devOtp').textContent='Development OTP: '+j.reset.dev_otp;$('#devOtp').classList.remove('hide')}else if(j.reset?.delivery==='sms_provider_required'){toast('OTP created; production SMS provider is not connected yet',true)}else toast('If this number is registered, a reset code was sent')}catch(e){toast(e.message,true)}};
$('#resetPassword').onclick=async()=>{try{if(!resetId)throw new Error('Request a reset code first');await api('/api/password_reset_confirm.php',{reset_id:resetId,code:$('#resetCode').value,new_password:$('#newPassword').value});toast('Password reset. You can log in now.');setTimeout(()=>{location.reload()},900)}catch(e){toast(e.message,true)}};
resumeExisting();
})();