import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import {
  ADMIN_LOCALES,
  type AdminLocale,
} from '../i18n/admin-messages';
import { ADMIN_LOCALE_STORAGE_KEY } from '../i18n';
import { preloadAdminLocale } from '../i18n/locale-loader';
import { resolveAdminMessage } from '../i18n/resolve-message';

export type { AdminLocale };
export { getAdminLocale } from '../i18n';

export function useAdminLocale() {
  const { locale } = useI18n();

  /** 扁平 key 查表 + 占位符，不依赖 vue-i18n 嵌套路径解析 */
  function t(key: string, params?: Record<string, string | number>): string {
    const loc = locale.value as AdminLocale;
    let raw = resolveAdminMessage(key, loc) ?? key;
    if (!params) return raw;
    return Object.entries(params).reduce(
      (s, [k, v]) => s.replace(new RegExp(`\\{${k}\\}`, 'g'), String(v)),
      raw,
    );
  }

  async function setLocale(code: AdminLocale) {
    await preloadAdminLocale(code);
    locale.value = code;
    localStorage.setItem(ADMIN_LOCALE_STORAGE_KEY, code);
    document.cookie = `${ADMIN_LOCALE_STORAGE_KEY}=${encodeURIComponent(code)};path=/;max-age=31536000;SameSite=Lax`;
  }

  return {
    locale: computed(() => locale.value as AdminLocale),
    localeTag: computed(() => String(locale.value)),
    locales: ADMIN_LOCALES,
    setLocale,
    t,
  };
}
