'use client';

import * as React from 'react';

import { cn } from '../../../lib/utils';

import { FLAG_COMPONENTS } from './flag-map';
import { getLanguageCountryCode } from './language-to-country';

export interface FlagProps extends Omit<React.SVGAttributes<SVGSVGElement>, 'children'> {
  /** ISO 3166-1 alpha-2 country code (e.g. `'US'`, `'JP'`). Case-insensitive. */
  countryCode: string;
  /** Optional rounded corners — common for tile / chip presentations. */
  rounded?: boolean;
}

/**
 * SVG country flag (3:2 aspect). Renders nothing for unknown country codes
 * — call sites should reserve space if they want a stable layout.
 */
export function Flag({ countryCode, rounded, className, ...props }: FlagProps) {
  const code = countryCode?.toUpperCase();
  const Component = code ? FLAG_COMPONENTS[code] : undefined;
  if (!Component) return null;
  // `country-flag-icons` types its components against an HTML+SVG intersection;
  // we narrow to plain `SVGAttributes` for our consumers.
  const Tag = Component as unknown as React.ComponentType<React.SVGAttributes<SVGSVGElement>>;
  return (
    <Tag
      className={cn(
        'inline-block shrink-0 select-none',
        rounded && 'overflow-hidden rounded-[2px]',
        className,
      )}
      aria-hidden="true"
      focusable={false}
      {...props}
    />
  );
}

export interface LanguageFlagProps extends Omit<FlagProps, 'countryCode'> {
  /** Locale / language code (`'en'`, `'pt-BR'`, `'zh_CN'`, …). */
  code: string;
}

/**
 * Convenience wrapper — resolves a locale to a country code and renders `Flag`.
 * Returns `null` when the locale has no country mapping.
 */
export function LanguageFlag({ code, ...props }: LanguageFlagProps) {
  const country = getLanguageCountryCode(code);
  if (!country) return null;
  return <Flag countryCode={country} {...props} />;
}
