// single-page offline manual

let OLM_PRODUCT;

function changePage() {
  let page = null;
  let hash = location.hash.substr(1);

  const tokens = hash.split("___");

  // find dom element matching the page hash
  page = document.getElementById(tokens[0]);

  // hide all non-matching pages
  if (page) {
    for (const p of document.querySelectorAll(".olm-page")) {
      if (p.id != page.id) {
        p.classList.add("d-none");
      }
    }
    // show requested page
    page.classList.remove("d-none");
    // scroll to page title, unless 3rd token (subheading or tab) is present
    if (tokens.length == 1) {
      window.scroll({ top: 0, behavior: "instant" });
    }
  } else {
    console.log(`Manual page not found: ${hash}`);
  }
}

window.addEventListener("hashchange", changePage);

document.addEventListener("DOMContentLoaded", () => {
  // redirect missing or empty hash to index
  if (location.hash.length < 2) {
    window.location = "#index";
    return;
  }

  OLM_PRODUCT = document.getElementById("index").dataset["olmProduct"];

  for (const link of document.querySelectorAll("a")) {
    const href = link.getAttribute("href");
    if (href === null) continue;

    // attach custom language switching event
    if (link.classList.contains("langswitch")) {
      if (window.location.protocol == "about:") {
        link.removeAttribute("href");
        link.setAttribute("role", "button");
        link.addEventListener("click", function () {
          this.dispatchEvent(
            new CustomEvent("UserSelectedLanguage", {
              detail: lang,
            }),
          );
        });
      }
      continue;
    }

    if (href.startsWith(`../../${OLM_PRODUCT}`)) {
      // fixup relative links to pages for current product
      const m = href.match(`^../../${OLM_PRODUCT}/([^#]+[^/#])?/?#?([^/]+)?$`);
      let new_href = "#" + m[1]?.replaceAll("/", "__");
      if (m[2] !== undefined) {
        new_href = new_href + `___${m[2]}`;
      }
      link.setAttribute("href", new_href);
    } else if (href.startsWith("../../")) {
      // fixup relative links to pages for other products
      link.setAttribute(
        "href",
        href.replace("../../", "https://support.torproject.org/"),
      );
      link.setAttribute("target", "_blank");
    } else if (href.startsWith("https://") || href.startsWith("http://")) {
      // add target="_blank" to external links
      link.setAttribute("target", "_blank");
    }
  }

  // prefix page id to subheading anchors
  for (const heading of document.querySelectorAll("div.heading-anchor")) {
    if (heading.id === null) continue;

    let section_id = heading.closest("div.olm-page")?.id;
    if (section_id) heading.id = `${section_id}___${heading.id}`;
  }

  changePage();
});
