(function () {
  var logo = document.querySelector(".site-logo");
  var gate = document.getElementById("admin-gate");
  var inp = document.getElementById("admin-token");
  var btnGo = document.getElementById("admin-token-go");
  var btnCancel = document.getElementById("admin-token-cancel");
  if (!logo || !gate || !inp || !btnGo || !btnCancel) return;
  var n = 0;
  var resetTimer = null;
  function showGate() {
    gate.hidden = false;
    inp.value = "";
    inp.focus();
  }
  function hideGate() {
    gate.hidden = true;
  }
  logo.addEventListener("click", function (e) {
    e.preventDefault();
    if (resetTimer) clearTimeout(resetTimer);
    n += 1;
    if (n >= 5) {
      n = 0;
      showGate();
      return;
    }
    resetTimer = setTimeout(function () {
      n = 0;
    }, 4000);
  });
  btnCancel.addEventListener("click", hideGate);
  function submit() {
    fetch("/admin/session", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "same-origin",
      body: JSON.stringify({ token: inp.value })
    })
      .then(function (r) {
        if (r.ok) {
          hideGate();
          location.href = "/admin";
          return;
        }
        inp.select();
        alert("Token 无效");
      })
      .catch(function () {
        alert("网络错误");
      });
  }
  btnGo.addEventListener("click", submit);
  inp.addEventListener("keydown", function (e) {
    if (e.key === "Enter") {
      e.preventDefault();
      submit();
    }
  });
})();
