import { zhTW } from "./catalog.zhTW";
import type { AppLocale, MessageDict } from "./types";

export type { MessageDict };

/*
預設語系跟著主程式走，其餘語系各自打包成 chunk 並在切換時才下載。
translate 維持同步：字典還沒到位前先用預設語系頂著，載完由 I18nProvider 觸發重繪。
*/
const catalogs: Partial<Record<AppLocale, MessageDict>> = { "zh-TW": zhTW };

const loaders: Record<AppLocale, () => Promise<MessageDict>> = {
  "zh-TW": async () => zhTW,
  en: async () => (await import("./catalog.en")).en,
};

const inflight = new Map<AppLocale, Promise<MessageDict>>();

export function isCatalogLoaded(locale: AppLocale): boolean {
  return Boolean(catalogs[locale]);
}

/** 載入並註冊語系字典；重複呼叫共用同一個 in-flight request。 */
export function ensureCatalog(locale: AppLocale): Promise<MessageDict> {
  const loaded = catalogs[locale];
  if (loaded) return Promise.resolve(loaded);
  const running = inflight.get(locale);
  if (running) return running;
  const task = loaders[locale]()
    .then((dict) => {
      catalogs[locale] = dict;
      return dict;
    })
    .finally(() => inflight.delete(locale));
  inflight.set(locale, task);
  return task;
}

export function getCatalog(locale: AppLocale): MessageDict {
  return catalogs[locale] ?? zhTW;
}

/** 對已取得的字典取字；缺字回退預設語系，再回退 key 本身。 */
export function formatMessage(
  dict: MessageDict,
  key: string,
  params?: Record<string, string | number>,
): string {
  let s = dict[key] ?? zhTW[key] ?? key;
  if (params) {
    for (const [k, v] of Object.entries(params)) {
      s = s.replace(new RegExp(`\\{${k}\\}`, "g"), String(v));
    }
  }
  return s;
}

export function translate(
  locale: AppLocale,
  key: string,
  params?: Record<string, string | number>,
): string {
  return formatMessage(getCatalog(locale), key, params);
}
