"use client";

import { useState } from "react";

/**
 * Renders a static thumbnail + play button. The YouTube iframe (and all its
 * third-party JS) only loads after the user clicks — so a trailer_enabled
 * game never costs page-speed budget for visitors who don't watch it.
 */
export function TrailerFacade({
  youtubeId,
  title,
}: {
  youtubeId: string;
  title: string;
}) {
  const [loaded, setLoaded] = useState(false);

  if (loaded) {
    return (
      <div className="aspect-video w-full overflow-hidden rounded-lg bg-black">
        <iframe
          className="h-full w-full"
          src={`https://www.youtube-nocookie.com/embed/${youtubeId}?autoplay=1`}
          title={`${title} — trailer`}
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowFullScreen
        />
      </div>
    );
  }

  return (
    <button
      type="button"
      onClick={() => setLoaded(true)}
      className="group relative aspect-video w-full overflow-hidden rounded-lg bg-ink-800"
      aria-label={`Play trailer for ${title}`}
    >
      {/* eslint-disable-next-line @next/next/no-img-element */}
      <img
        src={`https://i.ytimg.com/vi/${youtubeId}/hqdefault.jpg`}
        alt=""
        className="h-full w-full object-cover transition group-hover:brightness-90"
        loading="lazy"
      />
      <span className="absolute inset-0 flex items-center justify-center">
        <span className="flex h-16 w-16 items-center justify-center rounded-full bg-signal text-ink-950 shadow-lg transition group-hover:scale-105">
          <svg viewBox="0 0 24 24" className="ml-1 h-7 w-7" fill="currentColor">
            <path d="M8 5v14l11-7z" />
          </svg>
        </span>
      </span>
      <span className="absolute bottom-3 left-3 rounded bg-ink-950/80 px-2 py-1 text-xs text-bone-50">
        Watch trailer
      </span>
    </button>
  );
}
