'use client';

import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react';
import { translations, type Locale, type Translation } from '@/i18n';

// 数据库内容的类型
interface DbContent {
  zh: string;
  ru: string;
}

interface LanguageContextType {
  locale: Locale;
  t: Translation;
  setLocale: (locale: Locale) => void;
  dbContent: Record<string, DbContent>;
  getDbContent: (key: string) => string;
  isLoadingDb: boolean;
}

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

const STORAGE_KEY = 'xinqi-locale';

export function LanguageProvider({ children }: { children: ReactNode }) {
  const [locale, setLocaleState] = useState<Locale>('zh');
  const [dbContent, setDbContent] = useState<Record<string, DbContent>>({});
  const [isLoadingDb, setIsLoadingDb] = useState(true);

  // 初始化时从 localStorage 读取语言设置
  useEffect(() => {
    const savedLocale = localStorage.getItem(STORAGE_KEY) as Locale | null;
    if (savedLocale && (savedLocale === 'zh' || savedLocale === 'ru')) {
      setLocaleState(savedLocale);
    } else {
      // 尝试从浏览器语言检测
      const browserLang = navigator.language.toLowerCase();
      if (browserLang.startsWith('ru')) {
        setLocaleState('ru');
      } else {
        setLocaleState('zh');
      }
    }
  }, []);

  // 获取数据库中的多语言内容
  useEffect(() => {
    const fetchDbContent = async () => {
      try {
        const response = await fetch('/api/i18n');
        const data = await response.json();
        if (data.success && data.content) {
          setDbContent(data.content);
        }
      } catch (error) {
        console.error('Error fetching i18n content:', error);
      } finally {
        setIsLoadingDb(false);
      }
    };

    fetchDbContent();
  }, []);

  const setLocale = useCallback((newLocale: Locale) => {
    setLocaleState(newLocale);
    localStorage.setItem(STORAGE_KEY, newLocale);
    // 更新 HTML lang 属性
    document.documentElement.lang = newLocale;
  }, []);

  // 从数据库获取内容，如果没有则返回空字符串
  const getDbContent = useCallback((key: string): string => {
    const content = dbContent[key];
    if (!content) return '';
    return locale === 'zh' ? content.zh : content.ru;
  }, [dbContent, locale]);

  const value: LanguageContextType = {
    locale,
    t: translations[locale],
    setLocale,
    dbContent,
    getDbContent,
    isLoadingDb,
  };

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

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

// 导出一个便捷的 hook 用于获取翻译
export function useTranslation() {
  const { t, locale, setLocale, getDbContent, dbContent, isLoadingDb } = useLanguage();
  return { t, locale, setLocale, getDbContent, dbContent, isLoadingDb };
}
