import * as React from "react";

import { DynamicIcon } from "../icons/dynamic-icon.js";
import { flagIconNames, type FlagIconName } from "./dynamic-imports.js";
import { Globe } from "../icons/lucide-exports.js";

export interface DynamicFlagIconProps
  extends React.ComponentProps<"span"> {
  /** ISO 3166-1 alpha-3 country code (e.g. "USA", "GBR") */
  country: string;
  /**
   * Icon size in pixels (width and height)
   * @default 20
   */
  size?: number;
}

const flagIconNameSet = new Set<string>(flagIconNames);

const DynamicFlagIcon = React.forwardRef<HTMLSpanElement, DynamicFlagIconProps>(
  ({ country, size = 20, className, style, ...props }, ref) => {
    const isKnown = flagIconNameSet.has(country);

    return (
      <span
        ref={ref}
        aria-hidden="true"
        className={className}
        data-slot="flag-icon"
        style={{
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          flexShrink: 0,
          width: size,
          height: size,
          ...style,
        }}
        {...props}
      >
        {isKnown ? (
          <DynamicIcon
            name={country as FlagIconName}
            size={size}
          />
        ) : (
          <span
            data-slot="flag-icon-fallback"
            style={{
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
              width: size,
              height: size,
              borderRadius: "9999px",
              backgroundColor: "var(--color-muted, #f3f4f6)",
              color: "var(--color-muted-foreground, #6b7280)",
            }}
          >
            <Globe size={Math.round(size * 0.65)} />
          </span>
        )}
      </span>
    );
  }
);

DynamicFlagIcon.displayName = "DynamicFlagIcon";

export { DynamicFlagIcon };
