// Cross-platform flag rendering. Windows browsers do not render
// regional-indicator emoji (so 🇵🇹 shows up as "PT"). We swap every
// occurrence of `p.flag` for <FlagIcon emoji={p.flag} /> which:
//   1. Decodes the emoji into a two-letter ISO country code.
//   2. Renders the SVG from flagcdn.com – a stable free CDN, cached
//      cross-site, SVG so it scales crisply at any size.
//
// Also accepts a direct `code="PT"` prop for places where we don't keep
// an emoji on the data record (real-estate, future hardcoded uses).

function flagEmojiToCode(emoji) {
  if (!emoji || typeof emoji !== 'string' || emoji.length < 4) return null;
  try {
    const a = emoji.codePointAt(0) - 0x1F1E6;
    const b = emoji.codePointAt(2) - 0x1F1E6;
    if (a < 0 || a > 25 || b < 0 || b > 25) return null;
    return String.fromCharCode(65 + a) + String.fromCharCode(65 + b);
  } catch (_) { return null; }
}

function FlagIcon({ emoji, code, size = 22, style, alt }) {
  const iso = (code || flagEmojiToCode(emoji) || '').toLowerCase();
  if (!iso) {
    // Fallback: render the emoji directly (works on Mac/iOS, ugly on Windows)
    return <span style={{ fontSize: size, ...style }}>{emoji || ''}</span>;
  }
  // Aspect ratio: 4:3 for most flags; flagcdn supports this w aspect intrinsic.
  const w = Math.round(size * 1.33);
  const h = size;
  return (
    <img
      src={`https://flagcdn.com/${iso}.svg`}
      alt={alt || iso.toUpperCase()}
      loading="lazy"
      draggable="false"
      style={{
        width: w, height: h,
        objectFit: 'cover',
        display: 'inline-block',
        borderRadius: 2,
        boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.06)',
        flexShrink: 0,
        verticalAlign: 'middle',
        ...style,
      }}
      onError={(e) => {
        // If CDN ever fails, fall back to a neutral placeholder so the
        // layout doesn't shift.
        e.currentTarget.style.background = '#E4E2DC';
        e.currentTarget.removeAttribute('src');
      }}
    />
  );
}

// Convenience exports
window.FlagIcon = FlagIcon;
window.flagEmojiToCode = flagEmojiToCode;
