// import $ from 'jquery';
const $ = require('jquery');
class Masonry {
  constructor(row, buttonText, sizes) {
    this.section = row.addClass('initiated');
    this.sizes = sizes;
    this.items = [];
    this.visibleItems = [];
    this.batchSize = 0;
    this.btn = $('<button class="btn load-more has-icon icon-laden" />').text(buttonText);

    row.children().each((i, element) => {
      this.items.push($(element).remove());
    })


      row.after($('<div class="button-wrapper" />').append(this.btn));


    this.btn.on('click', (e) => {
      e.preventDefault();
      this.addBatch();
    })

    this.buildCols();
    this.addBatch();
    this.handleResize();
  }

  addBatch() {
    const newItems = [];
    for (let i = 0; i < this.batchSize; i++) {
      if (this.items.length > 0) {
        if (this.items[0].attr('data-thumb')) {
          this.loadImage(this.items[0]);
        }
        this.items[0].find('img[data-src]').each((i, el) => {
          $(el).one('load', (e) => {
            $(e.currentTarget).addClass('loaded');
          }).attr('src', $(el).attr('data-src'))
        })
        this.visibleItems.push(this.items[0]);
        newItems.push(this.items[0].css({'opacity': 0, 'transform': 'scale(0.8)', 'transition': '0.4s ease ' + (0.07 * i) + 's'}));
        this.items.splice(0,1);
      }
    }

    if (this.items.length === 0) {
      this.btn.parent().hide();
    }

    this.addToCols(newItems);
  }

  loadImage(item) {
    const img = $('<img src="' + this.items[0].attr('data-thumb') + '" alt="" />').one('load', () => {
      setTimeout(() => {
        item.addClass('loaded');
      },200)
    })
    item.find('a').append(img);
  }

  handleResize() {
    this.width = this.section.outerWidth();
    this.timer = null;

    $(window).on('resize', () => {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      setTimeout(() => {
        this.buildCols();
      },200);
    })
  }

  buildCols() {
    const w = this.section.width();
    let cols = 1;

    $.each(this.sizes, (i, size) => {
      if (w > size.minWidth) {
        cols = i + 1;
        this.batchSize = size.batchSize;
      }
      else {
        return false;
      }
    })

    if (this.cols && cols === this.cols.length) {
      return;
    }

    $.each(this.cols, (i, item) => {
      item.col.remove();
    })

    this.cols = [];
    this.section.attr('data-cols', cols);

    for (let i = 0; i < cols; i++) {
      const col = $('<div class="column" />').appendTo(this.section);

      this.cols.push({
        col: col,
        index: i,
        height: 0
      })
    }

    this.addToCols(this.visibleItems);
  }

  addToCols(items) {
    $.each(items, (i, element) => {
      const item = $(element);
      this.cols[0].col.append(item);
      this.cols[0].height = Math.round(item.position().top + item.outerHeight());
      this.cols.sort( this.compareCols );

      window.requestAnimationFrame(() => {
        item.css({'opacity': '1', 'transform': 'scale(1)'});
      })
    })
  }

  compareCols(a, b) {
    if (a.height < b.height) {
      return -1;
    }
    else if (a.height > b.height) {
      return 1;
    }
    else {
      if (a.index < b.index) {
        return -1;
      }
      if (a.index > b.index) {
        return 1;
      }
    }
    return 0;
  }
}

export default Masonry;


$('body').on('ihk-init dynamic-component-loaded gfi-dynamic-init', function () {
  $('.teasers[data-type="masonry"] .row:not(.initiated)').each((i, el) => {
    const btnText = window.ihk.translations.loadMoreArticles;
    const selector = $(el);
    if (!selector.find('dynamic-content').length) {
      new Masonry(selector, btnText,[
        { minWidth: 0, batchSize: 2 },
        { minWidth: 567, batchSize: 3 },
        { minWidth: 1000, batchSize: 6 }
      ]);
    }
  });
});
