'use client' import { useMemo } from 'react' import Link from 'next/link' import { usePathname, useSearchParams } from 'next/navigation' import { defaultLocale, locales, type Locale } from '@/i18n' function replaceLocale(pathname: string, nextLocale: Locale) { const segments = pathname.split('/').filter(Boolean) const current = segments[0] if (locales.includes(current as Locale)) { segments[0] = nextLocale } else { segments.unshift(nextLocale) } return '/' + segments.join('/') } export default function LanguageSwitch() { const pathname = usePathname() const searchParams = useSearchParams() const options: Array<{ locale: Locale; label: string }> = [ { locale: 'en', label: 'EN' }, ] const activeLocale = useMemo(() => { const seg = pathname.split('/').filter(Boolean)[0] return locales.includes(seg as Locale) ? (seg as Locale) : defaultLocale }, [pathname]) return (
{options.map(({ locale, label }) => { const active = activeLocale === locale const nextPath = replaceLocale(pathname || `/${defaultLocale}`, locale) const qs = searchParams.toString() const href = qs ? `${nextPath}?${qs}` : nextPath return ( {label} ) })}
) }