"use client";

import Link from "next/link";
import { useParams, usePathname } from "next/navigation";
import { Locale, locales, resolveLocale, getLocaleDisplayName } from "@/config/i18n";

type LanguageSwitchProps = {
  locale?: Locale;
  withLabels?: boolean;
  className?: string;
};

export function LanguageSwitch({ locale: providedLocale, withLabels = true, className }: LanguageSwitchProps) {
  const params = useParams() as { locale?: string };
  const pathname = usePathname();

  const currentLocale = providedLocale ?? resolveLocale(params?.locale);
  const segments = pathname.split("/").filter(Boolean);

  const getHref = (locale: Locale) => {
    if (segments[0] && locales.includes(segments[0] as Locale)) {
      const [, ...rest] = segments;
      return `/${locale}${rest.length ? `/${rest.join("/")}` : ""}`;
    }
    return `/${locale}${segments.length ? `/${segments.join("/")}` : ""}`;
  };

  return (
    <div className={className ?? ""} style={{ display: "flex", gap: "8px" }}>
      {locales.map((locale) => (
        <Link
          key={locale}
          href={getHref(locale)}
          style={{
            padding: "6px 12px",
            borderRadius: "999px",
            border: locale === currentLocale ? "1px solid rgba(0,0,0,0.6)" : "1px solid rgba(0,0,0,0.1)",
            background: locale === currentLocale ? "rgba(0,0,0,0.05)" : "transparent",
            textDecoration: "none"
          }}
        >
          {withLabels ? getLocaleDisplayName(locale, currentLocale) : locale.toUpperCase()}
        </Link>
      ))}
    </div>
  );
}
