const getChangeHeader = () => getClassNameElementsArray('change-header')[0]

const getFileElements = () => querySelectorAllArray('.file,.icon-folder-closed')

const getSelectedFile = () => getClassNameElementsArray('file-selected')[0]

const addScrollHints = () => {
    getClassNameElementsArray('sages-extra-breadcrumbs').forEach(e => e.parentNode.removeChild(e))
    const buildHint = (fileElement, prefix, top) => {
        const hint = document.createElement('div', {})
        hint.classList.add('sages-extra-breadcrumbs')
        if (fileElement.classList.contains('file-viewed')) {
            hint.classList.add('sages-extra-breadcrumbs-viewed')
        }
        hint.innerText = `${prefix} ${decodeURIComponent(fileElement.firstElementChild?.href?.split('#')[1] || 'In Folder...')}`
        if (top) {
            hint.style.top = top
        }
        return hint;
    }
    const selectedFile = getSelectedFile()
    const fileElements = getFileElements()
    const index = fileElements.indexOf(selectedFile)
    const breadcrumbs = Array.from(getChangeHeader().getElementsByTagName('h4'))[0]
    console.log({ breadcrumbs })
    if (index > 0) {
        breadcrumbs.prepend(buildHint(fileElements[index - 1], 'Prev:', '1.4em'))
    }
    if (index < fileElements.length - 1) {
        breadcrumbs.appendChild(buildHint(fileElements[index + 1], 'Next:'))
    }

}

const changeFile = (e, noRecurse) => {
    const selectedFile = getSelectedFile()
    const fileElements = getFileElements()

    const up = e.wheelDelta ? e.wheelDelta > 0 : e.deltaY < 0
    const index = fileElements.indexOf(selectedFile)
    const nextElement =
        (up && index > 0) ? fileElements[index - 1] :
        (!up && index < (fileElements.length - 1)) ? fileElements[index + 1] :
        null
    const isFolder = !nextElement?.firstElementChild
    const toClick = nextElement?.firstElementChild ?? nextElement
    toClick?.focus()
    toClick?.click()
    if (isFolder) {
        changeFile(e)
    }
}

let styled = false
addFix(() => {
    const header = getChangeHeader()
    header.onwheel = changeFile
    styled || addStyle(`
      .sages-extra-breadcrumbs {
        color: rgba(0, 0, 0, 0) !important;
        margin-top: -1.6em !important;
        /*margin-bottom: -1em !important;*/
        float: left !important;
        position: absolute;
        font-size: 11px;
        margin-left: 20%;
      }
      .diff-meta:hover h4 .sages-extra-breadcrumbs {
        color: rgba(0, 0, 0, 0.35) !important;
      }
      .diff-meta:hover h4 .sages-extra-breadcrumbs-viewed {
        color: rgba(0, 0, 0, 0.2) !important;
      }
    `)
    styled = true
})

window.addEventListener('load', () => setTimeout(addScrollHints, NEW_PAGE_DELAY))
addEventListener('hashchange', () => setTimeout(addScrollHints, 200))
