'use client'

import { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import {
  Language,
  defaultLanguage,
  getStoredLanguage,
  setStoredLanguage,
  translations,
  availableLanguages,
  isRTL,
} from './i18n'

interface LanguageContextType {
  language: Language
  setLanguage: (lang: Language) => void
  t: (key: string) => string
  isRTL: boolean
  availableLanguages: typeof availableLanguages
}

const LanguageContext = createContext<LanguageContextType | null>(null)

export function LanguageProvider({ children }: { children: ReactNode }) {
  const [language, setLanguageState] = useState<Language>(defaultLanguage)
  const [mounted, setMounted] = useState(false)

  // Nach dem ersten Render: Sprache aus localStorage laden
  useEffect(() => {
    const stored = getStoredLanguage()
    setLanguageState(stored)
    setMounted(true)
  }, [])

  // Sprache setzen und speichern
  const setLanguage = (lang: Language) => {
    setLanguageState(lang)
    setStoredLanguage(lang)
    // Optional: document.dir fuer RTL setzen
    if (typeof document !== 'undefined') {
      document.documentElement.dir = isRTL(lang) ? 'rtl' : 'ltr'
      document.documentElement.lang = lang
    }
  }

  // Uebersetzungsfunktion
  const t = (key: string): string => {
    return translations[language][key] || translations[defaultLanguage][key] || key
  }

  // Waehrend SSR: Default anzeigen
  if (!mounted) {
    return (
      <LanguageContext.Provider
        value={{
          language: defaultLanguage,
          setLanguage: () => {},
          t: (key) => translations[defaultLanguage][key] || key,
          isRTL: false,
          availableLanguages,
        }}
      >
        {children}
      </LanguageContext.Provider>
    )
  }

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

// Hook fuer einfache Verwendung
export function useLanguage() {
  const context = useContext(LanguageContext)
  if (!context) {
    throw new Error('useLanguage must be used within a LanguageProvider')
  }
  return context
}
