---
/**
 * LazyImage Component
 *
 * Lightweight image component with:
 * - Native lazy loading
 * - Placeholder background while loading
 * - Aspect ratio preservation (prevents CLS)
 * - Fade-in animation on load
 *
 * Use for placeholder/decorative images or when full Astro optimization isn't needed.
 */

interface Props {
  src: string;
  alt: string;
  width: number;
  height: number;
  class?: string;
  loading?: 'lazy' | 'eager';
  fetchpriority?: 'high' | 'low' | 'auto';
  placeholder?: string; // Background color while loading
}

const {
  src,
  alt,
  width,
  height,
  class: className = '',
  loading = 'lazy',
  fetchpriority = 'auto',
  placeholder = 'var(--color-surface-alt, #e2e8f0)', // adapts to theme
} = Astro.props;

const aspectRatio = (height / width) * 100;
---

<div
  class:list={['lazy-image-wrapper', className]}
  style={`--aspect-ratio: ${aspectRatio}%; --placeholder-bg: ${placeholder};`}
>
  <img
    src={src}
    alt={alt}
    width={width}
    height={height}
    loading={loading}
    decoding="async"
    fetchpriority={fetchpriority}
    class="lazy-image"
    onload="this.classList.add('loaded')"
  />
</div>

<style>
  .lazy-image-wrapper {
    position: relative;
    width: 100%;
    padding-bottom: var(--aspect-ratio);
    background-color: var(--placeholder-bg);
    overflow: hidden;
  }

  .lazy-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    opacity: 0;
    transition: opacity 0.3s ease-in-out;
  }

  .lazy-image.loaded {
    opacity: 1;
  }

  /* Disable transition for users who prefer reduced motion */
  @media (prefers-reduced-motion: reduce) {
    .lazy-image {
      transition: none;
      opacity: 1;
    }
  }
</style>
