// Adapted from Bluesky social-app embed-player logic

export const embedPlayerSources = [
  "youtube",
  "youtubeShorts",
  "twitch",
  "spotify",
  "soundcloud",
  "appleMusic",
  "vimeo",
  "giphy",
  "tenor",
  "flickr",
] as const;

export type EmbedPlayerSource = (typeof embedPlayerSources)[number];

export type EmbedPlayerType =
  | "youtube_video"
  | "youtube_short"
  | "twitch_video"
  | "spotify_album"
  | "spotify_playlist"
  | "spotify_song"
  | "soundcloud_track"
  | "soundcloud_set"
  | "apple_music_playlist"
  | "apple_music_album"
  | "apple_music_song"
  | "vimeo_video"
  | "giphy_gif"
  | "tenor_gif"
  | "flickr_album";

export interface EmbedPlayerParams {
  type: EmbedPlayerType;
  playerUri: string;
  isGif?: boolean;
  source: EmbedPlayerSource;
  metaUri?: string;
  hideDetails?: boolean;
  dimensions?: {
    height: number;
    width: number;
  };
}

const giphyRegex = /media(?:[0-4]\.giphy\.com|\.giphy\.com)/i;
const gifFilenameRegex = /^(\S+)\.(webp|gif|mp4)$/i;

export function parseEmbedPlayerFromUrl(url: string): EmbedPlayerParams | undefined {
  let urlp;
  try {
    urlp = new URL(url);
  } catch {
    return undefined;
  }

  // youtube
  if (urlp.hostname === "youtu.be") {
    const videoId = urlp.pathname.split("/")[1];
    const t = urlp.searchParams.get("t") ?? "0";
    const seek = t.replace(/s$/, "");

    if (videoId) {
      return {
        type: "youtube_video",
        source: "youtube",
        playerUri: `https://www.youtube.com/embed/${videoId}?start=${seek}`,
      };
    }
  }
  if (
    urlp.hostname === "www.youtube.com" ||
    urlp.hostname === "youtube.com" ||
    urlp.hostname === "m.youtube.com" ||
    urlp.hostname === "music.youtube.com"
  ) {
    const [, page, shortOrLiveVideoId] = urlp.pathname.split("/");

    const isShorts = page === "shorts";
    const isLive = page === "live";
    const videoId =
      isShorts || isLive ? shortOrLiveVideoId : (urlp.searchParams.get("v") as string);
    const t = urlp.searchParams.get("t") ?? "0";
    const seek = t.replace(/s$/, "");

    if (videoId) {
      return {
        type: isShorts ? "youtube_short" : "youtube_video",
        source: isShorts ? "youtubeShorts" : "youtube",
        hideDetails: isShorts ? true : undefined,
        playerUri: `https://www.youtube.com/embed/${videoId}?start=${seek}`,
      };
    }
  }

  // twitch
  if (
    urlp.hostname === "twitch.tv" ||
    urlp.hostname === "www.twitch.tv" ||
    urlp.hostname === "m.twitch.tv"
  ) {
    const parent = typeof window !== "undefined" ? window.location.hostname : "localhost";

    const [, channelOrVideo, clipOrId, id] = urlp.pathname.split("/");

    if (channelOrVideo === "videos") {
      return {
        type: "twitch_video",
        source: "twitch",
        playerUri: `https://player.twitch.tv/?volume=0.5&!muted&video=${clipOrId}&parent=${parent}`,
      };
    } else if (clipOrId === "clip") {
      return {
        type: "twitch_video",
        source: "twitch",
        playerUri: `https://clips.twitch.tv/embed?volume=0.5&clip=${id}&parent=${parent}`,
      };
    } else if (channelOrVideo) {
      return {
        type: "twitch_video",
        source: "twitch",
        playerUri: `https://player.twitch.tv/?volume=0.5&!muted&channel=${channelOrVideo}&parent=${parent}`,
      };
    }
  }

  // spotify
  if (urlp.hostname === "open.spotify.com") {
    const [, typeOrLocale, idOrType, id] = urlp.pathname.split("/");

    if (idOrType) {
      if (typeOrLocale === "playlist" || idOrType === "playlist") {
        return {
          type: "spotify_playlist",
          source: "spotify",
          playerUri: `https://open.spotify.com/embed/playlist/${id ?? idOrType}`,
        };
      }
      if (typeOrLocale === "album" || idOrType === "album") {
        return {
          type: "spotify_album",
          source: "spotify",
          playerUri: `https://open.spotify.com/embed/album/${id ?? idOrType}`,
        };
      }
      if (typeOrLocale === "track" || idOrType === "track") {
        return {
          type: "spotify_song",
          source: "spotify",
          playerUri: `https://open.spotify.com/embed/track/${id ?? idOrType}`,
        };
      }
      if (typeOrLocale === "episode" || idOrType === "episode") {
        return {
          type: "spotify_song",
          source: "spotify",
          playerUri: `https://open.spotify.com/embed/episode/${id ?? idOrType}`,
        };
      }
      if (typeOrLocale === "show" || idOrType === "show") {
        return {
          type: "spotify_song",
          source: "spotify",
          playerUri: `https://open.spotify.com/embed/show/${id ?? idOrType}`,
        };
      }
    }
  }

  // soundcloud
  if (urlp.hostname === "soundcloud.com" || urlp.hostname === "www.soundcloud.com") {
    const [, user, trackOrSets, set] = urlp.pathname.split("/");

    if (user && trackOrSets) {
      if (trackOrSets === "sets" && set) {
        return {
          type: "soundcloud_set",
          source: "soundcloud",
          playerUri: `https://w.soundcloud.com/player/?url=${url}&visual=false&hide_related=true`,
        };
      }

      return {
        type: "soundcloud_track",
        source: "soundcloud",
        playerUri: `https://w.soundcloud.com/player/?url=${url}&visual=false&hide_related=true`,
      };
    }
  }

  // apple music
  if (urlp.hostname === "music.apple.com") {
    const pathParams = urlp.pathname.split("/");
    const type = pathParams[2];
    const songId = urlp.searchParams.get("i");

    if (pathParams.length === 5 && (type === "playlist" || type === "album" || type === "song")) {
      const embedUri = `https://embed.music.apple.com${urlp.pathname}${
        songId ? "?i=" + songId : ""
      }`;

      if (type === "playlist") {
        return {
          type: "apple_music_playlist",
          source: "appleMusic",
          playerUri: embedUri,
        };
      } else if (type === "song") {
        return {
          type: "apple_music_song",
          source: "appleMusic",
          playerUri: embedUri,
        };
      } else if (type === "album") {
        if (songId) {
          return {
            type: "apple_music_song",
            source: "appleMusic",
            playerUri: embedUri,
          };
        } else {
          return {
            type: "apple_music_album",
            source: "appleMusic",
            playerUri: embedUri,
          };
        }
      }
    }
  }

  // vimeo
  if (urlp.hostname === "vimeo.com" || urlp.hostname === "www.vimeo.com") {
    const [, videoId] = urlp.pathname.split("/");
    if (videoId) {
      return {
        type: "vimeo_video",
        source: "vimeo",
        playerUri: `https://player.vimeo.com/video/${videoId}`,
      };
    }
  }

  // giphy - main site
  if (urlp.hostname === "giphy.com" || urlp.hostname === "www.giphy.com") {
    const [, gifs, nameAndId] = urlp.pathname.split("/");

    if (gifs === "gifs" && nameAndId) {
      const gifId = nameAndId.split("-").pop();

      if (gifId) {
        return {
          type: "giphy_gif",
          source: "giphy",
          isGif: true,
          hideDetails: true,
          metaUri: `https://giphy.com/gifs/${gifId}`,
          playerUri: `https://i.giphy.com/media/${gifId}/200.webp`,
        };
      }
    }
  }

  // giphy - media CDN
  if (giphyRegex.test(urlp.hostname)) {
    const [, media, trackingOrId, idOrFilename, filename] = urlp.pathname.split("/");

    if (media === "media") {
      if (idOrFilename && gifFilenameRegex.test(idOrFilename)) {
        return {
          type: "giphy_gif",
          source: "giphy",
          isGif: true,
          hideDetails: true,
          metaUri: `https://giphy.com/gifs/${trackingOrId}`,
          playerUri: `https://i.giphy.com/media/${trackingOrId}/200.webp`,
        };
      } else if (filename && gifFilenameRegex.test(filename)) {
        return {
          type: "giphy_gif",
          source: "giphy",
          isGif: true,
          hideDetails: true,
          metaUri: `https://giphy.com/gifs/${idOrFilename}`,
          playerUri: `https://i.giphy.com/media/${idOrFilename}/200.webp`,
        };
      }
    }
  }

  // giphy - i.giphy.com
  if (urlp.hostname === "i.giphy.com" || urlp.hostname === "www.i.giphy.com") {
    const [, mediaOrFilename, filename] = urlp.pathname.split("/");

    if (mediaOrFilename === "media" && filename) {
      const gifId = filename.split(".")[0];
      return {
        type: "giphy_gif",
        source: "giphy",
        isGif: true,
        hideDetails: true,
        metaUri: `https://giphy.com/gifs/${gifId}`,
        playerUri: `https://i.giphy.com/media/${gifId}/200.webp`,
      };
    } else if (mediaOrFilename) {
      const gifId = mediaOrFilename.split(".")[0];
      return {
        type: "giphy_gif",
        source: "giphy",
        isGif: true,
        hideDetails: true,
        metaUri: `https://giphy.com/gifs/${gifId}`,
        playerUri: `https://i.giphy.com/media/${gifId}/200.webp`,
      };
    }
  }

  // tenor
  const tenorGif = parseTenorGif(urlp);
  if (tenorGif.success) {
    const { playerUri, dimensions } = tenorGif;

    return {
      type: "tenor_gif",
      source: "tenor",
      isGif: true,
      hideDetails: true,
      playerUri,
      dimensions,
    };
  }

  // flickr albums and groups
  if (urlp.hostname === "www.flickr.com" || urlp.hostname === "flickr.com") {
    let i = urlp.pathname.length - 1;
    while (i > 0 && urlp.pathname.charAt(i) === "/") {
      --i;
    }

    const pathComponents = urlp.pathname.slice(1, i + 1).split("/");
    if (pathComponents.length === 4) {
      const [photos, , albums, id] = pathComponents;
      if (photos === "photos" && albums === "albums") {
        return {
          type: "flickr_album",
          source: "flickr",
          playerUri: `https://embedr.flickr.com/photosets/${id}`,
        };
      }
    }

    if (pathComponents.length === 3) {
      const [groups, id, pool] = pathComponents;
      if (groups === "groups" && pool === "pool") {
        return {
          type: "flickr_album",
          source: "flickr",
          playerUri: `https://embedr.flickr.com/groups/${id}`,
        };
      }
    }
  }

  // link shortened flickr path
  if (urlp.hostname === "flic.kr") {
    const b58alph = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
    const [, type, idBase58Enc] = urlp.pathname.split("/");
    let id = 0n;
    for (const char of idBase58Enc) {
      const nextIdx = b58alph.indexOf(char);
      if (nextIdx >= 0) {
        id = id * 58n + BigInt(nextIdx);
      } else {
        return undefined;
      }
    }

    switch (type) {
      case "go": {
        const formattedGroupId = `${id}`;
        return {
          type: "flickr_album",
          source: "flickr",
          playerUri: `https://embedr.flickr.com/groups/${formattedGroupId.slice(0, -2)}@N${formattedGroupId.slice(-2)}`,
        };
      }
      case "s":
        return {
          type: "flickr_album",
          source: "flickr",
          playerUri: `https://embedr.flickr.com/photosets/${id}`,
        };
      default:
        return undefined;
    }
  }

  return undefined;
}

export function getPlayerAspect({
  type,
  hasThumb,
  width,
}: {
  type: EmbedPlayerParams["type"];
  hasThumb: boolean;
  width: number;
}): { aspectRatio?: number; height?: number } {
  if (!hasThumb) return { aspectRatio: 16 / 9 };

  const screenHeight = typeof window !== "undefined" ? window.innerHeight : 800;

  switch (type) {
    case "youtube_video":
    case "twitch_video":
    case "vimeo_video":
      return { aspectRatio: 16 / 9 };
    case "youtube_short":
      if (screenHeight < 600) {
        return { aspectRatio: (9 / 16) * 1.75 };
      } else {
        return { aspectRatio: (9 / 16) * 1.5 };
      }
    case "spotify_album":
    case "spotify_playlist":
    case "soundcloud_set":
      return { height: 380 };
    case "apple_music_album":
    case "apple_music_playlist":
      return { height: 450 };
    case "spotify_song":
      if (width <= 300) {
        return { height: 155 };
      }
      return { height: 232 };
    case "soundcloud_track":
      return { height: 165 };
    case "apple_music_song":
      return { height: 150 };
    case "flickr_album":
      return { height: 400 };
    default:
      return { aspectRatio: 16 / 9 };
  }
}

function parseTenorGif(urlp: URL):
  | { success: false }
  | {
      success: true;
      playerUri: string;
      dimensions?: { height: number; width: number };
    } {
  // Match media.tenor.com or media1.tenor.com, etc.
  if (!urlp.hostname.match(/^media\d*\.tenor\.com$/)) {
    return { success: false };
  }

  const pathParts = urlp.pathname.split("/").filter((p) => p);

  if (pathParts.length < 2) {
    return { success: false };
  }

  // Get dimensions if available
  const h = urlp.searchParams.get("hh");
  const w = urlp.searchParams.get("ww");

  const dimensions =
    h && w
      ? {
          height: Number(h),
          width: Number(w),
        }
      : undefined;

  // Use the original URL directly - it's already playable
  return {
    success: true,
    playerUri: urlp.href,
    dimensions,
  };
}
