"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import type { ReactNode } from "react";
import { locales, type Locale } from "@/i18n/config";
import { LanguageIcon } from "@/components/icons";
import { buttonVariants } from "@/components/ui/button";

type LanguageSwitcherProps = {
  locale: Locale;
  label: string;
  /** Visible text instead of the icon button (the open phone menu shows the other language's name). */
  children?: ReactNode;
  className?: string;
  onNavigate?: () => void;
};

/** Links to the same page in the other locale and remembers the choice (read by proxy.ts). */
export function LanguageSwitcher({ locale, label, children, className, onNavigate }: LanguageSwitcherProps) {
  const pathname = usePathname();
  const target = locales.find((l) => l !== locale) ?? locale;
  const href = pathname.replace(new RegExp(`^/${locale}(?=/|$)`), `/${target}`);

  return (
    <Link
      href={href}
      hrefLang={target}
      lang={children ? target : undefined}
      aria-label={children ? undefined : label}
      title={label}
      onClick={() => {
        document.cookie = `NEXT_LOCALE=${target}; path=/; max-age=31536000; samesite=lax`;
        onNavigate?.();
      }}
      className={children ? className : buttonVariants({ variant: "glass", size: "icon-xl", className })}
    >
      {children ?? <LanguageIcon />}
    </Link>
  );
}
