"use client";

import { cn } from "@/lib/utils";

export type CountryFlagProps = {
  code: string;
  className?: string;
  title?: string;
};

/**
 * Image flag for an ISO 3166-1 alpha-2 code.
 * Prefer this over emoji flags — Windows often renders regional-indicator
 * sequences as plain letters (e.g. "PK") instead of a flag glyph.
 */
export function CountryFlag({ code, className, title }: CountryFlagProps) {
  const cc = String(code || "")
    .trim()
    .toLowerCase();
  if (!/^[a-z]{2}$/.test(cc)) return null;

  return (
    // eslint-disable-next-line @next/next/no-img-element
    <img
      src={`https://flagcdn.com/w40/${cc}.png`}
      srcSet={`https://flagcdn.com/w80/${cc}.png 2x`}
      width={20}
      height={15}
      alt=""
      title={title}
      loading="lazy"
      decoding="async"
      className={cn(
        "inline-block h-[15px] w-5 shrink-0 rounded-[2px] object-cover",
        className,
      )}
      aria-hidden
    />
  );
}

export default CountryFlag;
