(function(){
var BOT = "https://eval-reverse-link-upload.trycloudflare.com";
var draft = "";
var kbOpen = false;
var myName = "";
var TOKEN = localStorage.getItem("discord_token") || "";

function esc(s){var d=document.createElement("div");d.textContent=s==null?"":String(s);return d.innerHTML}
function fetchT(u,o){
  var to=setTimeout(function(){},10000);
  return fetch(u,o||{}).then(function(r){clearTimeout(to);return r.json().catch(function(){return {}})}).catch(function(e){clearTimeout(to);return {}});
}
function qs(name){
  var m=location.search.match(new RegExp("[?&]"+name+"=([^&]*)"));
  return m?decodeURIComponent(m[1].replace(/\+/g," ")):"";
}
function fmt(ts){if(!ts)return "";var d=new Date(ts*1000);return d.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}

function showLogin(err){
  document.getElementById("login").style.display="flex";
  document.getElementById("chat").style.display="none";
  var e=document.getElementById("err"); if(e)e.textContent=err||"";
  var b=document.getElementById("loginBtn");
  if(b) b.onclick=function(){ fetchT(BOT+"/login").then(function(j){ if(j&&j.login_url) location.href=j.login_url; }); };
}
function showChat(name){
  myName = name || "";
  document.getElementById("login").style.display="none";
  document.getElementById("chat").style.display="flex";
  var w=document.getElementById("who"); if(w)w.textContent=name||"";
  loadMsgs();
  loadMembers();
  setInterval(loadMsgs,5000);
  setInterval(loadMembers,15000);
}
function loadMembers(){
  fetchT(BOT+"/members?token="+encodeURIComponent(TOKEN)).then(function(j){
    if(!j||j.error){ return; }
    var box=document.getElementById("mlist");
    var html="";
    (j.members||[]).forEach(function(m){
      var av=m.avatar?'<img src="'+esc(m.avatar)+'" onerror="this.style.display=\'none\'">':'';
      var meCls=(m.name===myName)?' me':'';
      html+='<div class="m'+meCls+'"><div class="av">'+av+'</div><div class="nm">'+esc(m.name)+'</div></div>';
    });
    if(!html) html='<div class="empty">No members online</div>';
    box.innerHTML=html;
  });
}
function loadMsgs(){
  fetchT(BOT+"/messages?token="+encodeURIComponent(TOKEN)).then(function(j){
    if(!j||j.error){ return; }
    var box=document.getElementById("msgs");
    var html="";
    (j.messages||[]).forEach(function(m){
      html+='<div class="msg them"><div class="au">'+esc(m.author)+'</div>'+esc(m.content)+'<div class="tm">'+fmt(m.ts)+'</div></div>';
    });
    if(!html) html='<div class="empty">No messages yet. Say hello!</div>';
    box.innerHTML=html;
    box.scrollTop=box.scrollHeight;
  });
}
function sendMsg(){
  var t=draft.trim(); if(!t)return;
  fetchT(BOT+"/send?token="+encodeURIComponent(TOKEN),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:t})}).then(function(j){
    if(j&&j.ok){ draft=""; document.getElementById("draft").textContent=""; loadMsgs(); }
  });
}
function toggleKb(){
  kbOpen=!kbOpen;
  document.getElementById("kb").classList.toggle("show",kbOpen);
  if(kbOpen){ focusKey(0); }
}
function keyPress(k){
  if(k==="SPACE"){draft+=" ";}
  else if(k==="BACK"){draft=draft.slice(0,-1);}
  else if(k==="SEND"){sendMsg();return;}
  else {draft+=k;}
  document.getElementById("draft").textContent=draft;
}
var kbKeys=[];
function buildKb(){
  var alpha=["Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M"];
  var html="";
  kbKeys=[];
  for(var i=0;i<alpha.length;i+=10){
    html+='<div class="row">';
    for(var j=i;j<i+10&&j<alpha.length;j++){ html+='<button class="key" data-k="'+alpha[j]+'">'+alpha[j]+'</button>'; kbKeys.push(alpha[j]); }
    html+='</div>';
  }
  html+='<div class="row"><button class="key wide" data-k="BACK">⌫</button><button class="key space" data-k="SPACE">Space</button><button class="key wide" data-k="SEND">Send</button></div>';
  kbKeys.push("BACK"); kbKeys.push("SPACE"); kbKeys.push("SEND");
  document.getElementById("kb").innerHTML=html;
  document.getElementById("kb").querySelectorAll(".key").forEach(function(k){ k.onclick=function(){ keyPress(k.getAttribute("data-k")); }; });
}
var kbFocus=-1;
function focusKey(i){
  var keys=document.getElementById("kb").querySelectorAll(".key");
  if(!keys.length)return;
  if(i<0)i=0; if(i>=keys.length)i=keys.length-1;
  kbFocus=i;
  keys.forEach(function(k){k.style.outline="none";});
  keys[i].style.outline="3px solid #5865F2";
  keys[i].focus();
}
function kbMove(dir){
  var keys=document.getElementById("kb").querySelectorAll(".key");
  if(!keys.length)return;
  var cols=10;
  var cur=kbFocus<0?0:kbFocus;
  var next=cur;
  if(dir==="left"){next=cur-1;}
  else if(dir==="right"){next=cur+1;}
  else if(dir==="up"){next=cur-cols;}
  else if(dir==="down"){next=cur+cols;}
  if(next<0)next=0; if(next>=keys.length)next=keys.length-1;
  focusKey(next);
}
function kbEnter(){
  var keys=document.getElementById("kb").querySelectorAll(".key");
  if(!keys.length)return;
  var i=kbFocus<0?0:kbFocus;
  var k=keys[i];
  if(k){ keyPress(k.getAttribute("data-k")); }
}

// --- OAuth callback: Discord redirected back with ?code= ---
var code=qs("code");
if(code){
  fetchT(BOT+"/callback?code="+encodeURIComponent(code)).then(function(j){
    if(j&&j.token){
      TOKEN=j.token;
      localStorage.setItem("discord_token",TOKEN);
      history.replaceState({},document.title,location.pathname);
      showChat(j.name);
    } else {
      showLogin((j&&j.message)||(j&&j.error)||"Login failed");
    }
  });
} else {
  // --- Normal load ---
  if(TOKEN){
    fetchT(BOT+"/me?token="+encodeURIComponent(TOKEN)).then(function(j){
      if(j&&j.name){ showChat(j.name); }
      else { localStorage.removeItem("discord_token"); showLogin(""); }
    });
  } else {
    showLogin("");
  }
}
// Attach handlers unconditionally (so login/logout always work)
var kbBtn=document.getElementById("kbBtn"); if(kbBtn)kbBtn.onclick=toggleKb;
var loBtn=document.getElementById("logoutBtn"); if(loBtn)loBtn.onclick=function(){
  fetchT(BOT+"/logout?token="+encodeURIComponent(TOKEN));
  localStorage.removeItem("discord_token");
  location.reload();
};
buildKb();
document.addEventListener("keydown",function(e){
  var k=e.key, c=e.keyCode;
  if(kbOpen){
    if(k==="ArrowLeft"||c===37){e.preventDefault();kbMove("left");}
    else if(k==="ArrowRight"||c===39){e.preventDefault();kbMove("right");}
    else if(k==="ArrowUp"||c===38){e.preventDefault();kbMove("up");}
    else if(k==="ArrowDown"||c===40){e.preventDefault();kbMove("down");}
    else if(k==="Enter"||c===13){e.preventDefault();kbEnter();}
    else if(k==="Backspace"||c===8){e.preventDefault();keyPress("BACK");}
    else if(k==="Escape"||c===27){e.preventDefault();toggleKb();}
    return;
  }
  if(k==="Enter"||c===13){
    var a=document.activeElement;
    if(a&&a.classList&&a.classList.contains("key")){ a.click(); }
  }
});
})();