/**
 * Language Context — provides the current admin language context across all pages.
 *
 * Uses the server-provided `languageConfig` from `boostbotAdmin` on initial load,
 * then syncs changes back via the languages REST endpoint (which sets a cookie).
 *
 * @since 1.2.0
 */

import { createContext, useContext, useState, useCallback, type ReactNode } from 'react'
import { languagesApi, type LanguageConfig } from '@/api/languages'

interface LanguageContextValue {
  /** Currently selected admin language code (e.g. 'he', 'en') */
  currentLanguage: string
  /** All enabled language codes */
  enabledLanguages: string[]
  /** Language code → native label map */
  labels: Record<string, string>
  /** Whether the current admin language is RTL */
  isRtl: boolean
  /** Whether more than one language is enabled */
  isMultilingual: boolean
  /** Switch the admin language context */
  setLanguage: (lang: string) => void
}

const LanguageContext = createContext<LanguageContextValue | null>(null)

function getInitialConfig(): LanguageConfig {
  const cfg = (window as any).boostbotAdmin?.languageConfig as LanguageConfig | undefined
  return cfg ?? { enabled: ['he'], current: 'he', is_rtl: true, labels: { he: 'עברית' } }
}

export function LanguageProvider({ children }: { children: ReactNode }) {
  const initial = getInitialConfig()

  const [currentLanguage, setCurrentLanguage] = useState(initial.current)
  const [enabledLanguages] = useState(initial.enabled)
  const [labels] = useState(initial.labels)
  const [isRtl, setIsRtl] = useState(initial.is_rtl)

  const setLanguage = useCallback((lang: string) => {
    if (!enabledLanguages.includes(lang)) return
    setCurrentLanguage(lang)
    const rtlLangs = ['he', 'ar', 'fa', 'ur']
    setIsRtl(rtlLangs.includes(lang))

    languagesApi.setCurrent(lang).catch(() => {
      // Cookie set failed — still allow local switch
    })
  }, [enabledLanguages])

  return (
    <LanguageContext.Provider
      value={{
        currentLanguage,
        enabledLanguages,
        labels,
        isRtl,
        isMultilingual: enabledLanguages.length > 1,
        setLanguage,
      }}
    >
      {children}
    </LanguageContext.Provider>
  )
}

export function useLanguage(): LanguageContextValue {
  const ctx = useContext(LanguageContext)
  if (!ctx) throw new Error('useLanguage must be used within LanguageProvider')
  return ctx
}
