'use client';

import { createContext, useContext, useState, useCallback, type ReactNode } from 'react';
import deMessages from '@/messages/de.json';
import enMessages from '@/messages/en.json';

export type Locale = 'de' | 'en';

interface Messages {
  [key: string]: string;
}

const messageMap: Record<Locale, Messages> = {
  de: deMessages as Messages,
  en: enMessages as Messages,
};

interface I18nContextValue {
  locale: Locale;
  setLocale: (locale: Locale) => void;
  t: (key: string, params?: Record<string, string>) => string;
}

const I18nContext = createContext<I18nContextValue | null>(null);

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

  const setLocale = useCallback((newLocale: Locale) => {
    setLocaleState(newLocale);
    if (typeof document !== 'undefined') {
      document.documentElement.lang = newLocale;
    }
  }, []);

  const t = useCallback((key: string, params?: Record<string, string>) => {
    const messages = messageMap[locale];
    let message = messages[key] || key;
    if (params) {
      for (const [param, value] of Object.entries(params)) {
        message = message.replace(new RegExp(`\{${param}\}`, 'g'), value);
      }
    }
    return message;
  }, [locale]);

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

export function useI18n(): I18nContextValue {
  const ctx = useContext(I18nContext);
  if (!ctx) {
    throw new Error('useI18n must be used within I18nProvider');
  }
  return ctx;
}
