"use client";
import {usePathname} from "next/navigation";
import Link from "next/link";
import {locales, localeLabels, type Locale} from "@/lib/i18n";

function replaceLocale(pathname: string, nextLocale: Locale) {
  const parts = pathname.split("/").filter(Boolean);
  if (parts.length === 0) return `/${nextLocale}`;
  parts[0] = nextLocale;
  return "/" + parts.join("/");
}

export default function LanguageSwitcher({currentLocale}:{currentLocale: Locale}) {
  const pathname = usePathname() || `/${currentLocale}`;
  return (
    <div className="flex flex-wrap gap-2">
      {locales.map((lc) => {
        const href = replaceLocale(pathname, lc);
        const active = lc === currentLocale;
        return (
          <Link
            key={lc}
            href={href}
            className={[
              "rounded-full border px-3 py-1 text-sm",
              active ? "bg-slate-900 text-white border-slate-900" : "border-slate-200"
            ].join(" ")}
          >
            {localeLabels[lc]}
          </Link>
        );
      })}
    </div>
  );
}
