import React from 'react';
import {
  AR,
  AT,
  AU,
  BA,
  BE,
  BG,
  BR,
  CA,
  CH,
  CL,
  CN,
  CO,
  CZ,
  DE,
  DK,
  EE,
  ES,
  FI,
  FR,
  GB,
  GR,
  HR,
  HU,
  IE,
  IN,
  IS,
  IT,
  JP,
  KR,
  LI,
  LT,
  LU,
  LV,
  MT,
  MX,
  NL,
  NO,
  NZ,
  PL,
  PT,
  RO,
  SE,
  SI,
  SK,
  TR,
  UA,
  US,
  ZA
} from 'country-flag-icons/react/3x2';

const normalizeCountryCode = (value = '') => String(value || '').trim().toUpperCase();

const FLAG_COMPONENTS = {
  AR,
  AT,
  AU,
  BA,
  BE,
  BG,
  BR,
  CA,
  CH,
  CL,
  CN,
  CO,
  CZ,
  DE,
  DK,
  EE,
  ES,
  FI,
  FR,
  GB,
  GR,
  HR,
  HU,
  IE,
  IN,
  IS,
  IT,
  JP,
  KR,
  LI,
  LT,
  LU,
  LV,
  MT,
  MX,
  NL,
  NO,
  NZ,
  PL,
  PT,
  RO,
  SE,
  SI,
  SK,
  TR,
  UA,
  US,
  ZA
};

export default function CountryFlag({
  countryCode = '',
  title = '',
  className = 'h-4 w-6 rounded-[2px] shadow-sm'
}) {
  const normalizedCode = normalizeCountryCode(countryCode);
  const FlagIcon = FLAG_COMPONENTS[normalizedCode];

  if (!FlagIcon) {
    return (
      <span
        className="inline-flex h-4 w-6 items-center justify-center rounded-[2px] bg-gray-200 text-[10px] dark:bg-gray-700"
        title={title || 'Kein Land'}
      >
        🌍
      </span>
    );
  }

  return <FlagIcon title={title || normalizedCode} className={className} />;
}
