document.addEventListener('click', function(e) {
  var btn = e.target.closest('.sitsel-load-more-btn');
  if (!btn) return;

  var gridWrapper = btn.closest('.sitsel-grid-wrapper');
  var wrapper = btn.closest('.sitsel-load-more-wrap') || gridWrapper;
  var grid = gridWrapper.querySelector('.sitsel-grid');
  var widgetId = gridWrapper.dataset.widgetId;

  // Create loader if not exists
  var loader = wrapper.querySelector('.sitsel-load-more-loader');
  if (!loader) {
    loader = document.createElement('div');
    loader.className = 'sitsel-load-more-loader';
    loader.innerHTML = '<span class="sitsel-spinner"></span>'; // style spinner in CSS
    wrapper.appendChild(loader);
  }

  var page = parseInt(btn.dataset.page, 10);
  var max  = parseInt(btn.dataset.maxPages, 10);
  var url  = new URL(window.location.href);
  url.searchParams.set('paged', page);

  // UI: show loader, disable button
  btn.disabled = true;
  loader.style.display = 'inline-block';

  fetch(url, { credentials: 'same-origin' })
    .then(function(r) { if (!r.ok) throw new Error('Network response was not ok'); return r.text(); })
    .then(function(html) {
      var parser = new DOMParser();
      var doc = parser.parseFromString(html, 'text/html');
      // Scope to the matching widget wrapper so multiple widgets on a page don't bleed into each other
      var fetchedWrapper = widgetId
        ? doc.querySelector('.sitsel-grid-wrapper[data-widget-id="' + widgetId + '"]')
        : doc.querySelector('.sitsel-grid-wrapper');
      var newItems = fetchedWrapper
        ? fetchedWrapper.querySelectorAll('.sitsel-grid-item')
        : [];
      newItems.forEach(function(item) { grid.appendChild(item); });

      // update page
      btn.dataset.page = page + 1;

      // hide loader and re-enable or remove button
      loader.style.display = 'none';
      if (page >= max) {
        btn.remove();
      } else {
        btn.disabled = false;
      }
    })
    .catch(function(err) {
      console.error(err);
      loader.style.display = 'none';
      btn.disabled = false;
      // optional: show a small error message
      var errEl = wrapper.querySelector('.sitsel-load-more-error');
      if (!errEl) {
        errEl = document.createElement('div');
        errEl.className = 'sitsel-load-more-error';
        errEl.textContent = 'Could not load more items. Please try again.';
        wrapper.appendChild(errEl);
      }
    });
});