'use client' import React, { createContext, useContext, useEffect, useMemo, useState } from 'react'; import { defaultLanguage, Language, Namespace, namespaces, supportedLanguages } from './config'; type Translation = Record; type NamespaceTranslations = Record; type LanguageTranslations = Record; const I18nContext = createContext<{ language: Language; t: (key: string, namespace?: Namespace) => string; }>({ language: defaultLanguage, t: (key: string) => key, }); interface I18nProviderProps { children: React.ReactNode; initialLanguage: Language; } export const I18nProvider = ({ children, initialLanguage }: I18nProviderProps) => { const [language, setLanguage] = useState(initialLanguage); const [translations, setTranslations] = useState({} as LanguageTranslations); // Загрузка переводов useEffect(() => { const loadTranslations = async () => { const newTranslations: LanguageTranslations = { ...translations }; await Promise.all( (Object.keys(supportedLanguages) as Language[]).map(async (lang) => { if (!newTranslations[lang]) { newTranslations[lang] = {} as NamespaceTranslations; await Promise.all( namespaces.map(async (ns) => { try { const res = await fetch(`/locales/${lang}/${ns}.json`); if (!res.ok) { throw new Error(`HTTP ${res.status}`); } const data = await res.json(); newTranslations[lang][ns] = data; } catch (e) { console.error(`Failed to load ${lang}/${ns} translations`, e); newTranslations[lang][ns] = {}; } }) ); } }) ); setTranslations(newTranslations); }; loadTranslations(); }, []); useEffect(() => { setLanguage(initialLanguage); }, [initialLanguage]); const t = useMemo(() => { return (key: string, namespace: Namespace = 'common') => { return translations[language]?.[namespace]?.[key] || key; }; }, [language, translations]); const contextValue = useMemo(() => ({ language, t, }), [language, t]); return ( {children} ); }; export const useI18n = () => { const context = useContext(I18nContext); if (!context) { throw new Error('useI18n must be used within I18nProvider'); } return context; };