const $ = (sel) => document.querySelector(sel);

let tagGroups = null;

function showAuthError(msg) {
  const el = $("#auth-error");
  el.textContent = msg;
  el.classList.toggle("hidden", !msg);
}

function switchTab(tab) {
  document.querySelectorAll(".tab").forEach((b) => {
    b.classList.toggle("active", b.dataset.tab === tab);
  });
  $("#form-login").classList.toggle("hidden", tab !== "login");
  $("#form-register").classList.toggle("hidden", tab !== "register");
  showAuthError("");
}

document.querySelectorAll(".tab").forEach((btn) => {
  btn.addEventListener("click", () => switchTab(btn.dataset.tab));
});

$("#remember-password").addEventListener("change", () => {
  if (!$("#remember-password").checked) {
    $("#auto-login").checked = false;
  }
});

$("#auto-login").addEventListener("change", () => {
  if ($("#auto-login").checked) {
    $("#remember-password").checked = true;
  }
});

async function updateApiLinks() {
  const links = await BiliIndex.getApiLinks();
  $("#link-api-login").href = links.loginPage;
  $("#link-api-docs").href = links.docs;
  $("#link-admin").href = links.admin;
  $("#api-login-url").textContent = `登录接口 POST ${links.loginApi}`;
}

async function initAuthForm() {
  const prefs = await BiliIndex.getLoginPrefs();
  $("#remember-password").checked = prefs.rememberPassword;
  $("#auto-login").checked = prefs.autoLogin;
  const form = $("#form-login");
  if (prefs.rememberPassword && prefs.savedUsername) {
    form.username.value = prefs.savedUsername;
    if (prefs.savedPassword) {
      form.password.value = prefs.savedPassword;
    }
  }
  await updateApiLinks();
}

async function tryAutoLogin() {
  const token = await BiliIndex.getToken();
  if (token) return false;
  const prefs = await BiliIndex.getLoginPrefs();
  if (
    !prefs.autoLogin ||
    !prefs.rememberPassword ||
    !prefs.savedUsername ||
    !prefs.savedPassword
  ) {
    return false;
  }
  showAuthError("");
  try {
    await BiliIndex.login(prefs.savedUsername, prefs.savedPassword);
    await BiliIndex.refreshTagCaches(true);
    return true;
  } catch (err) {
    showAuthError(`自动登录失败：${err.message}`);
    return false;
  }
}

async function showBanner(membership) {
  const banner = $("#banner");
  if (!membership.is_member) {
    if (membership.label === "免费用户") {
      banner.textContent =
        "您的会员试用期已到期，部分功能已受限，请购买会员或使用积分兑换继续使用。";
      banner.className = "banner danger";
      banner.classList.remove("hidden");
    } else {
      banner.classList.add("hidden");
    }
    return;
  }
  if (
    membership.member_type === "trial" &&
    membership.remaining_days !== null &&
    membership.remaining_days <= 1
  ) {
    banner.textContent =
      "您的会员试用期将于明天到期，到期后您将无法使用高级屏蔽规则和无限打标功能，如需继续使用请购买会员或使用积分兑换。";
    banner.className = "banner warn";
    banner.classList.remove("hidden");
    return;
  }
  banner.classList.add("hidden");
}

function renderTagSections(groups) {
  const root = $("#tag-sections");
  root.innerHTML = "";

  const sections = [
    { key: "category", title: "一级分类（职业）", hint: "仅归类，点击可快速填入参考" },
    { key: "sub", title: "二级标签（细分）", hint: null },
    { key: "style", title: "三级标签（风格）", hint: null },
    { key: "emoji", title: "Emoji 图标标签", hint: null },
  ];

  let total = 0;
  for (const sec of sections) {
    const list = groups[sec.key] || [];
    total += list.length;
    const block = document.createElement("div");
    block.className = "tag-group";
    block.innerHTML = `<div class="tag-group-title">${sec.title}${sec.hint ? ` · ${sec.hint}` : ""}</div>`;
    const chips = document.createElement("div");
    chips.className = "tag-chips";

    if (!list.length) {
      chips.innerHTML = '<span class="hint">暂无</span>';
    } else {
      for (const tag of list) {
        const btn = document.createElement("button");
        btn.type = "button";
        btn.className = `tag-chip${sec.key === "emoji" ? " emoji" : ""}`;
        btn.textContent = BiliIndex.formatTagLabel(tag);
        btn.title = `code: ${tag.code}`;
        btn.addEventListener("click", () => onTagClick(tag, sec.key));
        chips.appendChild(btn);
      }
    }
    block.appendChild(chips);
    root.appendChild(block);
  }

  return total;
}

async function onTagClick(tag, kind) {
  const upMid = $("#tag-up-mid").value.trim();
  if (!upMid) {
    $("#action-msg").textContent = "请先填写或读取 UP主 UID";
    return;
  }

  if (kind === "category") {
    $("#action-msg").textContent = `已选一级「${tag.name}」，请继续选择二级/三级/Emoji 标签打标`;
    return;
  }

  $("#action-msg").textContent = "提交中…";
  try {
    const res = await BiliIndex.submitTag(upMid, tag.id);
    if (res?.ok) {
      $("#action-msg").textContent = res.message || `已对 ${upMid} 打标：${tag.name}`;
      const me = await BiliIndex.fetchMe();
      $("#points-status").textContent = `积分：${me.points}`;
    } else {
      $("#action-msg").textContent = res?.error || "打标失败";
    }
  } catch (e) {
    $("#action-msg").textContent = e.message;
  }
}

async function loadTags(force = false) {
  const status = $("#tags-load-status");
  status.textContent = "正在从服务器加载标签…";
  try {
    let tree = [];
    let emojiItems = [];
    try {
      if (force) {
        await BiliIndex.refreshTagCaches(true);
      }
      tree = await BiliIndex.getTagTree(force);
      const emojiRes = await BiliIndex.fetchPublic("/api/tag/quick-list?kind=emoji");
      emojiItems = emojiRes.items || [];
    } catch (e) {
      status.textContent = `后台加载失败，尝试直连… (${e.message})`;
      const [treeData, emojiRes] = await Promise.all([
        BiliIndex.fetchPublic("/api/tag/tree"),
        BiliIndex.fetchPublic("/api/tag/quick-list?kind=emoji"),
      ]);
      tree = treeData.items || [];
      emojiItems = emojiRes.items || [];
      await BiliIndex.storageSet({
        tagTree: tree,
        quickTags: tree.filter((t) => (t.tag_kind || "") !== "category" && t.level > 1),
        tagsCachedAt: Date.now(),
      });
    }

    const byCode = new Map(tree.map((t) => [t.code, t]));
    for (const t of emojiItems) {
      const prev = byCode.get(t.code);
      if (prev) {
        if (t.icon) prev.icon = BiliIndex.resolveTagIcon(t);
        if (t.tag_kind) prev.tag_kind = t.tag_kind;
      } else {
        byCode.set(t.code, { ...t, icon: BiliIndex.resolveTagIcon(t), tag_kind: "emoji" });
      }
    }
    tree = [...byCode.values()];

    if (!tree.length) {
      status.textContent = "未获取到标签。请确认 API 运行在 http://127.0.0.1:8000";
      $("#tag-sections").innerHTML =
        '<p class="hint">启动命令：uvicorn app.main:app --reload --port 8000</p>';
      return;
    }

    tagGroups = BiliIndex.groupTags(tree);
    const n = renderTagSections(tagGroups);
    const quickN = (tagGroups.sub?.length || 0) + (tagGroups.style?.length || 0) + (tagGroups.emoji?.length || 0);
    status.textContent = `已加载 ${n} 个标签（可打标 ${quickN} 个）· 缓存 1 小时`;
  } catch (e) {
    status.textContent = `加载失败：${e.message}`;
    $("#tag-sections").innerHTML =
      '<p class="hint">请检查 API 地址与密钥，并确认 biliindex-api 已启动。</p>';
  }
}

async function pickUpMidFromPage() {
  $("#action-msg").textContent = "";
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (!tab?.id) {
      $("#action-msg").textContent = "无法获取当前标签页";
      return;
    }
    const res = await chrome.tabs.sendMessage(tab.id, { type: "GET_LAST_UP_MID" });
    if (res?.upMid) {
      $("#tag-up-mid").value = res.upMid;
      $("#action-msg").textContent = `已读取 UID：${res.upMid}`;
    } else {
      $("#action-msg").textContent = "请先在页面上点击过评论/推荐区的标签槽";
    }
  } catch {
    $("#action-msg").textContent = "请刷新 B 站页面后再试";
  }
}

async function renderLoggedIn() {
  const token = await BiliIndex.getToken();
  if (!token) {
    $("#logged-out").classList.remove("hidden");
    $("#logged-in").classList.add("hidden");
    return;
  }

  try {
    const me = await BiliIndex.fetchMe();
    const membership = await BiliIndex.fetchMembership();
    $("#logged-out").classList.add("hidden");
    $("#logged-in").classList.remove("hidden");
    $("#username-label").textContent = me.username;
    $("#membership-status").textContent = membership.label || "免费用户";
    $("#points-status").textContent = `积分：${me.points}`;
    await showBanner(membership);
    await loadTags(false);
  } catch (e) {
    await BiliIndex.clearSession();
    await BiliIndex.invalidateTagCache();
    renderLoggedIn();
  }
}

$("#form-login").addEventListener("submit", async (e) => {
  e.preventDefault();
  showAuthError("");
  const fd = new FormData(e.target);
  const username = String(fd.get("username") || "").trim();
  const password = String(fd.get("password") || "");
  const rememberPassword = $("#remember-password").checked;
  const autoLogin = $("#auto-login").checked;
  try {
    await BiliIndex.login(username, password);
    await BiliIndex.saveLoginPrefs({
      username,
      password,
      rememberPassword,
      autoLogin,
    });
    await BiliIndex.refreshTagCaches(true);
    await renderLoggedIn();
  } catch (err) {
    showAuthError(err.message);
  }
});

$("#form-register").addEventListener("submit", async (e) => {
  e.preventDefault();
  showAuthError("");
  const fd = new FormData(e.target);
  try {
    await BiliIndex.register(fd.get("username"), fd.get("password"));
    await BiliIndex.refreshTagCaches(true);
    await renderLoggedIn();
  } catch (err) {
    showAuthError(err.message);
  }
});

$("#btn-logout").addEventListener("click", async () => {
  await BiliIndex.clearSession();
  await BiliIndex.invalidateTagCache();
  $("#action-msg").textContent = "";
  await renderLoggedIn();
});

$("#btn-exchange").addEventListener("click", async () => {
  $("#action-msg").textContent = "兑换中…";
  try {
    const res = await BiliIndex.exchangeMembership();
    $("#action-msg").textContent = res.message || "兑换成功";
    await renderLoggedIn();
  } catch (err) {
    $("#action-msg").textContent = err.message;
  }
});

$("#btn-refresh-tags").addEventListener("click", () => loadTags(true));
$("#btn-pick-up-mid").addEventListener("click", pickUpMidFromPage);

$("#api-base").addEventListener("change", async (e) => {
  await BiliIndex.storageSet({ apiBase: e.target.value.trim() });
  await BiliIndex.invalidateTagCache();
  await updateApiLinks();
});

(async () => {
  const base = await BiliIndex.getApiBase();
  $("#api-base").value = base;
  await initAuthForm();
  await tryAutoLogin();
  await renderLoggedIn();
})();
