"use client"

import React, { createContext, useContext, useState, useEffect } from "react"
import { translations } from "./translations"

type Language = "hu" | "en"

interface LanguageContextType {
    language: Language
    setLanguage: (lang: Language) => void
    t: any
}

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

export const LanguageProvider = ({ children }: { children: React.ReactNode }) => {
    const [language, setLanguage] = useState<Language>("hu")
    const [isInitialized, setIsInitialized] = useState(false)

    useEffect(() => {
        // 1. Check local storage
        const savedLang = localStorage.getItem("language") as Language
        if (savedLang && (savedLang === "hu" || savedLang === "en")) {
            setLanguage(savedLang)
        } else {
            // 2. Check browser language
            const browserLang = navigator.language.split("-")[0]
            if (browserLang === "hu" || browserLang === "en") {
                setLanguage(browserLang as Language)
            }
        }
        setIsInitialized(true)
    }, [])

    const handleSetLanguage = (lang: Language) => {
        setLanguage(lang)
        localStorage.setItem("language", lang)
        document.documentElement.lang = lang
    }

    const t = translations[language]

    return (
        <LanguageContext.Provider value={{ language, setLanguage: handleSetLanguage, t }}>
            {isInitialized ? children : <div className="opacity-0">{children}</div>}
        </LanguageContext.Provider>
    )
}

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