"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";

import { LOCALE_LABEL, LOCALE_NAME, LOCALES, type Locale } from "@/lib/locales";
import { rememberLocale } from "@/lib/remember-locale";
import { href, resolveRoute } from "@/lib/routes";

/**
 * The four languages, each pointing at the exact counterpart of the page
 * being read. The same resolution the header's switch uses, for the footer.
 */
export function LocaleLinks({
  locale,
  aria,
  className,
  itemClassName,
  currentClassName,
}: {
  locale: Locale;
  aria: string;
  className?: string;
  itemClassName?: string;
  currentClassName?: string;
}) {
  const pathname = usePathname() ?? "";

  function counterpart(other: Locale): string {
    const segments = pathname.split("/").filter(Boolean);
    const [first, ...rest] = segments;
    if (first === locale) {
      const target = resolveRoute(locale, rest);
      if (target) return href(target, other);
    }
    return href({ key: "home" }, other);
  }

  return (
    <div className={className} role="group" aria-label={aria}>
      {LOCALES.map((other) => {
        const current = other === locale;
        return (
          <Link
            key={other}
            href={counterpart(other)}
            hrefLang={other}
            lang={other}
            aria-label={LOCALE_NAME[other]}
            aria-current={current ? "true" : undefined}
            className={[itemClassName, current ? currentClassName : null].filter(Boolean).join(" ")}
            onClick={() => rememberLocale(other)}
          >
            {LOCALE_LABEL[other]}
          </Link>
        );
      })}
    </div>
  );
}
