import { Locale, TranslationDict } from './types';
import { en } from './locales/en';
import { sv } from './locales/sv';
import { ur } from './locales/ur';
import { ar } from './locales/ar';
import { fa } from './locales/fa';
import { tr } from './locales/tr';

const dictionaries: Record<Locale, TranslationDict> = {
  en,
  sv,
  ur,
  ar,
  fa,
  tr,
};

function resolve(obj: TranslationDict, path: string): string {
  const keys = path.split('.');
  let current: string | TranslationDict = obj;

  for (const key of keys) {
    if (typeof current !== 'object' || current === null || !(key in current)) {
      return path;
    }
    current = current[key];
  }

  return typeof current === 'string' ? current : path;
}

export function createTranslator(locale: Locale) {
  const dict = dictionaries[locale] ?? dictionaries.en;

  return function t(path: string, params?: Record<string, string | number>): string {
    let text = resolve(dict, path);

    if (params) {
      Object.entries(params).forEach(([key, value]) => {
        text = text.replace(new RegExp(`\\{${key}\\}`, 'g'), String(value));
      });
    }

    return text;
  };
}

export function isRtl(locale: Locale): boolean {
  return locale === 'ur' || locale === 'ar' || locale === 'fa';
}

export function getHtmlLang(locale: Locale): string {
  const map: Record<Locale, string> = {
    en: 'en',
    sv: 'sv',
    ur: 'ur',
    ar: 'ar',
    fa: 'fa',
    tr: 'tr',
  };
  return map[locale];
}

export function usesArabicScript(locale: Locale): boolean {
  return locale === 'ur' || locale === 'ar' || locale === 'fa';
}