'use client'

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

interface LocaleContextValue {
  activeLocale: string
  setLocale: (locale: string) => void
  locales: Array<{ code: string; label: string; dir?: 'ltr' | 'rtl' }>
}

const LocaleContext = createContext<LocaleContextValue>({
  activeLocale: 'en',
  setLocale: () => {},
  locales: [],
})

export function useLocale() {
  return useContext(LocaleContext)
}

const STORAGE_KEY = 'actuate-locale'

export interface LocaleProviderProps {
  config: {
    i18n?: {
      defaultLocale: string
      locales: Array<{ code: string; label: string; dir?: 'ltr' | 'rtl' }>
      fallbackLocale?: string
    }
  }
  children: ReactNode
}

export function LocaleProvider({ config, children }: LocaleProviderProps) {
  const locales = config.i18n?.locales ?? []
  const defaultLocale = config.i18n?.defaultLocale ?? 'en'

  const [activeLocale, setActiveLocale] = useState(defaultLocale)

  useEffect(() => {
    const stored = localStorage.getItem(STORAGE_KEY)
    if (stored && locales.some((l) => l.code === stored)) {
      setActiveLocale(stored)
    }
  }, [locales])

  const setLocale = useCallback((locale: string) => {
    setActiveLocale(locale)
    localStorage.setItem(STORAGE_KEY, locale)
  }, [])

  return (
    <LocaleContext.Provider value={{ activeLocale, setLocale, locales }}>
      {children}
    </LocaleContext.Provider>
  )
}
