import { createContext, useCallback, useEffect, useState, type ReactNode } from 'react'
import ko from './ko.ts'
import en from './en.ts'

export type Locale = 'ko' | 'en'
export type TranslationKey = keyof typeof ko

const TRANSLATIONS: Record<Locale, Record<string, string>> = { ko, en }
const STORAGE_KEY = 'sb-locale'

function getInitialLocale(): Locale {
  const stored = localStorage.getItem(STORAGE_KEY)
  if (stored === 'ko' || stored === 'en') return stored
  const browserLang = navigator.language.slice(0, 2)
  return browserLang === 'ko' ? 'ko' : 'en'
}

interface I18nContextValue {
  locale: Locale
  setLocale: (locale: Locale) => void
  toggleLocale: () => void
  t: (key: TranslationKey) => string
}

export const I18nContext = createContext<I18nContextValue>({
  locale: 'ko',
  setLocale: () => {},
  toggleLocale: () => {},
  t: (key) => key,
})

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

  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, locale)
    document.documentElement.lang = locale
  }, [locale])

  const setLocale = useCallback((l: Locale) => setLocaleState(l), [])

  const toggleLocale = useCallback(() => {
    setLocaleState(prev => (prev === 'ko' ? 'en' : 'ko'))
  }, [])

  const t = useCallback(
    (key: TranslationKey): string => TRANSLATIONS[locale][key] ?? key,
    [locale],
  )

  return (
    <I18nContext value={{ locale, setLocale, toggleLocale, t }}>
      {children}
    </I18nContext>
  )
}
