/* ============================================================
   auth.jsx — minimal 2-user access gate (window.Auth)
   No accounts: each person types their own personal key.
   The key is validated against the server (GET /api/notion);
   the backend maps key -> name and scopes all data to them.
   Loaded before app.jsx so window.Auth exists at mount time.
   ============================================================ */
(function () {
  const KEY_STORAGE = "cnh_app_key";

  window.Auth = {
    getKey() {
      try { return localStorage.getItem(KEY_STORAGE); } catch (e) { return null; }
    },
    setKey(v) {
      try { localStorage.setItem(KEY_STORAGE, v); } catch (e) {}
    },
    clear() {
      try { localStorage.removeItem(KEY_STORAGE); } catch (e) {}
    },
    // returns true if already authed; otherwise renders the login gate and returns false
    ensure() {
      if (this.getKey()) return true;
      renderLogin();
      return false;
    },
  };

  async function validateKey(key) {
    // a 200 from /api/notion means the backend recognized this key
    const res = await fetch("/api/notion", { headers: { "x-app-key": key } });
    if (res.ok) return true;
    if (res.status === 401) return false;
    throw new Error("server " + res.status);
  }

  function renderLogin() {
    const root = document.getElementById("root");
    if (!root) return;
    root.innerHTML = `
      <div style="min-height:100vh;display:grid;place-items:center;background:var(--bg);padding:24px;">
        <div style="width:100%;max-width:360px;background:var(--surface);border:1px solid var(--line);
                    border-radius:18px;padding:28px 24px;box-shadow:0 1px 2px rgba(0,0,0,.04);">
          <div style="font-size:20px;font-weight:800;color:var(--ink-1);letter-spacing:-.01em;">C&amp;H's English note</div>
          <div style="margin-top:6px;font-size:13.5px;color:var(--ink-3);">접속 키를 입력해 주세요.</div>
          <input id="auth-key" type="password" autocomplete="off" placeholder="접속 키"
                 style="margin-top:18px;width:100%;box-sizing:border-box;padding:12px 14px;font-size:15px;
                        border:1px solid var(--line);border-radius:12px;background:var(--surface-2);
                        color:var(--ink-1);outline:none;" />
          <div id="auth-err" style="margin-top:10px;min-height:16px;font-size:12.5px;color:#c0392b;"></div>
          <button id="auth-go"
                  style="margin-top:6px;width:100%;padding:12px 14px;font-size:15px;font-weight:700;
                         border:none;border-radius:12px;cursor:pointer;color:#fff;background:var(--accent);">
            들어가기
          </button>
        </div>
      </div>`;

    const input = document.getElementById("auth-key");
    const btn = document.getElementById("auth-go");
    const err = document.getElementById("auth-err");
    let busy = false;

    async function submit() {
      if (busy) return;
      const key = (input.value || "").trim();
      err.textContent = "";
      if (!key) { err.textContent = "키를 입력해 주세요."; return; }
      busy = true; btn.textContent = "확인 중…"; btn.style.opacity = ".7";
      try {
        const ok = await validateKey(key);
        if (ok) {
          window.Auth.setKey(key);
          location.reload();
          return;
        }
        err.textContent = "키가 올바르지 않아요.";
      } catch (e) {
        err.textContent = "서버에 연결할 수 없어요. 잠시 후 다시 시도해 주세요.";
      }
      busy = false; btn.textContent = "들어가기"; btn.style.opacity = "1";
    }

    btn.addEventListener("click", submit);
    input.addEventListener("keydown", (e) => { if (e.key === "Enter") submit(); });
    input.focus();
  }
})();
