<script lang="ts">
  import type { Snippet } from 'svelte';
  
  interface Props {
    src: string;
    alt?: string;
    children?: Snippet;
  }

  let { src, alt = "", children }: Props = $props();

  const placeholder = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiPjxyZWN0IGZpbGw9IiMzMzMiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiLz48L3N2Zz4=';
  
  let imageSrc = $derived(src || placeholder);

  // Generate srcset for optimized images from our proxy
  let srcset = $derived.by(() => {
    if (!src || !src.startsWith('/assets/')) return undefined;
    
    const widths = [400, 800, 1200, 1600];
    const sets = widths.map(w => `${src}${src.includes('?') ? '&' : '?'}w=${w} ${w}w`);
    
    // Add original as fallback
    sets.push(`${src} 2000w`);
    
    return sets.join(', ');
  });

  const sizes = "(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw";
</script>

<div class="grid grid-cols-1 grid-rows-1">
  <img
    src={imageSrc}
    {srcset}
    {sizes}
    {alt}
    loading="lazy"
    class="row-start-1 col-start-1 pointer-events-none w-full h-96 object-cover"
    onerror={(e) => {
      const img = e.currentTarget as HTMLImageElement;
      img.src = placeholder;
      // Clear srcset on error to avoid loading broken thumbnails
      img.srcset = "";
    }}
  />
  <div class="row-start-1 col-start-1">
    {@render children?.()}
  </div>
</div>
