'use client'

import { createContext, useContext, useState, useCallback, useEffect, ReactNode } from 'react'

type Language = 'de' | 'en'
type Theme = 'dark' | 'light'

interface AppContextType {
  lang: Language
  theme: Theme
  toggleLang: () => void
  toggleTheme: () => void
}

const AppContext = createContext<AppContextType>({
  lang: 'de',
  theme: 'dark',
  toggleLang: () => {},
  toggleTheme: () => {},
})

export function AppProvider({ children }: { children: ReactNode }) {
  const [lang, setLang] = useState<Language>('de')
  const [theme, setTheme] = useState<Theme>('dark')

  const toggleLang = useCallback(() => {
    setLang(prev => prev === 'de' ? 'en' : 'de')
  }, [])

  const toggleTheme = useCallback(() => {
    setTheme(prev => {
      const next = prev === 'dark' ? 'light' : 'dark'
      document.documentElement.classList.toggle('theme-light', next === 'light')
      return next
    })
  }, [])

  useEffect(() => {
    document.documentElement.classList.toggle('theme-light', theme === 'light')
  }, [theme])

  return (
    <AppContext.Provider value={{ lang, theme, toggleLang, toggleTheme }}>
      {children}
    </AppContext.Provider>
  )
}

export function useApp() {
  return useContext(AppContext)
}
