---
/**
 * OptimizedImage Component
 *
 * Features:
 * - Automatic WebP conversion via Astro's image service
 * - Native lazy loading with fallback
 * - Responsive srcset generation
 * - Blur placeholder support
 * - Proper aspect ratio to prevent CLS
 */

import { Image } from 'astro:assets';

interface Props {
  src: ImageMetadata | string;
  alt: string;
  width?: number;
  height?: number;
  class?: string;
  loading?: 'lazy' | 'eager';
  decoding?: 'async' | 'sync' | 'auto';
  fetchpriority?: 'high' | 'low' | 'auto';
  sizes?: string;
  widths?: number[];
  quality?: number;
  format?: 'webp' | 'avif' | 'png' | 'jpg';
  placeholder?: 'blur' | 'none';
}

const {
  src,
  alt,
  width,
  height,
  class: className = '',
  loading = 'lazy',
  decoding = 'async',
  fetchpriority = 'auto',
  sizes = '(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw',
  widths = [320, 640, 960, 1280, 1920],
  quality = 80,
  format = 'webp',
  placeholder = 'none',
} = Astro.props;

// Check if src is a remote URL string
const isRemote = typeof src === 'string' && (src.startsWith('http') || src.startsWith('//'));
---

{isRemote ? (
  <img
    src={src}
    alt={alt}
    width={width}
    height={height}
    class={className}
    loading={loading}
    decoding={decoding}
    fetchpriority={fetchpriority}
    style={width && height ? `aspect-ratio: ${width}/${height}` : undefined}
  />
) : typeof src === 'string' ? (
  <!-- Local path string - use native img with lazy loading -->
  <img
    src={src}
    alt={alt}
    width={width}
    height={height}
    class={className}
    loading={loading}
    decoding={decoding}
    fetchpriority={fetchpriority}
    style={width && height ? `aspect-ratio: ${width}/${height}` : undefined}
  />
) : (
  <!-- ImageMetadata - use Astro's optimized Image component -->
  <Image
    src={src}
    alt={alt}
    width={width || src.width}
    height={height || src.height}
    class={className}
    loading={loading}
    decoding={decoding}
    format={format}
    quality={quality}
    widths={widths}
    sizes={sizes}
  />
)}

<style>
  img {
    /* Prevent layout shift by maintaining aspect ratio */
    height: auto;
    max-width: 100%;
  }

  /* Add subtle fade-in effect for lazy loaded images */
  img[loading='lazy'] {
    opacity: 0;
    animation: fadeIn 0.3s ease-in-out forwards;
  }

  @keyframes fadeIn {
    to {
      opacity: 1;
    }
  }

  /* Disable animation for users who prefer reduced motion */
  @media (prefers-reduced-motion: reduce) {
    img[loading='lazy'] {
      animation: none;
      opacity: 1;
    }
  }
</style>
