'use client';

import { createContext, useContext, useState, useMemo, useCallback, ReactNode } from 'react';

type Language = 'zh' | 'en';

// 翻译内容
const zhTranslations = {
  // Navbar
  'nav.product': '产品',
  'nav.resource': '资源',
  'nav.community': '社区',
  'nav.ecosystem': '生态系统',
  'nav.launchApp': '启动应用',

  // Hero Section
  'hero.badge': '由纳斯达克及港交所上市合作伙伴支持',
  'hero.title1': '链上收益资产',
  'hero.title2': '触手可及。',
  'hero.description': '低门槛投资股票、房地产和商业贷款等收益资产。享受真实资产支持的10%-30%年化收益。',
  'hero.startInvesting': '开始投资',
  'hero.readWhitepaper': '阅读白皮书',
  'hero.readDocs': '阅读文档',

  // Stats Section
  'stats.tvl': '总锁仓价值',
  'stats.apy': '平均年化收益',
  'stats.yield': '累计收益',
  'stats.users': '连接用户',

  // Trusted By Section
  'trusted.title': '受到行业领导者信赖',

  // Why AssetX Section
  'why.title': '为什么选择ASSETX?',
  'why.subtitle': '机构级真实世界收益，兼具DeFi原生可组合性。',
  'why.sustainable.title': '可持续真实收益',
  'why.sustainable.desc': '从Delta中性套利策略和商业信贷中获得15%-30%的回报。没有通胀代币发行，只有真实利润。',
  'why.reliability.title': '经过验证的可靠性',
  'why.reliability.desc': '由持有香港证监会1/2/4/5/9号牌照的合作伙伴和纳斯达克上市实体支持。经过审计、合规且透明。',
  'why.liquidity.title': '灵活流动性',
  'why.liquidity.desc': '解决传统金融的流动性不足问题。通过二级市场即时退出，或通过杠杆头寸享受高达40%的年化收益。',
  'why.liquidity.badge1': '40%+年化',
  'why.liquidity.badge2': '即时退出',

  // How It Works Section
  'how.title': '如何运作',
  'how.step1.title': '连接并探索',
  'how.step1.desc': '浏览收益代币，比较收益/风险，查看关键指标。',
  'how.step2.title': '用USDC投资',
  'how.step2.desc': '用USDC购买收益代币，赚取现实世界收益。',
  'how.step3.title': '在DeFi中使用',
  'how.step3.desc': '通过二级市场提前退出，以抵押品借款，或提供流动性赚取手续费。',
  'how.simulator.title': '投资组合概览模拟器',
  'how.simulator.invest': '如果您投资',
  'how.simulator.earn': '您每年赚取',

  // Security Section
  'security.title': '安全优先架构',
  'security.subtitle': '实时数据透明度与隔离资产管理。',
  'security.audited.title': '已审计',
  'security.audited.desc': '智能合约由顶级公司审计。底层资产经过严格的尽职调查和财务审计。',
  'security.segregated.title': '隔离管理',
  'security.segregated.desc': 'SPV设置。用户资产保存在隔离的特殊目的实体中，与平台风险隔离。',
  'security.transparency.title': '透明度',
  'security.transparency.desc': '实时净值。基金表现数据和资产估值公开可查并在链上更新。',
  'security.partners.title': '由纳斯达克和港交所上市合作伙伴提供支持',

  // Footer
  'footer.products': '产品',
  'footer.product1': 'AX-基金',
  'footer.product2': 'AX-矩阵',
  'footer.product3': '启动平台',
  'footer.product4': '流动性市场',
  'footer.product5': '代币工厂',
  'footer.resources': '资源',
  'footer.resource1': '文档',
  'footer.resource2': '常见问题与支持',
  'footer.resource3': '信任与安全',
  'footer.resource4': '学习中心',
  'footer.resource5': '社区论坛',
  'footer.company': '公司',
  'footer.company1': '关于团队',
  'footer.company2': '职业机会',
  'footer.company3': '联系我们',
  'footer.company4': '新闻媒体',
  'footer.privacy': '隐私政策',
  'footer.terms': '服务条款',
  'footer.copyright': `© ${new Date().getFullYear()} ASSETX协议。保留所有权利。`,
} as const;

const enTranslations = {
  // Navbar
  'nav.product': 'Product',
  'nav.resource': 'Resource',
  'nav.community': 'Community',
  'nav.ecosystem': 'Ecosystem',
  'nav.launchApp': 'Launch App',

  // Hero Section
  'hero.badge': 'Powered By Nasdaq & HKEX Listed Partners',
  'hero.title1': 'Yield-Bearing Assets',
  'hero.title2': 'On Chain.',
  'hero.description': 'Access Yield-Bearing Asset like Equities, Real Estate, and Commercial Loans with low barriers. Enjoy 10%-30% APY backed by real assets.',
  'hero.startInvesting': 'Start Investing',
  'hero.readWhitepaper': 'Read Whitepaper',
  'hero.readDocs': 'Read Docs',

  // Stats Section
  'stats.tvl': 'Total Value Locked',
  'stats.apy': 'Avg. APY',
  'stats.yield': 'Yield Captured',
  'stats.users': 'Connected Users',

  // Trusted By Section
  'trusted.title': 'Trusted by Industry Leaders',

  // Why AssetX Section
  'why.title': 'Why ASSETX?',
  'why.subtitle': 'Institutional-grade access to real-world yield, with DeFi-native composability.',
  'why.sustainable.title': 'Sustainable Real Yield',
  'why.sustainable.desc': 'Access 15%-30% returns from Delta-neutral arbitrage strategies and commercial credit. No inflationary token emissions, just real profits.',
  'why.reliability.title': 'Proven Reliability',
  'why.reliability.desc': 'Backed by partners holding HK SFC Licenses (1/2/4/5/9) and NASDAQ-listed entities. Audited, compliant, and transparent.',
  'why.liquidity.title': 'Flexible Liquidity',
  'why.liquidity.desc': 'Solve the illiquidity of traditional finance. Enjoy instant exit via secondary markets or leverage your positions for up to 40% APY.',
  'why.liquidity.badge1': '40%+ APR',
  'why.liquidity.badge2': 'Instant Exit',

  // How It Works Section
  'how.title': 'How it works',
  'how.step1.title': 'Connect & Explore',
  'how.step1.desc': 'Browse Yield Tokens, compare yield/risk, and view key metrics.',
  'how.step2.title': 'Invest with USDC',
  'how.step2.desc': 'Buy Yield Tokens with USDC and earn real-world yield.',
  'how.step3.title': 'Use in DeFi',
  'how.step3.desc': 'Exit early via secondary markets, borrow against collateral, or provide liquidity to earn fees.',
  'how.simulator.title': 'Portfolio Overview Simulator',
  'how.simulator.invest': 'If you invest',
  'how.simulator.earn': 'You earn per year',

  // Security Section
  'security.title': 'Security First Architecture',
  'security.subtitle': 'Real-time data transparency with segregated asset management.',
  'security.audited.title': 'Audited',
  'security.audited.desc': 'Smart contracts audited by top-tier firms. Underlying assets undergo strict due diligence and financial auditing.',
  'security.segregated.title': 'Segregated',
  'security.segregated.desc': 'SPV Setup. User assets are held in segregated Special Purpose Vehicles, isolated from platform risks.',
  'security.transparency.title': 'Transparency',
  'security.transparency.desc': 'Real-Time NAV. Fund performance data and asset valuations are publicly available and updated on-chain.',
  'security.partners.title': 'Powered By NASDAQ & HKEX Listed Partners',

  // Footer
  'footer.products': 'Products',
  'footer.product1': 'AX-Fund',
  'footer.product2': 'AX-Matrix',
  'footer.product3': 'Launchpad',
  'footer.product4': 'Liquid Market',
  'footer.product5': 'Token Factory',
  'footer.resources': 'Resources',
  'footer.resource1': 'Docs',
  'footer.resource2': 'FAQ & Support',
  'footer.resource3': 'Trust & Security',
  'footer.resource4': 'Learning Center',
  'footer.resource5': 'Community Forum',
  'footer.company': 'Company',
  'footer.company1': 'About Team',
  'footer.company2': 'Careers',
  'footer.company3': 'Contact Us',
  'footer.company4': 'Press & Media',
  'footer.privacy': 'Privacy Policy',
  'footer.terms': 'Terms of Service',
  'footer.copyright': `© ${new Date().getFullYear()} ASSETX Protocol. All rights reserved.`,
} as const;

export type TranslationKey = keyof typeof enTranslations;

const translationMap: Record<Language, Record<TranslationKey, string>> = {
  zh: zhTranslations,
  en: enTranslations,
};

interface LanguageContextType {
  language: Language;
  setLanguage: (lang: Language) => void;
  t: (key: TranslationKey) => string;
}

const LanguageContext = createContext<LanguageContextType | undefined>(undefined);

export function LanguageProvider({ children }: { children: ReactNode }) {
  const [language, setLanguageState] = useState<Language>('en');

  const handleSetLanguage = useCallback((lang: Language) => {
    setLanguageState(prev => {
      if (lang === prev) return prev;
      return lang;
    });
  }, []);

  const translations = useMemo(() => translationMap[language], [language]);

  const t = useCallback(
    (key: TranslationKey): string => translations[key] || key,
    [translations]
  );

  const value = useMemo(
    () => ({ language, setLanguage: handleSetLanguage, t }),
    [language, handleSetLanguage, t]
  );

  return (
    <LanguageContext.Provider value={value}>
      {children}
    </LanguageContext.Provider>
  );
}

export function useLanguage() {
  const context = useContext(LanguageContext);
  if (!context) {
    throw new Error('useLanguage must be used within a LanguageProvider');
  }
  return context;
}
