"use client";

import { useState } from "react";

import MediaImage from "./MediaImage";

/**
 * A facade, not a player.
 *
 * A YouTube iframe costs about 1.1 MB of player script the moment it is parsed,
 * and `loading="lazy"` does not save you: Chrome's viewport margin is generous
 * enough that three embeds in the home page's videos band all downloaded before
 * anyone scrolled to them. That was 1.23 MB of third party — player script,
 * thumbnails and a Roboto webfont nothing on this site uses — charged against
 * the first paint of a page whose own markup is 80 KB.
 *
 * So the markup is the thumbnail and a play badge, and the iframe is created on
 * click. Nothing goes to youtube-nocookie.com until someone asks for a video.
 *
 * Without scripting the badge is a real link to the watch page, which is also
 * what a crawler follows.
 */
export default function VideoEmbed({
  video,
  eager = false,
  playLabel = "Play",
}: {
  video: any;
  eager?: boolean;
  playLabel?: string;
}) {
  const [playing, setPlaying] = useState(false);

  if (playing && video.embedUrl) {
    return (
      <div className="video-frame" data-video-embed data-video-id={video.youtubeId}>
        <iframe
          className="video-frame__player"
          src={`${video.embedUrl}${video.embedUrl.includes("?") ? "&" : "?"}autoplay=1`}
          title={video.title}
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowFullScreen
        />
      </div>
    );
  }

  return (
    <div
      className="video-frame video-frame--facade"
      data-video-embed
      data-video-title={video.title}
    >
      <a
        className="video-frame__poster"
        href={video.watchUrl}
        rel="noopener"
        aria-label={`${playLabel} ${video.title}`.trim()}
        onClick={(event) => {
          if (video.embedUrl) {
            event.preventDefault();
            setPlaying(true);
          }
        }}
      >
        {video.thumbnail ? (
          // Served from our own origin, so the facade costs no third-party
          // request at all.
          <MediaImage image={video.thumbnail} alt={video.title} eager={eager} />
        ) : (
          <img
            src={video.thumbnailUrl}
            alt={video.title}
            // maxresdefault is the 16:9 one, and the one size YouTube does not
            // have for every video, so the smaller still is the fallback.
            data-fallback-src={video.smallThumbnailUrl}
            width={1280}
            height={720}
            loading={eager ? "eager" : "lazy"}
            decoding="async"
          />
        )}
        <span className="video-frame__play" aria-hidden="true">
          ▶
        </span>
      </a>
    </div>
  );
}
