/* global location */
import deepSelector from './deep-selector.js'

const STEP = 100
const MAX_STEPS = 10
const STOP_EVENTS = ['mousedown', 'wheel', 'touchmove', 'keydown']

let listening = false

export default async function hashJump () {
  if (!listening) {
    listening = true
    globalThis.addEventListener('hashchange', () => scrollToElement(location.hash))
    globalThis.addEventListener('route', () => scrollToElement(location.hash))
  }

  await scrollToElement(location.hash)
}

async function scrollToElement (selector) {
  let cancel = false
  const listener = () => { cancel = true }

  for (const event of STOP_EVENTS) { document.addEventListener(event, listener) }

  for (let ii = 0; ii < MAX_STEPS; ++ii) {
    const [el] = await deepSelector(selector)
    el && !cancel && el.scrollIntoView()
    await new Promise(resolve => setTimeout(resolve, STEP))
  }

  for (const event of STOP_EVENTS) { document.removeEventListener(event, listener) }
}
