import { createContext, useContext, useState, useEffect } from 'react'
import { api } from '../utils/api'
import en from './en.json'
import ar from './ar.json'

const translations = { en, ar }

export const CURRENCIES = [
  { code: 'SAR', symbol: '⃁', labelEn: 'Saudi Riyal (SAR)', labelAr: 'ريال سعودي' },
  { code: 'AED', symbol: 'د.إ', labelEn: 'UAE Dirham (AED)', labelAr: 'درهم إماراتي' },
  { code: 'USD', symbol: '$', labelEn: 'US Dollar (USD)', labelAr: 'دولار أمريكي' },
  { code: 'EUR', symbol: '€', labelEn: 'Euro (EUR)', labelAr: 'يورو' },
  { code: 'GBP', symbol: '£', labelEn: 'British Pound (GBP)', labelAr: 'جنيه إسترليني' },
  { code: 'KWD', symbol: 'د.ك', labelEn: 'Kuwaiti Dinar (KWD)', labelAr: 'دينار كويتي' },
  { code: 'QAR', symbol: 'ر.ق', labelEn: 'Qatari Riyal (QAR)', labelAr: 'ريال قطري' },
  { code: 'BHD', symbol: 'د.ب', labelEn: 'Bahraini Dinar (BHD)', labelAr: 'دينار بحريني' },
  { code: 'OMR', symbol: 'ر.ع', labelEn: 'Omani Rial (OMR)', labelAr: 'ريال عماني' },
  { code: 'EGP', symbol: 'ج.م', labelEn: 'Egyptian Pound (EGP)', labelAr: 'جنيه مصري' },
]

const LanguageContext = createContext()

export function LanguageProvider({ children }) {
  const [lang, setLangState] = useState(() => {
    // Load from localStorage or default to 'en'
    return localStorage.getItem('digitalhub-lang') || 'en'
  })

  const [currency, setCurrencyState] = useState(() => {
    return localStorage.getItem('digitalhub-currency') || 'SAR'
  })

  const setLang = (newLang) => {
    if (newLang !== 'en' && newLang !== 'ar') return
    setLangState(newLang)
    localStorage.setItem('digitalhub-lang', newLang)
    api.patch('/api/users/me/language', { language: newLang }).catch(() => {})
  }

  const setCurrency = (code) => {
    const valid = CURRENCIES.find(c => c.code === code)
    if (!valid) return
    setCurrencyState(code)
    localStorage.setItem('digitalhub-currency', code)
  }

  const currencyObj = CURRENCIES.find(c => c.code === currency) || CURRENCIES[0]
  const currencySymbol = currencyObj.symbol

  const dir = lang === 'ar' ? 'rtl' : 'ltr'

  // Update HTML dir attribute whenever language changes
  useEffect(() => {
    document.documentElement.dir = dir
    document.documentElement.lang = lang
  }, [dir, lang])

  // Translation function (flat dot-notation keys)
  const t = (key) => {
    return translations[lang]?.[key] ?? translations.en?.[key] ?? key
  }

  return (
    <LanguageContext.Provider value={{ lang, setLang, t, dir, currency, setCurrency, currencySymbol }}>
      {children}
    </LanguageContext.Provider>
  )
}

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