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

interface Props {
  // Still image shown until playback starts.
  poster: ImageMetadata;
  alt: string;
  video: HeaderVideo;
  widths: number[];
  sizes: string;
  loading?: 'lazy' | 'eager';
  fetchpriority?: 'high' | 'low' | 'auto';
  // `banner` keeps the poster's own aspect ratio (article hero); `card` is a
  // compact badge over a cover-cropped thumbnail (project list).
  variant?: 'banner' | 'card';
  // When set, the wrapper joins the no-crop preview contract checked in QA.
  previewLabel?: string;
  class?: string;
}

const {
  poster,
  alt,
  video,
  widths,
  sizes,
  loading = 'lazy',
  fetchpriority,
  variant = 'banner',
  previewLabel,
  class: extraClass,
} = Astro.props;

const aspectRatio = `${poster.width} / ${poster.height}`;

// Swap the poster for the <video> and start playback on click. Guarded so the
// duplicate inline copies emitted per instance only wire listeners up once.
const playScript = `
(function () {
  if (window.__videoThumbnailInit) return;
  window.__videoThumbnailInit = true;
  function wireOne(root) {
    var button = root.querySelector('[data-video-play]');
    var video = root.querySelector('[data-video]');
    if (!(button instanceof HTMLButtonElement) || !(video instanceof HTMLVideoElement)) return;
    button.addEventListener('click', function () {
      video.hidden = false;
      video.setAttribute('controls', '');
      root.classList.add('is-playing');
      var played = video.play();
      if (played && typeof played.catch === 'function') played.catch(function () {});
      video.focus();
    }, { once: true });
  }
  function wireAll() {
    var roots = document.querySelectorAll('.video-thumbnail');
    for (var i = 0; i < roots.length; i++) wireOne(roots[i]);
  }
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', wireAll);
  } else {
    wireAll();
  }
})();
`;
---

<div
  class:list={['video-thumbnail', `video-thumbnail--${variant}`, extraClass]}
  style={variant === 'banner' ? `--video-aspect: ${aspectRatio}` : undefined}
  data-uncropped-preview={previewLabel ? '' : undefined}
  data-preview-label={previewLabel}
>
  <Picture
    src={poster}
    alt={alt}
    formats={['avif', 'webp']}
    fallbackFormat="jpg"
    widths={widths}
    sizes={sizes}
    quality="high"
    loading={loading}
    fetchpriority={fetchpriority}
    decoding="async"
  />

  <button
    class="video-thumbnail__play"
    type="button"
    data-video-play
    aria-label={`Play video: ${video.caption ?? alt}`}
  >
    <span class="video-thumbnail__play-icon" aria-hidden="true">
      <svg viewBox="0 0 24 24" focusable="false">
        <path d="M8 5v14l11-7z"></path>
      </svg>
    </span>
    <span class="sr-only">Play video</span>
  </button>

  <video
    class="video-thumbnail__video"
    data-video
    preload="none"
    playsinline
    poster={video.poster?.src}
    aria-label={video.caption}
    hidden
  >
    {video.webm && <source src={video.webm} type="video/webm" />}
    {video.mp4 && <source src={video.mp4} type="video/mp4" />}
  </video>

  <noscript>
    <p class="video-thumbnail__noscript">
      <a href={video.mp4 ?? video.webm}>Play video</a>
    </p>
  </noscript>
</div>

<script is:inline data-video-thumbnail-script set:html={playScript} />
