---
import type { CollectionEntry } from 'astro:content';
import { Picture } from 'astro:assets';

type MediaItem = CollectionEntry<'posts'>['data']['media'][number];

interface Props {
  item: MediaItem;
}

const { item } = Astro.props;

const fallbackFormatFor = (format: string | undefined): 'png' | 'jpg' =>
  format === 'png' ? 'png' : 'jpg';
---

<figure class="post-media">
  {
    item.type === 'video' ? (
      <video
        controls
        preload="none"
        poster={item.poster?.src}
        {...(item.decorative ? { 'aria-hidden': 'true' } : { 'aria-label': item.alt })}
      >
        {item.webm && <source src={item.webm} type="video/webm" />}
        {item.mp4 && <source src={item.mp4} type="video/mp4" />}
      </video>
    ) : (
      item.src && (
        <Picture
          src={item.src}
          alt={item.decorative ? '' : (item.alt ?? '')}
          formats={['avif', 'webp']}
          fallbackFormat={fallbackFormatFor(item.src.format)}
          widths={[480, 720, 960, 1280, 1600, 1920, 2400]}
          sizes="(max-width: 700px) calc(100vw - 2 * clamp(20px, 4vw, 32px)), (max-width: 1100px) min(calc(100vw - 4rem), 56rem), 56rem"
          loading="lazy"
          decoding="async"
        />
      )
    )
  }
  {item.caption && !item.decorative && <figcaption>{item.caption}</figcaption>}
  {item.transcript && <p class="media-transcript">{item.transcript}</p>}
</figure>
