'use client'

import { Globe, Check, ChevronDown } from 'lucide-react'
import * as DropdownMenu from '@radix-ui/react-dropdown-menu'
import { adminPortalContainer } from '../lib/portal-container.js'
import { useLocale } from './LocaleProvider.js'

export function LocaleSwitcher() {
  const { activeLocale, setLocale, locales } = useLocale()

  if (locales.length < 2) return null

  const activeLabel = locales.find((l) => l.code === activeLocale)?.label ?? activeLocale

  return (
    <DropdownMenu.Root>
      <DropdownMenu.Trigger asChild>
        <button
          className="flex items-center gap-1.5 rounded-lg px-2 py-1.5 text-sm transition-colors hover:bg-[var(--accent)]"
          aria-label="Switch locale"
        >
          <Globe className="h-4 w-4 text-[var(--muted-foreground)]" />
          <span className="hidden text-sm font-medium text-[var(--foreground)] sm:inline">
            {activeLabel}
          </span>
          <ChevronDown className="h-3 w-3 text-[var(--muted-foreground)]" />
        </button>
      </DropdownMenu.Trigger>

      <DropdownMenu.Portal container={adminPortalContainer()}>
        <DropdownMenu.Content
          className="z-50 min-w-[160px] rounded-lg border border-[var(--border)] bg-[var(--popover)] p-1 text-[var(--popover-foreground)] shadow-lg"
          align="end"
          sideOffset={5}
        >
          {locales.map((locale) => (
            <DropdownMenu.Item
              key={locale.code}
              onSelect={() => setLocale(locale.code)}
              className="flex cursor-pointer items-center justify-between gap-2 rounded px-3 py-2 text-sm outline-none hover:bg-[var(--accent)]"
            >
              <span>{locale.label}</span>
              {locale.code === activeLocale && <Check className="h-4 w-4 text-[var(--primary)]" />}
            </DropdownMenu.Item>
          ))}
        </DropdownMenu.Content>
      </DropdownMenu.Portal>
    </DropdownMenu.Root>
  )
}
