import { createI18n } from 'vue-i18n';
import zhCN from './zh-CN';
import enUS from './en-US';

export const LOCALE_STORAGE_KEY = 'ai-desk-core-demo-locale';
export const LOCALE_OPTIONS = ['zh-CN', 'en-US'] as const;

export type AppLocale = typeof LOCALE_OPTIONS[number];

const normalizeLocale = (locale?: string | null): AppLocale => {
    return locale === 'en-US' ? 'en-US' : 'zh-CN';
};

const getBrowserLocale = (): AppLocale => {
    if (typeof window === 'undefined') {
        return 'zh-CN';
    }

    return window.navigator.language.toLowerCase().startsWith('zh') ? 'zh-CN' : 'en-US';
};

const getInitialLocale = (): AppLocale => {
    if (typeof window === 'undefined') {
        return 'zh-CN';
    }

    const storedLocale = window.localStorage.getItem(LOCALE_STORAGE_KEY);
    return storedLocale ? normalizeLocale(storedLocale) : getBrowserLocale();
};

export const i18n = createI18n({
    legacy: false,
    globalInjection: true,
    locale: getInitialLocale(),
    fallbackLocale: 'zh-CN',
    messages: {
        'zh-CN': zhCN,
        'en-US': enUS,
    },
});

export const setLocale = (locale: AppLocale) => {
    const nextLocale = normalizeLocale(locale);
    i18n.global.locale.value = nextLocale;

    if (typeof window !== 'undefined') {
        window.localStorage.setItem(LOCALE_STORAGE_KEY, nextLocale);
    }
};

export const getLocale = (): AppLocale => {
    return normalizeLocale(i18n.global.locale.value.toString());
};

export const translate = (key: string, named?: Record<string, unknown>) => {
    return named ? i18n.global.t(key, named) : i18n.global.t(key);
};