'use client';

import { useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { Globe } from 'lucide-react';
import { setLocale } from '@/app/actions/locale';
import { LOCALES, LOCALE_LABEL, type Locale } from '@/i18n/config';
import { useLocale, useMessages } from '@/i18n/client';
import { cn } from '@/lib/cn';

/** ID / EN / 中文 segmented switch; saves the choice in a cookie and re-renders the page. */
export function LanguageSwitcher({ tone = 'light', className }: { tone?: 'light' | 'dark'; className?: string }) {
  const locale = useLocale();
  const t = useMessages().layout;
  const router = useRouter();
  const [pending, startTransition] = useTransition();

  const choose = (next: Locale) => {
    if (next === locale) return;
    startTransition(async () => {
      await setLocale(next);
      router.refresh();
    });
  };

  return (
    <div
      role="radiogroup"
      aria-label={t.language}
      className={cn(
        'inline-flex items-center gap-0.5 rounded-full p-0.5 text-[12px] font-medium',
        tone === 'light' ? 'bg-white/10 text-white/70' : 'bg-surface text-muted ring-1 ring-line',
        pending && 'opacity-60',
        className,
      )}
    >
      <Globe className="mx-1.5 size-3.5 opacity-70" aria-hidden />
      {LOCALES.map((l) => (
        <button
          key={l}
          type="button"
          role="radio"
          aria-checked={l === locale}
          title={LOCALE_LABEL[l].name}
          onClick={() => choose(l)}
          className={cn(
            'rounded-full px-2.5 py-1 transition-colors',
            l === locale
              ? tone === 'light'
                ? 'bg-white text-ink'
                : 'bg-ink text-white'
              : tone === 'light'
                ? 'hover:text-white'
                : 'hover:text-ink',
          )}
        >
          {LOCALE_LABEL[l].short}
        </button>
      ))}
    </div>
  );
}
