import "./i18n"
import App from "./App.svelte"

import { baseURL } from "./config"
import { hydrate } from "svelte"
import { location } from "./i18n"

const publishLocation = (_p?: string) => {
    let _s: string
    let _h: string
    if (_p) {
        const parts = _p.split("#")
        _p = parts.shift()
        _h = parts.join()
        if (_h) _h = "#" + _h

        const parts2 = _p.split("?")
        _p = parts2.shift()
        _s = parts2.join()
        if (_s) _s = "?" + _s
    }
    // make sure the path does not include the baseURL
    if (_p && _p.startsWith(baseURL)) {
        _p = _p.slice(baseURL.length)
    } else if (!_p) {
        _p = typeof window !== "undefined" && window.location?.pathname
    }

    const newLocation = {
        path: _p,
        search: _p ? _s : typeof window !== "undefined" && window.location?.search,
        hash: _p ? _h : typeof window !== "undefined" && window.location?.hash,
        push: !!_p,
        pop: !_p,
        url: "",
    }

    newLocation.url = `${baseURL}${newLocation.path}${newLocation.search ? "?" + newLocation.search : ""}`

    location.set(newLocation)
}

if (typeof history !== "undefined") {
    if (typeof Proxy !== "undefined") {
        // modern browser
        const historyApply = (target: any, thisArg: any, argumentsList: any[]) => {
            publishLocation(argumentsList && argumentsList.length >= 2 && argumentsList[2])
            Reflect.apply(target, thisArg, argumentsList)
        }

        history.pushState = new Proxy(history.pushState, {
            apply: historyApply,
        })

        history.replaceState = new Proxy(history.replaceState, {
            apply: historyApply,
        })
    } else {
        // ie11
        const pushStateFn = history.pushState
        const replaceStateFn = history.replaceState

        history.pushState = function (data: any, title: string, url?: string) {
            publishLocation(url)
            return pushStateFn.apply(history, [...arguments] as [any, string, string?])
        }
        history.replaceState = function (data: any, title: string, url?: string) {
            publishLocation(url)
            return replaceStateFn.apply(history, [...arguments] as [any, string, string?])
        }
    }
} // else ssr -> no history handling

typeof window !== "undefined" &&
    window.addEventListener("popstate", (event) => {
        publishLocation()
    })

let appContainer = document?.getElementById("appContainer")
const app = hydrate(App, { target: appContainer })

export default app
