"use client";

import { usePathname, useRouter } from "next/navigation";
import {
  DEFAULT_LOCALE,
  LOCALE_LABELS,
  LOCALE_SHORT_LABELS,
  SUPPORTED_LOCALES,
  localizedPath,
  saveLocale,
  type SupportedLocale,
} from "../../lib/locale";

export default function LanguageSwitcher({
  currentLocale = DEFAULT_LOCALE,
}: {
  currentLocale?: SupportedLocale;
}) {
  const router = useRouter();
  const pathname = usePathname() || "/";

  function switchLanguage(locale: SupportedLocale) {
    saveLocale(locale);
    const nextPath = localizedPath(pathname, locale);
    const query = typeof window !== "undefined" ? window.location.search : "";
    router.push(`${nextPath}${query}`);
  }

  return (
    <div className="fixed right-4 bottom-24 z-50 flex flex-col items-center gap-2 rounded-lg bg-black/30 px-3 py-3 text-xs font-semibold uppercase text-white backdrop-blur-md md:text-sm">
      {SUPPORTED_LOCALES.map((locale) => {
        const active = locale === currentLocale;
        return (
          <button
            key={locale}
            type="button"
            onClick={() => switchLanguage(locale)}
            className={active ? "text-[#eea71f]" : "hover:text-[#eea71f]"}
            aria-label={`Zmień język na ${LOCALE_LABELS[locale]}`}
            aria-current={active ? "true" : undefined}
          >
            {LOCALE_SHORT_LABELS[locale]}
          </button>
        );
      })}
    </div>
  );
}
