import type { SiteLocale } from '~/types/locale' import { uiEn } from '~/locales/ui/en' import { uiZh } from '~/locales/ui/zh' const LOCALE_COOKIE = 'umedglobal_locale' const uiMessages = { en: uiEn, zh: uiZh } as const function getNestedRaw(obj: Record, path: string): unknown { const keys = path.split('.') let current: unknown = obj for (const key of keys) { if (!current || typeof current !== 'object' || !(key in current)) { return undefined } current = (current as Record)[key] } return current } function getNestedValue(obj: Record, path: string): string | undefined { const current = getNestedRaw(obj, path) return typeof current === 'string' ? current : undefined } export function useSiteLocale() { const locale = useState('site-locale', () => 'en') const cookie = useCookie(LOCALE_COOKIE, { default: () => 'en', maxAge: 60 * 60 * 24 * 365, sameSite: 'lax' }) const htmlLang = computed(() => (locale.value === 'zh' ? 'zh-CN' : 'en')) useHead(() => ({ htmlAttrs: { lang: htmlLang.value } })) function t(key: string, params?: Record): string { const messages = uiMessages[locale.value] const value = getNestedValue(messages as Record, key) ?? getNestedValue(uiMessages.en as Record, key) ?? key if (!params) return value return Object.entries(params).reduce( (text, [name, replacement]) => text.replaceAll(`{${name}}`, replacement), value ) } function setLocale(next: SiteLocale) { locale.value = next cookie.value = next } function tr(key: string): T { const value = getNestedRaw(uiMessages[locale.value] as Record, key) ?? getNestedRaw(uiMessages.en as Record, key) return value as T } return { locale, htmlLang, setLocale, t, tr } }