const ROLE = document.body.dataset.role || "admin";
const REDIRECT = ROLE === "admin" ? "admin.html" : "company.html";

const form = document.getElementById("login-form");
const accountInput = document.getElementById("account");
const passwordInput = document.getElementById("password");
const accountErr = document.getElementById("account-err");
const passwordErr = document.getElementById("password-err");
const loginErr = document.getElementById("login-err");
const submitButton = form.querySelector('button[type="submit"]');

const modal = document.getElementById("pwd-modal");
const newPwd = document.getElementById("new-pwd");
const newPwd2 = document.getElementById("new-pwd2");
const newPwdErr = document.getElementById("new-pwd-err");
const newPwd2Err = document.getElementById("new-pwd2-err");
const pwdErr = document.getElementById("pwd-err");
const pwdConfirm = document.getElementById("pwd-confirm");

const submitLabel = "登 录";

function setLoading(loading) {
  submitButton.disabled = loading;
  submitButton.textContent = loading ? "登录中…" : submitLabel;
  accountInput.disabled = loading;
  passwordInput.disabled = loading;
}

function showLoginError(message) {
  loginErr.textContent = message || "";
  loginErr.hidden = !message;
}

function openPasswordModal() {
  newPwd.value = "";
  newPwd2.value = "";
  newPwdErr.hidden = true;
  newPwd2Err.hidden = true;
  pwdErr.hidden = true;
  modal.classList.add("open");
  newPwd.focus();
}

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  showLoginError("");
  const account = accountInput.value.trim();
  const password = passwordInput.value;
  accountErr.hidden = Boolean(account);
  passwordErr.hidden = Boolean(password);
  if (!account || !password) return;

  setLoading(true);
  const response = await fetch("/api/login", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ username: account, password, portal: ROLE }),
  }).catch(() => null);
  const result = await response?.json().catch(() => ({}));
  if (!response || !response.ok) {
    showLoginError(result?.message || "登录服务暂时不可用，请稍后重试。");
    setLoading(false);
    return;
  }
  if (result.must_change_password) {
    setLoading(false);
    openPasswordModal();
    return;
  }
  window.location.href = REDIRECT;
});

pwdConfirm.addEventListener("click", async () => {
  const p1 = newPwd.value;
  const p2 = newPwd2.value;
  const valid = p1.length >= 8 && /[a-zA-Z]/.test(p1) && /\d/.test(p1);
  newPwdErr.hidden = valid;
  newPwd2Err.hidden = p1 === p2;
  pwdErr.hidden = true;
  if (!valid || p1 !== p2) return;

  pwdConfirm.disabled = true;
  const response = await fetch("/api/password/change", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ old_password: passwordInput.value, new_password: p1 }),
  }).catch(() => null);
  const result = await response?.json().catch(() => ({}));
  if (!response || !response.ok) {
    pwdErr.textContent = result?.message || "修改密码失败，请稍后重试。";
    pwdErr.hidden = false;
    pwdConfirm.disabled = false;
    return;
  }
  window.location.href = REDIRECT;
});
