import { defaultLang, showDefaultLang, ui, type SupportedLang } from "./ui";

const hasOwn = (obj: object, key: string): boolean =>
  Object.prototype.hasOwnProperty.call(obj, key);

const getValueByPath = (value: unknown, key: string): unknown => {
  return key.split(".").reduce<unknown>((acc, part) => {
    if (acc && typeof acc === "object" && hasOwn(acc as object, part)) {
      return (acc as Record<string, unknown>)[part];
    }

    return undefined;
  }, value);
};

export function getLangFromUrl(url: URL): SupportedLang {
  const [, lang] = url.pathname.split("/");

  if (lang && hasOwn(ui, lang)) {
    return lang as SupportedLang;
  }

  return defaultLang;
}

export function useTranslations(lang: SupportedLang) {
  const localizedUI = ui[lang] as Record<string, unknown>;
  const fallbackUI = ui[defaultLang] as Record<string, unknown>;

  return function t(key: string): unknown {
    const localizedValue = getValueByPath(localizedUI, key);

    if (localizedValue !== undefined) {
      return localizedValue;
    }

    const fallbackValue = getValueByPath(fallbackUI, key);
    return fallbackValue ?? key;
  };
}

export function useTranslatedPath(lang: SupportedLang) {
  return function translatePath(path: string, l: SupportedLang = lang): string {
    const normalizedPath = path.startsWith("/") ? path : `/${path}`;

    if (!showDefaultLang && l === defaultLang) {
      return normalizedPath;
    }

    return `/${l}${normalizedPath}`;
  };
}
