const searchInput = document.getElementById("helpSearch");
const searchSummary = document.getElementById("searchSummary");
const sections = [...document.querySelectorAll(".doc-section")];
const tocLinks = [...document.querySelectorAll(".toc-link")];
const checkerResult = document.getElementById("checkerResult");

function updateSearch() {
  const query = searchInput.value.trim().toLowerCase();
  let matches = 0;
  sections.forEach((section) => {
    const haystack = `${section.textContent} ${section.dataset.searchText || ""}`.toLowerCase();
    const matched = !query || haystack.includes(query);
    section.classList.toggle("is-hidden", !matched);
    section.classList.toggle("is-match", Boolean(query && matched));
    if (matched) matches += 1;
  });
  searchSummary.textContent = query
    ? `找到 ${matches} 个相关模块。`
    : "输入关键词后会高亮匹配的帮助卡片。";
}

function setActiveToc() {
  const visible = sections
    .filter((section) => !section.classList.contains("is-hidden"))
    .map((section) => ({
      id: section.id,
      top: Math.abs(section.getBoundingClientRect().top - 120),
    }))
    .sort((a, b) => a.top - b.top)[0];
  if (!visible) return;
  tocLinks.forEach((link) => {
    link.classList.toggle("active", link.getAttribute("href") === `#${visible.id}`);
  });
}

function bindTabs() {
  document.querySelectorAll("[data-tabs]").forEach((root) => {
    const buttons = [...root.querySelectorAll('[role="tab"]')];
    const panels = [...root.querySelectorAll('[role="tabpanel"]')];
    buttons.forEach((button) => {
      button.addEventListener("click", () => {
        buttons.forEach((item) => item.setAttribute("aria-selected", String(item === button)));
        panels.forEach((panel) => {
          const active = panel.id === button.getAttribute("aria-controls");
          panel.hidden = !active;
          panel.classList.toggle("active", active);
        });
      });
    });
  });
}

function bindAccordion() {
  document.querySelectorAll("[data-accordion] article").forEach((item) => {
    const button = item.querySelector("button");
    const panel = item.querySelector("div");
    button.addEventListener("click", () => {
      const expanded = button.getAttribute("aria-expanded") === "true";
      button.setAttribute("aria-expanded", String(!expanded));
      panel.hidden = expanded;
    });
  });
}

function bindCopyButtons() {
  document.querySelectorAll("[data-copy]").forEach((button) => {
    button.addEventListener("click", async () => {
      const target = document.querySelector(button.dataset.copy);
      if (!target) return;
      await navigator.clipboard?.writeText(target.textContent.trim());
      const previous = button.textContent;
      button.textContent = "已复制";
      window.setTimeout(() => {
        button.textContent = previous;
      }, 1400);
    });
  });
}

function updateChecker() {
  const inputs = [...document.querySelectorAll(".export-checker input")];
  const done = inputs.filter((input) => input.checked).length;
  checkerResult.textContent = done === inputs.length
    ? "检查完成，可以返回制作器导出。"
    : `已完成 ${done}/${inputs.length} 项。`;
}

searchInput.addEventListener("input", updateSearch);
window.addEventListener("scroll", setActiveToc, { passive: true });
document.querySelectorAll(".export-checker input").forEach((input) => {
  input.addEventListener("change", updateChecker);
});

bindTabs();
bindAccordion();
bindCopyButtons();
updateSearch();
updateChecker();
