"use client"

import { useState } from "react"
import { cn } from "@/lib/utils"

interface ProfileImageProps {
  src?: string | null
  alt: string
  fallback: string
  size?: "sm" | "md" | "lg"
  className?: string
}

export function ProfileImage({ 
  src, 
  alt, 
  fallback, 
  size = "md",
  className 
}: ProfileImageProps) {
  const [imageError, setImageError] = useState(false)
  const [imageLoaded, setImageLoaded] = useState(false)

  const sizeClasses = {
    sm: "w-8 h-8 text-xs",
    md: "w-12 h-12 text-sm",
    lg: "w-16 h-16 text-lg"
  }

  const hasValidImage = src && src.trim() !== '' && !imageError

  return (
    <div className={cn(
      "rounded-full overflow-hidden flex-shrink-0 relative",
      sizeClasses[size],
      className
    )}>
      {hasValidImage ? (
        <>
          <img 
            src={src} 
            alt={alt}
            className={cn(
              "w-full h-full object-cover transition-opacity duration-200",
              imageLoaded ? "opacity-100" : "opacity-0"
            )}
            onLoad={() => setImageLoaded(true)}
            onError={() => setImageError(true)}
          />
          {/* Fallback que se muestra mientras carga */}
          {!imageLoaded && (
            <div className="absolute inset-0 bg-primary rounded-full flex items-center justify-center text-primary-foreground font-semibold">
              {fallback.charAt(0).toUpperCase()}
            </div>
          )}
        </>
      ) : (
        <div className="w-full h-full bg-primary rounded-full flex items-center justify-center text-primary-foreground font-semibold">
          {fallback.charAt(0).toUpperCase()}
        </div>
      )}
    </div>
  )
} 