import { writable, get } from "svelte/store"
import { getGeneralInformation, getNavigations } from "./api"

// Localtion

const initialLocation = {
    path: (typeof window !== "undefined" && window.location?.pathname) || "/",
    search: (typeof window !== "undefined" && window.location?.search) || "",
    push: false,
    pop: false,
}
export const location = writable(initialLocation)

// Current Language

export const defaultLang = writable<string>("de")

function langFromUrl(): string {
    if (new RegExp(`\/[a-zA-Z]*[-[a-zA-Z]*]{0,1}\/[a-zA-Z0-9-]*$`).test(get(location).path)) {
        return get(location)?.path.split("/")[1]
    }
    return get(defaultLang)
}
export const currentLang = writable<string>(langFromUrl())

// General Information

export const generalInfo = writable<GeneralInfo>()
const getGeneralProjectInformation = async () => {
    const infos = await getGeneralInformation()
    if (infos && infos.length) {
        generalInfo.set(infos[0])
    }
}
getGeneralProjectInformation()

// Navigations

export const showMobileNav = writable<boolean>(false)

export const navigations = writable<Navigation[]>([])
const getAllNavigations = async (locale: Locale) => {
    const list = await getNavigations(locale)
    navigations.set(list)
}
getAllNavigations({ key: get(currentLang) })

// Cookies - Webmakers Cookie Bar

export const ccTags = writable<string[]>([])

const updateCcTtags = () => {
    // @ts-ignore
    ccTags.set(window.ccLoadedTags || [])
}

if (typeof window !== "undefined") {
    window.addEventListener("ccInit", updateCcTtags)
    window.addEventListener("ccAccept", updateCcTtags)
}
