const I18N = {
  de: {
    chatHistory: 'Chat-Verlauf',
    newChat: 'Neuer Chat',
    noChats: 'Keine Chats vorhanden',
    settings: 'Einstellungen',
    close: 'Schliessen',
    modelPinned: 'Model entpinnen',
    modelPin: 'Model pinnen',
    apiKeyPresent: 'API Key vorhanden',
    apiKeyAdd: 'API Key hinzufuegen',
    summarize: 'Zusammenfassen',
    screenshot: 'Screenshot',
    openTabs: 'Offene Tabs',
    webSearch: 'Websuche',
    placeholder: 'Nachricht an Syntrix Nova...',
    send: 'Senden',
    stop: 'Stoppen',
    configured: 'Konfiguriert',
    noApiKey: 'Kein API Key',
    enterApiKey: 'API Key eingeben',
    save: 'Speichern',
    cancel: 'Abbrechen',
    deleteChat: 'Chat loeschen',
    deleteChatConfirm: 'Chat loeschen?',
    emptyChat: 'Leerer Chat',
    executing: 'Ausfuehren...',
    done: 'Fertig',
    error: 'Fehler',
    noApiKeyError: 'Kein API Key fuer {provider}. Bitte in Settings eintragen.',
    apiError: 'API Fehler: {message}',
    version: 'Version',
    newVersionAvailable: 'Neue Version {version} verfuegbar! Download',
    latestVersion: 'Du hast die neueste Version ({version})',
    updateCheckFailed: 'Update-Pruefung fehlgeschlagen',
    checkingUpdate: 'Pruefe...',
    checkUpdate: 'Update pruefen',
    providerActive: 'Aktiv',
    providerInactive: 'Inaktiv',
    testConnection: 'Verbindung testen',
    connectionOk: 'OK',
    connectionError: 'Fehler',
    testing: 'Testen...',
    noKey: 'Kein Key',
    panel: 'Panel',
    openSidePanel: 'Side Panel oeffnen',
    quickAccess: 'Schneller Zugriff auf Syntrix Nova.',
    quickQuestion: 'Schnelle Frage...',
    systemPromptPlaceholder: 'Optionaler System-Prompt...',
    maxTokens: 'Max Tokens',
    temperature: 'Temperature',
    defaultProvider: 'Standard Provider',
    defaultModel: 'Standard Modell',
    uiMode: 'UI Modus',
    sidepanelRecommended: 'Side Panel (Empfohlen)',
    popupMode: 'Popup',
    darkMode: 'Dark Mode',
    lightMode: 'Light Mode',
    theme: 'Theme',
    general: 'Allgemein',
    providers: 'Provider & API Keys',
    search: 'Web-Suche',
    about: 'Info',
    googleApiKey: 'Google API Key',
    customSearchCx: 'Custom Search Engine ID (CX)',
    googleCustomSearchInfo: 'Google Custom Search API',
    googleCustomSearchDesc: 'Benoetigt einen API Key und eine Custom Search Engine ID (CX).',
    createCustomSearch: 'Custom Search Engine erstellen',
    features: 'Features',
    streamingChat: 'Streaming Chat mit Function Calling',
    pageReadDomWrite: 'Seite lesen, DOM schreiben, JS ausfuehren',
    screenshotVision: 'Screenshots + Vision-Analyse',
    googleWebSearch: 'Google Web-Suche',
    terminalAccess: 'Terminal via Native Messaging Host',
    darkLightTheme: 'Dark/Light Theme',
    sidePanelPopup: 'Side Panel + Popup',
    cloudProviders: 'Cloud Provider',
    exportChat: 'Chat exportieren',
    exportMarkdown: 'Als Markdown speichern',
    fontSize: 'Schriftgroesse',
    language: 'Sprache',
    german: 'Deutsch',
    english: 'Englisch',
    shortcuts: 'Tastaturkuerzel',
    ctrlEnterSend: 'Strg+Enter: Senden',
    escapeCancel: 'Esc: Abbrechen',
    ctrlNewChat: 'Strg+N: Neuer Chat',
    systemPromptTemplates: 'System-Prompt Vorlagen',
    noTemplate: 'Keine Vorlage',
    codingAssistant: 'Coding Assistent',
    codingAssistantDesc: 'Du bist ein erfahrener Software-Entwickler. Schreibe sauberen, effizienten Code.',
    summarizer: 'Textersteller',
    summarizerDesc: 'Fasse Texte praegnant zusammen und extrahiere die wichtigsten Informationen.',
    researcher: 'Rechercheur',
    researcherDesc: 'Recherchiere gruendlich und liste Fakten und Quellen auf.'
  },
  en: {
    chatHistory: 'Chat History',
    newChat: 'New Chat',
    noChats: 'No chats yet',
    settings: 'Settings',
    close: 'Close',
    modelPinned: 'Unpin Model',
    modelPin: 'Pin Model',
    apiKeyPresent: 'API Key present',
    apiKeyAdd: 'Add API Key',
    summarize: 'Summarize',
    screenshot: 'Screenshot',
    openTabs: 'Open Tabs',
    webSearch: 'Web Search',
    placeholder: 'Message Syntrix Nova...',
    send: 'Send',
    stop: 'Stop',
    configured: 'Configured',
    noApiKey: 'No API Key',
    enterApiKey: 'Enter API Key',
    save: 'Save',
    cancel: 'Cancel',
    deleteChat: 'Delete Chat',
    deleteChatConfirm: 'Delete chat?',
    emptyChat: 'Empty Chat',
    executing: 'Executing...',
    done: 'Done',
    error: 'Error',
    noApiKeyError: 'No API Key for {provider}. Please configure in Settings.',
    apiError: 'API Error: {message}',
    version: 'Version',
    newVersionAvailable: 'New version {version} available! Download',
    latestVersion: 'You have the latest version ({version})',
    updateCheckFailed: 'Update check failed',
    checkingUpdate: 'Checking...',
    checkUpdate: 'Check Update',
    providerActive: 'Active',
    providerInactive: 'Inactive',
    testConnection: 'Test Connection',
    connectionOk: 'OK',
    connectionError: 'Error',
    testing: 'Testing...',
    noKey: 'No Key',
    panel: 'Panel',
    openSidePanel: 'Open Side Panel',
    quickAccess: 'Quick access to Syntrix Nova.',
    quickQuestion: 'Quick question...',
    systemPromptPlaceholder: 'Optional system prompt...',
    maxTokens: 'Max Tokens',
    temperature: 'Temperature',
    defaultProvider: 'Default Provider',
    defaultModel: 'Default Model',
    uiMode: 'UI Mode',
    sidepanelRecommended: 'Side Panel (Recommended)',
    popupMode: 'Popup',
    darkMode: 'Dark Mode',
    lightMode: 'Light Mode',
    theme: 'Theme',
    general: 'General',
    providers: 'Providers & API Keys',
    search: 'Web Search',
    about: 'About',
    googleApiKey: 'Google API Key',
    customSearchCx: 'Custom Search Engine ID (CX)',
    googleCustomSearchInfo: 'Google Custom Search API',
    googleCustomSearchDesc: 'Requires an API Key and Custom Search Engine ID (CX).',
    createCustomSearch: 'Create Custom Search Engine',
    features: 'Features',
    streamingChat: 'Streaming Chat with Function Calling',
    pageReadDomWrite: 'Read page, write DOM, execute JS',
    screenshotVision: 'Screenshots + Vision Analysis',
    googleWebSearch: 'Google Web Search',
    terminalAccess: 'Terminal via Native Messaging Host',
    darkLightTheme: 'Dark/Light Theme',
    sidePanelPopup: 'Side Panel + Popup',
    cloudProviders: 'Cloud Providers',
    exportChat: 'Export Chat',
    exportMarkdown: 'Save as Markdown',
    fontSize: 'Font Size',
    language: 'Language',
    german: 'German',
    english: 'English',
    shortcuts: 'Keyboard Shortcuts',
    ctrlEnterSend: 'Ctrl+Enter: Send',
    escapeCancel: 'Esc: Cancel',
    ctrlNewChat: 'Ctrl+N: New Chat',
    systemPromptTemplates: 'System Prompt Templates',
    noTemplate: 'No Template',
    codingAssistant: 'Coding Assistant',
    codingAssistantDesc: 'You are an experienced software developer. Write clean, efficient code.',
    summarizer: 'Text Summarizer',
    summarizerDesc: 'Summarize texts concisely and extract the most important information.',
    researcher: 'Researcher',
    researcherDesc: 'Research thoroughly and list facts and sources.'
  }
};

export async function t(key, lang = null) {
  if (!lang) {
    const result = await chrome.storage.sync.get('settings');
    lang = result.settings?.language || 'de';
  }
  const translations = I18N[lang] || I18N.de;
  return translations[key] || key;
}

export async function tReplace(el, key, replacements = {}) {
  const text = await t(key);
  let result = text;
  for (const [k, v] of Object.entries(replacements)) {
    result = result.replace(`{${k}}`, v);
  }
  if (el) el.textContent = result;
  return result;
}

export function getTranslations(lang) {
  return I18N[lang] || I18N.de;
}