import Component from 'ember-component';
import $ from 'jquery';
import computed from 'ember-computed';
import { htmlSafe } from 'ember-string';
import on from 'ember-evented/on';

export default Component.extend({
  scrollTop: 0,

  init() {
    this._super(...arguments);
    this.inDOM = false;
  },

  setupListeners: on('didInsertElement', function () {
    this.set('inDOM', true);
    this.scrollingParentEl = this.$().closest('.tse-content').parent();
    this.scrollingParentEl.on(`scroll.${this.get('elementId')}`, () => {
      this.set('scrollTop', this.scrollingParentEl[0].scrollTop);
    });
  }),

  breakdownListeners: on('willDestroyElement', function () {
    this.scrollingParentEl.off(`scroll.${this.get('elementId')}`);
  }),

  targetElement: computed('target', 'inDOM', function() {
    if (this.get('inDOM')) {
      let target = document.getElementById(this.get('target'));
      return target;
    }
  }),

  style: computed('targetElement', 'scrollTop', function() {
    let targetElement = this.get('targetElement');
    if (!targetElement) {
      return;
    }

    let $targetElement = $(targetElement);
    let { left, top } = $targetElement.offset();
    let width = $targetElement.width();
    let height = $targetElement.outerHeight();
    let leftPosition = left + width;
    let topPosition = top + (height / 2) - (this.$('.js-hotspot-height').height() / 2);

    return htmlSafe(`left: ${leftPosition}px; top: ${topPosition}px;`);
  }),

  actions: {
    dismiss() {}
  }
});
