import { useTranslation } from 'react-i18next'
import './LanguageSelector.css'

const languages = [
    { code: 'en', name: 'English', flag: '🇬🇧' },
    { code: 'es', name: 'Español', flag: '🇪🇸' }
]

function LanguageSelector() {
    const { i18n } = useTranslation()

    const changeLanguage = (langCode: string) => {
        i18n.changeLanguage(langCode)
        // Reload page to ensure all components refresh with new language
        // This is necessary because some data comes from API and won't update without refetch
        window.location.reload()
    }

    const currentLang = languages.find(l => l.code === i18n.language) || languages[0]

    return (
        <div className="language-selector">
            <button className="language-btn">
                <span className="lang-flag">{currentLang.flag}</span>
                <span className="lang-code">{currentLang.code.toUpperCase()}</span>
            </button>
            <div className="language-dropdown">
                {languages.map(lang => (
                    <button
                        key={lang.code}
                        className={`lang-option ${i18n.language === lang.code ? 'active' : ''}`}
                        onClick={() => changeLanguage(lang.code)}
                    >
                        <span className="lang-flag">{lang.flag}</span>
                        <span className="lang-name">{lang.name}</span>
                    </button>
                ))}
            </div>
        </div>
    )
}

export default LanguageSelector
