'use client'

import Image from 'next/image'
import { useState } from 'react'

interface SafeImageProps {
  src: string
  alt: string
  width: number
  height: number
  className?: string
  priority?: boolean
  fallback?: React.ReactNode
  unoptimized?: boolean
}

export function SafeImage({ 
  src, 
  alt, 
  width, 
  height, 
  className, 
  priority = false,
  fallback,
  unoptimized = false
}: SafeImageProps) {
  const [hasError, setHasError] = useState(false)
  const [isLoading, setIsLoading] = useState(true)

  // Reset error state when src changes
  const handleSrcChange = () => {
    setHasError(false)
    setIsLoading(true)
  }

  if (hasError) {
    return <>{fallback}</> || null
  }

  return (
    <div className="relative">
      {isLoading && (
        <div className={`absolute inset-0 bg-gray-200 animate-pulse rounded-lg ${className}`} />
      )}
      <Image
        src={src}
        alt={alt}
        width={width}
        height={height}
        className={className}
        priority={priority}
        unoptimized={unoptimized}
        onError={() => setHasError(true)}
        onLoad={() => setIsLoading(false)}
        onLoadingStart={handleSrcChange}
      />
    </div>
  )
}