import en from './en.json';
import de from './de.json';

export const languages = {
  en: { name: 'English', flag: '🇬🇧', translations: en },
  de: { name: 'Deutsch', flag: '🇩🇪', translations: de },
};

export const defaultLanguage = 'en';

export function getTranslation(lang, key) {
  const keys = key.split('.');
  const translations = languages[lang]?.translations || languages[defaultLanguage].translations;
  let value = translations;
  for (const k of keys) {
    value = value?.[k];
    if (value === undefined) {
      // Fallback to default language
      let fallback = languages[defaultLanguage].translations;
      for (const fk of keys) {
        fallback = fallback?.[fk];
      }
      return fallback || key;
    }
  }
  return value || key;
}

export function interpolate(template, params = {}) {
  if (!template) return '';
  return template.replace(/\{(\w+)\}/g, (_, key) => {
    return params[key] !== undefined ? params[key] : `{${key}}`;
  });
}

// Handle plural: "singular | plural" format
export function pluralize(template, count) {
  if (!template) return '';
  const parts = template.split(' | ');
  if (parts.length === 1) return interpolate(template, { count });
  return interpolate(count === 1 ? parts[0] : parts[1], { count });
}
