import {useEffect, useState} from 'react';
import {useTranslation} from 'react-i18next';

function LanguageSwitcher() {
    const {i18n} = useTranslation();
    const [margin, setMargin] = useState(0);
    const [language, setLanguage] = useState(() => {
        return localStorage.getItem('language') || 'zh'; // 从 localStorage 初始化
    });

    useEffect(() => {
        i18n.changeLanguage(language);
        localStorage.setItem('language', language); // 保存到 localStorage
    }, [language, i18n]);

    useEffect(() => {
        changeMargin()
    }, []);

    useEffect(() => {
        const handleResize = () => {
            changeMargin()
        };

        window.addEventListener('resize', handleResize);

        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, []);

    const changeMargin = () => {
        switch (window.location.pathname) {
            case "/home/":
            case "/help/":
                setMargin((window.innerWidth - 228) * 0.05);
                break;
            default:
                setMargin((window.innerWidth - 418) / 2);
                break;
        }
    }

    const changeLanguage = () => {
        const newLanguage = language === 'zh' ? 'en' : 'zh';
        setLanguage(newLanguage);
    };

    return (
        <button style={{position: "absolute", top: 0, right: margin, zIndex: 100}} onClick={changeLanguage}>
            {language === "zh" ? "English" : "中文"}
        </button>
    );
}

export default LanguageSwitcher;