import React, { createContext, useContext, useState, useEffect } from 'react';
import { translations, Language, TranslationKey } from '../lib/translations';
import { detectLanguageByIP } from '../lib/ipLocation';
import { updatePageMeta } from '../lib/seoHelper';

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

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

export const LanguageProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  // 初始化语言：优先使用 localStorage，否则使用浏览器语言作为临时值
  const [language, setLanguageState] = useState<Language>(() => {
    const saved = localStorage.getItem('language');
    if (saved === 'en' || saved === 'zh') return saved;
    // 临时使用浏览器语言，后续会被IP检测覆盖（如果没有保存的语言）
    return navigator.language.startsWith('zh') ? 'zh' : 'en';
  });

  // 检测IP地理位置并设置语言（仅在首次加载且没有保存的语言时）
  useEffect(() => {
    const saved = localStorage.getItem('language');
    
    // 如果用户已经手动选择过语言，则不进行IP检测
    if (saved === 'en' || saved === 'zh') {
      updatePageMeta(saved); // Update meta tags on initial load
      return;
    }

    // 异步检测IP并设置语言
    detectLanguageByIP()
      .then((detectedLang) => {
        setLanguageState(detectedLang);
        updatePageMeta(detectedLang); // Update meta tags after detection
        // 注意：这里不保存到 localStorage，让用户首次访问时使用IP检测的结果
        // 如果用户手动切换语言，才会保存到 localStorage
      })
      .catch((error) => {
        // IP检测失败时，保持使用浏览器语言检测的结果
        console.warn('Failed to detect language by IP:', error);
        updatePageMeta(language); // Update with fallback language
      });
  }, []); // 仅在组件挂载时执行一次

  const setLanguage = (lang: Language) => {
    setLanguageState(lang);
    localStorage.setItem('language', lang);
    updatePageMeta(lang); // Update page metadata when language changes
  };

  const t = translations[language];

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

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