import { useCookie } from "@/composable/useCookie"
import { useFetchJson } from "@/composable/useFetchJson"
import type { Language } from "@/types"
import { reactive, ref } from "vue"

export const langs = reactive([] as Language[])
export const currentLang = ref<Language>()

const deflang = ref<Language>()
const cookie = useCookie()
// Get available language codes for route matching
// export const availableLocales = computed(() => langs.map((l) => l.lang_code))

// Initialize languages from API
export async function initLangs() {
    try {
        const { items } = await useFetchJson<Language[]>('/api/v1/langs')
        langs.push(...items)

        let idfromcookie = null
        const cc = cookie.getCookie('lang_id')
        if (cc) {
            idfromcookie = langs.find((x) => x.id == parseInt(cc))
        }
        deflang.value = items.find((x) => x.is_default == true)
        currentLang.value = idfromcookie ?? deflang.value
    } catch (error) {
        console.error('Failed to fetch languages:', error)
    }
}
