import React, { createContext, useContext, useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { loadFrappeTranslations } from '../i18n';

type Language = 'en' | 'ar';

interface LanguageContextType {
  language: Language;
  changeLanguage: (lang: Language) => Promise<void>;
  isRTL: boolean;
}

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

export const LanguageProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { i18n } = useTranslation();
  const [language, setLanguage] = useState<Language>(() => {
    const saved = localStorage.getItem('i18nextLng') as Language;
    return saved === 'ar' ? 'ar' : 'en';
  });

  const isRTL = language === 'ar';

  // Apply language and RTL on mount and when it changes
  useEffect(() => {
    const root = document.documentElement;
    const html = document.documentElement;
    
    // Update i18n language
    i18n.changeLanguage(language);
    
    // Update HTML lang attribute
    html.setAttribute('lang', language);
    
    // Update HTML dir attribute for RTL
    if (isRTL) {
      html.setAttribute('dir', 'rtl');
      root.classList.add('rtl');
      root.classList.remove('ltr');
    } else {
      html.setAttribute('dir', 'ltr');
      root.classList.add('ltr');
      root.classList.remove('rtl');
    }
  }, [language, i18n, isRTL]);

  const changeLanguage = async (lang: Language) => {
    setLanguage(lang);
    localStorage.setItem('i18nextLng', lang);
    // Reload translations from Frappe when language changes
    await loadFrappeTranslations();
  };

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

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


