# Internationalization (i18n)

## Overview

Cookie Consent natively supports **7 European languages** with automatic browser language detection.

## Supported Languages

| Language | Code | Status | Coverage |
|----------|------|--------|----------|
| 🇫🇷 Français | `fr` | ✅ Complete | 100% |
| 🇬🇧 English | `en` | ✅ Complete | 100% |
| 🇪🇸 Español | `es` | ✅ Complete | 100% |
| 🇩🇪 Deutsch | `de` | ✅ Complete | 100% |
| 🇮🇹 Italiano | `it` | ✅ Complete | 100% |
| 🇳🇱 Nederlands | `nl` | ✅ Complete | 100% |
| 🇵🇹 Português | `pt` | ✅ Complete | 100% |

## Automatic Detection

By default, Cookie Consent detects the language via `navigator.language`:

```javascript
// Automatic detection
const userLang = navigator.language || navigator.userLanguage;
// Examples: 'fr-FR', 'en-US', 'es-ES', 'de-DE'

// Extract language code (2 letters)
const lang = userLang.split('-')[0]; // 'fr', 'en', 'es'...
```

**No configuration needed!**

## Force a Language

### Method 1: Via JavaScript API

```javascript
import t from '@synapxlab/cookie-consent/translat';

// Force English
t.setLocale('en');

// Initialize Cookie Consent
window.CookieConsent.init({
  statistics: {
    google_analytics_key: 'G-XXXXXXXXX'  // ✅ Correct name
  }
});
```

### Method 2: Based on Site Language

```javascript
// Detect your site's language (HTML lang attribute)
const siteLang = document.documentElement.lang.split('-')[0];

import t from '@synapxlab/cookie-consent/translat';
t.setLocale(siteLang);
```

### Method 3: User Choice

```html
<!-- Language selector -->
<select id="language-selector">
  <option value="fr">Français</option>
  <option value="en">English</option>
  <option value="es">Español</option>
  <option value="de">Deutsch</option>
  <option value="it">Italiano</option>
  <option value="nl">Nederlands</option>
  <option value="pt">Português</option>
</select>

<script type="module">
import t from '@synapxlab/cookie-consent/translat';

document.getElementById('language-selector').addEventListener('change', function(e) {
  const lang = e.target.value;
  
  // Change language
  t.setLocale(lang);
  
  // Reload banner if already displayed
  if (document.getElementById('politecookiebanner')) {
    window.CookieConsent.reset();
  }
  
  // Save choice
  localStorage.setItem('userLang', lang);
});

// Restore choice on load
const savedLang = localStorage.getItem('userLang');
if (savedLang) {
  t.setLocale(savedLang);
}
</script>
```

## Add a New Language

### Complete Translation Structure

All available translation keys:

```javascript
import t from '@synapxlab/cookie-consent/translat';

t.add('LANGUAGE_CODE', {
  // Header
  title: "Banner title",
  closeAria: "Accessible text to close",
  
  // Main message
  message: "Introduction message about cookies",
  
  // Buttons
  acceptAll: "Accept all",
  denyAll: "Deny all",
  viewPrefs: "Customize preferences",
  savePrefs: "Save preferences",
  delPrefs: "Delete preferences",
  
  // Status
  alwaysActive: "Always active",
  
  // Category: Functional (always active)
  functionalTitle: "Strictly necessary cookies",
  functionalDesc: "These cookies are necessary for the website to function...",
  
  // Category: Cookies (additional features)
  cookiesTitle: "Functional cookies",
  cookiesDesc: "These cookies enable improved and personalized features...",
  cookiesServices: "Services: {services}",
  
  // Category: Statistics
  statsTitle: "Analytics cookies (statistics)",
  statsDesc: "These cookies allow us to measure site traffic...",
  statsServices: "Services: {services}",
  
  // Category: Marketing
  marketingTitle: "Advertising and personalization cookies",
  marketingDesc: "These cookies personalize displayed advertisements...",
  marketingServices: "Services: {services}",
  
  // 🆕 Google Consent Mode v2 (optional)
  gcmBadge: "Google Consent Mode v2",
  gcmDesc: "Google Consent Mode v2 is enabled on this site...",
  
  // GDPR Logging
  loggingTitle: "📋 Cookie consent proof",
  loggingNotice: "In accordance with our legal obligations (GDPR Article 7.1)..."
});
```

### Example: Add Japanese

```javascript
import t from '@synapxlab/cookie-consent/translat';

t.add('ja', {
  title: "クッキー同意管理",
  closeAria: "クッキーバナーを閉じる",
  message: "最高のエクスペリエンスを提供するため、当サイトはクッキーを使用して利用状況を分析し、サービスを改善しています。",
  
  acceptAll: "すべて受け入れる",
  denyAll: "すべて拒否",
  viewPrefs: "設定をカスタマイズ",
  savePrefs: "設定を保存",
  delPrefs: "設定を削除",
  
  alwaysActive: "常に有効",
  
  functionalTitle: "必須クッキー",
  functionalDesc: "これらのクッキーはウェブサイトの動作に不可欠です。",
  
  cookiesTitle: "機能的クッキー",
  cookiesDesc: "これらのクッキーはウェブサイトの機能を向上させます。",
  cookiesServices: "サービス：{services}",
  
  statsTitle: "統計クッキー（アクセス解析）",
  statsDesc: "これらのクッキーは訪問者数の測定を可能にします。",
  statsServices: "サービス：{services}",
  
  marketingTitle: "広告・パーソナライゼーションクッキー",
  marketingDesc: "これらのクッキーは興味に合わせた広告をカスタマイズします。",
  marketingServices: "サービス：{services}",
  
  loggingTitle: "📋 クッキー同意の証明",
  loggingNotice: "法的要件に従い、同意設定の記録を保持します。"
});

// Activate Japanese
t.setLocale('ja');
```

## Variable Replacement

Some translations support **dynamic variables**:

```javascript
// In translations
statsServices: "Services: {services}"
marketingServices: "Services: {services}"
cookiesServices: "Services: {services}"
```

These variables are automatically replaced by the list of configured services:

```javascript
window.CookieConsent.init({
  statistics: {
    google_analytics_key: 'G-XXXXXXXXX',      // ✅
    google_tag_manager_key: 'GTM-XXXXXX',     // ✅
    hotjar_site_id: 123456,                   // ✅
    clarity_project_id: 'abc123'              // ✅
  },
  marketing: {
    google_adsense_key: 'ca-pub-123456',      // ✅
    facebook_pixel: {                         // ✅
      key: '123456789',
      track: 'PageView'
    }
  }
});

// Result displayed:
// "Services: Google Analytics, Google Tag Manager, Hotjar, Microsoft Clarity"
// "Services: Google AdSense, Facebook Pixel"
```

## ✅ CORRECT Property Names

### Statistics

```javascript
statistics: {
  google_analytics_key: 'G-XXX',              // ✅ Google Analytics
  google_tag_manager_key: 'GTM-XXX',          // ✅ Google Tag Manager
  matomo: { url: 'https://...', siteId: 1 },  // ✅ Matomo
  mixpanel_token: 'xxx',                      // ✅ Mixpanel
  amplitude_key: 'xxx',                       // ✅ Amplitude
  plausible: { domain: 'example.com' },       // ✅ Plausible
  hotjar_site_id: 123456,                     // ✅ Hotjar
  clarity_project_id: 'xxx'                   // ✅ Microsoft Clarity
}
```

### Marketing

```javascript
marketing: {
  google_adsense_key: 'ca-pub-xxx',           // ✅ Google AdSense
  facebook_pixel: {                           // ✅ Facebook Pixel
    key: 'xxx',
    track: 'PageView'
  },
  tiktok_pixel_id: 'xxx',                     // ✅ TikTok Pixel
  linkedin_partner_id: 'xxx'                  // ✅ LinkedIn Insight
}
```

### Functional

```javascript
functional: {
  intercom_app_id: 'xxx',                     // ✅ Intercom
  crisp_website_id: 'xxx',                    // ✅ Crisp
  hubspot_portal_id: 'xxx',                   // ✅ HubSpot
  segment_write_key: 'xxx'                    // ✅ Segment
}
```

## Framework Integration

### React

```jsx
// i18n-setup.js
import t from '@synapxlab/cookie-consent/translat';

export const setupCookieConsentI18n = (language) => {
  t.setLocale(language);
};

// App.jsx
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import '@synapxlab/cookie-consent';
import { setupCookieConsentI18n } from './i18n-setup';

function App() {
  const { i18n } = useTranslation();
  
  useEffect(() => {
    // Sync Cookie Consent with your i18n
    setupCookieConsentI18n(i18n.language);
    
    // Initialize with correct property names
    window.CookieConsent.init({
      statistics: {
        google_analytics_key: 'G-XXX'  // ✅
      }
    });
  }, [i18n.language]);
  
  return <div>Your App</div>;
}
```

### Vue.js

```javascript
// plugins/cookie-consent.js
import t from '@synapxlab/cookie-consent/translat';
import { watch } from 'vue';

export default {
  install(app) {
    const i18n = app.config.globalProperties.$i18n;
    
    app.config.globalProperties.$initCookieConsent = () => {
      t.setLocale(i18n.locale);
      
      window.CookieConsent.init({
        statistics: {
          google_analytics_key: 'G-XXX'  // ✅
        }
      });
    };
    
    // Watch i18n changes
    watch(() => i18n.locale, (newLocale) => {
      t.setLocale(newLocale);
    });
  }
};
```

### Next.js

```javascript
// pages/_app.js
import { useEffect } from 'react';
import { useRouter } from 'next/router';
import t from '@synapxlab/cookie-consent/translat';
import '@synapxlab/cookie-consent';

function MyApp({ Component, pageProps }) {
  const router = useRouter();
  const { locale } = router;
  
  useEffect(() => {
    t.setLocale(locale);
    
    window.CookieConsent.init({
      statistics: {
        google_analytics_key: 'G-XXX'  // ✅
      }
    });
  }, [locale]);
  
  return <Component {...pageProps} />;
}

export default MyApp;
```

## RTL Support (Right-to-Left)

For languages written right-to-left (Arabic, Hebrew, etc.):

```javascript
// Add Arabic language
t.add('ar', {
  title: "إدارة موافقة ملفات تعريف الارتباط",
  message: "لتقديم أفضل تجربة...",
  // ... all other keys
});

t.setLocale('ar');

// Enable RTL mode
document.documentElement.setAttribute('dir', 'rtl');
document.documentElement.setAttribute('lang', 'ar');
```

## i18n Testing

### Check a Translation

```javascript
import t from '@synapxlab/cookie-consent/translat';

// Get a key
console.log(t('title')); // "Manage cookie consent"

// Change language
t.setLocale('fr');
console.log(t('title')); // "Gérer le consentement aux cookies"

// Check active language
console.log(t.getLocale()); // "fr"
```

### Test All Languages

```javascript
const languages = ['fr', 'en', 'es', 'de', 'it', 'nl', 'pt'];

languages.forEach(lang => {
  t.setLocale(lang);
  console.log(`${lang}: ${t('title')}`);
});

// Result:
// fr: Gérer le consentement aux cookies
// en: Manage cookie consent
// es: Gestionar el consentimiento de cookies
// de: Cookie-Einwilligung verwalten
// it: Gestisci il consenso ai cookie
// nl: Cookietoestemming beheren
// pt: Gerir o consentimento de cookies
```

## Fallback

If a translation is missing, Cookie Consent uses French as default:

```javascript
t.add('custom', {
  title: "My custom title"
  // Other keys missing
});

t.setLocale('custom');

console.log(t('title')); // "My custom title"
console.log(t('acceptAll')); // "Tout Accepter" (French fallback)
```

## Contribution

Want to add a language? Contribute on GitHub!

### Languages in Progress

- 🇯🇵 Japanese (ja)
- 🇨🇳 Simplified Chinese (zh)
- 🇰🇷 Korean (ko)
- 🇷🇺 Russian (ru)
- 🇸🇦 Arabic (ar)
- 🇮🇱 Hebrew (he)
- 🇮🇳 Hindi (hi)

**Do you speak one of these languages?** Contribute on GitHub!

### Support

- 📧 contact@synapx.fr
- 💬 [Discord SynapxLab](https://discord.gg/synapxlab)
- 🐛 [GitHub Issues](https://github.com/synapxLab/cookie-consent/issues)
- 📚 [Complete Documentation](../configuration.md)

---

**i18n Guide by SynapxLab**  
**7 supported languages · Open source · Contributions welcome!**