import { I18nManager } from 'react-native';
import type { SupportedLocale } from '../types';
import fr from './locales/fr';
import en from './locales/en';
import ar from './locales/ar';

type TranslationMap = typeof fr;
const translations: Record<SupportedLocale, TranslationMap> = { fr, en, ar: ar as unknown as TranslationMap };

let currentLocale: SupportedLocale = 'fr';

export function setLocale(locale: SupportedLocale) {
  currentLocale = locale;
  const rtl = locale === 'ar';
  if (I18nManager.isRTL !== rtl) {
    I18nManager.allowRTL(rtl);
    I18nManager.forceRTL(rtl);
  }
}

export function getLocale(): SupportedLocale {
  return currentLocale;
}

export function isRTL(): boolean {
  return currentLocale === 'ar';
}

/**
 * Translate a key with optional interpolation.
 * Supports nested keys: t('quiz.step1Title')
 * Supports params: t('greeting', { name: 'Ali' }) with template "Hello {{name}}"
 */
export function t(key: string, params?: Record<string, string | number>): string {
  const keys = key.split('.');
  let value: any = translations[currentLocale];

  for (const k of keys) {
    if (value == null) break;
    value = value[k];
  }

  // Fallback to French
  if (value == null) {
    value = translations.fr;
    for (const k of keys) {
      if (value == null) break;
      value = value[k];
    }
  }

  if (typeof value !== 'string') {
    return key; // Key not found
  }

  if (params) {
    return value.replace(/\{\{(\w+)\}\}/g, (_, paramKey) =>
      params[paramKey] != null ? String(params[paramKey]) : `{{${paramKey}}}`
    );
  }

  return value;
}

export const LOCALE_LABELS: Record<SupportedLocale, string> = {
  fr: 'Français',
  en: 'English',
  ar: 'العربية',
};
