import smarterHover from './util/smarter-hover'

const OffCanvas = require('./components/off-canvas')

function getAfterContent(el) {
  if (typeof global.getComputedStyle !== 'function') return ''
  return global.getComputedStyle(el, ':after').content
}

function setupHeader(i, el) {
  const $el = $(el)
  const nav = new OffCanvas($el.data('target')).$element

  nav.find('.nav-section').each((_, section) => {
    smarterHover(section)
  })
  nav.on('mouseout', (e) => {
    if (getAfterContent(nav[0]).indexOf('off-canvas') === -1) {
      closeSections(nav)
    }
  })
  nav.on('hide.ui.offcanvas', closeSections.bind(null, nav))
  nav.on('hide.ui.collapse', '.collapse', backToTop.bind(null, nav))
}

function closeSections(nav, e) {
  nav.find('[data-toggle="collapse"][aria-expanded="true"]').trigger('click.ui.collapse.data-api')
}

function backToTop(nav, e) {
  const scrollTop = nav.scrollTop()
  if (scrollTop === 0) return

  global.requestAnimationFrame(backToTop.bind(null, nav))
  // Magic number alert: this is purely a result of eye-balling
  nav.scrollTop(scrollTop - scrollTop / 6)
}

function initNavigation() {
  $('[data-toggle="off-canvas"]').each(setupHeader)
}

export { initNavigation as init }
