'use client'

import { useRouter } from 'next/navigation'
import { useTransition } from 'react'

import { useI18n } from '@/components/providers/i18n-provider'
import { LOCALE_COOKIE, LOCALE_LABELS, LOCALES, type Locale } from '@/lib/i18n/config'
import { cn } from '@/lib/cn'

/**
 * Switching language rewrites the locale cookie and refreshes the server tree, so the
 * whole document — including `dir` on <html> — flips in one pass. Doing it client-side
 * only would leave the direction stale until the next navigation.
 */
export function LanguageSwitcher({ className, compact = false }: { className?: string; compact?: boolean }) {
  const { locale, t } = useI18n()
  const router = useRouter()
  const [pending, startTransition] = useTransition()

  const select = (next: Locale) => {
    if (next === locale) return
    document.cookie = `${LOCALE_COOKIE}=${next}; path=/; max-age=${60 * 60 * 24 * 365}; samesite=lax`
    startTransition(() => router.refresh())
  }

  return (
    <div
      role="radiogroup"
      aria-label={t('common.language')}
      className={cn(
        'inline-flex items-center gap-0.5 rounded-lg border border-border bg-surface-2 p-0.5',
        pending && 'opacity-60',
        className,
      )}
    >
      {LOCALES.map((code) => (
        <button
          key={code}
          type="button"
          role="radio"
          aria-checked={code === locale}
          onClick={() => select(code)}
          className={cn(
            'rounded-md px-2.5 py-1 text-xs font-medium transition-colors',
            code === locale
              ? 'bg-brand/18 text-brand'
              : 'text-text-muted hover:bg-surface-3 hover:text-text',
          )}
        >
          {compact ? code.toUpperCase() : LOCALE_LABELS[code].native}
        </button>
      ))}
    </div>
  )
}
