import tooltip from './lib/tooltip';
import { findAncestor } from './lib/dom';

export default (context) => {
  //---------
  // tooltip
  $('.js-acms-tooltip', context).click(function () {
    tooltip(this);
    return false;
  });


  const tooltips = document.querySelectorAll('.js-acms-tooltip-hover');

  [].forEach.call(tooltips, (item) => {
    let interval;

    if (findAncestor(item, '#js-edit_inplace-box')) {
      return;
    }

    item.addEventListener('mouseenter', () => {
      tooltip(item, true);
      interval = setInterval(() => {
        if (!document.body.contains(item)) {
          $('.js-tooltip').remove();
          clearInterval(interval);
        }
      }, 300);
    });

    item.addEventListener('mouseleave', (e) => {
      clearInterval(interval);
      if ($(e.relatedTarget).hasClass('js-tooltip')) {
        const leaveFunc = (evt) => {
          if (evt.relatedTarget !== item) {
            evt.relatedTarget.removeEventListener('mouseleave', leaveFunc);
            tooltip(item, false);
          }
        };
        e.relatedTarget.addEventListener('mouseleave', leaveFunc);
      } else {
        tooltip(item, false);
      }
    });
  });
};
