"use client"; import { useTransition, useState } from "react"; import { useRouter } from "next/navigation"; import ReactCountryFlag from "react-country-flag"; import { LANGUAGES } from "@/lib/languages"; import { Plus } from "lucide-react"; export function LanguageSwitcher({ targetLangs, currentLang, nativeLang, level, }: { targetLangs: string[]; currentLang: string; nativeLang: string; level: string; }) { const router = useRouter(); const [isPending, startTransition] = useTransition(); const [pendingLang, setPendingLang] = useState(null); const [isAdding, setIsAdding] = useState(false); function updateProfile(newTargetLangs: string[], switchTo: string) { if (isPending) return; setPendingLang(switchTo); startTransition(async () => { try { await fetch("/api/me/profile", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ nativeLang, targetLang: switchTo, targetLangs: newTargetLangs, level }), }); router.refresh(); } finally { setPendingLang(null); setIsAdding(false); } }); } const availableLangs = LANGUAGES.filter((l) => l.code !== nativeLang && !targetLangs.includes(l.code)); return (
{targetLangs.map((lang) => { const language = LANGUAGES.find((l) => l.code === lang); if (!language) return null; const isActive = lang === (pendingLang ?? currentLang); const isCurrentlySwitching = pendingLang === lang; return ( ); })}
{isAdding && (
{availableLangs.length > 0 ? ( availableLangs.map((lang) => ( )) ) : (
No more languages
)}
)}
); }