import { Play } from "lucide-react";

type Props = {
  provider: string;
  url: string | null;
  poster?: string | null;
  title: string;
};

/**
 * Render a responsive 16:9 embedded video.
 *
 * - YouTube: extracts the video id from share, watch, or youtu.be URLs and
 *   renders an <iframe src="https://www.youtube.com/embed/<id>">.
 * - Vimeo: extracts the numeric id and renders the player iframe.
 * - MP4: renders a native <video controls> element with optional poster.
 * - Anything else (including no URL) returns null so the caller can show
 *   a fallback.
 */
export function VideoEmbed({ provider, url, poster, title }: Props) {
  if (!url || provider === "none") return null;

  if (provider === "youtube") {
    const id = extractYouTubeId(url);
    if (!id) return <UnsupportedNotice url={url} />;
    return (
      <div className="relative aspect-video w-full overflow-hidden rounded-2xl border border-[var(--color-line)] bg-black shadow-sm">
        <iframe
          className="absolute inset-0 h-full w-full"
          src={`https://www.youtube.com/embed/${id}?rel=0&modestbranding=1`}
          title={title}
          loading="lazy"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
          allowFullScreen
          referrerPolicy="strict-origin-when-cross-origin"
        />
      </div>
    );
  }

  if (provider === "vimeo") {
    const id = extractVimeoId(url);
    if (!id) return <UnsupportedNotice url={url} />;
    return (
      <div className="relative aspect-video w-full overflow-hidden rounded-2xl border border-[var(--color-line)] bg-black shadow-sm">
        <iframe
          className="absolute inset-0 h-full w-full"
          src={`https://player.vimeo.com/video/${id}?title=0&byline=0&portrait=0`}
          title={title}
          loading="lazy"
          allow="autoplay; fullscreen; picture-in-picture"
          allowFullScreen
          referrerPolicy="strict-origin-when-cross-origin"
        />
      </div>
    );
  }

  if (provider === "mp4") {
    return (
      <div className="relative aspect-video w-full overflow-hidden rounded-2xl border border-[var(--color-line)] bg-black shadow-sm">
        {/* eslint-disable-next-line jsx-a11y/media-has-caption */}
        <video
          src={url}
          poster={poster ?? undefined}
          controls
          preload="metadata"
          className="h-full w-full object-cover"
        />
      </div>
    );
  }

  return <UnsupportedNotice url={url} />;
}

function UnsupportedNotice({ url }: { url: string }) {
  return (
    <div className="flex items-center gap-3 rounded-xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 px-5 py-4 text-[13px] text-[var(--color-slate)]">
      <Play className="h-4 w-4 text-[var(--color-blue)]" aria-hidden />
      Video preview unavailable.{" "}
      <a
        href={url}
        target="_blank"
        rel="noreferrer"
        className="font-semibold text-[var(--color-blue)] underline"
      >
        Open in new tab
      </a>
    </div>
  );
}

function extractYouTubeId(url: string): string | null {
  const direct = url.match(/^[\w-]{11}$/);
  if (direct) return url;
  try {
    const u = new URL(url);
    if (u.hostname.includes("youtu.be")) {
      return u.pathname.slice(1).split("/")[0] || null;
    }
    if (u.hostname.includes("youtube.com") || u.hostname.includes("youtube-nocookie.com")) {
      const v = u.searchParams.get("v");
      if (v) return v;
      const embedMatch = u.pathname.match(/\/embed\/([\w-]{11})/);
      if (embedMatch) return embedMatch[1];
      const shortsMatch = u.pathname.match(/\/shorts\/([\w-]{11})/);
      if (shortsMatch) return shortsMatch[1];
    }
  } catch {
    return null;
  }
  return null;
}

function extractVimeoId(url: string): string | null {
  if (/^\d+$/.test(url)) return url;
  try {
    const u = new URL(url);
    const m = u.pathname.match(/(\d+)(?:\/|$)/);
    if (m) return m[1];
  } catch {
    return null;
  }
  return null;
}
