function inferWebAdminBase() {
  var explicit = String(window.MX_WEB_ADMIN_BASE || "").trim().replace(/\/+$/, "");
  if (explicit) return explicit;
  var path = String(location.pathname || "").replace(/\/+$/, "");
  if (path.endsWith("/login")) {
    return path.slice(0, -"/login".length) || "/";
  }
  var parts = path.split("/").filter(Boolean);
  return parts.length ? "/" + parts[0] : "";
}

(function initWebAdminLogin() {
  var WEB_ADMIN_BASE = inferWebAdminBase();
  var form = document.getElementById("loginForm");
  var button = document.getElementById("submitBtn");
  var message = document.getElementById("message");

  function setMessage(text, error) {
    if (!message) return;
    message.textContent = text || "";
    message.className = "message" + (error ? " error" : "");
  }

  async function checkAuth() {
    var response = await fetch("/api/auth/me", { credentials: "include", cache: "no-store" });
    var data = await response.json().catch(function () { return {}; });
    if (data.authenticated && data.user && data.user.role === "admin") {
      location.replace(WEB_ADMIN_BASE);
    }
  }

  if (form && button) {
    form.addEventListener("submit", async function (event) {
      event.preventDefault();
      button.disabled = true;
      setMessage("正在验证管理员身份...");
      try {
        var usernameInput = document.getElementById("username");
        var passwordInput = document.getElementById("password");
        var usernameValue = "";
        if (usernameInput && typeof usernameInput.value === "string") {
          usernameValue = usernameInput.value.trim();
        }
        var passwordValue = "";
        if (passwordInput && typeof passwordInput.value === "string") {
          passwordValue = passwordInput.value;
        }
        var response = await fetch("/api/auth/login", {
          method: "POST",
          credentials: "include",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            username: usernameValue,
            password: passwordValue,
          }),
        });
        var data = await response.json().catch(function () { return {}; });
        if (!response.ok) {
          throw new Error(data.detail || "登录失败");
        }
        if (!data.user || data.user.role !== "admin") {
          await fetch("/api/auth/logout", { method: "POST", credentials: "include" }).catch(function () { return null; });
          throw new Error("当前账号不是管理员，无法进入网页版后台");
        }
        location.replace(WEB_ADMIN_BASE);
      } catch (error) {
        setMessage((error && error.message) || "登录失败", true);
      } finally {
        button.disabled = false;
      }
    });
  }

  checkAuth().catch(function () { return null; });
})();
