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: '问题跟踪',
    taskManagement: '任务管理',
    searchProject: '搜索项目记忆...',
    searchGlobal: '搜索全局记忆...',
    searchTag: '搜索标签...',
    status: { pending: '待处理', in_progress: '进行中', completed: '已完成', archived: '已归档', skipped: '已跳过' },
    allStatus: '全部状态',
    activeOnly: '活跃',
    allIncludeArchived: '全部（含归档）',
    allFeatures: '全部功能',
    sysDigest: '系统：碎片归纳',
    issuePrefix: '问题 #',
    taskProgress: '{done}/{total}',
    systemTask: '系统任务',
    manualTask: '手动任务',
    collapse: '收起',
    expand: '展开',
    addTask: '添加任务',
    addFeatureGroup: '新增功能组',
    editTask: '编辑任务',
    deleteTask: '删除任务',
    deleteFeatureGroup: '删除功能组',
    taskTitle: '任务标题',
    featureGroupName: '功能组名称',
    confirmDeleteTask: '确定删除此任务？',
    confirmDeleteFeatureGroup: '确定删除整个功能组及其所有任务？',
    taskCreated: '任务已创建',
    taskUpdated: '任务已更新',
    taskDeleted: '任务已删除',
    featureGroupDeleted: '功能组已删除',
    featureGroupCreated: '功能组已创建',
    page: '页',
    noMemories: '暂无记忆',
    noStatus: '暂无会话状态',
    noIssues: '暂无问题',
    noTasks: '暂无任务',
    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: '阻塞状态',
    normalStatus: '正常运行',
    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: '标签（逗号分隔）',
    moreFields: '更多字段',
    issueCreated: '问题已创建',
    issueUpdated: '问题已更新',
    issueArchived: '问题已归档',
    issueDeleted: '问题已删除',
    issueDuplicated: '已存在相同标题的问题',
    relatedTo: '关联',
    issueDescription: '问题描述',
    issueInvestigation: '排查过程',
    issueRootCause: '根本原因',
    issueSolution: '解决方案',
    issueFilesChanged: '修改文件',
    issueTestResult: '自测结果',
    issueNotes: '注意事项',
    issueFeatureId: '关联功能',
    issueParentId: '父问题',
    expandDetails: '展开详情',
    collapseDetails: '收起详情',
    filePath: '文件路径',
    fileDone: '已完成',
    fileNotDone: '未完成',
    catDecision: '决策记录',
    catModification: '修改记录',
    catPitfall: '踩坑记录',
    catTodo: '待办事项',
    catPreference: '偏好设置',
    searchDecision: '搜索决策记录...',
    searchModification: '搜索修改记录...',
    searchPitfall: '搜索踩坑记录...',
    searchTodo: '搜索待办事项...',
    searchPreference: '搜索偏好设置...',
    viewAll: '查看全部',
    today: '今天',
    searchIssue: '搜索问题...',
    search: '搜索',
    searchTask: '搜索任务...',
    noCategoryMemories: '暂无记录',
    'auth.login': '登录',
    'auth.loginDesc': '登录您的 AIVectorMemory 账户',
    'auth.createAccount': '创建账户',
    'auth.createAccountDesc': '注册新的 AIVectorMemory 账户',
    'auth.register': '注册',
    'auth.username': '用户名',
    'auth.password': '密码',
    'auth.confirmPassword': '确认密码',
    'auth.fieldsRequired': '请填写所有字段',
    'auth.passwordTooShort': '密码至少 6 位',
    'auth.passwordMismatch': '两次密码不一致',
    'auth.noAccount': '没有账户？',
    'auth.hasAccount': '已有账户？',
    'auth.logout': '退出登录',
    // --- Settings & Sidebar ---
    sectionMemory: '记忆',
    sectionSystem: '系统',
    settings: '设置',
    toggleTheme: '切换主题',
    language: '语言',
    dbStats: '数据库统计',
    fileSize: '文件大小',
    healthCheck: '健康检查',
    embeddingDim: '向量维度',
    embeddingStatus: '向量状态',
    orphanVectors: '孤立向量',
    repairOrphans: '修复孤立向量',
    repairSuccess: '修复完成',
    backup: '备份',
    createBackup: '创建备份',
    backupSuccess: '备份已创建',
    noBackups: '暂无备份',
    account: '账户',
    changePassword: '修改密码',
    currentPassword: '当前密码',
    newPassword: '新密码',
    confirmNewPassword: '确认新密码',
    passwordChanged: '密码修改成功',
    passwordChangeFailed: '密码修改失败',
  },
  'zh-TW': {
    selectProject: '選擇專案',
    stats: '統計概覽',
    projectMemories: '專案記憶',
    globalMemories: '全域記憶',
    sessionStatus: '會話狀態',
    tagManagement: '標籤管理',
    issueTracking: '問題追蹤',
    taskManagement: '任務管理',
    searchProject: '搜尋專案記憶...',
    searchGlobal: '搜尋全域記憶...',
    searchTag: '搜尋標籤...',
    status: { pending: '待處理', in_progress: '進行中', completed: '已完成', archived: '已歸檔', skipped: '已跳過' },
    allStatus: '全部狀態',
    activeOnly: '活躍',
    allIncludeArchived: '全部（含歸檔）',
    allFeatures: '全部功能',
    sysDigest: '系統：碎片歸納',
    issuePrefix: '問題 #',
    taskProgress: '{done}/{total}',
    systemTask: '系統任務',
    manualTask: '手動任務',
    collapse: '收起',
    expand: '展開',
    addTask: '新增任務',
    addFeatureGroup: '新增功能組',
    editTask: '編輯任務',
    deleteTask: '刪除任務',
    deleteFeatureGroup: '刪除功能組',
    taskTitle: '任務標題',
    featureGroupName: '功能組名稱',
    confirmDeleteTask: '確定刪除此任務？',
    confirmDeleteFeatureGroup: '確定刪除整個功能組及其所有任務？',
    taskCreated: '任務已建立',
    taskUpdated: '任務已更新',
    taskDeleted: '任務已刪除',
    featureGroupDeleted: '功能組已刪除',
    featureGroupCreated: '功能組已建立',
    memories: '記憶',
    issues: '問題',
    tags: '標籤',
    total: '共',
    items: '條',
    page: '頁',
    noMemories: '暫無記憶',
    noStatus: '暫無會話狀態',
    noIssues: '暫無問題',
    noTasks: '暫無任務',
    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: '阻塞狀態',
    normalStatus: '正常運行',
    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: '標籤（逗號分隔）',
    moreFields: '更多欄位',
    issueCreated: '問題已建立',
    issueUpdated: '問題已更新',
    issueArchived: '問題已歸檔',
    issueDeleted: '問題已刪除',
    issueDuplicated: '已存在相同標題的問題',
    relatedTo: '關聯',
    issueDescription: '問題描述',
    issueInvestigation: '排查過程',
    issueRootCause: '根本原因',
    issueSolution: '解決方案',
    issueFilesChanged: '修改檔案',
    issueTestResult: '自測結果',
    issueNotes: '注意事項',
    issueFeatureId: '關聯功能',
    issueParentId: '父問題',
    expandDetails: '展開詳情',
    collapseDetails: '收起詳情',
    filePath: '檔案路徑',
    fileDone: '已完成',
    fileNotDone: '未完成',
    catDecision: '決策記錄',
    catModification: '修改記錄',
    catPitfall: '踩坑記錄',
    catTodo: '待辦事項',
    catPreference: '偏好設定',
    searchDecision: '搜尋決策記錄...',
    searchModification: '搜尋修改記錄...',
    searchPitfall: '搜尋踩坑記錄...',
    searchTodo: '搜尋待辦事項...',
    searchPreference: '搜尋偏好設定...',
    viewAll: '查看全部',
    today: '今天',
    searchIssue: '搜尋問題...',
    search: '搜尋',
    searchTask: '搜尋任務...',
    noCategoryMemories: '暫無記錄',
    'auth.login': '登入',
    'auth.loginDesc': '登入您的 AIVectorMemory 帳戶',
    'auth.createAccount': '建立帳戶',
    'auth.createAccountDesc': '註冊新的 AIVectorMemory 帳戶',
    'auth.register': '註冊',
    'auth.username': '使用者名稱',
    'auth.password': '密碼',
    'auth.confirmPassword': '確認密碼',
    'auth.fieldsRequired': '請填寫所有欄位',
    'auth.passwordTooShort': '密碼至少 6 位',
    'auth.passwordMismatch': '兩次密碼不一致',
    'auth.noAccount': '沒有帳戶？',
    'auth.hasAccount': '已有帳戶？',
    'auth.logout': '登出',
    // --- Settings & Sidebar ---
    sectionMemory: '記憶',
    sectionSystem: '系統',
    settings: '設定',
    toggleTheme: '切換主題',
    language: '語言',
    dbStats: '資料庫統計',
    fileSize: '檔案大小',
    healthCheck: '健康檢查',
    embeddingDim: '向量維度',
    embeddingStatus: '向量狀態',
    orphanVectors: '孤立向量',
    repairOrphans: '修復孤立向量',
    repairSuccess: '修復完成',
    backup: '備份',
    createBackup: '建立備份',
    backupSuccess: '備份已建立',
    noBackups: '暫無備份',
    account: '帳戶',
    changePassword: '修改密碼',
    currentPassword: '目前密碼',
    newPassword: '新密碼',
    confirmNewPassword: '確認新密碼',
    passwordChanged: '密碼修改成功',
    passwordChangeFailed: '密碼修改失敗',
  },
  'en': {
    selectProject: 'Select Project',
    stats: 'Overview',
    projectMemories: 'Project Memories',
    globalMemories: 'Global Memories',
    sessionStatus: 'Session Status',
    tagManagement: 'Tags',
    issueTracking: 'Issues',
    taskManagement: 'Tasks',
    searchProject: 'Search project memories...',
    searchGlobal: 'Search global memories...',
    searchTag: 'Search tags...',
    status: { pending: 'Pending', in_progress: 'In Progress', completed: 'Completed', archived: 'Archived', skipped: 'Skipped' },
    allStatus: 'All Status',
    activeOnly: 'Active',
    allIncludeArchived: 'All (incl. Archived)',
    allFeatures: 'All Features',
    sysDigest: 'System: Memory Digest',
    issuePrefix: 'Issue #',
    taskProgress: '{done}/{total}',
    systemTask: 'System Task',
    manualTask: 'Manual Task',
    collapse: 'Collapse',
    expand: 'Expand',
    addTask: 'Add Task',
    addFeatureGroup: 'New Feature Group',
    editTask: 'Edit Task',
    deleteTask: 'Delete Task',
    deleteFeatureGroup: 'Delete Feature Group',
    taskTitle: 'Task Title',
    featureGroupName: 'Feature Group Name',
    confirmDeleteTask: 'Delete this task?',
    confirmDeleteFeatureGroup: 'Delete entire feature group and all its tasks?',
    taskCreated: 'Task created',
    taskUpdated: 'Task updated',
    taskDeleted: 'Task deleted',
    featureGroupDeleted: 'Feature group deleted',
    featureGroupCreated: 'Feature group created',
    memories: 'Memories',
    issues: 'Issues',
    tags: 'Tags',
    total: 'Total',
    items: 'items',
    page: 'page',
    noMemories: 'No memories yet',
    noStatus: 'No session status',
    noIssues: 'No issues yet',
    noTasks: 'No tasks 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',
    normalStatus: 'Running',
    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)',
    moreFields: 'More Fields',
    issueCreated: 'Issue created',
    issueUpdated: 'Issue updated',
    issueArchived: 'Issue archived',
    issueDeleted: 'Issue deleted',
    issueDuplicated: 'An issue with the same title already exists',
    relatedTo: 'Related to',
    issueDescription: 'Description',
    issueInvestigation: 'Investigation',
    issueRootCause: 'Root Cause',
    issueSolution: 'Solution',
    issueFilesChanged: 'Files Changed',
    issueTestResult: 'Test Result',
    issueNotes: 'Notes',
    issueFeatureId: 'Feature',
    issueParentId: 'Parent Issue',
    expandDetails: 'Expand Details',
    collapseDetails: 'Collapse Details',
    filePath: 'File Path',
    fileDone: 'Done',
    fileNotDone: 'Not Done',
    catDecision: 'Decisions',
    catModification: 'Modifications',
    catPitfall: 'Pitfalls',
    catTodo: 'Todos',
    catPreference: 'Preferences',
    searchDecision: 'Search decisions...',
    searchModification: 'Search modifications...',
    searchPitfall: 'Search pitfalls...',
    searchTodo: 'Search todos...',
    searchPreference: 'Search preferences...',
    viewAll: 'View All',
    today: 'Today',
    searchIssue: 'Search issues...',
    search: 'Search',
    searchTask: 'Search tasks...',
    noCategoryMemories: 'No records yet',
    'auth.login': 'Login',
    'auth.loginDesc': 'Sign in to your AIVectorMemory account',
    'auth.createAccount': 'Create Account',
    'auth.createAccountDesc': 'Register a new AIVectorMemory account',
    'auth.register': 'Register',
    'auth.username': 'Username',
    'auth.password': 'Password',
    'auth.confirmPassword': 'Confirm Password',
    'auth.fieldsRequired': 'All fields are required',
    'auth.passwordTooShort': 'Password must be at least 6 characters',
    'auth.passwordMismatch': 'Passwords do not match',
    'auth.noAccount': "Don't have an account?",
    'auth.hasAccount': 'Already have an account?',
    'auth.logout': 'Logout',
    // --- Settings & Sidebar ---
    sectionMemory: 'Memory',
    sectionSystem: 'System',
    settings: 'Settings',
    toggleTheme: 'Toggle Theme',
    language: 'Language',
    dbStats: 'Database Stats',
    fileSize: 'File Size',
    healthCheck: 'Health Check',
    embeddingDim: 'Embedding Dim',
    embeddingStatus: 'Embeddings',
    orphanVectors: 'Orphan Vectors',
    repairOrphans: 'Repair Orphans',
    repairSuccess: 'Repair completed',
    backup: 'Backup',
    createBackup: 'Create Backup',
    backupSuccess: 'Backup created',
    noBackups: 'No backups yet',
    account: 'Account',
    changePassword: 'Change Password',
    currentPassword: 'Current Password',
    newPassword: 'New Password',
    confirmNewPassword: 'Confirm New Password',
    passwordChanged: 'Password changed successfully',
    passwordChangeFailed: 'Password change failed',
  },
  'es': {
    selectProject: 'Seleccionar Proyecto',
    stats: 'Resumen',
    projectMemories: 'Memorias del Proyecto',
    globalMemories: 'Memorias Globales',
    sessionStatus: 'Estado de Sesión',
    tagManagement: 'Etiquetas',
    issueTracking: 'Problemas',
    taskManagement: 'Tareas',
    searchProject: 'Buscar memorias del proyecto...',
    searchGlobal: 'Buscar memorias globales...',
    searchTag: 'Buscar etiquetas...',
    status: { pending: 'Pendiente', in_progress: 'En Progreso', completed: 'Completado', archived: 'Archivado', skipped: 'Omitido' },
    allStatus: 'Todos los Estados',
    activeOnly: 'Activos',
    allIncludeArchived: 'Todos (incl. Archivados)',
    allFeatures: 'Todas las Funciones',
    sysDigest: 'Sistema: Resumen de Memorias',
    issuePrefix: 'Problema #',
    taskProgress: '{done}/{total}',
    systemTask: 'Tarea del Sistema',
    manualTask: 'Tarea Manual',
    collapse: 'Contraer',
    expand: 'Expandir',
    addTask: 'Agregar Tarea',
    addFeatureGroup: 'Nuevo Grupo de Funciones',
    editTask: 'Editar Tarea',
    deleteTask: 'Eliminar Tarea',
    deleteFeatureGroup: 'Eliminar Grupo de Funciones',
    taskTitle: 'Título de Tarea',
    featureGroupName: 'Nombre del Grupo',
    confirmDeleteTask: '¿Eliminar esta tarea?',
    confirmDeleteFeatureGroup: '¿Eliminar todo el grupo de funciones y todas sus tareas?',
    taskCreated: 'Tarea creada',
    taskUpdated: 'Tarea actualizada',
    taskDeleted: 'Tarea eliminada',
    featureGroupDeleted: 'Grupo de funciones eliminado',
    featureGroupCreated: 'Grupo de funciones creado',
    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',
    noTasks: 'Sin tareas',
    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',
    normalStatus: 'En Ejecución',
    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)',
    moreFields: 'Más Campos',
    issueCreated: 'Problema creado',
    issueUpdated: 'Problema actualizado',
    issueArchived: 'Problema archivado',
    issueDeleted: 'Problema eliminado',
    issueDuplicated: 'Ya existe un problema con el mismo título',
    relatedTo: 'Relacionado con',
    issueDescription: 'Descripción',
    issueInvestigation: 'Investigación',
    issueRootCause: 'Causa Raíz',
    issueSolution: 'Solución',
    issueFilesChanged: 'Archivos Modificados',
    issueTestResult: 'Resultado de Prueba',
    issueNotes: 'Notas',
    issueFeatureId: 'Funcionalidad',
    issueParentId: 'Problema Padre',
    expandDetails: 'Expandir Detalles',
    collapseDetails: 'Contraer Detalles',
    filePath: 'Ruta del Archivo',
    fileDone: 'Completado',
    fileNotDone: 'Pendiente',
    catDecision: 'Decisiones',
    catModification: 'Modificaciones',
    catPitfall: 'Problemas',
    catTodo: 'Pendientes',
    catPreference: 'Preferencias',
    searchDecision: 'Buscar decisiones...',
    searchModification: 'Buscar modificaciones...',
    searchPitfall: 'Buscar problemas...',
    searchTodo: 'Buscar pendientes...',
    searchPreference: 'Buscar preferencias...',
    viewAll: 'Ver Todo',
    today: 'Hoy',
    searchIssue: 'Buscar problemas...',
    search: 'Buscar',
    searchTask: 'Buscar tareas...',
    noCategoryMemories: 'Sin registros',
    'auth.login': 'Iniciar Sesion',
    'auth.loginDesc': 'Inicie sesion en su cuenta AIVectorMemory',
    'auth.createAccount': 'Crear Cuenta',
    'auth.createAccountDesc': 'Registrar una nueva cuenta AIVectorMemory',
    'auth.register': 'Registrarse',
    'auth.username': 'Nombre de usuario',
    'auth.password': 'Contrasena',
    'auth.confirmPassword': 'Confirmar Contrasena',
    'auth.fieldsRequired': 'Todos los campos son obligatorios',
    'auth.passwordTooShort': 'La contrasena debe tener al menos 6 caracteres',
    'auth.passwordMismatch': 'Las contrasenas no coinciden',
    'auth.noAccount': 'No tiene cuenta?',
    'auth.hasAccount': 'Ya tiene cuenta?',
    'auth.logout': 'Cerrar Sesion',
    // --- Settings & Sidebar ---
    sectionMemory: 'Memoria',
    sectionSystem: 'Sistema',
    settings: 'Configuración',
    toggleTheme: 'Cambiar Tema',
    language: 'Idioma',
    dbStats: 'Estadísticas de BD',
    fileSize: 'Tamaño',
    healthCheck: 'Verificación',
    embeddingDim: 'Dim. Embedding',
    embeddingStatus: 'Embeddings',
    orphanVectors: 'Vectores Huérfanos',
    repairOrphans: 'Reparar Huérfanos',
    repairSuccess: 'Reparación completada',
    backup: 'Respaldo',
    createBackup: 'Crear Respaldo',
    backupSuccess: 'Respaldo creado',
    noBackups: 'Sin respaldos',
    account: 'Cuenta',
    changePassword: 'Cambiar Contraseña',
    currentPassword: 'Contraseña Actual',
    newPassword: 'Nueva Contraseña',
    confirmNewPassword: 'Confirmar Nueva Contraseña',
    passwordChanged: 'Contraseña cambiada',
    passwordChangeFailed: 'Error al cambiar contraseña',
  },
  'de': {
    selectProject: 'Projekt Auswählen',
    stats: 'Übersicht',
    projectMemories: 'Projekt-Erinnerungen',
    globalMemories: 'Globale Erinnerungen',
    sessionStatus: 'Sitzungsstatus',
    tagManagement: 'Tags',
    issueTracking: 'Probleme',
    taskManagement: 'Aufgaben',
    searchProject: 'Projekt-Erinnerungen suchen...',
    searchGlobal: 'Globale Erinnerungen suchen...',
    searchTag: 'Tags suchen...',
    status: { pending: 'Ausstehend', in_progress: 'In Bearbeitung', completed: 'Abgeschlossen', archived: 'Archiviert', skipped: 'Übersprungen' },
    allStatus: 'Alle Status',
    activeOnly: 'Aktiv',
    allIncludeArchived: 'Alle (inkl. Archiviert)',
    allFeatures: 'Alle Funktionen',
    sysDigest: 'System: Erinnerungszusammenfassung',
    issuePrefix: 'Problem #',
    taskProgress: '{done}/{total}',
    systemTask: 'Systemaufgabe',
    manualTask: 'Manuelle Aufgabe',
    collapse: 'Einklappen',
    expand: 'Ausklappen',
    addTask: 'Aufgabe Hinzufügen',
    addFeatureGroup: 'Neue Funktionsgruppe',
    editTask: 'Aufgabe Bearbeiten',
    deleteTask: 'Aufgabe Löschen',
    deleteFeatureGroup: 'Funktionsgruppe Löschen',
    taskTitle: 'Aufgabentitel',
    featureGroupName: 'Gruppenname',
    confirmDeleteTask: 'Diese Aufgabe löschen?',
    confirmDeleteFeatureGroup: 'Gesamte Funktionsgruppe und alle Aufgaben löschen?',
    taskCreated: 'Aufgabe erstellt',
    taskUpdated: 'Aufgabe aktualisiert',
    taskDeleted: 'Aufgabe gelöscht',
    featureGroupDeleted: 'Funktionsgruppe gelöscht',
    featureGroupCreated: 'Funktionsgruppe erstellt',
    memories: 'Erinnerungen',
    issues: 'Probleme',
    tags: 'Tags',
    total: 'Gesamt',
    items: 'Einträge',
    page: 'Seite',
    noMemories: 'Keine Erinnerungen',
    noStatus: 'Kein Sitzungsstatus',
    noIssues: 'Keine Probleme',
    noTasks: 'Keine Aufgaben',
    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',
    normalStatus: 'Läuft Normal',
    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)',
    moreFields: 'Weitere Felder',
    issueCreated: 'Problem erstellt',
    issueUpdated: 'Problem aktualisiert',
    issueArchived: 'Problem archiviert',
    issueDeleted: 'Problem gelöscht',
    issueDuplicated: 'Ein Problem mit demselben Titel existiert bereits',
    relatedTo: 'Bezogen auf',
    issueDescription: 'Beschreibung',
    issueInvestigation: 'Untersuchung',
    issueRootCause: 'Grundursache',
    issueSolution: 'Lösung',
    issueFilesChanged: 'Geänderte Dateien',
    issueTestResult: 'Testergebnis',
    issueNotes: 'Hinweise',
    issueFeatureId: 'Funktion',
    issueParentId: 'Übergeordnetes Problem',
    expandDetails: 'Details Erweitern',
    collapseDetails: 'Details Zuklappen',
    filePath: 'Dateipfad',
    fileDone: 'Erledigt',
    fileNotDone: 'Ausstehend',
    catDecision: 'Entscheidungen',
    catModification: 'Änderungen',
    catPitfall: 'Stolperfallen',
    catTodo: 'Aufgaben',
    catPreference: 'Einstellungen',
    searchDecision: 'Entscheidungen suchen...',
    searchModification: 'Änderungen suchen...',
    searchPitfall: 'Stolperfallen suchen...',
    searchTodo: 'Aufgaben suchen...',
    searchPreference: 'Einstellungen suchen...',
    viewAll: 'Alle Anzeigen',
    today: 'Heute',
    searchIssue: 'Probleme suchen...',
    search: 'Suchen',
    searchTask: 'Aufgaben suchen...',
    noCategoryMemories: 'Keine Einträge',
    'auth.login': 'Anmelden',
    'auth.loginDesc': 'Melden Sie sich bei Ihrem AIVectorMemory-Konto an',
    'auth.createAccount': 'Konto erstellen',
    'auth.createAccountDesc': 'Neues AIVectorMemory-Konto registrieren',
    'auth.register': 'Registrieren',
    'auth.username': 'Benutzername',
    'auth.password': 'Passwort',
    'auth.confirmPassword': 'Passwort bestatigen',
    'auth.fieldsRequired': 'Alle Felder sind erforderlich',
    'auth.passwordTooShort': 'Passwort muss mindestens 6 Zeichen haben',
    'auth.passwordMismatch': 'Passworter stimmen nicht uberein',
    'auth.noAccount': 'Kein Konto?',
    'auth.hasAccount': 'Bereits ein Konto?',
    'auth.logout': 'Abmelden',
    // --- Settings & Sidebar ---
    sectionMemory: 'Erinnerung',
    sectionSystem: 'System',
    settings: 'Einstellungen',
    toggleTheme: 'Design wechseln',
    language: 'Sprache',
    dbStats: 'Datenbankstatistik',
    fileSize: 'Dateigröße',
    healthCheck: 'Gesundheitscheck',
    embeddingDim: 'Embedding-Dim',
    embeddingStatus: 'Embeddings',
    orphanVectors: 'Verwaiste Vektoren',
    repairOrphans: 'Verwaiste reparieren',
    repairSuccess: 'Reparatur abgeschlossen',
    backup: 'Sicherung',
    createBackup: 'Sicherung erstellen',
    backupSuccess: 'Sicherung erstellt',
    noBackups: 'Keine Sicherungen',
    account: 'Konto',
    changePassword: 'Passwort ändern',
    currentPassword: 'Aktuelles Passwort',
    newPassword: 'Neues Passwort',
    confirmNewPassword: 'Neues Passwort bestätigen',
    passwordChanged: 'Passwort geändert',
    passwordChangeFailed: 'Passwortänderung fehlgeschlagen',
  },
  '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',
    taskManagement: 'Tâches',
    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é', skipped: 'Ignoré' },
    allStatus: 'Tous les Statuts',
    activeOnly: 'Actifs',
    allIncludeArchived: 'Tous (incl. Archivés)',
    allFeatures: 'Toutes les Fonctions',
    sysDigest: 'Système : Résumé des Mémoires',
    issuePrefix: 'Problème #',
    taskProgress: '{done}/{total}',
    systemTask: 'Tâche Système',
    manualTask: 'Tâche Manuelle',
    collapse: 'Réduire',
    expand: 'Développer',
    addTask: 'Ajouter une Tâche',
    addFeatureGroup: 'Nouveau Groupe de Fonctions',
    editTask: 'Modifier la Tâche',
    deleteTask: 'Supprimer la Tâche',
    deleteFeatureGroup: 'Supprimer le Groupe de Fonctions',
    taskTitle: 'Titre de la Tâche',
    featureGroupName: 'Nom du Groupe',
    confirmDeleteTask: 'Supprimer cette tâche ?',
    confirmDeleteFeatureGroup: 'Supprimer tout le groupe de fonctions et toutes ses tâches ?',
    taskCreated: 'Tâche créée',
    taskUpdated: 'Tâche mise à jour',
    taskDeleted: 'Tâche supprimée',
    featureGroupDeleted: 'Groupe de fonctions supprimé',
    featureGroupCreated: 'Groupe de fonctions créé',
    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',
    noTasks: 'Aucune tâche',
    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é',
    normalStatus: 'En Cours',
    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)',
    moreFields: 'Plus de Champs',
    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à',
    relatedTo: 'Lié à',
    issueDescription: 'Description',
    issueInvestigation: 'Investigation',
    issueRootCause: 'Cause Racine',
    issueSolution: 'Solution',
    issueFilesChanged: 'Fichiers Modifiés',
    issueTestResult: 'Résultat du Test',
    issueNotes: 'Notes',
    issueFeatureId: 'Fonctionnalité',
    issueParentId: 'Problème Parent',
    expandDetails: 'Développer les Détails',
    collapseDetails: 'Réduire les Détails',
    filePath: 'Chemin du Fichier',
    fileDone: 'Terminé',
    fileNotDone: 'En Attente',
    catDecision: 'Décisions',
    catModification: 'Modifications',
    catPitfall: 'Pièges',
    catTodo: 'À faire',
    catPreference: 'Préférences',
    searchDecision: 'Rechercher décisions...',
    searchModification: 'Rechercher modifications...',
    searchPitfall: 'Rechercher pièges...',
    searchTodo: 'Rechercher à faire...',
    searchPreference: 'Rechercher préférences...',
    viewAll: 'Tout Afficher',
    today: "Aujourd'hui",
    searchIssue: 'Rechercher problèmes...',
    search: 'Rechercher',
    searchTask: 'Rechercher tâches...',
    noCategoryMemories: 'Aucun enregistrement',
    'auth.login': 'Connexion',
    'auth.loginDesc': 'Connectez-vous a votre compte AIVectorMemory',
    'auth.createAccount': 'Creer un Compte',
    'auth.createAccountDesc': 'Enregistrer un nouveau compte AIVectorMemory',
    'auth.register': "S'inscrire",
    'auth.username': "Nom d'utilisateur",
    'auth.password': 'Mot de passe',
    'auth.confirmPassword': 'Confirmer le Mot de passe',
    'auth.fieldsRequired': 'Tous les champs sont requis',
    'auth.passwordTooShort': 'Le mot de passe doit avoir au moins 6 caracteres',
    'auth.passwordMismatch': 'Les mots de passe ne correspondent pas',
    'auth.noAccount': 'Pas de compte ?',
    'auth.hasAccount': 'Deja un compte ?',
    'auth.logout': 'Deconnexion',
    // --- Settings & Sidebar ---
    sectionMemory: 'Mémoire',
    sectionSystem: 'Système',
    settings: 'Paramètres',
    toggleTheme: 'Changer le thème',
    language: 'Langue',
    dbStats: 'Statistiques BD',
    fileSize: 'Taille',
    healthCheck: 'Vérification',
    embeddingDim: 'Dim. Embedding',
    embeddingStatus: 'Embeddings',
    orphanVectors: 'Vecteurs orphelins',
    repairOrphans: 'Réparer orphelins',
    repairSuccess: 'Réparation terminée',
    backup: 'Sauvegarde',
    createBackup: 'Créer sauvegarde',
    backupSuccess: 'Sauvegarde créée',
    noBackups: 'Aucune sauvegarde',
    account: 'Compte',
    changePassword: 'Changer le mot de passe',
    currentPassword: 'Mot de passe actuel',
    newPassword: 'Nouveau mot de passe',
    confirmNewPassword: 'Confirmer le nouveau mot de passe',
    passwordChanged: 'Mot de passe modifié',
    passwordChangeFailed: 'Échec du changement de mot de passe',
  },
  'ja': {
    selectProject: 'プロジェクト選択',
    stats: '統計概要',
    projectMemories: 'プロジェクト記憶',
    globalMemories: 'グローバル記憶',
    sessionStatus: 'セッション状態',
    tagManagement: 'タグ管理',
    issueTracking: '問題追跡',
    taskManagement: 'タスク管理',
    searchProject: 'プロジェクト記憶を検索...',
    searchGlobal: 'グローバル記憶を検索...',
    searchTag: 'タグを検索...',
    status: { pending: '未処理', in_progress: '進行中', completed: '完了', archived: 'アーカイブ済', skipped: 'スキップ' },
    allStatus: 'すべてのステータス',
    activeOnly: 'アクティブ',
    allIncludeArchived: 'すべて（アーカイブ含む）',
    allFeatures: 'すべての機能',
    sysDigest: 'システム：記憶の要約',
    issuePrefix: '問題 #',
    taskProgress: '{done}/{total}',
    systemTask: 'システムタスク',
    manualTask: '手動タスク',
    collapse: '折りたたむ',
    expand: '展開する',
    addTask: 'タスク追加',
    addFeatureGroup: '新規機能グループ',
    editTask: 'タスク編集',
    deleteTask: 'タスク削除',
    deleteFeatureGroup: '機能グループ削除',
    taskTitle: 'タスクタイトル',
    featureGroupName: 'グループ名',
    confirmDeleteTask: 'このタスクを削除しますか？',
    confirmDeleteFeatureGroup: '機能グループとすべてのタスクを削除しますか？',
    taskCreated: 'タスクを作成しました',
    taskUpdated: 'タスクを更新しました',
    taskDeleted: 'タスクを削除しました',
    featureGroupDeleted: '機能グループを削除しました',
    featureGroupCreated: '機能グループを作成しました',
    memories: '記憶',
    issues: '問題',
    tags: 'タグ',
    total: '合計',
    items: '件',
    page: 'ページ',
    noMemories: '記憶がありません',
    noStatus: 'セッション状態がありません',
    noIssues: '問題がありません',
    noTasks: 'タスクがありません',
    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: 'ブロック状態',
    normalStatus: '正常稼働',
    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: 'タグ（カンマ区切り）',
    moreFields: 'その他のフィールド',
    issueCreated: '問題を作成しました',
    issueUpdated: '問題を更新しました',
    issueArchived: '問題をアーカイブしました',
    issueDeleted: '問題を削除しました',
    issueDuplicated: '同じタイトルの問題が既に存在します',
    relatedTo: '関連',
    issueDescription: '問題の説明',
    issueInvestigation: '調査過程',
    issueRootCause: '根本原因',
    issueSolution: '解決策',
    issueFilesChanged: '変更ファイル',
    issueTestResult: 'テスト結果',
    issueNotes: '注意事項',
    issueFeatureId: '関連機能',
    issueParentId: '親問題',
    expandDetails: '詳細を展開',
    collapseDetails: '詳細を折りたたむ',
    filePath: 'ファイルパス',
    fileDone: '完了',
    fileNotDone: '未完了',
    catDecision: '意思決定',
    catModification: '変更記録',
    catPitfall: '落とし穴',
    catTodo: 'やること',
    catPreference: '設定',
    searchDecision: '意思決定を検索...',
    searchModification: '変更記録を検索...',
    searchPitfall: '落とし穴を検索...',
    searchTodo: 'やることを検索...',
    searchPreference: '設定を検索...',
    viewAll: 'すべて表示',
    today: '今日',
    searchIssue: '問題を検索...',
    search: '検索',
    searchTask: 'タスクを検索...',
    noCategoryMemories: '記録がありません',
    'auth.login': 'ログイン',
    'auth.loginDesc': 'AIVectorMemory アカウントにログイン',
    'auth.createAccount': 'アカウント作成',
    'auth.createAccountDesc': '新しい AIVectorMemory アカウントを登録',
    'auth.register': '登録',
    'auth.username': 'ユーザー名',
    'auth.password': 'パスワード',
    'auth.confirmPassword': 'パスワード確認',
    'auth.fieldsRequired': 'すべての項目を入力してください',
    'auth.passwordTooShort': 'パスワードは6文字以上',
    'auth.passwordMismatch': 'パスワードが一致しません',
    'auth.noAccount': 'アカウントをお持ちでない方',
    'auth.hasAccount': 'アカウントをお持ちの方',
    'auth.logout': 'ログアウト',
    // --- Settings & Sidebar ---
    sectionMemory: 'メモリ',
    sectionSystem: 'システム',
    settings: '設定',
    toggleTheme: 'テーマ切替',
    language: '言語',
    dbStats: 'データベース統計',
    fileSize: 'ファイルサイズ',
    healthCheck: 'ヘルスチェック',
    embeddingDim: '埋め込み次元',
    embeddingStatus: '埋め込み状態',
    orphanVectors: '孤立ベクトル',
    repairOrphans: '孤立修復',
    repairSuccess: '修復完了',
    backup: 'バックアップ',
    createBackup: 'バックアップ作成',
    backupSuccess: 'バックアップ作成完了',
    noBackups: 'バックアップなし',
    account: 'アカウント',
    changePassword: 'パスワード変更',
    currentPassword: '現在のパスワード',
    newPassword: '新しいパスワード',
    confirmNewPassword: '新しいパスワード（確認）',
    passwordChanged: 'パスワードを変更しました',
    passwordChangeFailed: 'パスワードの変更に失敗しました',
  },
};

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

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

function setLang(lang, syncToServer = false) {
  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);
  if (syncToServer) {
    fetch('/api/settings/language', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ language: lang }),
    }).catch(() => {});
  }
}

function initLangFromServer() {
  fetch('/api/settings/language').then(r => r.json()).then(data => {
    if (data.language && messages[data.language] && data.language !== currentLang) {
      setLang(data.language);
    }
  }).catch(() => {});
}

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, true);
    if (typeof window._reloadCurrentView === 'function') window._reloadCurrentView();
  });
}