"use client";

import { createContext, useContext, useState, useEffect, startTransition, type ReactNode } from "react";

export type Locale = "zh" | "en";

const translations = {
  zh: {
    // nav
    "nav.overview": "总览",
    "nav.rankings": "排名",
    "nav.aggregation": "聚合",
    "nav.logs": "日志",
    // common
    "common.loading": "加载中...",
    "common.noData": "暂无数据",
    "common.records": "条记录",
    "common.systemOnline": "系统在线",
    "common.back": "返回",
    "common.backToRankings": "返回排名",
    "common.prevPage": "上一页",
    "common.nextPage": "下一页",
    "common.share": "占比",
    // time range
    "time.today": "今日",
    "time.7d": "7 天",
    "time.30d": "30 天",
    "time.all": "全部",
    "time.custom": "自定义",
    "time.startDate": "开始日期",
    "time.endDate": "结束日期",
    "time.confirm": "确认",
    // granularity
    "gran.hour": "小时",
    "gran.day": "日",
    "gran.week": "周",
    "gran.month": "月",
    // metrics
    "metric.token": "Token",
    "metric.cost": "金额",
    "metric.calls": "调用量",
    // dashboard
    "dash.title": "仪表盘",
    "dash.totalCalls": "调用次数",
    "dash.tokenUsage": "Token 消耗",
    "dash.activeUsers": "活跃用户",
    "dash.activeModels": "活跃模型",
    "dash.trend": "使用趋势",
    "dash.userTop10": "用户 Top 10 — Token 消耗",
    "dash.totalCost": "消费金额",
    "dash.modelTop10": "模型 Top 10 — Token 消耗",
    // table headers
    "th.rank": "#",
    "th.name": "名称",
    "th.user": "用户",
    "th.calls": "调用次数",
    "th.input": "输入",
    "th.output": "输出",
    "th.cacheCreation": "缓存创建",
    "th.cacheRead": "缓存读取",
    "th.cost": "金额",
    "th.totalToken": "总 Token",
    "th.time": "时间",
    "th.realModel": "真实模型",
    "th.channel": "渠道",
    "th.latency": "耗时",
    // rankings
    "rank.title": "排名",
    "rank.user": "用户",
    "rank.model": "模型",
    "rank.channel": "渠道",
    // aggregation
    "agg.title": "用户聚合",
    "agg.userCount": "用户数",
    "agg.totalCalls": "总调用",
    "agg.totalCost": "总金额",
    "agg.totalToken": "总 Token",
    "agg.ratio": "转换率",
    "agg.ratioTip": "输出Token / 输入Token，反映每次请求的生成效率。>1 表示输出多于输入（如生成、写作），<1 表示输入多于输出（如分析、摘要）",
    // logs
    "logs.title": "日志明细",
    "logs.filterUser": "用户名",
    "logs.filterModel": "模型",
    "logs.filterToken": "Token 名称",
    // detail
    "detail.user": "用户",
    "detail.model": "模型",
    "detail.channel": "渠道",
    "detail.trend": "使用趋势",
    "detail.modelDist": "模型分布",
    "detail.userDist": "用户分布",
    "detail.tokenDist": "令牌分布",
    "detail.primaryModels": "主要模型",
    "detail.unnamedToken": "未命名令牌",
    "detail.expandToken": "展开令牌",
    "detail.collapseToken": "收起令牌",
    // theme
    "theme.light": "浅色",
    "theme.dark": "深色",
    "theme.system": "系统",
    // portal
    "portal.subtitle": "智能 API 网关平台",
    "portal.monitoring": "监控站",
    "portal.monitoringDesc": "实时系统状态监控与告警通知",
    "portal.docs": "文档中心",
    "portal.docsDesc": "API 接口文档与集成指南",
    "portal.analytics": "使用统计",
    "portal.analyticsDesc": "API 调用数据分析与可视化看板",
    "portal.enter": "进入",
    "portal.nav.features": "功能",
    "portal.nav.services": "服务",
    "portal.nav.ecosystem": "生态",
    "portal.nav.start": "开始使用",
    "portal.hero.badge": "企业内部平台 · 系统运行中",
    "portal.hero.desc": "统一 AI 模型接口，兼容 OpenAI 格式，支持平滑迁移与稳定响应。为企业内所有人提供统一、稳定的 AI 能力入口。",
    "portal.hero.cta": "进入平台",
    "portal.hero.docs": "查看文档",
    "portal.features.tag": "核心能力",
    "portal.features.title": "平台特性",
    "portal.features.unified": "统一接口",
    "portal.features.unifiedDesc": "完全兼容 OpenAI API 格式，一行代码切换 GPT、Claude、Gemini、DeepSeek 等主流模型",
    "portal.features.security": "安全可靠",
    "portal.features.securityDesc": "企业级加密传输，密钥隔离管理，完整审计日志，数据安全有保障",
    "portal.features.monitor": "用量监控",
    "portal.features.monitorDesc": "实时 Token 消耗统计，按模型、按渠道精细化分析，成本一目了然",
    "portal.features.global": "全球加速",
    "portal.features.globalDesc": "跨区域链路调度与稳定转发能力，自动选择更优访问路径，兼顾响应速度与可用性。",
    "portal.features.failover": "自动容灾",
    "portal.features.failoverDesc": "内置多渠道负载均衡与故障转移，单一渠道异常时自动切换，服务永不中断",
    "portal.features.flexible": "灵活扩展",
    "portal.features.flexibleDesc": "支持自定义模型映射、请求改写、速率限制，完善的 Webhook 与回调机制",
    "portal.services.tag": "平台服务",
    "portal.services.title": "服务入口",
    "portal.ecosystem.tag": "生态接入",
    "portal.ecosystem.title": "支持的模型与工具",
    "portal.ecosystem.models": "主流 AI 模型",
    "portal.ecosystem.tools": "AI 编程工具",
    "portal.ecosystem.toolsDesc": "统一 API Key，即可接入以下工具",
    "portal.disclaimer.tag": "合规声明",
    "portal.disclaimer.title": "服务使用与内容责任说明",
    "portal.disclaimer.p1": "本平台作为 AI 模型 API 网关服务提供者，严禁利用本平台生成任何涉及色情、暴力、政治敏感、侵犯知识产权或其他违反中华人民共和国法律法规的内容。如发现违规使用，平台有权立即终止服务并配合相关部门依法处理。",
    "portal.disclaimer.p2": "用户须自觉遵守所在地区法律法规及相关政策。因用户自身行为产生的一切法律后果，由用户自行承担。",
    "portal.disclaimer.copyright": "© 2025 SinoCode",
  },
  en: {
    "nav.overview": "Overview",
    "nav.rankings": "Rankings",
    "nav.aggregation": "Aggregation",
    "nav.logs": "Logs",
    "common.loading": "Loading...",
    "common.noData": "No data",
    "common.records": "records",
    "common.systemOnline": "System Online",
    "common.back": "Back",
    "common.backToRankings": "Back to Rankings",
    "common.prevPage": "Previous",
    "common.nextPage": "Next",
    "common.share": "Share",
    "time.today": "Today",
    "time.7d": "7 Days",
    "time.30d": "30 Days",
    "time.all": "All",
    "time.custom": "Custom",
    "time.startDate": "Start",
    "time.endDate": "End",
    "time.confirm": "Confirm",
    "gran.hour": "Hour",
    "gran.day": "Day",
    "gran.week": "Week",
    "gran.month": "Month",
    "metric.token": "Token",
    "metric.cost": "Cost",
    "metric.calls": "Calls",
    "dash.title": "Dashboard",
    "dash.totalCalls": "Total Calls",
    "dash.tokenUsage": "Token Usage",
    "dash.activeUsers": "Active Users",
    "dash.activeModels": "Active Models",
    "dash.trend": "Usage Trend",
    "dash.userTop10": "User Top 10 — Token Usage",
    "dash.totalCost": "Total Cost",
    "dash.modelTop10": "Model Top 10 — Token Usage",
    "th.rank": "#",
    "th.name": "Name",
    "th.user": "User",
    "th.calls": "Calls",
    "th.input": "Input",
    "th.output": "Output",
    "th.cacheCreation": "Cache Write",
    "th.cacheRead": "Cache Read",
    "th.cost": "Cost",
    "th.totalToken": "Total Token",
    "th.time": "Time",
    "th.realModel": "Real Model",
    "th.channel": "Channel",
    "th.latency": "Latency",
    "rank.title": "Rankings",
    "rank.user": "User",
    "rank.model": "Model",
    "rank.channel": "Channel",
    "agg.title": "User Aggregation",
    "agg.userCount": "Users",
    "agg.totalCalls": "Total Calls",
    "agg.totalCost": "Total Cost",
    "agg.totalToken": "Total Token",
    "agg.ratio": "Out/In Ratio",
    "agg.ratioTip": "Completion tokens / Prompt tokens. >1 means more output than input (generation, writing); <1 means more input than output (analysis, summarization)",
    "logs.title": "Log Details",
    "logs.filterUser": "Username",
    "logs.filterModel": "Model",
    "logs.filterToken": "Token Name",
    "detail.user": "User",
    "detail.model": "Model",
    "detail.channel": "Channel",
    "detail.trend": "Usage Trend",
    "detail.modelDist": "Model Distribution",
    "detail.userDist": "User Distribution",
    "detail.tokenDist": "Token Distribution",
    "detail.primaryModels": "Primary Models",
    "detail.unnamedToken": "Unnamed Token",
    "detail.expandToken": "Expand token",
    "detail.collapseToken": "Collapse token",
    "theme.light": "Light",
    "theme.dark": "Dark",
    "theme.system": "System",
    "portal.subtitle": "Intelligent API Gateway Platform",
    "portal.monitoring": "Monitoring",
    "portal.monitoringDesc": "Real-time system status monitoring & alerts",
    "portal.docs": "Documentation",
    "portal.docsDesc": "API reference docs & integration guides",
    "portal.analytics": "Usage Analytics",
    "portal.analyticsDesc": "API usage data analytics & visualization dashboard",
    "portal.enter": "Enter",
    "portal.nav.features": "Features",
    "portal.nav.services": "Services",
    "portal.nav.ecosystem": "Ecosystem",
    "portal.nav.start": "Get Started",
    "portal.hero.badge": "Enterprise Internal Platform · System Online",
    "portal.hero.desc": "A unified AI model interface compatible with the OpenAI format, designed for smooth migration and stable response times. It provides a single, reliable AI access point for everyone across the enterprise.",
    "portal.hero.cta": "Enter Platform",
    "portal.hero.docs": "View Docs",
    "portal.features.tag": "Core Capabilities",
    "portal.features.title": "Platform Features",
    "portal.features.unified": "Unified Interface",
    "portal.features.unifiedDesc": "Fully compatible with OpenAI API format. Switch between GPT, Claude, Gemini, DeepSeek with a single line of code",
    "portal.features.security": "Security & Reliability",
    "portal.features.securityDesc": "Enterprise-grade encryption, isolated key management, complete audit logs, data security guaranteed",
    "portal.features.monitor": "Usage Monitoring",
    "portal.features.monitorDesc": "Real-time token consumption stats, granular analysis by model and channel, costs at a glance",
    "portal.features.global": "Global Acceleration",
    "portal.features.globalDesc": "Cross-region routing and resilient forwarding automatically choose the better path for responsive and reliable access.",
    "portal.features.failover": "Auto Failover",
    "portal.features.failoverDesc": "Built-in multi-channel load balancing and failover, automatic switching on channel failure, zero downtime",
    "portal.features.flexible": "Flexible Extension",
    "portal.features.flexibleDesc": "Custom model mapping, request rewriting, rate limiting, complete webhook and callback mechanisms",
    "portal.services.tag": "Platform Services",
    "portal.services.title": "Service Portal",
    "portal.ecosystem.tag": "Ecosystem",
    "portal.ecosystem.title": "Supported Models & Tools",
    "portal.ecosystem.models": "AI Models",
    "portal.ecosystem.tools": "AI Coding Tools",
    "portal.ecosystem.toolsDesc": "One unified API Key for the following tools",
    "portal.disclaimer.tag": "Compliance",
    "portal.disclaimer.title": "Service Usage & Content Responsibility",
    "portal.disclaimer.p1": "As an AI model API gateway, this platform strictly prohibits generating content involving pornography, violence, political sensitivity, IP infringement, or other violations of PRC laws. Violations will result in immediate service termination and cooperation with authorities.",
    "portal.disclaimer.p2": "Users must comply with local laws and regulations. All legal consequences arising from user actions are the sole responsibility of the user.",
    "portal.disclaimer.copyright": "© 2025 SinoCode",
  },
} as const;

export type TranslationKey = keyof typeof translations.zh;

interface I18nContextType {
  locale: Locale;
  setLocale: (l: Locale) => void;
  t: (key: TranslationKey) => string;
}

const I18nContext = createContext<I18nContextType>({
  locale: "zh",
  setLocale: () => {},
  t: (key) => key,
});

export function I18nProvider({ children }: { children: ReactNode }) {
  const [locale, setLocale] = useState<Locale>("zh");

  useEffect(() => {
    const saved = localStorage.getItem("locale") as Locale | null;
    if (saved && (saved === "zh" || saved === "en")) {
      startTransition(() => setLocale(saved));
    }
  }, []);

  const handleSetLocale = (l: Locale) => {
    setLocale(l);
    localStorage.setItem("locale", l);
  };

  const t = (key: TranslationKey): string => {
    return translations[locale][key] || key;
  };

  return (
    <I18nContext.Provider value={{ locale, setLocale: handleSetLocale, t }}>
      {children}
    </I18nContext.Provider>
  );
}

export function useI18n() {
  return useContext(I18nContext);
}
