import "server-only";
import type { Locale } from "./config";

const dictionaries = {
  en: () => import("../../../locales/en.json").then((m) => m.default),
  pl: () => import("../../../locales/pl.json").then((m) => m.default)
};

export type Dictionary = Awaited<ReturnType<(typeof dictionaries)["en"]>>;

export async function getDictionary(locale: Locale): Promise<Dictionary> {
  const loader = dictionaries[locale] ?? dictionaries.en;
  return loader();
}

/**
 * Resolve a dot-path translation key against a dictionary, with
 * {placeholder} interpolation. Falls back to the key itself if missing so
 * broken translations are visible instead of crashing the UI.
 */
export function translate(
  dict: Record<string, unknown>,
  key: string,
  vars?: Record<string, string | number>
): string {
  const parts = key.split(".");
  let node: unknown = dict;
  for (const part of parts) {
    if (node && typeof node === "object" && part in (node as object)) {
      node = (node as Record<string, unknown>)[part];
    } else {
      return key;
    }
  }
  if (typeof node !== "string") return key;
  if (!vars) return node;
  return Object.entries(vars).reduce(
    (acc, [k, v]) => acc.replaceAll(`{${k}}`, String(v)),
    node
  );
}
