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

const initLoc = {
    path: (typeof window !== "undefined" && window.location?.pathname) || "/",
    search: (typeof window !== "undefined" && window.location?.search) || "",
    push: false,
    pop: false,
    categoryPath: "",
}
initLoc.categoryPath = initLoc.path.replace(/\/\d{4,99}[^\/]+$/, "")

export const location = writable(initLoc)

// General Information

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

// Articles

export const articles = writable<TibiArticle[]>()
const getAllArticles = async () => {
    const list = await getArticles()
    articles.set(list)
}
getAllArticles()

// 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)
}
