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

const LangContext = createContext({ lang: 'fr', toggle: () => {}, setLang: () => {} })

function readInitialLang() {
  try {
    const stored = localStorage.getItem('mk_lang')
    if (stored === 'fr' || stored === 'en') return stored
  } catch (e) {
    /* ignore */
  }
  return 'fr'
}

export function LanguageProvider({ children }) {
  const [lang, setLangState] = useState(readInitialLang)

  const setLang = useCallback((next) => {
    setLangState(next)
    try {
      localStorage.setItem('mk_lang', next)
    } catch (e) {
      /* ignore */
    }
  }, [])

  const toggle = useCallback(() => {
    setLang(lang === 'fr' ? 'en' : 'fr')
  }, [lang, setLang])

  // Keep <html lang> in sync for accessibility.
  useEffect(() => {
    document.documentElement.lang = lang
  }, [lang])

  return (
    <LangContext.Provider value={{ lang, toggle, setLang }}>{children}</LangContext.Provider>
  )
}

export function useLang() {
  return useContext(LangContext)
}
