// StellarCaptions — Extension i18n
let _strings = {}
let _locale = 'en'

const SUPPORTED_LOCALES = ['en','es','fr','de','it','pt','nl','zh','ja','ko','hi','ar','ru','pl','tr','vi','id']

// Best-effort detection of the user's region/UI language, mapped to a supported
// locale (falls back to English).
function detectLocale() {
  let lang = ''
  try {
    lang = (chrome.i18n && chrome.i18n.getUILanguage && chrome.i18n.getUILanguage()) || ''
  } catch {}
  if (!lang && typeof navigator !== 'undefined') lang = navigator.language || ''
  const base = String(lang).toLowerCase().split('-')[0]
  return SUPPORTED_LOCALES.includes(base) ? base : 'en'
}

async function loadI18n() {
  try {
    const res = await fetch(chrome.runtime.getURL('i18n-strings.json'))
    _strings = await res.json()
  } catch (e) {
    console.warn('[i18n] Failed to load strings', e)
  }
  const stored = await chrome.storage.local.get('ext-locale')
  if (stored['ext-locale']) {
    _locale = stored['ext-locale']
  } else {
    // First run: auto-set to the detected region language and remember it.
    _locale = detectLocale()
    try { await chrome.storage.local.set({ 'ext-locale': _locale }) } catch {}
  }
}

function t(key) {
  const entry = _strings[key]
  if (!entry) return key
  return entry[_locale] || entry['en'] || key
}

function setExtLocale(code) {
  _locale = code
  chrome.storage.local.set({ 'ext-locale': code })
}

function getExtLocale() {
  return _locale
}
