// Translations for the desktop's NATIVE chrome — the tray menu and the
// Control-Center popover. These live outside the React dashboard (the menu is
// built in the main process; the popover is a file:// page), so they can't read
// the dashboard's i18n. The active locale is mirrored from the dashboard via the
// `freeapi:locale-changed` IPC (preload watches <html lang>) and persisted in
// config, exactly like the theme. Keep these keys in sync with the six locales
// shipped by the client (client/src/i18n/locales).

export const NATIVE_LOCALES = ['en', 'zh-CN', 'fr', 'es', 'pt-BR', 'it'] as const;
export type NativeLocale = (typeof NATIVE_LOCALES)[number];
export const DEFAULT_NATIVE_LOCALE: NativeLocale = 'en';

// `navigator.language`-style value → closest supported locale (primary subtag).
export function normalizeLocale(raw: string | undefined | null): NativeLocale {
  const l = (raw ?? '').toLowerCase();
  if (l.startsWith('zh')) return 'zh-CN';
  if (l.startsWith('pt')) return 'pt-BR';
  if (l.startsWith('fr')) return 'fr';
  if (l.startsWith('es')) return 'es';
  if (l.startsWith('it')) return 'it';
  return 'en';
}

type Strings = Record<string, string>;

const STRINGS: Record<NativeLocale, Strings> = {
  en: {
    tooltip: 'FreeLLMAPI — local LLM router',
    runningOn: 'Running on {addr}',
    openDashboard: 'Open Dashboard',
    showCompactPanel: 'Show Compact Panel',
    lanAccess: 'Allow LAN access (0.0.0.0)',
    showInDock: 'Show in Dock',
    openLogs: 'Open Logs Folder',
    openBackups: 'Open Backups Folder',
    quitApp: 'Quit FreeLLMAPI',
    running: 'running',
    requestsToday: 'Requests today',
    tokensToday: 'Tokens today',
    lastModel: 'Last model',
    copyUrl: 'Copy URL',
    copyKey: 'Copy Key',
    copied: 'Copied ✓',
    startAtLogin: 'Start at login',
    quit: 'Quit',
    hoursAgo: '24h ago',
    now: 'now',
    peak: 'peak {n}/h',
    successSuffix: '{n}% success',
    checkForUpdates: "Check for Updates…",
    restartToUpdateTray: "Restart to Update (v{version})",
    upToDate: "FreeLLMAPI v{version} is the latest version.",
    updateAvailable: "FreeLLMAPI v{version} is available",
    updateAvailableDetail: "You have v{current}. The update downloads in the background; your data is backed up before it installs.",
    downloadUpdate: "Download",
    releaseNotes: "Release Notes",
    later: "Later",
    updateFailed: "Update failed",
    updateReadyTitle: "FreeLLMAPI v{version} is ready to install",
    updateReadyBody: "Restart FreeLLMAPI to finish updating. It also installs the next time you quit.",
    restartToUpdate: "Restart Now",
  },
  'zh-CN': {
    tooltip: 'FreeLLMAPI — 本地 LLM 路由器',
    runningOn: '运行于 {addr}',
    openDashboard: '打开仪表板',
    showCompactPanel: '显示紧凑面板',
    lanAccess: '允许局域网访问 (0.0.0.0)',
    showInDock: '在程序坞中显示',
    openLogs: '打开日志文件夹',
    openBackups: '打开备份文件夹',
    quitApp: '退出 FreeLLMAPI',
    running: '运行中',
    requestsToday: '今日请求',
    tokensToday: '今日 token',
    lastModel: '上次模型',
    copyUrl: '复制 URL',
    copyKey: '复制密钥',
    copied: '已复制 ✓',
    startAtLogin: '登录时启动',
    quit: '退出',
    hoursAgo: '24 小时前',
    now: '现在',
    peak: '峰值 {n}/小时',
    successSuffix: '{n}% 成功',
    checkForUpdates: "检查更新…",
    restartToUpdateTray: "重启以更新 (v{version})",
    upToDate: "FreeLLMAPI v{version} 已是最新版本。",
    updateAvailable: "FreeLLMAPI v{version} 可用",
    updateAvailableDetail: "当前版本为 v{current}。更新会在后台下载，安装前会先备份你的数据。",
    downloadUpdate: "下载",
    releaseNotes: "更新说明",
    later: "稍后",
    updateFailed: "更新失败",
    updateReadyTitle: "FreeLLMAPI v{version} 已可安装",
    updateReadyBody: "重启 FreeLLMAPI 以完成更新。下次退出时也会自动安装。",
    restartToUpdate: "立即重启",
  },
  fr: {
    tooltip: 'FreeLLMAPI — routeur LLM local',
    runningOn: 'En cours sur {addr}',
    openDashboard: 'Ouvrir le tableau de bord',
    showCompactPanel: 'Afficher la fenêtre compacte',
    lanAccess: 'Autoriser l\'accès LAN (0.0.0.0)',
    showInDock: 'Afficher dans le Dock',
    openLogs: 'Ouvrir le dossier des journaux',
    openBackups: 'Ouvrir le dossier des sauvegardes',
    quitApp: 'Quitter FreeLLMAPI',
    running: 'en cours',
    requestsToday: "Requêtes aujourd'hui",
    tokensToday: "Tokens aujourd'hui",
    lastModel: 'Dernier modèle',
    copyUrl: "Copier l'URL",
    copyKey: 'Copier la clé',
    copied: 'Copié ✓',
    startAtLogin: "Lancer à l'ouverture de session",
    quit: 'Quitter',
    hoursAgo: 'il y a 24 h',
    now: 'maintenant',
    peak: 'pic {n}/h',
    successSuffix: '{n} % de réussite',
    checkForUpdates: "Rechercher des mises à jour…",
    restartToUpdateTray: "Redémarrer pour mettre à jour (v{version})",
    upToDate: "FreeLLMAPI v{version} est la dernière version.",
    updateAvailable: "FreeLLMAPI v{version} est disponible",
    updateAvailableDetail: "Vous avez la v{current}. La mise à jour se télécharge en arrière-plan ; vos données sont sauvegardées avant l’installation.",
    downloadUpdate: "Télécharger",
    releaseNotes: "Notes de version",
    later: "Plus tard",
    updateFailed: "Échec de la mise à jour",
    updateReadyTitle: "FreeLLMAPI v{version} est prête à être installée",
    updateReadyBody: "Redémarrez FreeLLMAPI pour terminer la mise à jour. Elle s’installe aussi à la prochaine fermeture.",
    restartToUpdate: "Redémarrer maintenant",
  },
  es: {
    tooltip: 'FreeLLMAPI — enrutador LLM local',
    runningOn: 'En ejecución en {addr}',
    openDashboard: 'Abrir el panel',
    showCompactPanel: 'Mostrar ventana compacta',
    lanAccess: 'Permitir acceso LAN (0.0.0.0)',
    showInDock: 'Mostrar en el Dock',
    openLogs: 'Abrir la carpeta de registros',
    openBackups: 'Abrir la carpeta de copias de seguridad',
    quitApp: 'Salir de FreeLLMAPI',
    running: 'en ejecución',
    requestsToday: 'Solicitudes hoy',
    tokensToday: 'Tokens hoy',
    lastModel: 'Último modelo',
    copyUrl: 'Copiar URL',
    copyKey: 'Copiar clave',
    copied: 'Copiado ✓',
    startAtLogin: 'Iniciar al arrancar sesión',
    quit: 'Salir',
    hoursAgo: 'hace 24 h',
    now: 'ahora',
    peak: 'pico {n}/h',
    successSuffix: '{n}% de aciertos',
    checkForUpdates: "Buscar actualizaciones…",
    restartToUpdateTray: "Reiniciar para actualizar (v{version})",
    upToDate: "FreeLLMAPI v{version} es la versión más reciente.",
    updateAvailable: "FreeLLMAPI v{version} está disponible",
    updateAvailableDetail: "Tienes la v{current}. La actualización se descarga en segundo plano y tus datos se respaldan antes de instalarla.",
    downloadUpdate: "Descargar",
    releaseNotes: "Notas de la versión",
    later: "Más tarde",
    updateFailed: "La actualización falló",
    updateReadyTitle: "FreeLLMAPI v{version} está lista para instalarse",
    updateReadyBody: "Reinicia FreeLLMAPI para terminar de actualizar. También se instala la próxima vez que salgas.",
    restartToUpdate: "Reiniciar ahora",
  },
  'pt-BR': {
    tooltip: 'FreeLLMAPI — roteador LLM local',
    runningOn: 'Em execução em {addr}',
    openDashboard: 'Abrir o painel',
    showCompactPanel: 'Mostrar janela compacta',
    lanAccess: 'Permitir acesso LAN (0.0.0.0)',
    showInDock: 'Mostrar no Dock',
    openLogs: 'Abrir a pasta de logs',
    openBackups: 'Abrir a pasta de backups',
    quitApp: 'Sair do FreeLLMAPI',
    running: 'em execução',
    requestsToday: 'Solicitações hoje',
    tokensToday: 'Tokens hoje',
    lastModel: 'Último modelo',
    copyUrl: 'Copiar URL',
    copyKey: 'Copiar chave',
    copied: 'Copiado ✓',
    startAtLogin: 'Iniciar ao fazer login',
    quit: 'Sair',
    hoursAgo: '24 h atrás',
    now: 'agora',
    peak: 'pico {n}/h',
    successSuffix: '{n}% de sucesso',
    checkForUpdates: "Verificar atualizações…",
    restartToUpdateTray: "Reiniciar para atualizar (v{version})",
    upToDate: "FreeLLMAPI v{version} é a versão mais recente.",
    updateAvailable: "FreeLLMAPI v{version} está disponível",
    updateAvailableDetail: "Você tem a v{current}. A atualização é baixada em segundo plano e seus dados recebem backup antes da instalação.",
    downloadUpdate: "Baixar",
    releaseNotes: "Notas da versão",
    later: "Mais tarde",
    updateFailed: "Falha na atualização",
    updateReadyTitle: "FreeLLMAPI v{version} está pronto para instalar",
    updateReadyBody: "Reinicie o FreeLLMAPI para concluir a atualização. Ela também é instalada na próxima vez que você sair.",
    restartToUpdate: "Reiniciar agora",
  },
  it: {
    tooltip: 'FreeLLMAPI — router LLM locale',
    runningOn: 'In esecuzione su {addr}',
    openDashboard: 'Apri il pannello',
    showCompactPanel: 'Mostra finestra compatta',
    lanAccess: 'Consenti accesso LAN (0.0.0.0)',
    showInDock: 'Mostra nel Dock',
    openLogs: 'Apri la cartella dei log',
    openBackups: 'Apri la cartella dei backup',
    quitApp: 'Esci da FreeLLMAPI',
    running: 'in esecuzione',
    requestsToday: 'Richieste oggi',
    tokensToday: 'Token oggi',
    lastModel: 'Ultimo modello',
    copyUrl: 'Copia URL',
    copyKey: 'Copia chiave',
    copied: 'Copiato ✓',
    startAtLogin: "Avvia all'accesso",
    quit: 'Esci',
    hoursAgo: '24 h fa',
    now: 'ora',
    peak: 'picco {n}/h',
    successSuffix: '{n}% di successo',
    checkForUpdates: "Controlla aggiornamenti…",
    restartToUpdateTray: "Riavvia per aggiornare (v{version})",
    upToDate: "FreeLLMAPI v{version} è la versione più recente.",
    updateAvailable: "FreeLLMAPI v{version} è disponibile",
    updateAvailableDetail: "Hai la v{current}. L’aggiornamento si scarica in background e i tuoi dati vengono salvati prima dell’installazione.",
    downloadUpdate: "Scarica",
    releaseNotes: "Note di rilascio",
    later: "Più tardi",
    updateFailed: "Aggiornamento non riuscito",
    updateReadyTitle: "FreeLLMAPI v{version} è pronto per l’installazione",
    updateReadyBody: "Riavvia FreeLLMAPI per completare l’aggiornamento. Viene installato anche alla prossima chiusura.",
    restartToUpdate: "Riavvia ora",
  },
};

// Translate a native key, falling back to English then the key itself.
export function dt(locale: NativeLocale, key: string, vars?: Record<string, string | number>): string {
  const raw = STRINGS[locale]?.[key] ?? STRINGS.en[key] ?? key;
  if (!vars) return raw;
  return raw.replace(/\{(\w+)\}/g, (_, name) => (name in vars ? String(vars[name]) : `{${name}}`));
}

// The full string bundle for one locale, sent to the popover in the snapshot so
// its file:// renderer (which has no access to this module) can label itself.
export function nativeStrings(locale: NativeLocale): Strings {
  return { ...STRINGS.en, ...STRINGS[locale] };
}
