import { register, init, locale, waitLocale, getLocaleFromNavigator } from "svelte-i18n"
import { get } from "svelte/store"
import {
    SUPPORTED_LANGUAGES,
    DEFAULT_LANGUAGE,
    extractLanguageFromPath,
    selectedLanguage,
    type SupportedLanguage,
} from "../i18n"

// Re-export svelte-i18n utilities for convenience
export { _, format, time, date, number, json } from "svelte-i18n"
export { locale, isLoading, addMessages } from "svelte-i18n"

// Register locale files for lazy loading
register("de", () => import("./locales/de.json"))
register("en", () => import("./locales/en.json"))

let isI18nInitialized = false
let syncSubscriptionsInitialized = false

function ensureI18nInitialized(initialLocale: SupportedLanguage = DEFAULT_LANGUAGE): void {
    if (isI18nInitialized) {
        return
    }

    init({
        fallbackLocale: DEFAULT_LANGUAGE,
        initialLocale,
    })

    isI18nInitialized = true
}

function ensureLocaleSync(): void {
    if (syncSubscriptionsInitialized) {
        return
    }

    // Keep svelte-i18n locale and selectedLanguage store in sync
    locale.subscribe((newLocale) => {
        if (newLocale && SUPPORTED_LANGUAGES.includes(newLocale as SupportedLanguage)) {
            selectedLanguage.set(newLocale as SupportedLanguage)
        }
    })

    selectedLanguage.subscribe((newLang) => {
        const currentLocale = get(locale)
        if (newLang && newLang !== currentLocale) {
            locale.set(newLang)
        }
    })

    syncSubscriptionsInitialized = true
}

ensureI18nInitialized()
ensureLocaleSync()

/**
 * Determine the initial locale from URL, browser, or fallback.
 */
function getInitialLocale(url?: string): SupportedLanguage {
    // 1. Try URL path
    if (url) {
        const langFromUrl = extractLanguageFromPath(url)
        if (langFromUrl) return langFromUrl
    }
    if (typeof window !== "undefined") {
        const langFromPath = extractLanguageFromPath(window.location.pathname)
        if (langFromPath) return langFromPath
    }
    // 2. Try browser settings
    if (typeof navigator !== "undefined") {
        const browserLocale = getLocaleFromNavigator()
        if (browserLocale) {
            const langCode = browserLocale.split("-")[0] as SupportedLanguage
            if (SUPPORTED_LANGUAGES.includes(langCode)) {
                return langCode
            }
        }
    }
    // 3. Fallback
    return DEFAULT_LANGUAGE
}

/**
 * Initialize i18n for client-side rendering.
 * Call this before mounting the Svelte app.
 */
export async function setupI18n(url?: string): Promise<void> {
    const initialLocale = getInitialLocale(url)

    ensureI18nInitialized(initialLocale)
    ensureLocaleSync()

    selectedLanguage.set(initialLocale)
    locale.set(initialLocale)

    await waitLocale()
}
