const search = document.querySelector(".docs-search input");
const sections = [...document.querySelectorAll(".docs-main section[data-title]")];
const navigationLinks = [...document.querySelectorAll(".docs-sidebar a[href^='#']")];
const tocLinks = [...document.querySelectorAll(".docs-toc a")];

for (const button of document.querySelectorAll("[data-copy]")) {
  button.addEventListener("click", async () => {
    const code = button.closest(".code-block")?.querySelector("code")?.textContent ?? "";
    await navigator.clipboard.writeText(code);
    const original = button.textContent;
    button.textContent = "Copied";
    setTimeout(() => (button.textContent = original), 1200);
  });
}

search?.addEventListener("input", () => {
  const query = search.value.trim().toLowerCase();
  for (const section of sections) {
    const matches = !query || section.textContent.toLowerCase().includes(query);
    section.classList.toggle("search-hidden", !matches);
  }
});

addEventListener("keydown", (event) => {
  if (event.key === "/" && document.activeElement !== search) {
    event.preventDefault();
    search?.focus();
  }
});

const activate = (id) => {
  for (const link of [...navigationLinks, ...tocLinks]) {
    link.classList.toggle("active", link.hash === `#${id}`);
  }
};

const observer = new IntersectionObserver(
  (entries) => {
    const visible = entries.filter((entry) => entry.isIntersecting);
    if (visible.length) activate(visible.sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top)[0].target.id);
  },
  { rootMargin: "-70px 0px -72%", threshold: 0 },
);
for (const section of sections) observer.observe(section);
