import { type MouseEvent } from 'react'

export const KEY_PREFIX_UPLOAD = 'upload_'

let route_index = 0
let route_state: { path: string; with: any; keep: any }[] = [{ path: getWindowPath(), with: null, keep: null }]

window.addEventListener('popstate', (e) => {
    if (e.state?.route_index !== undefined) {
        route_index = e.state.route_index
    }
})

export function getWindowPath() {
    return window.location.href.slice(window.location.origin.length)
}

export function setTitle(title: string) {
    document.title = `${title} • gifuu`
}

export function routeTo(path: string, withData?: any, keepData?: any) {
    route_state[route_index].keep = keepData ?? null
    route_state.splice(route_index + 1)
    route_state.push({ path, with: withData, keep: null })
    route_index++
    window.history.pushState({ route_index }, '', path)
    window.dispatchEvent(new PopStateEvent('popstate'))
}

export function routeIntercept(event: MouseEvent<HTMLAnchorElement>, withData?: any, keepData?: any) {
    if (event.currentTarget instanceof HTMLAnchorElement) {
        event.preventDefault()
        routeTo(event.currentTarget.getAttribute('href') ?? '/', withData, keepData)
    }
}

export function routeBack() {
    if (route_index <= 0) {
        routeTo('/')
        return
    }
    route_index--
    const entry = route_state[route_index]
    window.history.pushState({ route_index }, '', entry.path)
    window.dispatchEvent(new PopStateEvent('popstate'))
}

export function routeBackURI() {
    return route_state[route_index - 1]?.path ?? '/'
}

export function stateRecover<T>(): T | undefined {
    return (route_state[route_index]?.with ?? route_state[route_index]?.keep) as T
}
