"use client"; import { useLocale } from "next-intl"; import { useParams, useSearchParams } from "next/navigation"; import { locales } from "@/config"; import { usePathname, useRouter } from "@/i18n/routing"; import { useEffect, useState, useTransition } from "react"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import Image from "next/image"; import Cookies from "js-cookie"; export const getLanguage = (): string | null => { if (typeof window === "undefined") return null; return localStorage.getItem("language"); }; export const setLanguage = (value: string) => { if (typeof window === "undefined") return; localStorage.setItem("language", value); }; export default function LocalSwitcher() { const [isPending, startTransition] = useTransition(); const router = useRouter(); const pathname = usePathname(); const params = useParams(); const locale = useLocale() || "in"; const [selectedLang, setSelectedLang] = useState("in"); const searchParams = useSearchParams(); const [hasInitialized, setHasInitialized] = useState(false); useEffect(() => { const storedLang = getLanguage(); let joinParam = ""; if (searchParams) { joinParam = Array.from(searchParams.entries()) .map(([key, value]) => `${key}=${value}`) .join("&"); } const redirectTo = (lang: string) => { startTransition(() => { router.replace(pathname + (joinParam ? `?${joinParam}` : ""), { locale: lang, }); }); }; if (!hasInitialized) { if (!storedLang) { setLanguage("in"); setSelectedLang("in"); redirectTo("in"); } else { setSelectedLang(storedLang); if (locale !== storedLang) { redirectTo(storedLang); } } setHasInitialized(true); } }, []); const onSelectChange = (nextLocale: string) => { setLanguage(nextLocale); setSelectedLang(nextLocale); startTransition(() => { router.replace(pathname, { locale: nextLocale }); }); }; return ( ); }