<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <link rel="icon" href="{{ site_branding.favicon_url }}">
  <title>登录 - {{ site_branding.browser_title }}</title>
  <style>
    * { box-sizing: border-box; }
    body {
      margin: 0;
      font-family: Arial, "Microsoft YaHei", sans-serif;
      background: #f5f5f7;
      color: #222;
    }
    a { text-decoration: none; color: inherit; }

    .topbar {
      background: #111;
      color: #fff;
      padding: 14px 24px;
      border-bottom: 1px solid rgba(255,255,255,0.06);
    }
    .topbar-inner {
      width: 1200px;
      max-width: calc(100vw - 48px);
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 24px;
    }
    .topbar-brand a {
      color: #fff;
      font-size: 20px;
      font-weight: 800;
      text-decoration: none;
    }
    .topbar-links {
      display: flex;
      align-items: center;
      gap: 18px;
      flex-wrap: wrap;
      justify-content: flex-end;
    }
    .topbar-links a {
      color: #f3f3f3;
      font-size: 14px;
      line-height: 1;
      white-space: nowrap;
    }

    .wrap {
      width: 460px;
      margin: 80px auto;
      background: #fff;
      padding: 32px;
      border-radius: 18px;
      box-shadow: 0 2px 12px rgba(0,0,0,.08);
    }
    h1 {
      margin-top: 0;
      margin-bottom: 8px;
      text-align: center;
      font-size: 30px;
      font-weight: 800;
    }
    .sub {
      text-align: center;
      color: #666;
      font-size: 14px;
      margin-bottom: 24px;
      line-height: 1.8;
    }
    input {
      width: 100%;
      height: 46px;
      margin-bottom: 14px;
      padding: 0 12px;
      border: 1px solid #ddd;
      border-radius: 10px;
      font-size: 15px;
      outline: none;
    }
    input:focus { border-color: #111; }

    button {
      width: 100%;
      height: 46px;
      border: none;
      border-radius: 10px;
      background: #111;
      color: #fff;
      cursor: pointer;
      font-size: 15px;
      font-weight: 700;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 10px;
    }
    button:disabled {
      opacity: 0.85;
      cursor: not-allowed;
    }

    .spinner {
      width: 16px;
      height: 16px;
      border: 2px solid rgba(255,255,255,0.35);
      border-top-color: #fff;
      border-radius: 50%;
      animation: spin 0.8s linear infinite;
      display: none;
    }
    .loading .spinner { display: inline-block; }
    @keyframes spin { to { transform: rotate(360deg); } }

    .msg {
      margin: 12px 0;
      padding: 10px 12px;
      border-radius: 10px;
      font-size: 14px;
      display: none;
      line-height: 1.7;
    }
    .err {
      background: #fff3f3;
      color: #c40000;
    }

    .links {
      margin-top: 18px;
      text-align: center;
      font-size: 14px;
      color: #666;
      line-height: 1.9;
    }
    .links a {
      color: #111;
      text-decoration: none;
      font-weight: 700;
    }
  </style>
</head>
<body>
  <div class="topbar">
    <div class="topbar-inner">
      <div class="topbar-brand">
        <a href="/">{{ site_branding.site_name }}</a>
      </div>
      <div class="topbar-links">
        <a href="/">首页</a>
        <a href="/products">全部商品</a>
        <a href="/register">注册</a>
      </div>
    </div>
  </div>

  <div class="wrap">
    <h1>用户登录</h1>
    <div class="sub">请输入用户名或邮箱与密码。</div>

    <div id="err" class="msg err"></div>

    <input id="account" type="text" placeholder="用户名或邮箱" />
    <input id="password" type="password" placeholder="密码" />
    <button id="loginBtn">
      <span class="spinner"></span>
      <span id="btnText">登录</span>
    </button>

    <div class="links">
      没有账号？<a href="/firebase-register">立即注册</a><br>
      忘记密码？<a href="/reset-password">重置密码</a>
    </div>
  </div>

  <script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.5/firebase-app.js";
    import { getAuth, signInWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/10.12.5/firebase-auth.js";

    const firebaseConfig = {{ firebase_config|tojson }};
    const app = initializeApp(firebaseConfig);
    const auth = getAuth(app);

    const errBox = document.getElementById("err");
    const loginBtn = document.getElementById("loginBtn");
    const btnText = document.getElementById("btnText");

    function showErr(msg) {
      errBox.style.display = "block";
      errBox.textContent = msg;
    }

    function clearErr() {
      errBox.style.display = "none";
      errBox.textContent = "";
    }

    function setLoading(loading) {
      if (loading) {
        loginBtn.disabled = true;
        loginBtn.classList.add("loading");
        btnText.textContent = "登录中…";
      } else {
        loginBtn.disabled = false;
        loginBtn.classList.remove("loading");
        btnText.textContent = "登录";
      }
    }

    async function doLocalLogin(account, password) {
      const resp = await fetch("/localLogin", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ account, password })
      });
      return await resp.json();
    }

    async function doFirebaseLogin(email, password) {
      const cred = await signInWithEmailAndPassword(auth, email, password);
      const idToken = await cred.user.getIdToken(true);

      const resp = await fetch("/sessionLogin", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ idToken })
      });
      return await resp.json();
    }

    function normalizeFirebaseError(err) {
      const msg = String(err && (err.code || err.message) || "");

      if (msg.includes("auth/invalid-credential")) return "邮箱或密码错误";
      if (msg.includes("auth/user-not-found")) return "该邮箱未注册";
      if (msg.includes("auth/wrong-password")) return "邮箱或密码错误";
      if (msg.includes("auth/invalid-email")) return "邮箱格式不正确";
      if (msg.includes("auth/too-many-requests")) return "请求过多，请稍后再试";
      return "登录失败";
    }

    loginBtn.addEventListener("click", async () => {
      clearErr();

      const account = document.getElementById("account").value.trim();
      const password = document.getElementById("password").value.trim();

      if (!account || !password) {
        showErr("请输入用户名/邮箱和密码");
        return;
      }

      setLoading(true);

      try {
        if (account.includes("@")) {
          try {
            const data = await doFirebaseLogin(account, password);
            if (!data.ok) {
              showErr(data.error || "登录失败");
              setLoading(false);
              return;
            }
            window.location.href = data.redirect || "/";
            return;
          } catch (e) {
            showErr(normalizeFirebaseError(e));
            setLoading(false);
            return;
          }
        } else {
          const data = await doLocalLogin(account, password);
          if (!data.ok) {
            showErr(data.error || "登录失败");
            setLoading(false);
            return;
          }
          window.location.href = data.redirect || "/";
          return;
        }
      } catch (e) {
        showErr("登录请求失败");
        setLoading(false);
      }
    });
  </script>
</body>
</html>
