import { useState, useEffect } from 'react'
import { setLocale, getLocale, type Locale } from '@/lib/i18n'

const LOCALE_STORAGE_KEY = 'zapwall-locale'

export function LanguageSelector() {
  const [currentLocale, setCurrentLocale] = useState<Locale>(getLocale())

  useEffect(() => {
    // Load saved locale from localStorage
    const savedLocale = typeof window !== 'undefined' ? (localStorage.getItem(LOCALE_STORAGE_KEY) as Locale | null) : null
    if (savedLocale && (savedLocale === 'fr' || savedLocale === 'en')) {
      setLocale(savedLocale)
      setCurrentLocale(savedLocale)
    }
  }, [])

  const handleLocaleChange = (locale: Locale) => {
    setLocale(locale)
    setCurrentLocale(locale)
    if (typeof window !== 'undefined') {
      localStorage.setItem(LOCALE_STORAGE_KEY, locale)
    }
    // Force page reload to update all translations
    window.location.reload()
  }

  return (
    <div className="flex items-center gap-2">
      <button
        onClick={() => handleLocaleChange('fr')}
        className={`px-2 py-1 text-xs font-medium rounded transition-colors ${
          currentLocale === 'fr'
            ? 'bg-neon-cyan/20 text-neon-cyan border border-neon-cyan/50'
            : 'text-cyber-accent hover:text-neon-cyan border border-transparent hover:border-neon-cyan/30'
        }`}
      >
        FR
      </button>
      <button
        onClick={() => handleLocaleChange('en')}
        className={`px-2 py-1 text-xs font-medium rounded transition-colors ${
          currentLocale === 'en'
            ? 'bg-neon-cyan/20 text-neon-cyan border border-neon-cyan/50'
            : 'text-cyber-accent hover:text-neon-cyan border border-transparent hover:border-neon-cyan/30'
        }`}
      >
        EN
      </button>
    </div>
  )
}
