68 lines
1.8 KiB
TypeScript
68 lines
1.8 KiB
TypeScript
'use client';
|
|
|
|
import Cookies from 'js-cookie';
|
|
import { usePathname, useRouter } from 'next/navigation';
|
|
import { useEffect, useState } from 'react';
|
|
|
|
export function LanguageSwitcher() {
|
|
const router = useRouter();
|
|
const pathname = usePathname();
|
|
const [currentLocale, setCurrentLocale] = useState('hr');
|
|
|
|
// Detect current language from URL
|
|
useEffect(() => {
|
|
const locale = pathname.startsWith('/en') ? 'en' : 'hr';
|
|
setCurrentLocale(locale);
|
|
}, [pathname]);
|
|
|
|
const switchLanguage = (locale: string) => {
|
|
// Set cookie for future visits
|
|
Cookies.set('NEXT_LOCALE', locale, { expires: 365, path: '/' });
|
|
|
|
// Construct proper path based on current path and target locale
|
|
let newPath;
|
|
|
|
if (locale === 'en') {
|
|
// If switching to English
|
|
if (pathname.startsWith('/en')) {
|
|
// Already in English, no need to change path
|
|
newPath = pathname;
|
|
} else {
|
|
// Add /en prefix to current path
|
|
newPath = `/en${pathname}`;
|
|
}
|
|
} else {
|
|
// If switching to Croatian
|
|
if (pathname.startsWith('/en')) {
|
|
// Remove /en prefix
|
|
newPath = pathname.substring(3) || '/';
|
|
} else {
|
|
// Already in Croatian, no need to change path
|
|
newPath = pathname;
|
|
}
|
|
}
|
|
|
|
// Navigate to the new path
|
|
router.push(newPath);
|
|
};
|
|
|
|
return (
|
|
<div className="flex items-center space-x-2">
|
|
<button
|
|
onClick={() => switchLanguage('hr')}
|
|
className={`px-2 py-1 ${currentLocale === 'hr' ? 'font-bold' : ''}`}
|
|
aria-label="Prebaci na hrvatski"
|
|
>
|
|
HR
|
|
</button>
|
|
<span>|</span>
|
|
<button
|
|
onClick={() => switchLanguage('en')}
|
|
className={`px-2 py-1 ${currentLocale === 'en' ? 'font-bold' : ''}`}
|
|
aria-label="Switch to English"
|
|
>
|
|
EN
|
|
</button>
|
|
</div>
|
|
);
|
|
}
|