import type { AdminLocale } from './admin-messages';
import { adminMessages } from './admin-messages';

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

const inflight = new Map<AdminLocale, Promise<void>>();
const loaded = new Set<AdminLocale>();

/** 按语言动态加载文案包（仅当前 locale 进入主路径，其余为独立 chunk）。 */
export async function ensureAdminLocaleLoaded(locale: AdminLocale): Promise<void> {
  if (loaded.has(locale)) return;
  const pending = inflight.get(locale);
  if (pending) return pending;

  const task = loaders[locale]().then((mod) => {
    Object.assign(adminMessages[locale], mod.default);
    loaded.add(locale);
  });
  inflight.set(locale, task);
  try {
    await task;
  } finally {
    inflight.delete(locale);
  }
}

/** 切换语言时预加载目标 locale（与 ensureAdminLocaleLoaded 相同，供 setLocale 调用）。 */
export async function preloadAdminLocale(locale: AdminLocale): Promise<void> {
  await ensureAdminLocaleLoaded(locale);
}
