"use client"

import { createContext, useContext, useState, useCallback, useEffect, type ReactNode } from "react"
import { dictionaries, type Locale, type Dictionary } from "./dictionaries"

type LocaleContextType = {
  locale: Locale
  t: Dictionary
  setLocale: (locale: Locale) => void
  toggleLocale: () => void
}

const LocaleContext = createContext<LocaleContextType | null>(null)

export function LocaleProvider({ children }: { children: ReactNode }) {
  const [locale, setLocaleState] = useState<Locale>("tr")

  useEffect(() => {
    const saved = localStorage.getItem("derindevlet-locale")
    if (saved === "tr" || saved === "en") {
      setLocaleState(saved)
    }
  }, [])

  const setLocale = useCallback((newLocale: Locale) => {
    setLocaleState(newLocale)
    localStorage.setItem("derindevlet-locale", newLocale)
  }, [])

  const toggleLocale = useCallback(() => {
    setLocaleState((prev) => {
      const next = prev === "tr" ? "en" : "tr"
      localStorage.setItem("derindevlet-locale", next)
      return next
    })
  }, [])

  return (
    <LocaleContext.Provider value={{ locale, t: dictionaries[locale], setLocale, toggleLocale }}>
      {children}
    </LocaleContext.Provider>
  )
}

export function useLocale() {
  const context = useContext(LocaleContext)
  if (!context) {
    throw new Error("useLocale must be used within a LocaleProvider")
  }
  return context
}
