document.addEventListener("DOMContentLoaded", function () {

  if (
    !window.ElasticFulltextSearchSettings ||
    !window.ElasticFulltextSearchSettings.searchActive
  ) {
    console.log("Elastic disabled ❌");
    return;
  }

  const enableHighlight = window.ElasticFulltextSearchSettings.highlightSearchTerm;
  const enableFavorites = window.ElasticFulltextSearchSettings.recommendationActive;

  let debounceTimeout;
  let lastNamesKey = "";
  let lastResponse = null;

  function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  }

  function getQuery() {
    const input = document.querySelector("#small-searchterms");
    return input?.value?.trim() || "";
  }

  function getWrappers() {
    return document.querySelectorAll(".ui-menu-item-wrapper");
  }

  function ensureOriginalNames() {
    getWrappers().forEach(el => {
      if (!el.dataset.originalName) {
        el.dataset.originalName = el.textContent.trim();
      }
    });
  }

  function getNames() {
    return Array.from(getWrappers())
      .map(el => el.dataset.originalName)
      .filter(x => x);
  }

  function getKey(names) {
    return names.join("|").toLowerCase();
  }

  function checkPurchased(names, callback) {
    if (!enableFavorites || !names.length) {
      callback([]);
      return;
    }

    const key = getKey(names);

    if (key === lastNamesKey && lastResponse) {
      callback(lastResponse);
      return;
    }

    lastNamesKey = key;

    fetch("/ElasticMarker/CheckPurchasedProducts", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(names),
    })
      .then(r => r.json())
      .then(data => {
        lastResponse = data;
        callback(data);
      })
      .catch(() => callback([]));
  }

  function render(purchasedList) {
    const wrappers = getWrappers();
    const query = getQuery();

    const regex = (enableHighlight && query)
      ? new RegExp(`(${escapeRegExp(query)})`, "ig")
      : null;

    const maxCount = Math.max(0, ...purchasedList.map(x => x.count || 0));
    const topProducts = purchasedList.filter(x => x.count === maxCount && x.count > 0);

    wrappers.forEach(el => {

      const original = el.dataset.originalName;
      if (!original) return;

      let html = original;

      if (regex) {
        html = original.replace(regex, `<span class="elastic-highlight">$1</span>`);
      }

      el.innerHTML = html;
      el.removeAttribute("style");

      if (enableFavorites) {
        const nameLower = original.trim().toLowerCase();

        const isTop = topProducts.some(
          x => x.name.trim().toLowerCase() === nameLower
        );

        if (isTop) {
          el.style.color = "#cfa93e";
          el.style.fontWeight = "600";

          const label =
            (window.ElasticSearchLocalization &&
              window.ElasticSearchLocalization.favoriteLabel) ||
            "Vaše oblíbené";

          const span = document.createElement("span");
          span.style.marginLeft = "6px";
          span.style.color = "#cfa93e";
          span.style.fontWeight = "600";
          span.style.fontSize = "0.9em";
          span.textContent = `⭐ ${label}`;

          el.appendChild(span);
        }
      }

    });
  }

  function process() {
    ensureOriginalNames();
    const names = getNames();

    checkPurchased(names, render);
  }

  const observer = new MutationObserver(() => {
    clearTimeout(debounceTimeout);
    debounceTimeout = setTimeout(process, 100);
  });

  function startObserver() {
    const ac = document.querySelector(".ui-autocomplete");
    if (!ac) return setTimeout(startObserver, 300);

    observer.observe(ac, { childList: true, subtree: true });
  }

  startObserver();

  const input = document.querySelector("#small-searchterms");
  if (input) {
    input.addEventListener("input", process);
  }

});