import { createContext, useContext, useState, useEffect, type ReactNode } from 'react';
import { en, type TextConfig } from '../config/locales/en';
import { de } from '../config/locales/de';
import type { Language } from '../data/types';

interface LanguageContextType {
  language: Language;
  setLanguage: (lang: Language) => void;
  texts: TextConfig;
}

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

/** Derive the language from the URL pathname prefix (/en/… or /de/…). */
export function getLanguageFromPath(pathname: string): Language | null {
  if (pathname.startsWith('/en')) return 'en';
  if (pathname.startsWith('/de')) return 'de';
  return null;
}

export function LanguageProvider({ initialLanguage = 'de', children }: Readonly<{ initialLanguage?: Language; children: ReactNode; }>) {
  const [language, setLanguage] = useState<Language>(initialLanguage);

  const texts = language === 'de' ? de : en;

  const handleSetLanguage = (lang: Language) => {
    setLanguage(lang);
    document.documentElement.lang = lang;
  };

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

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

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