(() => {
  const grid = document.querySelector('[data-blog-grid]');
  if (!grid) {
    return;
  }

  const loadMore = document.querySelector('[data-blog-load-more]');
  if (!loadMore) {
    return;
  }

  const ajaxUrl = window.fjordBlogScroll?.ajax_url;
  if (!ajaxUrl) {
    loadMore.classList.add('is-hidden');
    return;
  }

  let currentPage = Number(grid.dataset.blogPage) || 1;
  let totalPages = Number(grid.dataset.blogTotal) || 0;
  const exclude = grid.dataset.blogExclude || '';
  let loading = false;

  const sentinelObserver = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          loadNextPage();
        }
      });
    },
    {
      rootMargin: '200px',
    }
  );

  function loadNextPage() {
    if (loading || currentPage >= totalPages) {
      sentinelObserver.disconnect();
      return;
    }
    loading = true;
    loadMore.classList.add('is-loading');
    currentPage += 1;

    const body = new URLSearchParams({
      action: 'fjord_load_more_blog',
      page: currentPage,
    });
    if (exclude) {
      body.append('exclude', exclude);
    }

    fetch(ajaxUrl, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      },
      body: body.toString(),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then((data) => {
        if (!data || !data.success) {
          throw new Error('Invalid response');
        }
        const { html, total } = data.data || {};
        if (html) {
          grid.insertAdjacentHTML('beforeend', html);
        }
        const maxPages = Number(total) || totalPages;
        totalPages = maxPages;
        grid.dataset.blogTotal = maxPages;
        if (currentPage >= maxPages) {
          loadMore.classList.add('is-hidden');
          sentinelObserver.disconnect();
        }
      })
      .catch(() => {
        currentPage -= 1;
      })
      .finally(() => {
        loading = false;
        loadMore.classList.remove('is-loading');
      });
  }

  if (currentPage < totalPages) {
    sentinelObserver.observe(loadMore);
  } else {
    loadMore.classList.add('is-hidden');
  }
})();
