'use client';

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { de } from './de';
import { en } from './en';
import { TranslationKeys } from './types';

type Locale = 'de' | 'en';

interface I18nContextType {
    locale: Locale;
    setLocale: (locale: Locale) => void;
    t: (path: string) => string;
}

const translations: Record<Locale, TranslationKeys> = { de, en };

const I18nContext = createContext<I18nContextType | undefined>(undefined);

export const I18nProvider = ({ children }: { children: ReactNode }) => {
    const [locale, setLocaleState] = useState<Locale>('de');

    useEffect(() => {
        const savedLocale = localStorage.getItem('locale') as Locale;
        if (savedLocale && (savedLocale === 'de' || savedLocale === 'en')) {
            setLocaleState(savedLocale);
        } else {
            // Try to detect browser language
            const browserLang = navigator.language.split('-')[0];
            if (browserLang === 'en') {
                setLocaleState('en');
            }
        }
    }, []);

    const setLocale = (newLocale: Locale) => {
        setLocaleState(newLocale);
        localStorage.setItem('locale', newLocale);
    };

    const t = (path: string): string => {
        const keys = path.split('.');
        let current: any = translations[locale];

        for (const key of keys) {
            if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
                console.warn(`Blocked potentially malicious translation key: ${key}`);
                return path;
            }
            if (current[key] === undefined) {
                console.warn(`Translation missing for key: ${key} in path: ${path} in locale: ${locale}`);
                return path;
            }
            current = current[key];
        }

        return current;
    };

    return (
        <I18nContext.Provider value={{ locale, setLocale, t }}>
            {children}
        </I18nContext.Provider>
    );
};

export const useI18n = () => {
    const context = useContext(I18nContext);
    if (!context) {
        throw new Error('useI18n must be used within an I18nProvider');
    }
    return context;
};
