import $ from 'jquery';
import { getSelector, inserted } from './feature_highlight_helper';
import { togglePopover, mouseenter, debouncedMouseleave } from '../shared/popover';

export function setupFeatureHighlightPopover(id, debounceTimeout = 300) {
  const $selector = $(getSelector(id));
  const $parent = $selector.parent();
  const $popoverContent = $parent.siblings('.feature-highlight-popover-content');
  const hideOnScroll = togglePopover.bind($selector, false);

  $selector
    // Set up popover
    .data('content', $popoverContent.prop('outerHTML'))
    .popover({
      html: true,
      // Override the existing template to add custom CSS classes
      template: `
        <div class="popover feature-highlight-popover" role="tooltip">
          <div class="arrow"></div>
          <div class="popover-body"></div>
        </div>
      `,
    })
    .on('mouseenter', mouseenter)
    .on('mouseleave', debouncedMouseleave(debounceTimeout))
    .on('inserted.bs.popover', inserted)
    .on('show.bs.popover', () => {
      window.addEventListener('scroll', hideOnScroll, { once: true });
    })
    // Display feature highlight
    .removeAttr('disabled');
}

export function findHighestPriorityFeature() {
  let priorityFeature;

  const sortedFeatureEls = [].slice
    .call(document.querySelectorAll('.js-feature-highlight'))
    .sort((a, b) => (a.dataset.highlightPriority || 0) < (b.dataset.highlightPriority || 0));

  const [priorityFeatureEl] = sortedFeatureEls;
  if (priorityFeatureEl) {
    priorityFeature = priorityFeatureEl.dataset.highlight;
  }

  return priorityFeature;
}

export function highlightFeatures() {
  const priorityFeature = findHighestPriorityFeature();

  if (priorityFeature) {
    setupFeatureHighlightPopover(priorityFeature);
  }

  return priorityFeature;
}

@@ -1163,24 +1163,98 @@
 abled');%0A%7D%0A%0A
+const getPriority = e =%3E parseInt(e.dataset.highlightPriority, 10) %7C%7C 0;%0A%0A
 export funct
@@ -1434,64 +1434,27 @@
  =%3E 
-(a.dataset.highlightPriority %7C%7C 0) %3C (b.dataset.highligh
+getPriority(b) - ge
 tPri
@@ -1458,21 +1458,18 @@
 Priority
- %7C%7C 0
+(a
 ));%0A%0A  c

Fix sorting in feature_highlight