/**
 * Extract the 11-char YouTube video ID from any common URL shape:
 *   https://www.youtube.com/watch?v=ID
 *   https://youtu.be/ID
 *   https://www.youtube.com/shorts/ID
 *   https://www.youtube.com/embed/ID
 *   https://www.youtube.com/live/ID
 * Returns null when the URL is not a recognizable YouTube video link.
 */
export function parseYouTubeId(url: string): string | null {
  let u: URL;
  try {
    u = new URL(url.trim());
  } catch {
    return null;
  }

  const host = u.hostname.replace(/^www\.|^m\./, "");
  const isId = (s: string | null | undefined): s is string =>
    !!s && /^[A-Za-z0-9_-]{11}$/.test(s);

  if (host === "youtu.be") {
    const id = u.pathname.split("/")[1];
    return isId(id) ? id : null;
  }

  if (host === "youtube.com" || host === "youtube-nocookie.com") {
    const v = u.searchParams.get("v");
    if (isId(v)) return v;
    const m = u.pathname.match(/^\/(?:shorts|embed|live|v)\/([A-Za-z0-9_-]{11})/);
    return m ? m[1] : null;
  }

  return null;
}

/** Canonical watch URL for a video ID — what gets stored as the content URL. */
export function youTubeWatchUrl(id: string): string {
  return `https://www.youtube.com/watch?v=${id}`;
}

/** Static thumbnail served by YouTube for any public video. */
export function youTubeThumbnail(id: string): string {
  return `https://img.youtube.com/vi/${id}/hqdefault.jpg`;
}
