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

  if (
    !window.ElasticFulltextSearchSettings ||
    !window.ElasticFulltextSearchSettings.searchActive ||
    !window.ElasticFulltextSearchSettings.recommendationActive
  ) {
    console.log("ElasticSearch marker disabled ❌ (SearchActive or RecommendationActive is false)");
    return;
  }

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

  function getVisibleProductNames() {
    const wrappers = document.querySelectorAll(".ui-menu-item-wrapper");

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

    return Array.from(wrappers)
      .map((el) => el.dataset.originalName.trim())
      .filter((t) => t.length > 0);
  }

  function markPurchasedProducts(purchasedList) {
    const wrappers = document.querySelectorAll(".ui-menu-item-wrapper");

    if (!purchasedList || !purchasedList.length) return;

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

    wrappers.forEach((el) => {
      const originalName = el.dataset.originalName?.trim().toLowerCase();

      el.innerHTML = el.dataset.originalName;
      el.removeAttribute("style");

      const productData = purchasedList.find(
        (x) => originalName === x.name.trim().toLowerCase()
      );

      if (!productData) return;

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

      if (isTop) {
        highlightElement(el);
      }
    });
  }

  function highlightElement(el) {
    el.style.color = "#cfa93e";
    el.style.fontWeight = "600";
    el.style.textShadow = "0 0 4px rgba(207,169,62,0.5)";
    el.style.background = "rgba(255, 215, 0, 0.05)";
    el.style.borderRadius = "4px";
    el.style.padding = "1px 4px";

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

    el.innerHTML += `
      <span style="
        margin-left:6px;
        color:#cfa93e;
        font-weight:600;
        font-size:0.9em;
        vertical-align:middle;
      ">
        ⭐ ${label}
      </span>`;
  }

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

  function checkPurchased(names, callback) {
    if (!names.length) 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(() => { });
  }

  const observer = new MutationObserver(() => {
    clearTimeout(debounceTimeout);

    debounceTimeout = setTimeout(() => {
      const names = getVisibleProductNames();

      if (!names.length) return;

      checkPurchased(names, markPurchasedProducts);
    }, 300);
  });

  function startObserver() {
    const ac = document.querySelector(".ui-autocomplete");
    if (!ac) return setTimeout(startObserver, 500);
    observer.observe(ac, { childList: true, subtree: true });
  }

  startObserver();

  function handleSearchPage() {
    const productItems = document.querySelectorAll(".product-item");
    if (!productItems.length) return;

    const names = Array.from(productItems)
      .map((item) => {
        const titleEl = item.querySelector(".product-title a");
        if (!titleEl) return null;
        item.dataset.originalName = titleEl.textContent.trim();
        return titleEl.textContent.trim();
      })
      .filter((t) => t && t.length > 0);

    if (!names.length) return;

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

      productItems.forEach((item) => {
        const name = item.dataset.originalName?.trim().toLowerCase();
        const isTop = topProducts.some(x => x.name.trim().toLowerCase() === name);

        if (isTop) {
          const titleEl = item.querySelector(".product-title a");
          if (titleEl) {
            titleEl.style.color = "#cfa93e";
            item.style.position = "relative";

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

            const badge = document.createElement("div");
            badge.textContent = `⭐ ${label}`;
            badge.style.position = "absolute";
            badge.style.top = "10px";
            badge.style.right = "10px";
            badge.style.background = "linear-gradient(135deg, rgba(255,245,200,0.95), rgba(255,220,120,0.95))";
            badge.style.color = "#7a5a00";
            badge.style.padding = "4px 8px";
            badge.style.borderRadius = "6px";
            badge.style.fontWeight = "600";
            badge.style.fontSize = "0.85em";
            badge.style.boxShadow = "0 2px 4px rgba(0,0,0,0.1), inset 0 1px 1px rgba(255,255,255,0.3)";
            badge.style.border = "1px solid rgba(207,169,62,0.4)";
            badge.style.textShadow = "0 1px 1px rgba(255,255,255,0.3)";
            badge.style.zIndex = "2";
            badge.style.pointerEvents = "none";

            item.appendChild(badge);
          }
        }
      });
    });
  }

  if (window.location.pathname.toLowerCase().includes("/search")) {
    handleSearchPage();
  }
});