const Instafeed = require('@static/jquery/wpj-instafeed.js');

const feed = new Instafeed({
   get: 'username',
   username: 'kosmetika.zdravi',
   limit: 5,
   resolution: 'standard_resolution',
   template:
      '<a href="{{model.images.standard_resolution.url}}" class="imgbox" data-rel="gallery" title="{{caption}}">' +
      '<div style="background-image: url({{model.images.standard_resolution.url}});" title="{{caption}}">' +
      '<div class="caption"><p>{{caption}}</p></div>' +
      '</div>' +
      '</a>',
   after: function() {
      // remove hashtags from image caption
      var caption = $("#instafeed p");

      // loop thought images that have caption
      for (var i = 0; i < caption.length; i++) {
         if (caption[i].textContent.length > 0) {
            // remove words starting with # or @
            var newCaption = caption[i].textContent.replace(/[#@]\w+\s?/g, "");
            // trim to 70 characters and replace original textContent
            caption[i].textContent = (newCaption.length >= 70) ? newCaption.substring(0, 70) + "..." : newCaption;
         }
      }
   }
});

function observeElement(entries) {
   for (let i = 0; i < entries.length; i++) {
      if (entries[i].intersectionRatio > 0 && !entries[i].target.children.length) {
         feed.run();
      }
   }
}

const observerOptions = {
   rootMargin: '300px 0px 300px 0px'
};

const observer = new IntersectionObserver(observeElement, observerOptions);

const target = document.querySelector('#instafeed');

if (target) {
   observer.observe(target);
}
