/**
 * Reusable flag image with country-name tooltip.
 */
import React from 'react';
import { Tooltip } from '@wordpress/components';
import { getCountryName } from '../utils/countries';
import { getLogo } from '../utils/getAsset';

interface CountryFlagProps {
	countryCode: string;
}

const FLAG_STYLE: React.CSSProperties = {
	width: 24,
	height: 18,
	objectFit: 'cover',
	borderRadius: 2,
};

const PLACEHOLDER_STYLE: React.CSSProperties = {
	display: 'inline-block',
	width: 24,
	height: 18,
	background: '#eee',
	borderRadius: 2,
};

function CountryFlagInner({ countryCode }: CountryFlagProps) {
	const code = countryCode.trim().toUpperCase();
	if (!code) {
		return <span style={PLACEHOLDER_STYLE} aria-hidden />;
	}

	const countryName = getCountryName(code);
	const flagCode = code === 'UK' ? 'GB' : code;
	const flagSrc = getLogo(flagCode);

	return (
		<Tooltip text={countryName}>
			<span style={{ display: 'inline-flex', cursor: 'help' }}>
				{flagSrc ? (
					<img src={flagSrc} alt={countryName} style={FLAG_STYLE} />
				) : (
					<span style={PLACEHOLDER_STYLE} aria-hidden />
				)}
			</span>
		</Tooltip>
	);
}

const CountryFlag = React.memo(CountryFlagInner);
export default CountryFlag;
