import React from 'react';
import { translations, Language } from '../utils/translations';

interface LanguageContextType {
  language: Language;
  setLanguage: (lang: Language) => void;
  t: (key: keyof typeof translations['zh'], ...args: any[]) => string;
}

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

export const LanguageProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [language, setLanguage] = React.useState<Language>(() => {
    const saved = localStorage.getItem('userLanguage');
    const envDefault = (import.meta as any).env.VITE_DEFAULT_LANGUAGE as Language;
    return (saved as Language) || envDefault || 'en';
  });

  const handleSetLanguage = (lang: Language) => {
    setLanguage(lang);
    localStorage.setItem('userLanguage', lang);
  };

  const t = (key: keyof typeof translations['zh'], ...args: any[]) => {
    let str = translations[language][key] || key;
    if (args.length > 0) {
      args.forEach((arg, i) => {
        str = str.replace(new RegExp(`\\$${i + 1}`, 'g'), String(arg));
      });
    }
    return str;
  };

  return React.createElement(
    LanguageContext.Provider,
    { value: { language, setLanguage: handleSetLanguage, t } },
    children
  );
};

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