const LANGS = {
  'zh-CN': { label: '简体中文', flag: '🇨🇳' },
  'zh-TW': { label: '繁體中文', flag: '🇹🇼' },
  'en':    { label: 'English',  flag: '🇺🇸' },
  'es':    { label: 'Español',  flag: '🇪🇸' },
  'de':    { label: 'Deutsch',  flag: '🇩🇪' },
  'fr':    { label: 'Français', flag: '🇫🇷' },
  'ja':    { label: '日本語',   flag: '🇯🇵' },
};

const messages = {
  'zh-CN': {
    selectProject: '选择项目',
    stats: '统计概览',
    projectMemories: '项目记忆',
    globalMemories: '全局记忆',
    sessionStatus: '会话状态',
    tagManagement: '标签管理',
    issueTracking: '问题跟踪',
    searchProject: '搜索项目记忆...',
    searchGlobal: '搜索全局记忆...',
    searchTag: '搜索标签...',
    status: { pending: '待处理', in_progress: '进行中', completed: '已完成', archived: '已归档' },
    allStatus: '全部状态',
    memories: '记忆',
    issues: '问题',
    tags: '标签',
    total: '共',
    items: '条',
    page: '页',
    noMemories: '暂无记忆',
    noStatus: '暂无会话状态',
    noIssues: '暂无问题',
    noTags: '暂无标签',
    edit: '编辑',
    delete: '删除',
    rename: '重命名',
    view: '查看',
    save: '保存',
    cancel: '取消',
    confirm: '确认',
    confirmDelete: '确认删除？',
    editMemory: '编辑记忆',
    content: '内容',
    tagsCommaSep: '标签（逗号分隔）',
    renameTag: '重命名标签',
    currentName: '当前名称',
    newName: '新名称',
    mergeTags: '合并标签',
    mergeFollowing: '将以下标签合并',
    mergeInto: '合并为',
    confirmDeleteTag: '确认删除标签：{names}？\n标签将从所有关联记忆中移除。',
    selected: '已选',
    tagsUnit: '个标签',
    batchMerge: '合并为...',
    batchDelete: '批量删除',
    cancelSelect: '取消选择',
    tagName: '标签名',
    memoryCount: '记忆数',
    actions: '操作',
    blocked: '阻塞状态',
    currentTask: '当前任务',
    nextStep: '下一步',
    updateTime: '更新时间',
    progress: '进度',
    recentChanges: '最近修改',
    pending: '待处理',
    yes: '是',
    no: '无',
    clickExpand: '点击展开详情',
    archivedAt: '归档于',
    createdAt: '创建于',
    vectorNetwork: '记忆向量网络',
    vectorSub: '语义关联 · 3D 拓扑 · 鼠标旋转 · {n} 节点',
    showMore: '查看更多',
    allTags: '全部标签（{n}）',
    tagLabel: '标签：{name}',
    issueList: '问题列表',
    projects: '个项目',
    footer: '~/.aivectormemory/memory.db · {n} 个项目',
    confirmDeleteProject: '确认删除项目 "{name}" 的所有数据？\n（全局记忆不会被删除）',
    deleteProjectBtn: '删除项目',
    addProject: '添加项目',
    addProjectTitle: '添加项目',
    projectPath: '项目路径',
    browse: '浏览',
    parentDir: '上级目录',
    addProjectPlaceholder: '输入或选择项目目录路径...',
    pathRequired: '请输入项目路径',
    welcomeTitle: '欢迎使用 AIVectorMemory',
    welcomeDesc: '这是一个 AI 跨会话持久记忆系统。\n在你的项目中运行以下命令开始使用：',
    welcomeCmd: 'aivectormemory install',
    addProjectSuccess: '项目已添加',
    addProjectInstallHint: '请在项目目录运行 aivectormemory install 完成 IDE 集成',
    emptyStatsHint: '数据由 AI 对话自动产生，开始对话后这里会显示统计信息',
    opSuccess: '操作成功',
    tagRenamed: '标签已重命名',
    tagsMerged: '标签已合并',
    tagsDeleted: '标签已删除',
    memorySaved: '记忆已保存',
    memoryDeleted: '记忆已删除',
    exportBtn: '导出',
    importBtn: '导入',
    exportSuccess: '导出成功',
    importSuccess: '已导入 {n} 条记忆',
    importFailed: '导入失败',
    selectFile: '选择 JSON 文件',
    backToProjects: '返回项目列表',
    addIssue: '添加问题',
    editIssue: '编辑问题',
    deleteIssue: '删除问题',
    archiveIssue: '归档问题',
    confirmDeleteIssue: '确认永久删除此问题？关联的记忆也会被删除。',
    confirmArchiveIssue: '确认归档此问题？',
    issueTitle: '问题标题',
    issueContent: '问题内容',
    issueTags: '标签（逗号分隔）',
    issueCreated: '问题已创建',
    issueUpdated: '问题已更新',
    issueArchived: '问题已归档',
    issueDeleted: '问题已删除',
    issueDuplicated: '已存在相同标题的问题',
  },
  'zh-TW': {
    selectProject: '選擇專案',
    stats: '統計概覽',
    projectMemories: '專案記憶',
    globalMemories: '全域記憶',
    sessionStatus: '會話狀態',
    tagManagement: '標籤管理',
    issueTracking: '問題追蹤',
    searchProject: '搜尋專案記憶...',
    searchGlobal: '搜尋全域記憶...',
    searchTag: '搜尋標籤...',
    status: { pending: '待處理', in_progress: '進行中', completed: '已完成', archived: '已歸檔' },
    allStatus: '全部狀態',
    memories: '記憶',
    issues: '問題',
    tags: '標籤',
    total: '共',
    items: '條',
    page: '頁',
    noMemories: '暫無記憶',
    noStatus: '暫無會話狀態',
    noIssues: '暫無問題',
    noTags: '暫無標籤',
    edit: '編輯',
    delete: '刪除',
    rename: '重新命名',
    view: '查看',
    save: '儲存',
    cancel: '取消',
    confirm: '確認',
    confirmDelete: '確認刪除？',
    editMemory: '編輯記憶',
    content: '內容',
    tagsCommaSep: '標籤（逗號分隔）',
    renameTag: '重新命名標籤',
    currentName: '目前名稱',
    newName: '新名稱',
    mergeTags: '合併標籤',
    mergeFollowing: '將以下標籤合併',
    mergeInto: '合併為',
    confirmDeleteTag: '確認刪除標籤：{names}？\n標籤將從所有關聯記憶中移除。',
    selected: '已選',
    tagsUnit: '個標籤',
    batchMerge: '合併為...',
    batchDelete: '批次刪除',
    cancelSelect: '取消選擇',
    tagName: '標籤名',
    memoryCount: '記憶數',
    actions: '操作',
    blocked: '阻塞狀態',
    currentTask: '目前任務',
    nextStep: '下一步',
    updateTime: '更新時間',
    progress: '進度',
    recentChanges: '最近修改',
    pending: '待處理',
    yes: '是',
    no: '無',
    clickExpand: '點擊展開詳情',
    archivedAt: '歸檔於',
    createdAt: '建立於',
    vectorNetwork: '記憶向量網路',
    vectorSub: '語義關聯 · 3D 拓撲 · 滑鼠旋轉 · {n} 節點',
    showMore: '查看更多',
    allTags: '全部標籤（{n}）',
    tagLabel: '標籤：{name}',
    issueList: '問題列表',
    projects: '個專案',
    footer: '~/.aivectormemory/memory.db · {n} 個專案',
    confirmDeleteProject: '確認刪除專案 "{name}" 的所有資料？\n（全域記憶不會被刪除）',
    deleteProjectBtn: '刪除專案',
    addProject: '新增專案',
    addProjectTitle: '新增專案',
    projectPath: '專案路徑',
    browse: '瀏覽',
    parentDir: '上層目錄',
    addProjectPlaceholder: '輸入或選擇專案目錄路徑...',
    pathRequired: '請輸入專案路徑',
    welcomeTitle: '歡迎使用 AIVectorMemory',
    welcomeDesc: '這是一個 AI 跨會話持久記憶系統。\n在你的專案中執行以下命令開始使用：',
    welcomeCmd: 'aivectormemory install',
    addProjectSuccess: '專案已新增',
    addProjectInstallHint: '請在專案目錄執行 aivectormemory install 完成 IDE 整合',
    emptyStatsHint: '資料由 AI 對話自動產生，開始對話後這裡會顯示統計資訊',
    opSuccess: '操作成功',
    tagRenamed: '標籤已重新命名',
    tagsMerged: '標籤已合併',
    tagsDeleted: '標籤已刪除',
    memorySaved: '記憶已儲存',
    memoryDeleted: '記憶已刪除',
    exportBtn: '匯出',
    importBtn: '匯入',
    exportSuccess: '匯出成功',
    importSuccess: '已匯入 {n} 條記憶',
    importFailed: '匯入失敗',
    selectFile: '選擇 JSON 檔案',
    backToProjects: '返回專案列表',
    addIssue: '新增問題',
    editIssue: '編輯問題',
    deleteIssue: '刪除問題',
    archiveIssue: '歸檔問題',
    confirmDeleteIssue: '確認永久刪除此問題？關聯的記憶也會被刪除。',
    confirmArchiveIssue: '確認歸檔此問題？',
    issueTitle: '問題標題',
    issueContent: '問題內容',
    issueTags: '標籤（逗號分隔）',
    issueCreated: '問題已建立',
    issueUpdated: '問題已更新',
    issueArchived: '問題已歸檔',
    issueDeleted: '問題已刪除',
    issueDuplicated: '已存在相同標題的問題',
  },
  'en': {
    selectProject: 'Select Project',
    stats: 'Overview',
    projectMemories: 'Project Memories',
    globalMemories: 'Global Memories',
    sessionStatus: 'Session Status',
    tagManagement: 'Tags',
    issueTracking: 'Issues',
    searchProject: 'Search project memories...',
    searchGlobal: 'Search global memories...',
    searchTag: 'Search tags...',
    status: { pending: 'Pending', in_progress: 'In Progress', completed: 'Completed', archived: 'Archived' },
    allStatus: 'All Status',
    memories: 'Memories',
    issues: 'Issues',
    tags: 'Tags',
    total: 'Total',
    items: 'items',
    page: 'page',
    noMemories: 'No memories yet',
    noStatus: 'No session status',
    noIssues: 'No issues yet',
    noTags: 'No tags yet',
    edit: 'Edit',
    delete: 'Delete',
    rename: 'Rename',
    view: 'View',
    save: 'Save',
    cancel: 'Cancel',
    confirm: 'Confirm',
    confirmDelete: 'Confirm delete?',
    editMemory: 'Edit Memory',
    content: 'Content',
    tagsCommaSep: 'Tags (comma separated)',
    renameTag: 'Rename Tag',
    currentName: 'Current Name',
    newName: 'New Name',
    mergeTags: 'Merge Tags',
    mergeFollowing: 'Merge the following tags',
    mergeInto: 'Merge into',
    confirmDeleteTag: 'Delete tags: {names}?\nTags will be removed from all associated memories.',
    selected: 'Selected',
    tagsUnit: 'tags',
    batchMerge: 'Merge into...',
    batchDelete: 'Batch Delete',
    cancelSelect: 'Deselect',
    tagName: 'Tag Name',
    memoryCount: 'Count',
    actions: 'Actions',
    blocked: 'Blocked',
    currentTask: 'Current Task',
    nextStep: 'Next Step',
    updateTime: 'Updated',
    progress: 'Progress',
    recentChanges: 'Recent Changes',
    pending: 'Pending',
    yes: 'Yes',
    no: 'None',
    clickExpand: 'Click to expand',
    archivedAt: 'Archived at',
    createdAt: 'Created at',
    vectorNetwork: 'Memory Vector Network',
    vectorSub: 'Semantic · 3D Topology · Mouse Rotate · {n} nodes',
    showMore: 'Show More',
    allTags: 'All Tags ({n})',
    tagLabel: 'Tag: {name}',
    issueList: 'Issue List',
    projects: 'projects',
    footer: '~/.aivectormemory/memory.db · {n} projects',
    confirmDeleteProject: 'Delete all data for project "{name}"?\n(Global memories will not be deleted)',
    deleteProjectBtn: 'Delete Project',
    addProject: 'Add Project',
    addProjectTitle: 'Add Project',
    projectPath: 'Project Path',
    browse: 'Browse',
    parentDir: 'Parent',
    addProjectPlaceholder: 'Enter or select project directory path...',
    pathRequired: 'Please enter a project path',
    welcomeTitle: 'Welcome to AIVectorMemory',
    welcomeDesc: 'A persistent cross-session memory system for AI.\nRun the following command in your project to get started:',
    welcomeCmd: 'aivectormemory install',
    addProjectSuccess: 'Project added',
    addProjectInstallHint: 'Run aivectormemory install in the project directory to complete IDE integration',
    emptyStatsHint: 'Data is generated automatically from AI conversations. Start a conversation to see stats here',
    opSuccess: 'Success',
    tagRenamed: 'Tag renamed',
    tagsMerged: 'Tags merged',
    tagsDeleted: 'Tags deleted',
    memorySaved: 'Memory saved',
    memoryDeleted: 'Memory deleted',
    exportBtn: 'Export',
    importBtn: 'Import',
    exportSuccess: 'Export successful',
    importSuccess: '{n} memories imported',
    importFailed: 'Import failed',
    selectFile: 'Select JSON file',
    backToProjects: 'Back to projects',
    addIssue: 'Add Issue',
    editIssue: 'Edit Issue',
    deleteIssue: 'Delete Issue',
    archiveIssue: 'Archive Issue',
    confirmDeleteIssue: 'Permanently delete this issue? Associated memory will also be deleted.',
    confirmArchiveIssue: 'Archive this issue?',
    issueTitle: 'Issue Title',
    issueContent: 'Issue Content',
    issueTags: 'Tags (comma separated)',
    issueCreated: 'Issue created',
    issueUpdated: 'Issue updated',
    issueArchived: 'Issue archived',
    issueDeleted: 'Issue deleted',
    issueDuplicated: 'An issue with the same title already exists',
  },
  'es': {
    selectProject: 'Seleccionar Proyecto',
    stats: 'Resumen',
    projectMemories: 'Memorias del Proyecto',
    globalMemories: 'Memorias Globales',
    sessionStatus: 'Estado de Sesión',
    tagManagement: 'Etiquetas',
    issueTracking: 'Problemas',
    searchProject: 'Buscar memorias del proyecto...',
    searchGlobal: 'Buscar memorias globales...',
    searchTag: 'Buscar etiquetas...',
    status: { pending: 'Pendiente', in_progress: 'En Progreso', completed: 'Completado', archived: 'Archivado' },
    allStatus: 'Todos los Estados',
    memories: 'Memorias',
    issues: 'Problemas',
    tags: 'Etiquetas',
    total: 'Total',
    items: 'elementos',
    page: 'página',
    noMemories: 'Sin memorias',
    noStatus: 'Sin estado de sesión',
    noIssues: 'Sin problemas',
    noTags: 'Sin etiquetas',
    edit: 'Editar',
    delete: 'Eliminar',
    rename: 'Renombrar',
    view: 'Ver',
    save: 'Guardar',
    cancel: 'Cancelar',
    confirm: 'Confirmar',
    confirmDelete: '¿Confirmar eliminación?',
    editMemory: 'Editar Memoria',
    content: 'Contenido',
    tagsCommaSep: 'Etiquetas (separadas por comas)',
    renameTag: 'Renombrar Etiqueta',
    currentName: 'Nombre Actual',
    newName: 'Nuevo Nombre',
    mergeTags: 'Fusionar Etiquetas',
    mergeFollowing: 'Fusionar las siguientes etiquetas',
    mergeInto: 'Fusionar en',
    confirmDeleteTag: '¿Eliminar etiquetas: {names}?\nSe eliminarán de todas las memorias asociadas.',
    selected: 'Seleccionados',
    tagsUnit: 'etiquetas',
    batchMerge: 'Fusionar en...',
    batchDelete: 'Eliminar Lote',
    cancelSelect: 'Deseleccionar',
    tagName: 'Nombre',
    memoryCount: 'Cantidad',
    actions: 'Acciones',
    blocked: 'Bloqueado',
    currentTask: 'Tarea Actual',
    nextStep: 'Siguiente Paso',
    updateTime: 'Actualizado',
    progress: 'Progreso',
    recentChanges: 'Cambios Recientes',
    pending: 'Pendiente',
    yes: 'Sí',
    no: 'Ninguno',
    clickExpand: 'Clic para expandir',
    archivedAt: 'Archivado el',
    createdAt: 'Creado el',
    vectorNetwork: 'Red de Vectores de Memoria',
    vectorSub: 'Semántica · Topología 3D · Rotar con ratón · {n} nodos',
    showMore: 'Ver Más',
    allTags: 'Todas las Etiquetas ({n})',
    tagLabel: 'Etiqueta: {name}',
    issueList: 'Lista de Problemas',
    projects: 'proyectos',
    footer: '~/.aivectormemory/memory.db · {n} proyectos',
    confirmDeleteProject: '¿Eliminar todos los datos del proyecto "{name}"?\n(Las memorias globales no se eliminarán)',
    deleteProjectBtn: 'Eliminar Proyecto',
    addProject: 'Agregar Proyecto',
    addProjectTitle: 'Agregar Proyecto',
    projectPath: 'Ruta del Proyecto',
    browse: 'Explorar',
    parentDir: 'Superior',
    addProjectPlaceholder: 'Ingrese o seleccione la ruta del directorio...',
    pathRequired: 'Ingrese una ruta de proyecto',
    welcomeTitle: 'Bienvenido a AIVectorMemory',
    welcomeDesc: 'Un sistema de memoria persistente entre sesiones para IA.\nEjecute el siguiente comando en su proyecto para comenzar:',
    welcomeCmd: 'aivectormemory install',
    addProjectSuccess: 'Proyecto agregado',
    addProjectInstallHint: 'Ejecute aivectormemory install en el directorio del proyecto para completar la integración IDE',
    emptyStatsHint: 'Los datos se generan automáticamente desde conversaciones de IA. Inicie una conversación para ver estadísticas',
    opSuccess: 'Éxito',
    tagRenamed: 'Etiqueta renombrada',
    tagsMerged: 'Etiquetas fusionadas',
    tagsDeleted: 'Etiquetas eliminadas',
    memorySaved: 'Memoria guardada',
    memoryDeleted: 'Memoria eliminada',
    exportBtn: 'Exportar',
    importBtn: 'Importar',
    exportSuccess: 'Exportación exitosa',
    importSuccess: '{n} memorias importadas',
    importFailed: 'Importación fallida',
    selectFile: 'Seleccionar archivo JSON',
    backToProjects: 'Volver a proyectos',
    addIssue: 'Agregar Problema',
    editIssue: 'Editar Problema',
    deleteIssue: 'Eliminar Problema',
    archiveIssue: 'Archivar Problema',
    confirmDeleteIssue: '¿Eliminar permanentemente este problema? La memoria asociada también se eliminará.',
    confirmArchiveIssue: '¿Archivar este problema?',
    issueTitle: 'Título del Problema',
    issueContent: 'Contenido del Problema',
    issueTags: 'Etiquetas (separadas por comas)',
    issueCreated: 'Problema creado',
    issueUpdated: 'Problema actualizado',
    issueArchived: 'Problema archivado',
    issueDeleted: 'Problema eliminado',
    issueDuplicated: 'Ya existe un problema con el mismo título',
  },
  'de': {
    selectProject: 'Projekt Auswählen',
    stats: 'Übersicht',
    projectMemories: 'Projekt-Erinnerungen',
    globalMemories: 'Globale Erinnerungen',
    sessionStatus: 'Sitzungsstatus',
    tagManagement: 'Tags',
    issueTracking: 'Probleme',
    searchProject: 'Projekt-Erinnerungen suchen...',
    searchGlobal: 'Globale Erinnerungen suchen...',
    searchTag: 'Tags suchen...',
    status: { pending: 'Ausstehend', in_progress: 'In Bearbeitung', completed: 'Abgeschlossen', archived: 'Archiviert' },
    allStatus: 'Alle Status',
    memories: 'Erinnerungen',
    issues: 'Probleme',
    tags: 'Tags',
    total: 'Gesamt',
    items: 'Einträge',
    page: 'Seite',
    noMemories: 'Keine Erinnerungen',
    noStatus: 'Kein Sitzungsstatus',
    noIssues: 'Keine Probleme',
    noTags: 'Keine Tags',
    edit: 'Bearbeiten',
    delete: 'Löschen',
    rename: 'Umbenennen',
    view: 'Ansehen',
    save: 'Speichern',
    cancel: 'Abbrechen',
    confirm: 'Bestätigen',
    confirmDelete: 'Löschen bestätigen?',
    editMemory: 'Erinnerung Bearbeiten',
    content: 'Inhalt',
    tagsCommaSep: 'Tags (kommagetrennt)',
    renameTag: 'Tag Umbenennen',
    currentName: 'Aktueller Name',
    newName: 'Neuer Name',
    mergeTags: 'Tags Zusammenführen',
    mergeFollowing: 'Folgende Tags zusammenführen',
    mergeInto: 'Zusammenführen zu',
    confirmDeleteTag: 'Tags löschen: {names}?\nTags werden aus allen verknüpften Erinnerungen entfernt.',
    selected: 'Ausgewählt',
    tagsUnit: 'Tags',
    batchMerge: 'Zusammenführen...',
    batchDelete: 'Stapel Löschen',
    cancelSelect: 'Abwählen',
    tagName: 'Tag-Name',
    memoryCount: 'Anzahl',
    actions: 'Aktionen',
    blocked: 'Blockiert',
    currentTask: 'Aktuelle Aufgabe',
    nextStep: 'Nächster Schritt',
    updateTime: 'Aktualisiert',
    progress: 'Fortschritt',
    recentChanges: 'Letzte Änderungen',
    pending: 'Ausstehend',
    yes: 'Ja',
    no: 'Keine',
    clickExpand: 'Klicken zum Erweitern',
    archivedAt: 'Archiviert am',
    createdAt: 'Erstellt am',
    vectorNetwork: 'Erinnerungs-Vektornetzwerk',
    vectorSub: 'Semantik · 3D-Topologie · Maus drehen · {n} Knoten',
    showMore: 'Mehr Anzeigen',
    allTags: 'Alle Tags ({n})',
    tagLabel: 'Tag: {name}',
    issueList: 'Problemliste',
    projects: 'Projekte',
    footer: '~/.aivectormemory/memory.db · {n} Projekte',
    confirmDeleteProject: 'Alle Daten des Projekts "{name}" löschen?\n(Globale Erinnerungen werden nicht gelöscht)',
    deleteProjectBtn: 'Projekt Löschen',
    addProject: 'Projekt Hinzufügen',
    addProjectTitle: 'Projekt Hinzufügen',
    projectPath: 'Projektpfad',
    browse: 'Durchsuchen',
    parentDir: 'Übergeordnet',
    addProjectPlaceholder: 'Projektverzeichnis eingeben oder auswählen...',
    pathRequired: 'Bitte Projektpfad eingeben',
    welcomeTitle: 'Willkommen bei AIVectorMemory',
    welcomeDesc: 'Ein persistentes sitzungsübergreifendes Gedächtnissystem für KI.\nFühren Sie den folgenden Befehl in Ihrem Projekt aus:',
    welcomeCmd: 'aivectormemory install',
    addProjectSuccess: 'Projekt hinzugefügt',
    addProjectInstallHint: 'Führen Sie aivectormemory install im Projektverzeichnis aus, um die IDE-Integration abzuschließen',
    emptyStatsHint: 'Daten werden automatisch aus KI-Gesprächen generiert. Starten Sie ein Gespräch, um Statistiken zu sehen',
    opSuccess: 'Erfolg',
    tagRenamed: 'Tag umbenannt',
    tagsMerged: 'Tags zusammengeführt',
    tagsDeleted: 'Tags gelöscht',
    memorySaved: 'Erinnerung gespeichert',
    memoryDeleted: 'Erinnerung gelöscht',
    exportBtn: 'Exportieren',
    importBtn: 'Importieren',
    exportSuccess: 'Export erfolgreich',
    importSuccess: '{n} Erinnerungen importiert',
    importFailed: 'Import fehlgeschlagen',
    selectFile: 'JSON-Datei auswählen',
    backToProjects: 'Zurück zu Projekten',
    addIssue: 'Problem Hinzufügen',
    editIssue: 'Problem Bearbeiten',
    deleteIssue: 'Problem Löschen',
    archiveIssue: 'Problem Archivieren',
    confirmDeleteIssue: 'Dieses Problem dauerhaft löschen? Die zugehörige Erinnerung wird ebenfalls gelöscht.',
    confirmArchiveIssue: 'Dieses Problem archivieren?',
    issueTitle: 'Problemtitel',
    issueContent: 'Probleminhalt',
    issueTags: 'Tags (kommagetrennt)',
    issueCreated: 'Problem erstellt',
    issueUpdated: 'Problem aktualisiert',
    issueArchived: 'Problem archiviert',
    issueDeleted: 'Problem gelöscht',
    issueDuplicated: 'Ein Problem mit demselben Titel existiert bereits',
  },
  'fr': {
    selectProject: 'Sélectionner un Projet',
    stats: 'Aperçu',
    projectMemories: 'Mémoires du Projet',
    globalMemories: 'Mémoires Globales',
    sessionStatus: 'État de Session',
    tagManagement: 'Étiquettes',
    issueTracking: 'Problèmes',
    searchProject: 'Rechercher mémoires du projet...',
    searchGlobal: 'Rechercher mémoires globales...',
    searchTag: 'Rechercher étiquettes...',
    status: { pending: 'En Attente', in_progress: 'En Cours', completed: 'Terminé', archived: 'Archivé' },
    allStatus: 'Tous les Statuts',
    memories: 'Mémoires',
    issues: 'Problèmes',
    tags: 'Étiquettes',
    total: 'Total',
    items: 'éléments',
    page: 'page',
    noMemories: 'Aucune mémoire',
    noStatus: 'Aucun état de session',
    noIssues: 'Aucun problème',
    noTags: 'Aucune étiquette',
    edit: 'Modifier',
    delete: 'Supprimer',
    rename: 'Renommer',
    view: 'Voir',
    save: 'Enregistrer',
    cancel: 'Annuler',
    confirm: 'Confirmer',
    confirmDelete: 'Confirmer la suppression ?',
    editMemory: 'Modifier la Mémoire',
    content: 'Contenu',
    tagsCommaSep: 'Étiquettes (séparées par des virgules)',
    renameTag: 'Renommer l\'Étiquette',
    currentName: 'Nom Actuel',
    newName: 'Nouveau Nom',
    mergeTags: 'Fusionner les Étiquettes',
    mergeFollowing: 'Fusionner les étiquettes suivantes',
    mergeInto: 'Fusionner en',
    confirmDeleteTag: 'Supprimer les étiquettes : {names} ?\nElles seront retirées de toutes les mémoires associées.',
    selected: 'Sélectionnés',
    tagsUnit: 'étiquettes',
    batchMerge: 'Fusionner en...',
    batchDelete: 'Suppression Groupée',
    cancelSelect: 'Désélectionner',
    tagName: 'Nom',
    memoryCount: 'Nombre',
    actions: 'Actions',
    blocked: 'Bloqué',
    currentTask: 'Tâche Actuelle',
    nextStep: 'Prochaine Étape',
    updateTime: 'Mis à jour',
    progress: 'Progression',
    recentChanges: 'Modifications Récentes',
    pending: 'En Attente',
    yes: 'Oui',
    no: 'Aucun',
    clickExpand: 'Cliquer pour développer',
    archivedAt: 'Archivé le',
    createdAt: 'Créé le',
    vectorNetwork: 'Réseau de Vecteurs Mémoire',
    vectorSub: 'Sémantique · Topologie 3D · Rotation souris · {n} nœuds',
    showMore: 'Voir Plus',
    allTags: 'Toutes les Étiquettes ({n})',
    tagLabel: 'Étiquette : {name}',
    issueList: 'Liste des Problèmes',
    projects: 'projets',
    footer: '~/.aivectormemory/memory.db · {n} projets',
    confirmDeleteProject: 'Supprimer toutes les données du projet "{name}" ?\n(Les mémoires globales ne seront pas supprimées)',
    deleteProjectBtn: 'Supprimer le Projet',
    addProject: 'Ajouter un Projet',
    addProjectTitle: 'Ajouter un Projet',
    projectPath: 'Chemin du Projet',
    browse: 'Parcourir',
    parentDir: 'Parent',
    addProjectPlaceholder: 'Entrez ou sélectionnez le chemin du répertoire...',
    pathRequired: 'Veuillez entrer un chemin de projet',
    welcomeTitle: 'Bienvenue sur AIVectorMemory',
    welcomeDesc: 'Un système de mémoire persistante inter-sessions pour l\'IA.\nExécutez la commande suivante dans votre projet pour commencer :',
    welcomeCmd: 'aivectormemory install',
    addProjectSuccess: 'Projet ajouté',
    addProjectInstallHint: 'Exécutez aivectormemory install dans le répertoire du projet pour terminer l\'intégration IDE',
    emptyStatsHint: 'Les données sont générées automatiquement par les conversations IA. Commencez une conversation pour voir les statistiques',
    opSuccess: 'Succès',
    tagRenamed: 'Étiquette renommée',
    tagsMerged: 'Étiquettes fusionnées',
    tagsDeleted: 'Étiquettes supprimées',
    memorySaved: 'Mémoire enregistrée',
    memoryDeleted: 'Mémoire supprimée',
    exportBtn: 'Exporter',
    importBtn: 'Importer',
    exportSuccess: 'Export réussi',
    importSuccess: '{n} mémoires importées',
    importFailed: 'Échec de l\'import',
    selectFile: 'Sélectionner un fichier JSON',
    backToProjects: 'Retour aux projets',
    addIssue: 'Ajouter un Problème',
    editIssue: 'Modifier le Problème',
    deleteIssue: 'Supprimer le Problème',
    archiveIssue: 'Archiver le Problème',
    confirmDeleteIssue: 'Supprimer définitivement ce problème ? La mémoire associée sera également supprimée.',
    confirmArchiveIssue: 'Archiver ce problème ?',
    issueTitle: 'Titre du Problème',
    issueContent: 'Contenu du Problème',
    issueTags: 'Étiquettes (séparées par des virgules)',
    issueCreated: 'Problème créé',
    issueUpdated: 'Problème mis à jour',
    issueArchived: 'Problème archivé',
    issueDeleted: 'Problème supprimé',
    issueDuplicated: 'Un problème avec le même titre existe déjà',
  },
  'ja': {
    selectProject: 'プロジェクト選択',
    stats: '統計概要',
    projectMemories: 'プロジェクト記憶',
    globalMemories: 'グローバル記憶',
    sessionStatus: 'セッション状態',
    tagManagement: 'タグ管理',
    issueTracking: '問題追跡',
    searchProject: 'プロジェクト記憶を検索...',
    searchGlobal: 'グローバル記憶を検索...',
    searchTag: 'タグを検索...',
    status: { pending: '未処理', in_progress: '進行中', completed: '完了', archived: 'アーカイブ済' },
    allStatus: 'すべてのステータス',
    memories: '記憶',
    issues: '問題',
    tags: 'タグ',
    total: '合計',
    items: '件',
    page: 'ページ',
    noMemories: '記憶がありません',
    noStatus: 'セッション状態がありません',
    noIssues: '問題がありません',
    noTags: 'タグがありません',
    edit: '編集',
    delete: '削除',
    rename: '名前変更',
    view: '表示',
    save: '保存',
    cancel: 'キャンセル',
    confirm: '確認',
    confirmDelete: '削除しますか？',
    editMemory: '記憶を編集',
    content: '内容',
    tagsCommaSep: 'タグ（カンマ区切り）',
    renameTag: 'タグ名変更',
    currentName: '現在の名前',
    newName: '新しい名前',
    mergeTags: 'タグを統合',
    mergeFollowing: '以下のタグを統合',
    mergeInto: '統合先',
    confirmDeleteTag: 'タグを削除：{names}？\nすべての関連記憶からタグが削除されます。',
    selected: '選択済',
    tagsUnit: 'タグ',
    batchMerge: '統合先...',
    batchDelete: '一括削除',
    cancelSelect: '選択解除',
    tagName: 'タグ名',
    memoryCount: '記憶数',
    actions: '操作',
    blocked: 'ブロック状態',
    currentTask: '現在のタスク',
    nextStep: '次のステップ',
    updateTime: '更新日時',
    progress: '進捗',
    recentChanges: '最近の変更',
    pending: '未処理',
    yes: 'はい',
    no: 'なし',
    clickExpand: 'クリックで展開',
    archivedAt: 'アーカイブ日',
    createdAt: '作成日',
    vectorNetwork: '記憶ベクトルネットワーク',
    vectorSub: '意味関連 · 3Dトポロジー · マウス回転 · {n} ノード',
    showMore: 'もっと見る',
    allTags: 'すべてのタグ（{n}）',
    tagLabel: 'タグ：{name}',
    issueList: '問題一覧',
    projects: 'プロジェクト',
    footer: '~/.aivectormemory/memory.db · {n} プロジェクト',
    confirmDeleteProject: 'プロジェクト "{name}" のすべてのデータを削除しますか？\n（グローバル記憶は削除されません）',
    deleteProjectBtn: 'プロジェクト削除',
    addProject: 'プロジェクト追加',
    addProjectTitle: 'プロジェクト追加',
    projectPath: 'プロジェクトパス',
    browse: '参照',
    parentDir: '上位',
    addProjectPlaceholder: 'プロジェクトディレクトリを入力または選択...',
    pathRequired: 'プロジェクトパスを入力してください',
    welcomeTitle: 'AIVectorMemory へようこそ',
    welcomeDesc: 'AIのためのセッション間永続記憶システムです。\nプロジェクトで以下のコマンドを実行して開始してください：',
    welcomeCmd: 'aivectormemory install',
    addProjectSuccess: 'プロジェクトを追加しました',
    addProjectInstallHint: 'プロジェクトディレクトリで aivectormemory install を実行してIDE統合を完了してください',
    emptyStatsHint: 'データはAI会話から自動生成されます。会話を開始すると統計が表示されます',
    opSuccess: '成功',
    tagRenamed: 'タグ名を変更しました',
    tagsMerged: 'タグを統合しました',
    tagsDeleted: 'タグを削除しました',
    memorySaved: '記憶を保存しました',
    memoryDeleted: '記憶を削除しました',
    exportBtn: 'エクスポート',
    importBtn: 'インポート',
    exportSuccess: 'エクスポート成功',
    importSuccess: '{n} 件の記憶をインポートしました',
    importFailed: 'インポート失敗',
    selectFile: 'JSONファイルを選択',
    backToProjects: 'プロジェクト一覧に戻る',
    addIssue: '問題を追加',
    editIssue: '問題を編集',
    deleteIssue: '問題を削除',
    archiveIssue: '問題をアーカイブ',
    confirmDeleteIssue: 'この問題を完全に削除しますか？関連する記憶も削除されます。',
    confirmArchiveIssue: 'この問題をアーカイブしますか？',
    issueTitle: '問題タイトル',
    issueContent: '問題内容',
    issueTags: 'タグ（カンマ区切り）',
    issueCreated: '問題を作成しました',
    issueUpdated: '問題を更新しました',
    issueArchived: '問題をアーカイブしました',
    issueDeleted: '問題を削除しました',
    issueDuplicated: '同じタイトルの問題が既に存在します',
  },
};

let currentLang = localStorage.getItem('avm-lang') || 'zh-CN';

function t(key) {
  const lang = messages[currentLang] || messages['zh-CN'];
  return key.split('.').reduce((o, k) => o?.[k], lang) ?? key;
}

function setLang(lang) {
  if (!messages[lang]) return;
  currentLang = lang;
  localStorage.setItem('avm-lang', lang);
  document.documentElement.lang = lang.startsWith('zh') ? (lang === 'zh-TW' ? 'zh-Hant' : 'zh-Hans') : lang;
  document.querySelectorAll('[data-i18n]').forEach(el => {
    const val = t(el.dataset.i18n);
    if (el.tagName === 'OPTION') el.textContent = val;
    else if (el.childElementCount === 0) el.textContent = val;
    else {
      const textNodes = [...el.childNodes].filter(n => n.nodeType === 3);
      if (textNodes.length) textNodes[0].textContent = val;
      else el.textContent = val;
    }
  });
  document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
    el.placeholder = t(el.dataset.i18nPlaceholder);
  });
  const langSelects = document.querySelectorAll('.lang-select');
  langSelects.forEach(s => s.value = lang);
}

function renderLangSwitcher(containerId) {
  const el = document.getElementById(containerId);
  if (!el) return;
  const options = Object.entries(LANGS).map(([code, { flag, label }]) =>
    `<option value="${code}"${code === currentLang ? ' selected' : ''}>${flag} ${label}</option>`
  ).join('');
  el.innerHTML = `<select class="lang-select">${options}</select>`;
  el.querySelector('.lang-select').addEventListener('change', (e) => {
    setLang(e.target.value);
    if (typeof window._reloadCurrentView === 'function') window._reloadCurrentView();
  });
}