// Central UI i18n layer. Keep keys stable so new locales can be added without touching page logic.

const GGG_I18N_STORAGE_KEY = "ggg.ui.language";

const GGG_I18N_LOCALES = [
  { id: "zh", label: "中文", fullLabel: "中文", htmlLang: "zh-CN" },
  { id: "en", label: "EN", fullLabel: "English", htmlLang: "en" },
];

const GGG_I18N = {
  zh: {
    "app.title": "好出海 Good Go Global - AI 出海市场调研与决策平台",
    "language.current": "中文",
    "language.switch": "切换语言",
    "nav.main": "主要功能",
    "nav.dashboard": "总览",
    "nav.projects": "项目",
    "nav.files": "资料解析",
    "nav.reports": "报告",
    "nav.special": "专项报告",
    "nav.expert": "专家确认",
    "nav.resources": "资源",
    "nav.dataRoom": "资料库",
    "nav.billing": "订阅与计费",
    "nav.settings": "设置",
    "nav.newProject": "新建项目",
    "nav.search": "搜索项目 / 报告 / 文件...",
    "settings.nav.language": "语言",
    "settings.nav.report": "报告",
    "settings.language.title": "语言",
    "settings.language.subtitle": "影响界面显示语言。",
    "settings.report.title": "报告",
    "settings.report.subtitle": "影响默认报告生成语言和报告深度。",
    "settings.saveLanguage": "保存语言",
    "settings.saveReport": "保存报告偏好",
    "brand.loading": "正在加载 好出海...",
    "status.processing": "处理中",
    "status.needsAction": "需要处理",
    "status.system": "系统状态",
    "status.worker": "Worker 在线",
    "status.connected": "已连接",
    "status.disconnected": "未连接",
    "status.configured": "已配置",
    "status.notConfigured": "待配置",
    Product: "产品",
    Files: "文件",
    Market: "市场",
    "Customer & Channel": "客群与渠道",
    Resources: "资源",
    Goals: "目标",
    "AI Follow-up": "AI 追问",
    Review: "确认",
    Ready: "已就绪",
    Draft: "草稿",
    "Need Review": "待复核",
    "Needs input": "待补充",
    Overview: "总览",
    Projects: "项目",
    "Data Room": "资料解析",
    Reports: "报告",
    "Special Reports": "专项报告",
    "Expert Review": "专家确认",
    Billing: "订阅与计费",
    Settings: "设置",
    Main: "主要功能",
    Resources: "资源",
    "New Project": "新建项目",
    "Search projects, reports, files...": "搜索项目 / 报告 / 文件...",
    High: "高",
    Medium: "中",
    Low: "低",
    English: "英文",
    "Market Entry Research Report": "市场进入调研报告",
    "AI Assistant": "AI 助手",
    "Risk levels": "风险等级",
    "Recommendation": "建议",
    "Current Plan": "当前订阅",
  },
  en: {
    "app.title": "Good Go Global - AI Market Entry Research Platform",
    "language.current": "English",
    "language.switch": "Switch language",
    "nav.main": "Main",
    "nav.dashboard": "Overview",
    "nav.projects": "Projects",
    "nav.files": "Data Room",
    "nav.reports": "Reports",
    "nav.special": "Special Reports",
    "nav.expert": "Expert Review",
    "nav.resources": "Resources",
    "nav.dataRoom": "Data Room",
    "nav.billing": "Billing",
    "nav.settings": "Settings",
    "nav.newProject": "New Project",
    "nav.search": "Search projects, reports, files...",
    "settings.nav.language": "Language",
    "settings.nav.report": "Report",
    "settings.language.title": "Language",
    "settings.language.subtitle": "Controls the UI display language.",
    "settings.report.title": "Report",
    "settings.report.subtitle": "Controls the default report language and report depth.",
    "settings.saveLanguage": "Save Language",
    "settings.saveReport": "Save Report",
    "brand.loading": "Loading Good Go Global...",
    "status.processing": "Processing",
    "status.needsAction": "Needs Action",
    "status.system": "System Status",
    "status.worker": "Worker online",
    "status.connected": "connected",
    "status.disconnected": "disconnected",
    "status.configured": "configured",
    "status.notConfigured": "not configured",

    "产品": "Product",
    "中文": "Chinese",
    "英文": "English",
    "法文": "French",
    "专项报告": "Special Reports",
    "专项报告中心": "Special Reports Center",
    "价格": "Pricing",
    "样例报告": "Sample Report",
    "关于": "About",
    "登录": "Sign in",
    "注册": "Register",
    "免费开始": "Get started",
    "返回首页": "Back home",
    "服务条款": "Terms of Service",
    "隐私政策": "Privacy Policy",
    "继续即表示同意": "By continuing, you agree to the",
    "欢迎回来": "Welcome back",
    "使用已验证邮箱继续您的出海调研项目": "Continue your expansion projects with a verified email.",
    "邮箱": "Email",
    "密码": "Password",
    "忘记密码？": "Forgot password?",
    "至少 8 位，含字母和数字": "At least 8 characters with letters and numbers",
    "邮箱尚未验证": "Email not verified",
    "请打开验证邮件中的链接。没有收到时，可重新发送。": "Open the verification link in your email. If you did not receive it, send it again.",
    "重发": "Resend",
    "30 天内保持登录": "Keep me signed in for 30 days",
    "还没有账号？": "No account yet?",
    "免费注册": "Create a free account",
    "创建账户": "Create account",
    "先完成邮箱验证，再进入真实公司资料流程": "Verify your email before entering the real company profile flow.",
    "您的姓名": "Your name",
    "联系人姓名": "Contact name",
    "设置密码": "Create password",
    "确认密码": "Confirm password",
    "再次输入密码": "Enter password again",
    "我已阅读并同意服务条款和隐私政策，理解 AI 报告不构成法律、税务、移民、投资或专业报关意见。": "I agree to the Terms of Service and Privacy Policy, and understand that AI reports are not legal, tax, immigration, investment or customs advice.",
    "已经有账号？": "Already have an account?",
    "立即登录": "Sign in",
    "请验证邮箱": "Verify your email",
    "打开邮箱": "Open your inbox",
    "点击验证链接": "Click the verification link",
    "首次登录后补全公司资料": "Complete company details after first login",
    "返回登录": "Back to sign in",
    "重新发送验证邮件": "Resend verification email",
    "找回密码": "Reset password",
    "密码重置邮件能力将接入同一套 Resend 邮件服务。当前请联系管理员处理密码重置。": "Password reset email will use the same Resend service. Contact an administrator for password reset in this version.",
    "当前版本不发送模拟重置邮件。": "This version does not send mock reset emails.",
    "请输入有效邮箱地址。": "Enter a valid email address.",
    "请输入可接收验证邮件的真实邮箱域名。": "Use a real email domain that can receive verification mail.",
    "密码至少需要 8 位。": "Password must be at least 8 characters.",
    "密码需要同时包含字母和数字。": "Password must include both letters and numbers.",
    "两次输入的密码不一致。": "Passwords do not match.",
    "请先同意服务条款和隐私政策。": "Agree to the Terms of Service and Privacy Policy first.",
    "登录失败，请检查邮箱和密码。": "Sign-in failed. Check your email and password.",
    "注册失败，请稍后重试。": "Registration failed. Try again later.",
    "验证邮件发送失败。": "Failed to send verification email.",
    "请先登录。": "Please sign in first.",
    "D1 数据已加载": "D1 data loaded",
    "正在从 D1 加载工作台数据...": "Loading workspace data from D1...",
    "正在登录...": "Signing in...",
    "登录成功": "Signed in",
    "正在创建账户并发送邮箱验证...": "Creating account and sending verification email...",
    "验证邮件已发送": "Verification email sent",
    "正在重新发送验证邮件...": "Resending verification email...",
    "验证邮件已重新发送": "Verification email resent",
    "正在保存公司信息...": "Saving company information...",
    "公司信息已保存": "Company information saved",
    "正在保存账户资料...": "Saving account profile...",
    "账户资料已保存": "Account profile saved",
    "正在保存企业资料...": "Saving company profile...",
    "企业资料已保存": "Company profile saved",
    "正在保存语言与报告偏好...": "Saving language and report preferences...",
    "语言与报告偏好已保存": "Language and report preferences saved",
    "正在上传头像...": "Uploading avatar...",
    "头像已保存": "Avatar saved",
    "正在上传资料...": "Uploading files...",
    "资料已保存": "Files saved",
    "正在使用 OpenAI 推荐阶段目标...": "Using OpenAI to recommend stage goals...",
    "AI 目标建议已生成": "AI goal recommendations generated",
    "正在基于本节报告内容回答...": "Answering from this report section...",
    "AI 助手已回答": "AI assistant answered",
    "请先创建真实项目，再上传资料。": "Create a real project before uploading files.",
    "请先创建真实项目，再生成报告。": "Create a real project before generating a report.",
    "正在生成报告：AI 将调用 MCP 资料搜集与真实来源校验...": "Generating report: AI will call MCP research and real-source verification...",
    "报告已生成，可下载 PDF / DOCX / Markdown": "Report generated. PDF / DOCX / Markdown are available.",
    "当前账号暂无报告，请先基于真实项目生成报告。": "No report exists for this account. Generate one from a real project first.",
    "准备下载": "Preparing download",
    "下载已开始": "download started",
    "正在创建订阅会话": "Creating subscription session",
    "支付会话已创建": "payment session created",
    "订阅会话已创建": "subscription session created",
    "已退出登录": "Signed out",
    "邮箱验证服务尚未配置，无法创建新账号。": "Email verification is not configured, so new accounts cannot be created.",
    "该邮箱已注册。": "This email is already registered.",
    "该邮箱已注册，请直接登录。": "This email is already registered. Sign in instead.",
    "请先完成邮箱验证后再登录。": "Verify your email before signing in.",
    "邮箱验证服务尚未配置。": "Email verification is not configured.",
    "邮箱已验证，请直接登录。": "Email is already verified. Sign in directly.",
    "验证邮件已重新发送，请检查邮箱。": "Verification email resent. Check your inbox.",
    "验证邮件已发送，请前往邮箱完成验证。": "Verification email sent. Check your inbox to complete verification.",

    "首次设置": "First-time setup",
    "公司信息详情": "Company Details",
    "切换账号": "Switch account",
    "已完成邮箱验证": "Email verified",
    "用真实企业资料建立出海工作台": "Build your workspace with real company information",
    "这些信息会用于企业画像、项目建议、报告上下文和订阅工作区，不会填入任何演示数据。": "This information powers your company profile, project suggestions, report context and billing workspace. No demo data will be inserted.",
    "企业身份": "Company identity",
    "主营品类": "Main category",
    "出海经验": "Export experience",
    "正在加载...": "Loading...",
    "请补全公司信息": "Complete company information",
    "带 * 的字段为首次进入后台前必填项。": "Fields marked with * are required before entering the dashboard.",
    "联系人姓名 *": "Contact name *",
    "职务 *": "Role *",
    "公司名称 *": "Company name *",
    "公司英文名": "Company English name",
    "所在城市 *": "City *",
    "国家 / 地区 *": "Country / Region *",
    "主营品类 *": "Main category *",
    "目标市场": "Target markets",
    "联系电话": "Phone",
    "官网": "Website",
    "员工规模": "Employee count",
    "年营收区间": "Annual revenue range",
    "请选择": "Select",
    "尚未出口": "No export experience",
    "已有 OEM / 外贸订单": "OEM / export orders",
    "已做跨境电商": "Cross-border ecommerce",
    "已有海外经销或本地团队": "Overseas distributor or local team",
    "公司简介 *": "Company profile *",
    "请简要说明主营产品、生产/供应能力、已有客户或渠道、希望解决的出海问题。": "Briefly describe products, production/supply capacity, existing customers/channels, and expansion questions.",
    "保存并进入工作台": "Save and enter workspace",
    "公司信息加载失败。": "Failed to load company information.",
    "请补全所有必填字段。": "Complete all required fields.",
    "公司信息保存失败。": "Failed to save company information.",
    "例：创始人 / 外贸负责人": "Example: Founder / Export Lead",
    "例：深圳": "Example: Shenzhen",
    "例：成衣、家居用品、电子配件": "Example: apparel, homewares, electronics accessories",
    "例：50-100 人": "Example: 50-100 people",
    "例：1000万-5000万人民币": "Example: RMB 10M-50M",

    "项目总览": "Overview",
    "项目": "Projects",
    "出海项目": "Expansion Project",
    "早上好，": "Good morning, ",
    "好出海用户": "Good Go Global user",
    "正在从 D1 加载项目数据...": "Loading workspace data from D1...",
    "筛选": "Filter",
    "创建新项目": "Create project",
    "我的项目": "My Projects",
    "· 共": "·",
    "个": "total",
    "全部": "All",
    "进行中": "In Progress",
    "已完成": "Completed",
    "草稿": "Draft",
    "还没有真实出海项目": "No real expansion project yet",
    "从一个真实产品、目标国家和渠道假设开始。系统会基于您上传的资料和 MCP 采集的真实来源生成报告。": "Start with a real product, target country and channel hypothesis. Reports will be generated from your uploaded files and MCP-collected real sources.",
    "创建项目": "Create Project",
    "完成度": "Progress",
    "下一步推荐": "Recommended Next Steps",
    "暂无下一步事项。": "No next actions.",
    "最近活动": "Recent Activity",
    "暂无账号活动。": "No account activity yet.",
    "本月报告额度": "Monthly report quota",
    "升级到 Business 计划": "Upgrade to Business",
    "欢迎进入 Good Go Global 工作台": "Welcome to the Good Go Global workspace",
    "这里不会预置演示数据。请从真实产品和目标市场创建第一个项目。": "No demo data is preloaded here. Create your first project from a real product and market.",
    "资料先行": "Files first",
    "上传报价单、SKU、认证、包装标签，报告会更准确。": "Upload quotations, SKUs, certifications and packaging labels for better reports.",
    "知道了": "Got it",
    "真实项目": "Real Projects",
    "尚未创建项目": "No projects yet",
    "资料文件": "Files",
    "等待上传真实资料": "Waiting for real files",
    "已生成报告": "Reports Generated",
    "完成项目资料后生成": "Generate after completing project files",
    "需专家确认": "Expert Review",
    "暂无待确认事项": "No review items",
    "创建第一个出海项目": "Create your first expansion project",
    "填写真实产品、目标市场和渠道计划": "Add real product, target market and channel plan",
    "创建": "Create",
    "用户登录": "User signed in",
    "公司信息已更新": "Company information updated",

    "资料解析": "Data Room",
    "产品目录、报价单、认证文件和图片都从 D1 项目文件表读取，后续可接 R2 存储原件。": "Product catalogs, quotations, certifications and images are read from the D1 project files table. R2 can be added for original file storage.",
    "上传资料": "Upload files",
    "拖入文件，或点击浏览": "Drop files here, or click to browse",
    "拖入文件，或": "Drop files here, or",
    "点击浏览": "click to browse",
    "支持 .docx · .pdf · .xlsx · .csv · .jpg · .png · .webp · 单文件最大 50MB": "Supports .docx · .pdf · .xlsx · .csv · .jpg · .png · .webp · max 50MB per file",
    "已上传资料": "Uploaded Files",
    "个文件": "file(s)",
    "AI 已提取关键信息": "AI Extracted Key Information",
    "15 个 SKU · 3 个规格层级 · 平均出厂价 ¥18.50 · 已识别 FDA、SGS 认证 · 缺失：包装尺寸、装柜数。": "15 SKUs · 3 spec tiers · avg. factory price RMB 18.50 · FDA and SGS detected · missing: package dimensions and container loading.",

    "专项报告中心": "Special Reports",
    "主报告就绪后，可继续生成细分方向的深度报告。模板和已生成版本来自 D1。": "After the main report is ready, generate deep-dive reports for specific topics. Templates and generated versions come from D1.",
    "筛选类型": "Filter Types",
    "已生成": "Generated",
    "已生成 (": "Generated (",
    "可生成": "Available",
    "可生成 (": "Available (",
    "草稿": "Draft",
    "基于当前项目上下文生成的专项报告。": "Special report generated from current project context.",
    "查看": "View",
    "分钟": "min",
    "风险": "Risk",
    "建议专家审核": "Expert review suggested",
    "· 建议专家审核": "· Expert review suggested",
    "信息齐全": "Information complete",
    "缺": "Missing",
    "项信息": "item(s)",
    "立即生成": "Generate now",
    "关于专项报告的合规边界": "Compliance Boundary for Special Reports",
    "标注「建议专家审核」的专项报告涉及法律、税务、移民等高风险领域。AI 输出作为整理与提示，不构成专业意见。": "Special reports marked as expert review suggested may involve legal, tax, immigration or other high-risk topics. AI output is for organization and prompting only, not professional advice.",
    "市场营销专项报告": "Marketing Special Report",
    "目标客群细分、广告组合、KOL/红人渠道与预算分配。": "Customer segmentation, ad mix, KOL/influencer channels and budget allocation.",
    "物流报关专项报告": "Logistics & Customs Report",
    "海运/空运、清关、海外仓比选、SKU 周转、退货物流网络。": "Sea/air freight, clearance, overseas warehouse comparison, SKU turnover and return logistics network.",
    "海运/空运、清关、海外仓比选、SKU 分仓策略。": "Sea/air freight, customs clearance, overseas warehouse comparison and SKU allocation strategy.",
    "法律风险专项报告": "Legal Risk Report",
    "产品责任、合同模板要点、争议解决条款梳理。": "Product liability, contract highlights and dispute-resolution clauses.",
    "财务税务专项报告": "Finance & Tax Report",
    "BN 商业号、GST/HST 注册、跨境利润税务。": "BN, GST/HST registration and cross-border profit tax.",
    "经销商开发报告": "Distributor Development Report",
    "目标经销商画像、初次接洽话术、利润分成结构。": "Distributor profile, first-contact scripts and margin-sharing structure.",
    "海外仓建设报告": "Overseas Warehouse Setup Report",
    "自营 vs 三方仓比选、SKU 周转、退货物流网络。": "Owned vs 3PL warehouse comparison, SKU turnover and return logistics network.",
    "电商平台进入报告": "Marketplace Entry Report",
    "Walmart Marketplace、Best Buy、Indigo 上架可行性。": "Feasibility for Walmart Marketplace, Best Buy and Indigo listings.",
    "企业家移民商业计划辅助": "Entrepreneur Immigration Business Plan Support",
    "营商签证、企业家移民、资金来源整理框架。": "Business visa, entrepreneur immigration and source-of-funds structure.",

    "专家确认事项": "Expert Review Items",
    "全部": "All",
    "全部 (": "All (",
    "高风险": "High Risk",
    "高风险 (": "High Risk (",
    "中风险": "Medium Risk",
    "中风险 (": "Medium Risk (",
    "AI 初步判断": "AI Preliminary Finding",
    "需要确认的问题：": "Questions to Confirm:",
    "推荐专家类型": "Recommended Expert Type",
    "已确认": "Confirmed",
    "联系推荐专家": "Contact Expert",
    "上传专家意见": "Upload Expert Opinion",
    "标记为已确认": "Mark as Confirmed",
    "合规声明": "Compliance Notice",
    "本项目涉及": "This project has",
    "和": "and",
    "事项，建议在执行前与持牌专业人士确认。": "items. Confirm with licensed professionals before execution.",
    "项高风险": "high-risk item(s)",
    "项中风险": "medium-risk item(s)",
    "上述事项的 AI 分析基于公开资料和您输入的信息整理，不构成法律、税务、移民、投资、报关或认证方面的专业意见。": "AI analysis above is based on public information and your inputs. It is not legal, tax, immigration, investment, customs or certification advice.",
    "加拿大商标 (CIPO) 注册": "Canadian trademark (CIPO) registration",
    "产品责任险 (Product Liability)": "Product liability insurance",
    "BN 商业号 + GST/HST 注册": "Business Number + GST/HST registration",
    "HS Code 与进口责任确认": "HS code and importer responsibility confirmation",
    "食品接触合规与双语标签": "Food-contact compliance and bilingual labels",

    "报告": "Reports",
    "主报告": "Main Report",
    "市场进入报告": "Market Entry Report",
    "市场进入调研报告": "Market Entry Research Report",
    "Ready · 已就绪": "Ready",
    "生成 / 重新生成": "Generate / Regenerate",
    "编辑": "Edit",
    "保存版本": "Save Version",
    "当前账号还没有报告": "No report yet",
    "请先创建真实项目并上传资料，再调用 MCP 和 AI 生成报告。": "Create a real project and upload files before generating a report with MCP and AI.",
    "报告目录": "Report Contents",
    "专项报告 (": "Special Reports (",
    "数据来源（节选）：": "Selected Sources:",
    "本报告由 AI 基于用户输入和公开资料生成，仅用于市场调研和商业决策参考，不构成法律、税务、移民、投资、报关或认证方面的专业意见。": "This AI report is generated from user inputs and public information for market research and business decision support only. It is not legal, tax, immigration, investment, customs or certification advice.",
    "需要专家确认": "Expert Confirmation Required",
    "风险内容，请在执行前咨询持牌专业人士。": "risk content. Consult licensed professionals before execution.",
    "您正在阅读": "You are reading",
    "报告章节": "report section",
    "可以基于本章节继续追问，或重新生成。": "You can ask follow-up questions about this section or regenerate it.",
    "。可以基于本章节继续追问，或重新生成。": ". You can ask follow-up questions about this section or regenerate it.",
    "针对本节追问": "Ask about this section",
    "重新生成本节": "Regenerate this section",
    "生成营销专项报告": "Generate marketing special report",
    "上传补充数据": "Upload supporting data",
    "本节置信度": "Section Confidence",
    "价格与竞品数据": "Pricing and competitor data",
    "合规判断": "Compliance judgement",
    "市场份额估算": "Market share estimate",
    "当前项目涉及": "Current project has",
    "专家确认事项": "expert review items",
    "专家确认事项。": "expert review item(s).",
    "项": "",
    "查看专家确认事项": "View Expert Review Items",
    "数据来源（本报告）": "Sources in This Report",
    "中文 · 简体": "English",
    "高": "High",
    "中": "Medium",
    "低": "Low",

    "创建出海调研项目": "Create Market Entry Research Project",
    "分步收集您的产品资料、目标市场和资源情况。 全程约 8-12 分钟。": "Collect product files, target market and resource context step by step. Takes about 8-12 minutes.",
    "保存草稿并退出": "Save draft and exit",
    "项目完成度": "Project Progress",
    "上一步": "Back",
    "跳过": "Skip",
    "下一步": "Next",
    "生成报告": "Generate Report",
    "AI 助手": "AI Assistant",
    "让 AI 帮我填写": "Let AI help fill this",
    "资源评估": "Resource Assessment",
    "确认并生成": "Review and Generate",
    "请尽量填写真实信息。AI 会基于产品名称、品类和价格做潜在品类识别和合规预判。": "Use real information where possible. AI uses product name, category and price to infer product class and compliance signals.",
    "上传的产品目录、价格表、认证文件会被 AI 解析，提取 SKU、价格、规格、卖点和缺失字段。": "Uploaded catalogs, price sheets and certificates are parsed by AI to extract SKUs, pricing, specs, selling points and missing fields.",
    "MVP 阶段聚焦加拿大 / 北美市场。已支持多市场对比，AI 会输出每个市场的机会与难度评分。": "The MVP focuses on Canada and North America. Multi-market comparison is supported, with opportunity and difficulty scores for each market.",
    "客群和渠道决定了 AI 推荐的价格区间、广告策略与本地化要求。建议至少选择 1 个主渠道。": "Customers and channels determine recommended price bands, ad strategy and localization needs. Pick at least one primary channel.",
    "如实评估资源能让 AI 给出更现实的「自建 vs 外包」建议，避免输出空泛建议。": "A realistic resource assessment lets AI recommend practical build-vs-outsource priorities.",
    "目标越具体，AI 越能生成可执行的阶段性动作清单。可以填「不确定」由 AI 推荐。": "Specific goals help AI create actionable phased tasks. You can choose \"not sure\" and let AI recommend.",
    "AI 已发现 5 项关键信息缺失。每回答 1 个问题，相关章节会更精准，预计耗时约 90 秒。": "AI found 5 missing key inputs. Each answer improves the related sections and takes about 90 seconds.",
    "确认后开始执行 7 个 Agent 并行调研。完整主报告约 90 秒生成，可继续追加专项报告。": "After confirmation, 7 agents run research in parallel. The main report takes about 90 seconds and can be extended with special reports.",
    "💡 输入产品英文名有助于 AI 搜索海外竞品": "Tip: an English product name helps AI find overseas competitors.",
    "📦 「品类」决定关税编码与合规清单": "Tip: category drives tariff code and compliance checklist.",
    "💰 价格区间影响渠道与广告策略": "Tip: price range affects channel and advertising strategy.",
    "📄 推荐上传报价单（含成本）和产品目录": "Tip: upload quotations with costs and product catalogs.",
    "🖼️ 产品图片可用于英文文案与本地化": "Tip: product images support English copy and localization.",
    "🔍 OCR 支持扫描版认证文件": "Tip: OCR supports scanned certificate files.",
    "🌎 加拿大 / 美国 报告深度最高": "Tip: Canada and United States reports have the deepest coverage.",
    "🆚 多市场对比适合 2-3 个国家": "Tip: multi-market comparison works best for 2-3 countries.",
    "🏷️ 客群分级影响价格策略": "Tip: customer tiers affect pricing strategy.",
    "🎯 渠道选错比选少更耗成本": "Tip: the wrong channel is costlier than choosing fewer channels.",
    "🤝 「不确定」时让 AI 推荐": "Tip: when unsure, let AI recommend.",
    "📊 AI 会给每个渠道打适配度评分": "Tip: AI scores each channel for fit.",
    "⚖️ 资源短板自动转化为「外包优先级」": "Tip: resource gaps become outsourcing priorities.",
    "💼 已有海外公司可加速 6 个月": "Tip: an existing overseas entity can shorten setup by 6 months.",
    "👥 本地团队是 long-term 决策": "Tip: a local team is a long-term decision.",
    "📅 1 年目标建议聚焦验证": "Tip: 1-year goals should focus on validation.",
    "📈 3 年目标关注稳态利润率": "Tip: 3-year goals should focus on steady margin.",
    "🌐 5 年目标考虑多市场扩张": "Tip: 5-year goals can consider multi-market expansion.",
    "❓ 「暂时不知道」会保留默认假设": "Tip: \"not sure yet\" keeps default assumptions.",
    "🔄 可随时返回上一步": "Tip: you can go back at any time.",
    "⏱️ 大约还需 90 秒完成": "Tip: about 90 seconds remaining.",
    "✅ 所有 Agent 协同生成主报告": "Tip: all agents collaborate on the main report.",
    "📑 报告可在「报告工作台」继续编辑": "Tip: reports can be edited in the report workspace.",
    "📥 支持 Markdown / PDF / Word 导出": "Tip: Markdown, PDF and Word exports are supported.",
    "产品基础信息": "Product Basics",
    "为 AI 建立产品画像。所有字段都可以稍后补充。": "Build a product profile for AI. All fields can be completed later.",
    "产品中文名称": "Product Chinese Name",
    "产品英文名称": "Product English Name",
    "产品品类": "Product Category",
    "家居收纳用品 · Home Storage": "Home Storage",
    "厨具及餐饮用品": "Kitchenware & Food Service",
    "清洁与日用": "Cleaning & Daily Goods",
    "海关编码 (HS Code)": "HS Code",
    "AI 已根据品类预判，可手动修改": "AI inferred this from category; edit manually if needed.",
    "产品描述": "Product Description",
    "出厂价 (CNY)": "Factory Price (CNY)",
    "国内零售价 (CNY)": "Domestic Retail Price (CNY)",
    "最小起订量 MOQ": "Minimum Order Quantity",
    "月生产能力": "Monthly Production Capacity",
    "是否已有品牌": "Existing Brand",
    "已有 · Maple Home": "Yes · Maple Home",
    "暂无": "None",
    "让 AI 推荐": "Let AI Recommend",
    "现有认证": "Existing Certifications",
    "上传产品资料": "Upload Product Files",
    "Word / PDF / Excel / CSV / 图片。AI 自动解析 SKU、价格、规格、认证文件。": "Word / PDF / Excel / CSV / images. AI parses SKUs, prices, specs and certification files.",
    "目标市场选择": "Target Market",
    "可选择 1 个主市场，或选择 2-3 个进行多市场对比。": "Choose one primary market, or 2-3 markets for comparison.",
    "单市场进入": "Single Market Entry",
    "多市场对比 (2-3 个)": "Multi-market Comparison (2-3)",
    "加拿大": "Canada",
    "美国": "United States",
    "英国": "United Kingdom",
    "阿联酋": "United Arab Emirates",
    "新加坡": "Singapore",
    "德国": "Germany",
    "成熟市场 · English / French": "Mature market · English / French",
    "成熟市场 · English": "Mature market · English",
    "高潜力 · English / Arabic": "High potential · English / Arabic",
    "枢纽 · English / 中文": "Hub · English / Chinese",
    "成熟市场 · German": "Mature market · German",
    "机会": "Opportunity",
    "难度": "Difficulty",
    "合规": "Compliance",
    "中等": "Medium",
    "中高": "Medium-high",
    "高": "High",
    "低": "Low",
    "目标城市 / 区域 (可多选)": "Target Cities / Regions",
    "多伦多": "Toronto",
    "蒙特利尔": "Montreal",
    "温哥华": "Vancouver",
    "渥太华": "Ottawa",
    "卡尔加里": "Calgary",
    "全国分销": "National Distribution",
    "客群与渠道": "Customers & Channels",
    "明确卖给谁、通过什么渠道卖。AI 会给每个组合打适配度评分。": "Define who you sell to and through which channels. AI scores each combination.",
    "目标客群 (可多选)": "Target Customers",
    "中端家庭": "Mid-market Families",
    "中高端家庭": "Upper-mid Families",
    "大众市场": "Mass Market",
    "高端客户": "Premium Customers",
    "B2B 企业客户": "B2B Customers",
    "华人社区": "Chinese Community",
    "本地主流": "Local Mainstream",
    "学校 / 机构": "Schools / Institutions",
    "目标渠道 (建议至少选 1 个主渠道)": "Target Channels (pick at least one primary channel)",
    "让 AI 推荐渠道": "Let AI Recommend Channels",
    "电商": "Ecommerce",
    "线下": "Offline",
    "渠道": "Channel",
    "基建": "Infrastructure",
    "获客": "Acquisition",
    "团队": "Team",
    "Shopify 独立站": "Shopify Site",
    "本地批发": "Local Wholesale",
    "本地零售": "Local Retail",
    "代理商": "Agents",
    "经销商": "Distributors",
    "海外仓": "Overseas Warehouse",
    "展会": "Trade Shows",
    "本地销售团队": "Local Sales Team",
    "社媒私域": "Social / Private Traffic",
    "AI 渠道建议": "AI Channel Recommendation",
    "资源与现状": "Resources & Current State",
    "评估您当前的资源储备。AI 据此判断「自建 vs 外包」优先级。": "Assess current resources. AI uses this to prioritize build vs outsource.",
    "已有国内工厂": "Domestic Factory",
    "是": "Yes",
    "是 · 跨境电商": "Yes · Cross-border ecommerce",
    "是 · 2 人": "Yes · 2 people",
    "国内有": "Domestic only",
    "不确定": "Not sure",
    "电商团队": "Ecommerce Team",
    "外贸 / 业务团队": "Export / Sales Team",
    "海外公司": "Overseas Entity",
    "海外仓 / 合作伙伴": "Overseas Warehouse / Partners",
    "本地员工": "Local Staff",
    "法律顾问": "Legal Counsel",
    "持牌会计师 (北美)": "Licensed Accountant (North America)",
    "持牌移民顾问": "Licensed Immigration Consultant",
    "报关行": "Customs Broker",
    "出海预算 (CNY)": "Expansion Budget (CNY)",
    "预计启动时间": "Expected Start Time",
    "未来 3 个月": "Next 3 months",
    "未来 6 个月": "Next 6 months",
    "未来 12 个月": "Next 12 months",
    "1 / 3 / 5 年目标": "1 / 3 / 5-Year Goals",
    "目标越具体，AI 越能生成可执行的阶段动作清单。允许填「不确定」。": "The more specific the goals, the more actionable the phased plan. \"Not sure\" is acceptable.",
    "目标": "Goal",
    "不确定，让 AI 推荐": "Not sure, let AI recommend",
    "AI 追问补全": "AI Follow-up",
    "AI 发现关键信息缺失。回答这些问题能让相关报告章节更精准。": "AI found missing key information. Answering improves related report sections.",
    "调研 AI · 关于合规": "Research AI · Compliance",
    "已拥有": "Already have it",
    "正在申请": "Applying",
    "没有": "No",
    "需要 AI 帮我判断": "Need AI to assess",
    "此回答影响：": "This affects:",
    "合规风险章节 · 商标与品牌建议 · 行动清单": "Compliance risk · trademark/brand recommendations · action checklist",
    "调研 AI · 关于预算": "Research AI · Budget",
    "让 AI 推荐 (基于 MOQ)": "Let AI recommend (based on MOQ)",
    "暂时不知道": "Not sure yet",
    "调研 AI · 关于定价": "Research AI · Pricing",
    "最低 CAD": "Min CAD",
    "最高 CAD": "Max CAD",
    "参考竞品价格": "Reference competitor prices",
    "确认信息并生成报告": "Review and Generate Report",
    "检查各项设置。报告将由 7 个 AI Agent 协同生成，预计 90 秒。": "Review settings. The report will be generated by 7 AI agents in about 90 seconds.",
    "项目名称": "Project Name",
    "目标市场": "Target Market",
    "客群": "Customers",
    "预算 / 时间": "Budget / Timeline",
    "1 年目标": "1-Year Goal",
    "已上传文件": "Uploaded Files",
    "将生成以下章节": "Sections to Generate",
    "执行摘要": "Executive Summary",
    "产品分析": "Product Analysis",
    "目标市场分析": "Target Market Analysis",
    "客群分析": "Customer Analysis",
    "竞品分析": "Competitor Analysis",
    "价格区间与成本": "Pricing and Cost",
    "渠道策略": "Channel Strategy",
    "物流与报关": "Logistics and Customs",
    "合规与认证": "Compliance and Certification",
    "品牌与商标": "Brand and Trademark",
    "本地运营建议": "Local Operations",
    "1/3/5 年路线图": "1/3/5-Year Roadmap",
    "风险清单": "Risk Checklist",
    "需要专家确认事项": "Expert Confirmation Items",
    "⚠️ 合规边界": "Compliance Boundary",

    "设置": "Settings",
    "账户设置": "Account Settings",
    "管理您的资料、订阅、数据隐私和通知偏好。": "Manage profile, subscription, data privacy and notifications.",
    "个人资料": "Profile",
    "企业资料": "Company",
    "语言与报告偏好": "Language & Report Preferences",
    "订阅与计费": "Billing",
    "数据隐私": "Data Privacy",
    "团队成员": "Team Members",
    "通知": "Notifications",
    "账户操作": "Account Actions",
    "这些信息会显示在团队成员和报告作者栏。": "This information appears for team members and report authors.",
    "更换头像": "Change avatar",
    "最大 2MB": "Max 2MB",
    "JPG / PNG · 最大 2MB": "JPG / PNG · Max 2MB",
    "姓名": "Name",
    "职位": "Role",
    "手机": "Mobile",
    "所在城市": "City",
    "所在时区": "Timezone",
    "取消": "Cancel",
    "保存修改": "Save Changes",
    "用于生成报告页眉、商业计划书和服务转介。": "Used in report headers, business plans and service referrals.",
    "公司名称": "Company Name",
    "主要品类": "Main Category",
    "年产值": "Annual Output",
    "公司简介": "Company Profile",
    "影响 UI 显示语言和默认报告生成语言。": "Controls UI language and default report language.",
    "影响界面显示语言。": "Controls the UI display language.",
    "影响默认报告生成语言和报告深度。": "Controls the default report language and report depth.",
    "保存语言": "Save Language",
    "保存报告偏好": "Save Report",
    "界面语言": "UI Language",
    "报告默认语言": "Default Report Language",
    "中英双语": "Chinese + English",
    "仅中文": "Chinese only",
    "仅 English": "English only",
    "报告深度偏好": "Report Depth",
    "简版 (3-5 章)": "Brief (3-5 sections)",
    "标准版 (10-12 章)": "Standard (10-12 sections)",
    "深度版 (15+ 章)": "Deep (15+ sections)",
    "当前订阅": "Current Subscription",
    "续费日": "Renewal date",
    "月": "month",
    "份": "reports",
    "份报告 / 月 · PDF / DOCX 导出": "reports / month · PDF / DOCX export",
    "本月已用": "Used this month",
    "支付方式": "Payment Method",
    "过期": "Expires",
    "更换": "Change",
    "Stripe 订阅": "Stripe Subscription",
    "微信支付": "WeChat Pay",
    "支付宝": "Alipay",
    "账单历史": "Billing History",
    "日期": "Date",
    "计划": "Plan",
    "金额": "Amount",
    "状态": "Status",
    "月付": "Monthly",
    "已支付": "Paid",
    "下载发票": "Download Invoice",
    "您的产品资料和报告内容受加密保护。我们不使用您的私有数据训练 AI 模型。": "Your product files and reports are encrypted. We do not use private data to train AI models.",
    "文件加密存储": "Encrypted file storage",
    "上传文件以 AES-256 加密存储，仅您可访问。": "Uploaded files are AES-256 encrypted and accessible only to you.",
    "禁止用于模型训练": "Not used for model training",
    "您的私有资料不会被用于 AI 模型训练或其他用户。": "Your private data is never used to train AI models or other users.",
    "项目权限隔离": "Project access isolation",
    "每个项目独立访问控制，团队成员需单独授权。": "Each project has separate access control. Team members need explicit permission.",
    "审计日志": "Audit logs",
    "所有项目访问、修改、导出记录可追溯。": "Project access, edits and exports are traceable.",
    "导出我的全部数据": "Export all my data",
    "清空所有项目资料": "Clear all project data",
    "邀请合作者加入项目。Business 计划支持最多 10 名成员。": "Invite collaborators. Business supports up to 10 members.",
    "邀请新成员": "Invite Member",
    "通知偏好": "Notification Preferences",
    "选择您希望接收哪些类型的提醒。": "Choose which notifications you want to receive.",
    "报告生成完成": "Report generated",
    "AI 发现关键缺失信息": "AI found key missing information",
    "团队成员评论 / 修改": "Team comments / edits",
    "订阅 / 账单提醒": "Subscription / billing reminders",
    "产品更新与新功能": "Product updates and new features",
    "邮件 + 应用内": "Email + in-app",
    "应用内": "In-app",
    "邮件": "Email",
    "邮件 (每月摘要)": "Email (monthly digest)",
    "删除账户": "Delete Account",
    "一旦删除，您的所有项目、报告和上传文件将被永久销毁，无法恢复。订阅会立即取消，未消费部分不予退款。": "Once deleted, all projects, reports and uploaded files will be permanently destroyed and cannot be recovered. Subscription will be cancelled immediately and unused balance is not refunded.",
    "永久删除我的账户": "Permanently Delete My Account",
  },
};

const GGG_I18N_PATTERNS = {
  en: [
    [/^当前工作区共有 (\d+) 个出海项目，下一步事项 (\d+) 项。$/, (m) => `Current workspace has ${m[1]} expansion project(s) and ${m[2]} next action(s).`],
    [/^我的项目 · 共 (\d+) 个$/, (m) => `My Projects · ${m[1]} total`],
    [/^· 共 (\d+) 个$/, (m) => `· ${m[1]} total`],
    [/^已上传资料 · (\d+) 个文件$/, (m) => `Uploaded Files · ${m[1]} file(s)`],
    [/^· (\d+) 个文件$/, (m) => `· ${m[1]} file(s)`],
    [/^专项报告 \((\d+)\)$/, (m) => `Special Reports (${m[1]})`],
    [/^主报告 · v(\d+)$/, (m) => `Main Report · v${m[1]}`],
    [/^已生成 \((\d+)\)$/, (m) => `Generated (${m[1]})`],
    [/^可生成 \((\d+)\)$/, (m) => `Available (${m[1]})`],
    [/^全部 \((\d+)\)$/, (m) => `All (${m[1]})`],
    [/^高风险 \((\d+)\)$/, (m) => `High Risk (${m[1]})`],
    [/^中风险 \((\d+)\)$/, (m) => `Medium Risk (${m[1]})`],
    [/^(\d+) 项$/, (m) => `${m[1]}`],
    [/^(.+) 项高风险$/, (m) => `${m[1]} high-risk item(s)`],
    [/^(.+) 项中风险$/, (m) => `${m[1]} medium-risk item(s)`],
    [/^本项目涉及 (\d+) 项高风险 和 (\d+) 项中风险 事项，建议在执行前与持牌专业人士确认。$/, (m) => `This project has ${m[1]} high-risk item(s) and ${m[2]} medium-risk item(s). Confirm with licensed professionals before execution.`],
    [/^本节包含 (高|中|低) 风险内容，请在执行前咨询持牌专业人士。$/, (m) => `This section contains ${translatePhrase(m[1], "en").toLowerCase()} risk content. Consult licensed professionals before execution.`],
    [/^当前项目涉及 (\d+) 项专家确认事项。$/, (m) => `Current project has ${m[1]} expert review item(s).`],
    [/^(.+) 分钟$/, (m) => `${m[1]} min`],
    [/^风险 (高|中|低)$/, (m) => `Risk ${translatePhrase(m[1], "en")}`],
    [/^缺 (\d+) 项信息$/, (m) => `${m[1]} missing item(s)`],
    [/^(.+) 年目标$/, (m) => `${m[1]}-Year Goal`],
    [/^\/ (\d+) 份$/, (m) => `/ ${m[1]} reports`],
    [/^(.+) 份$/, (m) => `${m[1]} report(s)`],
    [/^(.+) 份报告 \/ 月 · PDF \/ DOCX 导出$/, (m) => `${m[1]} reports / month · PDF / DOCX export`],
    [/^(.+) · 续费日 (.+)$/, (m) => `${translatePhrase(m[1], "en")} · Renewal date ${m[2]}`],
    [/^(.+) · 月付$/, (m) => `${translatePhrase(m[1], "en")} · Monthly`],
  ],
};

const GGG_I18N_ORIGINAL_TEXT = new WeakMap();
const GGG_I18N_LAST_TEXT = new WeakMap();

function initialLanguage() {
  try {
    const stored = localStorage.getItem(GGG_I18N_STORAGE_KEY);
    if (GGG_I18N_LOCALES.some((item) => item.id === stored)) return stored;
  } catch {}
  return "zh";
}

const GGGI18nStore = {
  lang: initialLanguage(),
  listeners: new Set(),
  t(key, values) {
    return interpolate(translatePhrase(key, this.lang), values);
  },
  setLanguage(lang) {
    if (!GGG_I18N_LOCALES.some((item) => item.id === lang)) return;
    this.lang = lang;
    try { localStorage.setItem(GGG_I18N_STORAGE_KEY, lang); } catch {}
    applyDocumentLanguage();
    this.listeners.forEach((listener) => listener(lang));
    queueTranslate(document.body);
  },
  subscribe(listener) {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  }
};

function translatePhrase(input, lang = GGGI18nStore.lang) {
  const key = String(input ?? "");
  const translated = GGG_I18N[lang]?.[key];
  if (translated != null) return translated;
  if (lang !== "zh") {
    for (const [pattern, replace] of GGG_I18N_PATTERNS[lang] || []) {
      const match = key.match(pattern);
      if (match) return replace(match);
    }
  }
  return key;
}

function interpolate(input, values) {
  if (!values) return input;
  return String(input).replace(/\{(\w+)\}/g, (_, key) => values[key] ?? "");
}

function useI18n() {
  const [lang, setLangState] = React.useState(GGGI18nStore.lang);
  React.useEffect(() => GGGI18nStore.subscribe(setLangState), []);
  return {
    lang,
    locale: GGG_I18N_LOCALES.find((item) => item.id === lang) || GGG_I18N_LOCALES[0],
    setLanguage: (next) => GGGI18nStore.setLanguage(next),
    t: (key, values) => interpolate(translatePhrase(key, lang), values),
    isZh: lang === "zh"
  };
}

function LanguageToggle({ compact = false }) {
  const { lang, setLanguage, t } = useI18n();
  return (
    <div className={"language-toggle " + (compact ? "compact" : "")} title={t("language.switch")} data-i18n-skip="true">
      {GGG_I18N_LOCALES.map((locale) => (
        <button
          key={locale.id}
          type="button"
          className={lang === locale.id ? "active" : ""}
          onClick={() => setLanguage(locale.id)}
          aria-pressed={lang === locale.id}
        >
          {compact ? locale.label : locale.fullLabel}
        </button>
      ))}
    </div>
  );
}

function splitWhitespace(value) {
  const match = String(value).match(/^(\s*)([\s\S]*?)(\s*)$/);
  return { lead: match?.[1] || "", body: match?.[2] || "", tail: match?.[3] || "" };
}

function translateNodeValue(value, lang) {
  const { lead, body, tail } = splitWhitespace(value);
  if (!body) return value;
  return lead + translatePhrase(body, lang) + tail;
}

let translateQueued = false;
function queueTranslate(root) {
  if (!root || translateQueued) return;
  translateQueued = true;
  requestAnimationFrame(() => {
    translateQueued = false;
    translateTree(root);
  });
}

function translateTree(root) {
  if (!root) return;
  const lang = GGGI18nStore.lang;
  const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
    acceptNode(node) {
      const parent = node.parentElement;
      if (!parent) return NodeFilter.FILTER_REJECT;
      if (["SCRIPT", "STYLE", "TEXTAREA", "CODE", "PRE"].includes(parent.tagName)) return NodeFilter.FILTER_REJECT;
      if (parent.closest("[data-i18n-skip]")) return NodeFilter.FILTER_REJECT;
      return node.nodeValue && node.nodeValue.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
    }
  });
  const nodes = [];
  while (walker.nextNode()) nodes.push(walker.currentNode);
  nodes.forEach((node) => {
    const lastTranslated = GGG_I18N_LAST_TEXT.get(node);
    if (!GGG_I18N_ORIGINAL_TEXT.has(node) || (lastTranslated !== undefined && node.nodeValue !== lastTranslated)) {
      GGG_I18N_ORIGINAL_TEXT.set(node, node.nodeValue);
    }
    const original = GGG_I18N_ORIGINAL_TEXT.get(node);
    const translated = translateNodeValue(original, lang);
    if (node.nodeValue !== translated) node.nodeValue = translated;
    GGG_I18N_LAST_TEXT.set(node, translated);
  });

  const elementWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
  const attrs = ["placeholder", "title", "aria-label"];
  while (elementWalker.nextNode()) {
    const el = elementWalker.currentNode;
    if (el.closest?.("[data-i18n-skip]")) continue;
    attrs.forEach((attr) => {
      if (!el.hasAttribute?.(attr)) return;
      const store = `i18nOriginal${attr.replace(/(^|-)([a-z])/g, (_, _dash, c) => c.toUpperCase())}`;
      const storeLast = `i18nLast${attr.replace(/(^|-)([a-z])/g, (_, _dash, c) => c.toUpperCase())}`;
      const current = el.getAttribute(attr);
      if (!el.dataset[store] || (el.dataset[storeLast] !== undefined && current !== el.dataset[storeLast])) el.dataset[store] = current;
      const translated = translateNodeValue(el.dataset[store], lang);
      if (current !== translated) el.setAttribute(attr, translated);
      el.dataset[storeLast] = translated;
    });
  }
}

function applyDocumentLanguage() {
  const locale = GGG_I18N_LOCALES.find((item) => item.id === GGGI18nStore.lang) || GGG_I18N_LOCALES[0];
  document.documentElement.lang = locale.htmlLang;
  document.title = translatePhrase("app.title", GGGI18nStore.lang);
}

function installI18nDomObserver() {
  applyDocumentLanguage();
  queueTranslate(document.body);
  const observer = new MutationObserver((mutations) => {
    if (mutations.some((mutation) => mutation.type === "childList" || mutation.type === "characterData" || mutation.type === "attributes")) {
      queueTranslate(document.body);
    }
  });
  observer.observe(document.body, {
    childList: true,
    subtree: true,
    characterData: true,
    attributes: true,
    attributeFilter: ["placeholder", "title", "aria-label"]
  });
}

if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", installI18nDomObserver, { once: true });
} else {
  installI18nDomObserver();
}

window.GGGI18n = GGGI18nStore;
window.useI18n = useI18n;
window.LanguageToggle = LanguageToggle;
window.t = (key, values) => GGGI18nStore.t(key, values);
