import { render } from "svelte/server"
import { addMessages, init, locale } from "svelte-i18n"
import { DEFAULT_LANGUAGE, extractLanguageFromPath } from "./lib/i18n"
import deLocale from "./lib/i18n/locales/de.json"
import enLocale from "./lib/i18n/locales/en.json"
import App from "./App.svelte"

// SSR: load messages synchronously before rendering.
addMessages("de", deLocale)
addMessages("en", enLocale)

/**
 * SSR render wrapper for Svelte 5.
 *
 * tibi-server calls `app.default.render({ url })`.
 * Svelte 5 no longer provides a `.render()` method on components —
 * instead `render()` must be imported from `svelte/server`.
 *
 * This wrapper keeps the hook-side API compatible while delegating
 * to the Svelte 5 render function internally.
 */
export default {
    render({ url }: { url: string }) {
        const lang = extractLanguageFromPath(url) || DEFAULT_LANGUAGE

        init({
            fallbackLocale: DEFAULT_LANGUAGE,
            initialLocale: lang,
        })
        locale.set(lang)

        const { body, head } = render(App, {
            props: { url },
        })

        return { html: body, head }
    },
}
