interface VideoEmbedProps {
  url: string | null | undefined;
  poster?: string;
  className?: string;
}

function toEmbed(url: string): string {
  // YouTube watch / share / shorts
  const yt = url.match(/(?:youtube\.com\/(?:watch\?v=|shorts\/|embed\/)|youtu\.be\/)([\w-]{6,})/);
  if (yt) return `https://www.youtube.com/embed/${yt[1]}`;
  // Vimeo
  const vm = url.match(/vimeo\.com\/(\d+)/);
  if (vm) return `https://player.vimeo.com/video/${vm[1]}`;
  return url;
}

export function VideoEmbed({ url, poster, className }: VideoEmbedProps) {
  if (!url) {
    return (
      <div className={`relative grid aspect-video w-full place-items-center overflow-hidden rounded-xl border border-border bg-muted text-sm text-muted-foreground ${className ?? ""}`}>
        Video coming soon
      </div>
    );
  }
  const isHtml5 = /\.(mp4|webm|ogv|mov)(\?|$)/i.test(url);
  const embed = isHtml5 ? url : toEmbed(url);
  return (
    <div className={`relative aspect-video w-full overflow-hidden rounded-xl border border-border bg-black shadow-card ${className ?? ""}`}>
      {isHtml5 ? (
        <video src={embed} poster={poster} controls className="h-full w-full" />
      ) : (
        <iframe
          src={embed}
          className="absolute inset-0 h-full w-full"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowFullScreen
          title="Video player"
          loading="lazy"
        />
      )}
    </div>
  );
}
