import fetchMoreProducts from "../../api/fetchMoreProducts";
import loadProducts from "../../widget/products/loadProducts";

function createLoadingElement() {
  const loadingElement = document.createElement("div");
  loadingElement.classList.add("firevert-powerwidget__loading");
  loadingElement.innerHTML = `
    <div class="firevert-powerwidget__loading-spinner">
      <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none">
        <circle cx="12" cy="12" r="10" stroke-width="2" stroke-linecap="round" stroke-dasharray="31.416" stroke-dashoffset="31.416"/>
        <circle cx="12" cy="12" r="6" stroke-width="1" opacity="0.6"/>
      </svg>
    </div>
  `;
  return loadingElement;
}

function showLoading(productsList) {
  const existingLoading = productsList.querySelector(
    ".firevert-powerwidget__loading"
  );
  if (existingLoading) return existingLoading;

  const loadingElement = createLoadingElement();
  productsList.appendChild(loadingElement);
  return loadingElement;
}

function hideLoading(productsList) {
  const loadingElement = productsList.querySelector(
    ".firevert-powerwidget__loading"
  );
  if (loadingElement) {
    loadingElement.style.opacity = "0";
    loadingElement.style.transform = "translateY(-20px)";

    setTimeout(() => {
      loadingElement.remove();
    }, 300);
  }
}

export default function setupInfinityScroll(
  shadowRoot,
  theme,
  paginationState
) {
  const productsList = shadowRoot.querySelector(
    ".firevert-powerwidget__products-list"
  );

  if (!productsList) return;

  let isLoading = false;

  const handleScroll = async () => {
    if (isLoading || !paginationState.hasMore) return;

    const scrollTop = productsList.scrollTop;
    const scrollHeight = productsList.scrollHeight;
    const clientHeight = productsList.clientHeight;

    if (scrollTop + clientHeight >= scrollHeight - 50) {
      isLoading = true;

      showLoading(productsList);

      try {
        const nextPage = paginationState.currentPage + 1;
        const response = await fetchMoreProducts(nextPage);

        if (response && response.data && response.data.length > 0) {
          hideLoading(productsList);
          loadProducts(shadowRoot, response.data, theme, true);

          paginationState.currentPage = response.pagination.currentPage;
          paginationState.totalPages = response.pagination.totalPages;
          paginationState.hasMore = response.pagination.hasMore;
        } else {
          hideLoading(productsList);
        }
      } catch (error) {
        console.error("Error loading more products:", error);
        hideLoading(productsList);
      } finally {
        isLoading = false;
      }
    }
  };

  productsList.addEventListener("scroll", handleScroll);
}
