import { getLocaleBundle } from "./resources";
import type { AppLanguage } from "./registry";

/** Server-safe lookup in common.json by dot path (e.g. `errors.pageLoad`) */
export function translateCommon(
  lang: AppLanguage,
  key: string,
  params?: Record<string, string | number>
): string {
  const bundle = getLocaleBundle(lang).common as Record<string, unknown>;
  const parts = key.split(".");
  let cur: unknown = bundle;
  for (const part of parts) {
    if (cur == null || typeof cur !== "object") {
      cur = undefined;
      break;
    }
    cur = (cur as Record<string, unknown>)[part];
  }
  if (typeof cur !== "string") return key;
  if (!params) return cur;
  return Object.entries(params).reduce(
    (text, [name, value]) =>
      text.replace(new RegExp(`\\{\\{${name}\\}\\}`, "g"), String(value)),
    cur
  );
}
