(() => {
  "use strict";

  const I18N = window.ARRI18n;

  const form = document.querySelector("#login-form");
  const username = document.querySelector("#username");
  const password = document.querySelector("#password");
  const toggle = document.querySelector("#password-toggle");
  const submit = document.querySelector("#login-submit");
  const submitLabel = submit.querySelector(".submit-label");
  const errorNode = document.querySelector("#login-error");
  let lastError = null;

  function copy(key, fallback) {
    return I18N?.t(key) || fallback;
  }

  function safeNext() {
    const candidate = new URLSearchParams(window.location.search).get("next");
    return candidate === "/h5" ? "/h5" : "/";
  }

  function setBusy(busy) {
    form.setAttribute("aria-busy", String(busy));
    username.disabled = busy;
    password.disabled = busy;
    toggle.disabled = busy;
    submit.disabled = busy;
    submit.classList.toggle("is-loading", busy);
    submitLabel.textContent = busy ? copy("auth.validating", "正在验证…") : copy("auth.submit", "登录 ARR Report");
  }

  function validateFields() {
    username.setCustomValidity(username.value.trim() ? "" : copy("auth.required_username", "请输入用户名"));
    password.setCustomValidity(password.value ? "" : copy("auth.required_password", "请输入密码"));
    return form.reportValidity();
  }

  function clearError() {
    lastError = null;
    errorNode.hidden = true;
    errorNode.textContent = "";
  }

  function showError(error) {
    lastError = error instanceof Error ? error : new Error(String(error || ""));
    const message = lastError.arrErrorCode
      ? (I18N?.errorMessage(lastError.arrErrorCode, lastError.arrFallback) || lastError.message)
      : (I18N?.text(lastError.message) || lastError.message);
    errorNode.textContent = message;
    errorNode.hidden = false;
  }

  toggle.addEventListener("click", () => {
    const visible = password.type === "text";
    password.type = visible ? "password" : "text";
    toggle.textContent = visible ? copy("auth.show", "显示") : copy("auth.hide", "隐藏");
    toggle.setAttribute("aria-label", visible ? copy("auth.show_password", "显示密码") : copy("auth.hide_password", "隐藏密码"));
    toggle.setAttribute("aria-pressed", String(!visible));
    password.focus();
  });

  [username, password].forEach((field) => field.addEventListener("input", () => {
    field.setCustomValidity("");
    clearError();
  }));

  form.addEventListener("submit", async (event) => {
    event.preventDefault();
    clearError();
    if (!validateFields()) return;
    setBusy(true);
    try {
      const response = await fetch("/api/login", {
        method: "POST",
        credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          username: username.value.trim(),
          password: password.value,
        }),
      });
      let payload = null;
      try { payload = await response.json(); } catch (_) { /* handled below */ }
      if (!response.ok || !payload?.ok) {
        const error = payload?.error || {};
        const failure = new Error(I18N?.errorMessage(error.code, error.message) || error.message || copy("auth.unavailable", "登录暂时不可用，请稍后重试"));
        failure.arrErrorCode = error.code || "";
        failure.arrFallback = error.message || "";
        throw failure;
      }
      window.location.replace(safeNext());
    } catch (error) {
      showError(error instanceof Error ? error : new Error(copy("auth.unavailable", "登录暂时不可用，请稍后重试")));
      password.value = "";
      password.focus();
    } finally {
      setBusy(false);
    }
  });

  document.addEventListener("arr:locale-change", () => {
    const busy = form.getAttribute("aria-busy") === "true";
    setBusy(busy);
    toggle.textContent = password.type === "text" ? copy("auth.hide", "隐藏") : copy("auth.show", "显示");
    toggle.setAttribute("aria-label", password.type === "text" ? copy("auth.hide_password", "隐藏密码") : copy("auth.show_password", "显示密码"));
    if (!username.value) username.setCustomValidity(copy("auth.required_username", "请输入用户名"));
    if (!password.value) password.setCustomValidity(copy("auth.required_password", "请输入密码"));
    if (!errorNode.hidden && lastError) showError(lastError);
  });
})();
