import type { Locale } from '@thebet365/shared';

export const PLAYER_LOCALE_STORAGE_KEY = 'locale';

export type PlayerLocale = Locale;

const localeLoaders: Record<PlayerLocale, () => Promise<{ default: Record<string, unknown> }>> = {
  'zh-CN': () => import('./zh-CN'),
  'en-US': () => import('./en-US'),
  'ms-MY': () => import('./ms-MY'),
};

export async function loadLocaleMessages(locale: PlayerLocale) {
  const loader = localeLoaders[locale] ?? localeLoaders['zh-CN'];
  const mod = await loader();
  return mod.default;
}

const loadedLocales = new Set<PlayerLocale>();

export function markLocaleLoaded(locale: PlayerLocale) {
  loadedLocales.add(locale);
}

/** 切换语言时按需加载文案包（与首屏单语言拆包配合） */
export async function ensurePlayerLocale(
  composer: {
    mergeLocaleMessage: (locale: string, message: Record<string, unknown>) => void;
    availableLocales: string[];
  },
  locale: PlayerLocale,
) {
  if (loadedLocales.has(locale) || composer.availableLocales.includes(locale)) return;
  const messages = await loadLocaleMessages(locale);
  composer.mergeLocaleMessage(locale, messages);
  loadedLocales.add(locale);
}

export function readStoredLocale(): PlayerLocale {
  const raw = localStorage.getItem(PLAYER_LOCALE_STORAGE_KEY) || 'zh-CN';
  if (raw in localeLoaders) return raw as PlayerLocale;
  return 'zh-CN';
}
