'use client';

import { createContext, type ReactNode, useEffect, useState } from 'react';

import enTranslations from '../locales/en.json';
import ruTranslations from '../locales/ru.json';

// Define available languages
export const languages = {
  en: { name: 'English', flag: '🇬🇧' },
  ru: { name: 'Русский', flag: '🇷🇺' },
};

export type Language = keyof typeof languages;

// Define translations type with flat structure
export type Translations = Record<string, string>;

// Load translations
const translations: Record<Language, Translations> = {
  en: enTranslations,
  ru: ruTranslations,
};

// Create context
type LanguageContextType = {
  language: Language;
  setLanguage: (lang: Language) => void;
  t: (key: string) => string;
};

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

// Create provider
export function LanguageProvider({ children }: { children: ReactNode }) {
  // Default to Russian, but check localStorage on client
  const [language, setLanguageState] = useState<Language>('ru');

  useEffect(() => {
    // Check if we're in the browser
    if (typeof window !== 'undefined') {
      const savedLanguage = localStorage.getItem('language') as Language;
      if (savedLanguage && languages[savedLanguage]) {
        setLanguageState(savedLanguage);
      }
    }
  }, []);

  const setLanguage = (lang: Language) => {
    setLanguageState(lang);
    if (typeof window !== 'undefined') {
      localStorage.setItem('language', lang);
    }
  };

  // Translation function for flat structure
  const t = (key: string): string => {
    if (translations[language][key]) {
      return translations[language][key];
    }

    console.warn(`Translation key not found: ${key}`);
    return key;
  };

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