import { createI18n } from 'vue-i18n';
import { safeLocalStorage } from '../utils/storage.js';

// Import all locale files
import de from './locales/de.json';
import enGB from './locales/en-GB.json';
import enUS from './locales/en-US.json';
import enAU from './locales/en-AU.json';
import deCH from './locales/de-CH.json';
import fr from './locales/fr.json';
import es from './locales/es.json';
import it from './locales/it.json';
import pl from './locales/pl.json';
import ja from './locales/ja.json';
import zh from './locales/zh.json';
import tl from './locales/tl.json';
import th from './locales/th.json';
import fil from './locales/fil.json';
import ceb from './locales/ceb.json';

function deepMergeMessages(base, override) {
  if (!base || typeof base !== 'object' || Array.isArray(base)) {
    return override ?? base;
  }
  const result = { ...base };
  for (const [key, value] of Object.entries(override || {})) {
    if (
      value &&
      typeof value === 'object' &&
      !Array.isArray(value) &&
      result[key] &&
      typeof result[key] === 'object' &&
      !Array.isArray(result[key])
    ) {
      result[key] = deepMergeMessages(result[key], value);
    } else {
      result[key] = value;
    }
  }
  return result;
}

// Language mapping for browser language detection
const languageMap = {
  'de': 'de',
  'de-DE': 'de',
  'de-AT': 'de',
  'en': 'en-GB', // Default to British English
  'en-GB': 'en-GB',
  'en-US': 'en-US',
  'en-AU': 'en-AU',
  'de-CH': 'de-CH',
  'fr': 'fr',
  'fr-FR': 'fr',
  'es': 'es',
  'es-ES': 'es',
  'it': 'it',
  'it-IT': 'it',
  'pl': 'pl',
  'pl-PL': 'pl',
  'ja': 'ja',
  'ja-JP': 'ja',
  'zh': 'zh',
  'zh-CN': 'zh',
  'zh-TW': 'zh',
  'tl': 'tl',
  'th': 'th',
  'th-TH': 'th',
  'fil': 'fil',
  'fil-PH': 'fil',
  'ceb': 'ceb',
  'ceb-PH': 'ceb',
};

// Detect browser language
function detectBrowserLanguage() {
  const browserLang = navigator.language || navigator.userLanguage;
  const langCode = browserLang.split('-')[0];
  const fullLang = browserLang;
  
  // Check for exact match first
  if (languageMap[fullLang]) {
    return languageMap[fullLang];
  }
  
  // Check for language code match
  if (languageMap[langCode]) {
    return languageMap[langCode];
  }
  
  // Default to German
  return 'de';
}

// Get saved language or detect from browser
function getInitialLocale() {
  // Prüfe zuerst URL-Parameter für manuelles Setzen (für Tests)
  if (typeof window !== 'undefined') {
    const urlParams = new URLSearchParams(window.location.search);
    const langParam = urlParams.get('lang');
    if (langParam && languageMap[langParam]) {
      // Speichere die Sprache aus URL-Parameter
      safeLocalStorage.setItem('userLanguage', languageMap[langParam]);
      return languageMap[langParam];
    }
  }
  
  const saved = safeLocalStorage.getItem('userLanguage');
  if (saved && languageMap[saved]) {
    return saved;
  }
  return detectBrowserLanguage();
}

const i18n = createI18n({
  locale: getInitialLocale(),
  fallbackLocale: 'de',
  messages: {
    'de': de,
    'en-GB': deepMergeMessages(de, enGB),
    'en-US': deepMergeMessages(de, enUS),
    'en-AU': deepMergeMessages(de, enAU),
    'de-CH': deepMergeMessages(de, deCH),
    'fr': deepMergeMessages(de, fr),
    'es': deepMergeMessages(de, es),
    'it': deepMergeMessages(de, it),
    'pl': deepMergeMessages(de, pl),
    'ja': deepMergeMessages(de, ja),
    'zh': deepMergeMessages(de, zh),
    'tl': deepMergeMessages(de, tl),
    'th': deepMergeMessages(de, th),
    'fil': deepMergeMessages(de, fil),
    'ceb': deepMergeMessages(de, ceb),
  },
  legacy: true, // Use Options API mode (required for $t in templates with Options API)
  // globalInjection is automatically enabled with legacy: true
});

/**
 * Setzt die Sprache manuell (für Tests)
 * @param {string} locale - Sprachcode (z.B. 'de', 'en-GB', 'fr')
 * @returns {boolean} - true wenn erfolgreich, false wenn ungültiger Code
 */
export function setLanguage(locale) {
  if (!languageMap[locale]) {
    console.warn(`Ungültiger Sprachcode: ${locale}. Verfügbare Sprachen:`, Object.keys(languageMap));
    return false;
  }
  
  const mappedLocale = languageMap[locale];
  // Bei legacy: true ist locale direkt ein String
  i18n.global.locale = mappedLocale;
  safeLocalStorage.setItem('userLanguage', mappedLocale);
  console.log(`✅ Sprache geändert zu: ${mappedLocale}`);
  
  // Seite neu laden, damit alle Komponenten die neue Sprache verwenden
  if (typeof window !== 'undefined') {
    window.location.reload();
  }
  return true;
}

/**
 * Gibt die aktuelle Sprache zurück
 * @returns {string} - Aktueller Sprachcode
 */
export function getCurrentLanguage() {
  return i18n.global.locale;
}

/**
 * Gibt alle verfügbaren Sprachen zurück
 * @returns {string[]} - Array von Sprachcodes
 */
export function getAvailableLanguages() {
  return Object.keys(languageMap);
}

// Exponiere setLanguage global für Browser-Konsole (nur im Development)
if (typeof window !== 'undefined' && (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'dev')) {
  window.setLanguage = setLanguage;
  window.getCurrentLanguage = getCurrentLanguage;
  window.getAvailableLanguages = getAvailableLanguages;
}

export default i18n;

