import { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { getTranslation, interpolate, pluralize, defaultLanguage } from '../i18n';

const LanguageContext = createContext(null);

export function LanguageProvider({ children }) {
  const [language, setLanguageState] = useState(() => {
    return localStorage.getItem('language') || defaultLanguage;
  });

  useEffect(() => {
    localStorage.setItem('language', language);
    document.documentElement.setAttribute('lang', language);
  }, [language]);

  const setLanguage = useCallback((lang) => {
    setLanguageState(lang);
  }, []);

  // t('auth.login') -> translated string
  // t('dashboard.roomCount', { count: 5 }) -> with interpolation
  const t = useCallback((key, params) => {
    const raw = getTranslation(language, key);
    if (params && params.count !== undefined) {
      return pluralize(raw, params.count);
    }
    if (params) {
      return interpolate(raw, params);
    }
    return raw;
  }, [language]);

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

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