/**
 * Turns a plain video link into something embeddable.
 *
 * The portfolio API has no video field, so a link is pasted manually (see
 * `projectVideos` in `src/data/site.ts`) rather than fetched — this just
 * figures out how to play whatever link gets pasted there: an Aparat page
 * URL, a YouTube URL, or a direct video file.
 */

export type VideoEmbed =
  | { kind: "iframe"; src: string }
  | { kind: "file"; src: string };

function aparatEmbed(url: URL): VideoEmbed | null {
  // Aparat page URLs look like aparat.com/v/HASH or aparat.com/video/video/.../HASH/...
  const hash = url.pathname.split("/").filter(Boolean).pop();
  if (!hash) return null;
  return { kind: "iframe", src: `https://www.aparat.com/video/video/embed/videohash/${hash}/vt/frame` };
}

function youtubeEmbed(url: URL): VideoEmbed | null {
  const id =
    url.hostname.includes("youtu.be")
      ? url.pathname.slice(1)
      : (url.searchParams.get("v") ?? url.pathname.split("/").pop());
  if (!id) return null;
  return { kind: "iframe", src: `https://www.youtube.com/embed/${id}` };
}

export function resolveVideoEmbed(link: string): VideoEmbed | null {
  let url: URL;
  try {
    url = new URL(link);
  } catch {
    return null;
  }

  if (url.hostname.includes("aparat.com")) return aparatEmbed(url);
  if (url.hostname.includes("youtube.com") || url.hostname.includes("youtu.be")) {
    return youtubeEmbed(url);
  }

  // Anything else is treated as a direct video file link.
  return { kind: "file", src: link };
}
