---
import { Picture } from 'astro:assets';
import type { WorkMedia } from '../lib/site';

type MediaItem = WorkMedia;

interface Props {
  item: MediaItem;
}

const { item } = Astro.props;

const videoWidth = item.type === 'video' ? (item.poster?.width ?? 1280) : undefined;
const videoHeight = item.type === 'video' ? (item.poster?.height ?? 720) : undefined;
---

<figure class="post-media">
  {
    item.type === 'video' ? (
      // Decorative videos stay inert and hidden from assistive tech. Meaningful
      // videos expose controls and an accessible name.
      item.decorative ? (
        <video
          muted
          playsinline
          preload="metadata"
          poster={item.poster?.src}
          width={videoWidth}
          height={videoHeight}
          aria-hidden="true"
          tabindex="-1"
        >
          {item.webm && <source src={item.webm} type="video/webm" />}
          {item.mp4 && <source src={item.mp4} type="video/mp4" />}
        </video>
      ) : (
        <video
          controls
          preload="none"
          poster={item.poster?.src}
          width={videoWidth}
          height={videoHeight}
          aria-label={item.caption}
        >
          {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.caption ?? '')}
          formats={['avif', 'webp']}
          widths={[480, 960, 1280, 1920]}
          sizes="(max-width: 700px) calc(100vw - 2 * clamp(20px, 4vw, 32px)), (max-width: 1100px) min(calc(100vw - 4rem), 56rem), 56rem"
          quality="high"
          loading="lazy"
          decoding="async"
        />
      )
    )
  }
  {item.caption && !item.decorative && <figcaption>{item.caption}</figcaption>}
  {
    item.transcript && (
      <p class="media-transcript">
        <strong>Transcript:</strong> {item.transcript}
      </p>
    )
  }
</figure>
