"use client";

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

type LanguageSwitcherProps = {
  locale: Locale;
  label: string;
};

export default function LanguageSwitcher({ locale, label }: LanguageSwitcherProps) {
  const pathname = usePathname();
  const segments = pathname.split("/").filter(Boolean);

  const switchPath = (targetLocale: Locale) => {
    const nextSegments = [...segments];

    if (nextSegments.length === 0) {
      return `/${targetLocale}`;
    }

    if (locales.includes(nextSegments[0] as Locale)) {
      nextSegments[0] = targetLocale;
    } else {
      nextSegments.unshift(targetLocale);
    }

    return `/${nextSegments.join("/")}`;
  };

  return (
    <div className="language-switcher" role="group" aria-label={label}>
      {locales.map((item) => {
        const active = item === locale;

        return (
          <Link
            key={item}
            href={switchPath(item)}
            className={active ? "lang-chip active" : "lang-chip"}
            aria-current={active ? "page" : undefined}
          >
            {item.toUpperCase()}
          </Link>
        );
      })}
    </div>
  );
}
