(()=>{'use strict';
const $=s=>document.querySelector(s);
let key=sessionStorage.getItem('lz_admin_key')||'';

function toast(t){alert(t)}
async function api(url,opt={}){
  const h={...(opt.headers||{}),'X-Zoo-Admin-Key':key};
  if(opt.body)h['Content-Type']='application/json';
  const r=await fetch(url,{cache:'no-store',...opt,headers:h});
  const j=await r.json().catch(()=>({}));
  if(!r.ok||!j.ok)throw new Error(j.error||'Request failed');
  return j;
}
function showSecret(agent,title='AGENT LOGIN DETAILS — SAVE NOW'){
  $('#secretTitle').textContent=title;
  $('#newCode').textContent=agent.agent_code||'—';
  $('#secretText').textContent=agent.access_secret||'—';
  $('#newSecret').classList.remove('hide');
  $('#newSecret').scrollIntoView({behavior:'smooth',block:'center'});
}
async function load(){
  const j=await api('/api/admin_raast_agents.php?ts='+Date.now());
  $('#app').classList.remove('hide');
  $('.login').classList.add('hide');
  $('#agents').innerHTML=(j.agents||[]).map(a=>`
    <div class="agent ${a.status==='active'?'':'inactive'}">
      <div>
        <b>${a.agent_code} • ${a.display_name}</b>
        <small>${a.supported_channels||''} • active ${a.active_requests||0}/${a.max_active_requests} • daily limit ${a.daily_limit}</small>
      </div>
      <button data-id="${a.id}" data-status="active">ACTIVE</button>
      <button data-id="${a.id}" data-status="inactive">INACTIVE</button>
      <button data-reset="${a.id}">RESET LOGIN SECRET</button>
    </div>`).join('');

  document.querySelectorAll('[data-status]').forEach(b=>b.onclick=()=>setStatus(b.dataset.id,b.dataset.status));
  document.querySelectorAll('[data-reset]').forEach(b=>b.onclick=()=>resetSecret(Number(b.dataset.reset)));
}
async function setStatus(id,status){
  await api('/api/admin_raast_agents.php',{
    method:'POST',body:JSON.stringify({action:'status',agent_id:Number(id),status})
  });
  await load();
}
async function resetSecret(id){
  if(!confirm('Generate a new login secret for this agent? Existing agent sessions will be logged out.'))return;
  const j=await api('/api/admin_raast_agents.php',{
    method:'POST',body:JSON.stringify({action:'reset_secret',agent_id:id})
  });
  showSecret(j.agent,'NEW LOGIN SECRET — SAVE NOW');
}
$('#unlock').onclick=()=>{
  key=$('#key').value.trim();
  sessionStorage.setItem('lz_admin_key',key);
  load().catch(e=>toast(e.message));
};
$('#create').onclick=async()=>{
  try{
    const j=await api('/api/admin_raast_agents.php',{
      method:'POST',
      body:JSON.stringify({
        action:'create',
        display_name:$('#name').value.trim(),
        supported_channels:$('#channels').value.trim(),
        max_active_requests:Number($('#max').value||10),
        daily_limit:Number($('#limit').value||0)
      })
    });
    showSecret(j.agent,'NEW AGENT — SAVE LOGIN DETAILS NOW');
    await load();
  }catch(e){toast(e.message)}
};
$('#copySecret').onclick=async()=>{
  const text='LuckZoo Raast Agent ID: '+$('#newCode').textContent.trim()+
             '\nLogin Secret: '+$('#secretText').textContent.trim();
  try{await navigator.clipboard.writeText(text);toast('Login details copied')}
  catch(e){toast('Copy failed')}
};
$('#refresh').onclick=()=>load().catch(e=>toast(e.message));
if(key)load().catch(()=>{});
})();