"use client";

import type { MouseEvent } from "react";
import { LOCALE_COOKIE, type Locale } from "@/lib/i18n";

type Props = {
  current: Locale;
  label: string; // e.g. "Language"
  className?: string;
};

const NAMES: Record<Locale, { short: string; long: string }> = {
  en: { short: "EN", long: "English" },
  id: { short: "ID", long: "Bahasa Indonesia" },
};

/** EN / ID switch. Remembers the choice in a cookie and keeps the current section (hash). */
function rememberLocale(locale: Locale) {
  document.cookie = `${LOCALE_COOKIE}=${locale}; path=/; max-age=31536000; samesite=lax`;
}

export default function LanguageSwitch({ current, label, className = "" }: Props) {
  const go = (e: MouseEvent<HTMLAnchorElement>, locale: Locale) => {
    rememberLocale(locale);
    if (locale === current) {
      e.preventDefault();
      return;
    }
    e.currentTarget.href = `/${locale}${location.hash}`;
  };

  return (
    <nav aria-label={label} className={`flex items-center gap-1 text-[0.72rem] font-semibold tracking-[0.18em] ${className}`}>
      {(Object.keys(NAMES) as Locale[]).map((l, i) => (
        <span key={l} className="flex items-center gap-1">
          {i > 0 && <span aria-hidden="true" className="opacity-40">/</span>}
          <a
            href={`/${l}`}
            hrefLang={l}
            lang={l}
            aria-current={l === current ? "true" : undefined}
            aria-label={NAMES[l].long}
            onClick={(e) => go(e, l)}
            className={`inline-flex min-h-[44px] min-w-[36px] items-center justify-center px-1 transition-opacity ${
              l === current ? "text-gold opacity-100" : "opacity-60 hover:opacity-100"
            }`}
          >
            {NAMES[l].short}
          </a>
        </span>
      ))}
    </nav>
  );
}
