import { useState } from 'react';
import { Image, StyleSheet } from 'react-native';
import { assetUrl } from '../lib/api';

/**
 * The source's brand badge, shown beside its name.
 *
 * Renders nothing when there is no icon, and nothing when the image fails
 * to load. A phone is offline constantly and these are remote images, so
 * the failure case is normal rather than exceptional — a broken-image box
 * on every card would be worse than the plain text the icon decorates.
 *
 * Loads the .png rather than the .svg the API returns: React Native's
 * <Image> cannot decode SVG without react-native-svg, and fails silently
 * when handed one. The generator writes both from the same source, so the
 * two files differ only by extension.
 */
export function SourceIcon({ src, size = 14 }: { src: string | null | undefined; size?: number }) {
  const [failed, setFailed] = useState(false);

  if (!src || failed) return null;

  const uri = assetUrl(src.replace(/\.svg$/i, '.png'));
  if (!uri) return null;

  return (
    <Image
      source={{ uri }}
      style={[styles.icon, { width: size, height: size, borderRadius: size * 0.22 }]}
      onError={() => setFailed(true)}
      accessibilityRole="image"
      // The source name always sits beside it, so announcing the badge
      // too would just repeat what the label already says.
      accessible={false}
    />
  );
}

const styles = StyleSheet.create({
  icon: {
    resizeMode: 'contain',
  },
});
