import React, { useState } from "react";
import {
  Image,
  StyleSheet,
  Text,
  View,
  type StyleProp,
  type ViewStyle,
} from "react-native";

type Props = {
  logoUrl?: string | null;
  /** Nom du tenant / app — sert a derouler l'initiale du fallback. */
  name: string;
  /** Couleur de marque : fond du fallback initiale. */
  brandColor: string;
  size: number;
  radius?: number;
  /** Style du conteneur (fond/bordure/ombre) applique en mode image. */
  style?: StyleProp<ViewStyle>;
};

// SVG non supporte par <Image> de React Native (rendrait un cadre blanc). On le
// detecte pour retomber directement sur le fallback initiale, sans tenter le
// chargement.
function isRenderableImageUrl(url: string): boolean {
  return !/\.svg(\?|#|$)/i.test(url);
}

/**
 * Logo de marque tenant avec fallback robuste : affiche l'image si l'URL est
 * exploitable (raster, pas SVG) et qu'elle charge ; sinon une pastille coloree
 * avec l'initiale du nom. Evite le "cadre blanc" quand le backend renvoie un
 * logo absent, en SVG, ou une URL cassee.
 */
export default function BrandLogo({
  logoUrl,
  name,
  brandColor,
  size,
  radius,
  style,
}: Readonly<Props>) {
  const [failed, setFailed] = useState(false);

  const borderRadius = radius ?? Math.round(size * 0.22);
  const showImage = Boolean(logoUrl && isRenderableImageUrl(logoUrl) && !failed);
  const box = { width: size, height: size, borderRadius };

  if (showImage) {
    return (
      <View style={[box, style]}>
        <Image
          source={{ uri: logoUrl as string }}
          style={box}
          resizeMode="contain"
          onError={() => setFailed(true)}
        />
      </View>
    );
  }

  const initial = name.trim().charAt(0).toUpperCase() || "M";
  return (
    <View
      style={[box, styles.fallback, { backgroundColor: brandColor }, style]}
    >
      <Text style={[styles.fallbackText, { fontSize: Math.round(size * 0.45) }]}>
        {initial}
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  fallback: {
    alignItems: "center",
    justifyContent: "center",
  },
  fallbackText: {
    color: "#ffffff",
    fontWeight: "800",
  },
});
