(function () {
  function normalize(value) {
    return (value || "")
      .toLowerCase()
      .replace(/ä/g, "ae")
      .replace(/ö/g, "oe")
      .replace(/ü/g, "ue")
      .replace(/ß/g, "ss")
      .replace(/&auml;/g, "ae")
      .replace(/&ouml;/g, "oe")
      .replace(/&uuml;/g, "ue")
      .replace(/&szlig;/g, "ss");
  }

  function currentPath() {
    return window.location.pathname.replace(/\/+$/, "") || "/help/index.html";
  }

  window.addEventListener("DOMContentLoaded", function () {
    var path = currentPath();
    document.querySelectorAll(".help-nav a[href]").forEach(function (link) {
      var linkPath = new URL(link.getAttribute("href"), window.location.origin).pathname.replace(/\/+$/, "");
      if (path === linkPath) {
        link.setAttribute("aria-current", "page");
      }
    });

    var input = document.getElementById("helpSearch");
    var results = document.getElementById("helpSearchResults");
    var index = window.A4W_HELP_INDEX || [];
    if (!input || !results) {
      return;
    }

    input.addEventListener("input", function () {
      var query = normalize(input.value.trim());
      results.innerHTML = "";
      results.classList.toggle("is-visible", query.length > 0);
      if (!query) {
        return;
      }

      var words = query.split(/\s+/).filter(Boolean);
      var matches = index
        .map(function (item) {
          var title = normalize(item.title);
          var headings = normalize(item.headings);
          var keywords = normalize(item.keywords);
          var haystack = normalize([item.title, item.headings, item.keywords, item.text].join(" "));
          var score = words.reduce(function (sum, word) {
            return sum
              + (title.indexOf(word) >= 0 ? 4 : 0)
              + (keywords.indexOf(word) >= 0 ? 3 : 0)
              + (headings.indexOf(word) >= 0 ? 2 : 0)
              + (haystack.indexOf(word) >= 0 ? 1 : 0);
          }, 0);
          if (title.indexOf(query) >= 0) score += 6;
          if (keywords.indexOf(query) >= 0) score += 4;
          return { item: item, score: score };
        })
        .filter(function (match) { return match.score > 0; })
        .sort(function (a, b) { return b.score - a.score || a.item.title.localeCompare(b.item.title); })
        .slice(0, 10);

      if (matches.length === 0) {
        results.innerHTML = '<div class="search-empty">Keine Treffer gefunden.</div>';
        return;
      }

      matches.forEach(function (match) {
        var link = document.createElement("a");
        link.href = match.item.url;
        link.innerHTML = "<strong></strong><span></span>";
        link.querySelector("strong").textContent = match.item.title;
        link.querySelector("span").textContent = match.item.text;
        results.appendChild(link);
      });
    });
  });
})();
