(()=>{
'use strict';
const $=s=>document.querySelector(s);
let verificationId=0;
let mode=localStorage.getItem('zoo_auth_mode')||'';
let token=localStorage.getItem('zoo_token')||'';

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 toast(t,error=false){
  const x=$('#toast');x.textContent=t;x.classList.toggle('error',error);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 showBinding(b){
  const phoneBound=!!b?.phone_verified_at;
  $('#phoneBadge').textContent=phoneBound?'Verified':'Not bound';
  $('#phoneBadge').classList.toggle('ok',phoneBound);
  $('#phoneBound').classList.toggle('hide',!phoneBound);
  $('#phoneForm').classList.toggle('hide',phoneBound);
  if(phoneBound)$('#boundPhone').textContent=b.phone_local||b.phone_e164||b.phone_national;

  const intBound=!!b?.internal_login_id;
  $('#internalBadge').textContent=intBound?'Bound':'Not bound';
  $('#internalBadge').classList.toggle('ok',intBound);
  $('#internalBound').classList.toggle('hide',!intBound);
  $('#internalForm').classList.toggle('hide',intBound);
  if(intBound)$('#boundInternal').textContent=b.internal_login_id;

  if(mode==='guest'){
    $('#passwordCard').classList.toggle('disabled',!phoneBound);
    $('#loginBadge').textContent=phoneBound?'Ready':'Verify mobile first';
  }else{
    $('#passwordForm').classList.add('hide');
    $('#registeredBox').classList.remove('hide');
    $('#loginBadge').textContent='Secured';
    $('#loginBadge').classList.add('ok');
  }
}
async function refresh(){
  if(!token){location.href='/lobby/';return}
  try{
    const j=await call('/api/account_bind_status.php',{headers:headers()});
    showBinding(j.binding||{});
    $('#state').textContent='Ready';
  }catch(e){
    $('#state').textContent='Session error';
    toast(e.message,true);
  }
}
$('#back').onclick=()=>location.href='/lobby/';

$('#requestOtp').onclick=async()=>{
  const phone=$('#phone').value.trim();
  if(!phone){toast('Enter your mobile number',true);return}
  try{
    const j=await call('/api/request_phone_verification.php',{
      method:'POST',headers:headers(true),body:JSON.stringify({phone})
    });
    verificationId=Number(j.verification?.verification_id||0);
    $('#otpBox').classList.remove('hide');
    $('#otpHint').textContent='OTP request created. Enter the verification code delivered by the configured provider.';
    toast('Verification request created');
  }catch(e){toast(e.message,true)}
};

$('#verifyOtp').onclick=async()=>{
  const code=$('#otp').value.trim();
  if(!verificationId||!code){toast('Request and enter the OTP first',true);return}
  try{
    const j=await call('/api/verify_bind_phone.php',{
      method:'POST',headers:headers(true),body:JSON.stringify({verification_id:verificationId,code})
    });
    showBinding(j.binding||{});
    toast('Mobile number verified and permanently bound');
  }catch(e){toast(e.message,true)}
};

$('#secureAccount').onclick=async()=>{
  if(mode!=='guest'){toast('Account is already registered');return}
  const p=$('#password').value,p2=$('#password2').value;
  if(p.length<8){toast('Password must be at least 8 characters',true);return}
  if(p!==p2){toast('Passwords do not match',true);return}
  try{
    const j=await call('/api/complete_account_registration.php',{
      method:'POST',headers:headers(true),body:JSON.stringify({password:p})
    });
    if(j.user?.session_token){
      token=j.user.session_token;mode='registered';
      localStorage.setItem('zoo_token',token);
      localStorage.setItem('zoo_auth_mode','registered');
    }
    showBinding(j.binding||{});
    $('#passwordForm').classList.add('hide');
    $('#registeredBox').classList.remove('hide');
    $('#loginBadge').textContent='Secured';
    $('#loginBadge').classList.add('ok');
    toast('Account secured. Guest history and balance preserved.');
  }catch(e){toast(e.message,true)}
};

$('#claimInternal').onclick=async()=>{
  const login_id=$('#internalId').value.trim();
  const activation_code=$('#activationCode').value.trim();
  if(!login_id||!activation_code){toast('Enter the internal ID and activation code',true);return}
  try{
    const j=await call('/api/claim_internal_login_id.php',{
      method:'POST',headers:headers(true),body:JSON.stringify({login_id,activation_code})
    });
    showBinding(j.binding||{});
    toast('Internal Login ID permanently bound');
  }catch(e){toast(e.message,true)}
};

refresh();
})();