'use client'

import { useMemo } from 'react'
import { useLocale } from 'next-intl'
import { COUNTRIES, localizedCountryName } from '@/lib/geo/countries'

interface CountrySelectProps {
  value: string
  onChange: (countryName: string) => void
  className?: string
}

// Country dropdown for storefront address forms. Shows names in the
// shopper's language; the value is always the English name, which is what
// orders.shipping_country / addresses.country store.
export default function CountrySelect({ value, onChange, className }: CountrySelectProps) {
  const locale = useLocale()
  const options = useMemo(
    () =>
      COUNTRIES.map((c) => ({ value: c.name, label: localizedCountryName(c, locale) })).sort((a, b) =>
        a.label.localeCompare(b.label, locale),
      ),
    [locale],
  )

  return (
    <select value={value} onChange={(e) => onChange(e.target.value)} className={className}>
      {options.map((o) => (
        <option key={o.value} value={o.value}>
          {o.label}
        </option>
      ))}
    </select>
  )
}
