'use client';

import { useLocale } from 'next-intl';
import { useRouter, usePathname } from 'next/navigation';
import { useTransition } from 'react';
import { Globe } from 'lucide-react';
import styles from '../layout/Navbar.module.css';

export default function LanguageSwitcher() {
    const locale = useLocale();
    const router = useRouter();
    const pathname = usePathname();
    const [isPending, startTransition] = useTransition();

    const toggleLanguage = () => {
        const nextLocale = locale === 'en' ? 'vi' : 'en';

        // EN: Remove current locale from pathname and add new locale
        // VI: Xóa locale hiện tại khỏi pathname và thêm locale mới
        const currentPath = pathname.replace(`/${locale}`, '') || '';

        startTransition(() => {
            router.replace(`/${nextLocale}${currentPath}`);
        });
    };

    return (
        <button
            onClick={toggleLanguage}
            className={styles.link}
            disabled={isPending}
            aria-label={`Switch to ${locale === 'en' ? 'Vietnamese' : 'English'}`}
            style={{
                display: 'flex',
                alignItems: 'center',
                gap: '0.5rem',
                background: 'none',
                border: 'none',
                cursor: 'pointer'
            }}
        >
            <Globe size={16} />
            <span>{locale === 'en' ? 'VI' : 'EN'}</span>
        </button>
    );
}

