'use client';

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

type Language = 'zh' | 'en';

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

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

export function LanguageProvider({ children }: { children: ReactNode }) {
  // 默认语言为英文
  const [language, setLanguage] = useState<Language>('en');
  const [transitionKey, setTransitionKey] = useState(0);
  const [pendingLanguage, setPendingLanguage] = useState<Language | null>(null);

  // 监听 pendingLanguage，延迟切换语言
  useEffect(() => {
    if (pendingLanguage !== null) {
      // 延迟 300ms 切换语言，此时蒙版已经完全覆盖
      const timer = setTimeout(() => {
        setLanguage(pendingLanguage);
        setPendingLanguage(null);
      }, 300);
      return () => clearTimeout(timer);
    }
  }, [pendingLanguage]);

  // 切换语言
  const handleSetLanguage = (lang: Language) => {
    if (lang === language) return; // 如果语言相同，不执行切换

    // 先递增transitionKey触发动画
    setTransitionKey(prev => prev + 1);

    // 设置待切换的语言，稍后才真正切换
    setPendingLanguage(lang);
  };

  // 简单的翻译函数
  const t = (key: string): string => {
    const translations = getTranslations(language);
    return translations[key] || key;
  };

  return (
    <LanguageContext.Provider value={{ language, setLanguage: handleSetLanguage, t, transitionKey }}>
      {children}
    </LanguageContext.Provider>
  );
}

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

// 翻译内容
function getTranslations(lang: Language): Record<string, string> {
  const translations = {
    zh: {
      // Navbar
      'nav.product': '产品',
      'nav.resource': '资源',
      'nav.community': '社区',
      'nav.launchApp': '启动应用',

      // Hero Section
      'hero.title1': '链上收益资产',
      'hero.title2': '随时可得',
      'hero.description': '低门槛投资股票、房地产和商业贷款等收益资产。享受真实资产支持的10%-30%年化收益。',
      'hero.startInvesting': '开始投资',
      'hero.readWhitepaper': '阅读白皮书',

      // 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': '存入并铸造WUSD',
      'how.step1.desc': '连接您的钱包并存入USDC兑换WUSD。这是整个AssetX生态系统的原生稳定币和入口。',
      'how.step2.title': '双重投资选择',
      'how.step2.desc': '选择您的策略：使用WUSD购买特定的收益资产以获得现实世界回报，或在DeFi池中提供流动性赚取交易费用。',
      'how.step3.title': '赚取与提升',
      'how.step3.desc': '获得每日收益分配。使用资产代币作为抵押品借入WUSD，利用高达2.5倍的杠杆实现收益最大化。',
      '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': '© 2025 ASSETX协议。保留所有权利。',
    },
    en: {
      // Navbar
      'nav.product': 'Product',
      'nav.resource': 'Resource',
      'nav.community': 'Community',
      'nav.launchApp': 'Launch App',

      // Hero Section
      'hero.title1': 'Yield-Bearing Asset',
      '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 the Whitepaper',

      // 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': 'Deposit & Mint WUSD',
      'how.step1.desc': 'Connect your wallet and deposit USDC to swap WUSD. This serves as the native stablecoin and gateway to the entire AssetX ecosystem.',
      'how.step2.title': 'Dual Investment Options',
      'how.step2.desc': 'Choose your strategy: use WUSD to purchase specific Yield-Bearing Assets for real-world returns, or provide liquidity in DeFi Pools to earn trading fees.',
      'how.step3.title': 'Earn & Boost',
      'how.step3.desc': 'Receive daily yield distributions. Use Asset Tokens as collateral to borrow WUSD and leverage up to 2.5x for maximized returns.',
      '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': '© 2025 ASSETX Protocol. All rights reserved.',
    }
  };

  return translations[lang];
}
