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

type Language = 'pt-br' | 'en' | 'es';

interface LanguageContextType {
  lang: Language;
  setLang: (lang: Language) => void;
  translate: (text: any, context?: string, isObject?: boolean) => Promise<any>;
  isTranslating: boolean;
}

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

export const LanguageProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [lang, setLang] = useState<Language>(() => {
    const saved = localStorage.getItem('app-lang');
    return (saved as Language) || 'pt-br';
  });

  useEffect(() => {
    localStorage.setItem('app-lang', lang);
    document.documentElement.lang = lang;

    // Trigger Google Translate Widget
    const triggerGoogleTranslate = () => {
      const select = document.querySelector('.goog-te-combo') as HTMLSelectElement;
      if (select) {
        const googleLangCode = lang === 'pt-br' ? 'pt' : lang;
        select.value = googleLangCode;
        select.dispatchEvent(new Event('change'));
      }
    };

    // Delay a bit to ensure the widget is loaded
    const timer = setTimeout(triggerGoogleTranslate, 1000);
    return () => clearTimeout(timer);
  }, [lang]);

  return (
    <LanguageContext.Provider value={{ lang, setLang, translate: async (t) => t, isTranslating: false }}>
      {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;
};
