"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { Check, Globe } from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { locales, localeMeta, type Locale } from "@/lib/i18n/config";
import { cn } from "@/lib/utils";

function pathForLocale(pathname: string, locale: Locale) {
  const parts = pathname.split("/").filter(Boolean);
  if (parts.length > 0 && (locales as readonly string[]).includes(parts[0])) {
    parts[0] = locale;
    return `/${parts.join("/")}`;
  }
  return `/${locale}${pathname === "/" ? "" : pathname}`;
}

export function LocaleSwitcher({
  locale,
  label,
  className,
  compact = false,
}: {
  locale: Locale;
  label: string;
  className?: string;
  compact?: boolean;
}) {
  const pathname = usePathname() || `/${locale}`;

  return (
    <DropdownMenu>
      <DropdownMenuTrigger
        className={cn(
          "inline-flex items-center gap-1.5 text-[12px] uppercase tracking-[0.16em] text-charcoal/70 transition-colors hover:text-charcoal",
          className,
        )}
        aria-label={label}
      >
        <Globe className="h-4 w-4" strokeWidth={1.4} />
        {!compact && <span>{localeMeta[locale].short}</span>}
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="min-w-[170px]">
        {locales.map((code) => (
          <DropdownMenuItem key={code} asChild>
            <Link href={pathForLocale(pathname, code)} className="flex items-center justify-between gap-3">
              <span className="flex items-center gap-2">
                <span className="text-[12px] uppercase tracking-widest text-charcoal/40">
                  {localeMeta[code].short}
                </span>
                {localeMeta[code].label}
              </span>
              {code === locale && <Check className="h-3.5 w-3.5 text-gold" />}
            </Link>
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
