"use client"

import Image, { ImageProps } from "next/image"
import { useState } from "react"

interface OptimizedImageProps extends Omit<ImageProps, 'onLoad'> {
  showPlaceholder?: boolean
}

export function OptimizedImage({
  showPlaceholder = true,
  className = "",
  alt,
  ...props
}: OptimizedImageProps) {
  const [isLoading, setIsLoading] = useState(true)
  const [hasError, setHasError] = useState(false)

  // Don't show placeholder for priority images (hero sections)
  const shouldShowPlaceholder = showPlaceholder && !props.priority

  return (
    <div className="relative w-full h-full">
      {/* Placeholder shown while loading (not for priority images) */}
      {shouldShowPlaceholder && isLoading && !hasError && (
        <div className="absolute inset-0 flex items-center justify-center bg-gray-50">
          <Image
            src="/placeholder.svg"
            alt="Loading..."
            fill
            className="object-contain opacity-30"
            priority={false}
          />
        </div>
      )}

      {/* Main image */}
      <Image
        {...props}
        alt={alt}
        className={`${className} ${
          // Only fade in non-priority images
          !props.priority && isLoading ? 'opacity-0' : 'opacity-100'
        } ${!props.priority ? 'transition-opacity duration-300' : ''}`}
        onLoad={() => setIsLoading(false)}
        onError={() => {
          setHasError(true)
          setIsLoading(false)
        }}
        quality={props.quality || 85}
        loading={props.priority ? undefined : (props.loading || "lazy")}
      />

      {/* Error fallback */}
      {hasError && (
        <div className="absolute inset-0 flex items-center justify-center bg-gray-100">
          <Image
            src="/placeholder.svg"
            alt="Failed to load image"
            fill
            className="object-contain opacity-30"
          />
        </div>
      )}
    </div>
  )
}
