import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
  getYouTubeVideoId,
  getYoutubeShortsId,
  isYouTubeShorts,
  getVimeoVideoId,
  getVimeoParts,
  extractEmbedHeight,
  getTikTokVideoId,
  isTikTokLink,
  tiktokIdFromOembed,
  tiktokPlayerEmbedUrl,
  getDailymotionId,
  getStreamableId,
  getTwitchTarget,
  getSpotifyEmbedTarget,
  isSoundCloudTrack,
  getAppleMusicEmbed,
  getTweetId,
  getTidalEmbed,
  getInstagramEmbed,
  getRedditPostEmbed,
  getBlueskyEmbed,
  getLoomId,
  getKickChannel,
  getMixcloudFeed,
  getDeezerEmbed,
  deezerEmbedHeight,
  getSteamTarget,
  steamWidgetEmbedUrl,
  buildVideoEmbedUrl,
  spotifyEmbedHeight,
  parseMediaEmbed,
} from './videoEmbed';

const HOST = 'chat.lotusguild.org';

test('YouTube: watch / youtu.be / embed / shorts', () => {
  assert.equal(getYouTubeVideoId('https://www.youtube.com/watch?v=dQw4w9WgXcQ'), 'dQw4w9WgXcQ');
  assert.equal(getYouTubeVideoId('https://youtu.be/dQw4w9WgXcQ?t=42'), 'dQw4w9WgXcQ');
  assert.equal(getYouTubeVideoId('https://www.youtube.com/embed/dQw4w9WgXcQ'), 'dQw4w9WgXcQ');
  assert.equal(getYouTubeVideoId('https://youtube.com/shorts/abc123DEF_-'), 'abc123DEF_-');
  assert.equal(getYouTubeVideoId('https://www.youtube.com/live/abcLIVE123'), 'abcLIVE123');
  assert.equal(getYouTubeVideoId('https://music.youtube.com/watch?v=musicId12'), 'musicId12');
  assert.equal(getYouTubeVideoId('https://vimeo.com/123'), null);
  assert.equal(isYouTubeShorts('https://www.youtube.com/shorts/abc123'), true);
  assert.equal(getYoutubeShortsId('https://youtube.com/shorts/abc123'), 'abc123');
});

test('Vimeo (incl. unlisted hash + channel/group/album forms)', () => {
  assert.equal(getVimeoVideoId('https://vimeo.com/123456789'), '123456789');
  assert.equal(getVimeoVideoId('https://vimeo.com/channels/staffpicks'), null);
  assert.deepEqual(getVimeoParts('https://vimeo.com/123456789/abc123'), {
    id: '123456789',
    hash: 'abc123',
  });
  assert.ok(
    parseMediaEmbed('https://vimeo.com/123456789/abc123', 'h')?.embedUrl.includes('h=abc123'),
  );
  // channel / group / album share a trailing numeric video id
  assert.equal(getVimeoParts('https://vimeo.com/channels/staffpicks/76979871')?.id, '76979871');
  assert.equal(getVimeoParts('https://vimeo.com/groups/motion/videos/12345')?.id, '12345');
  assert.equal(getVimeoParts('https://vimeo.com/album/99/video/54321')?.id, '54321');
  // a normal video with a trailing sub-path segment must NOT capture it as a hash
  assert.equal(getVimeoParts('https://vimeo.com/123456789/likes')?.hash, undefined);
  assert.equal(getVimeoParts('https://vimeo.com/123456789/settings')?.hash, undefined);
  assert.equal(getVimeoParts('https://vimeo.com/123456789/likes')?.id, '123456789');
});

test('extractEmbedHeight: Instagram / Reddit / Twitter shapes', () => {
  assert.equal(extractEmbedHeight({ type: 'MEASURE', details: { height: 640 } }), 640);
  assert.equal(extractEmbedHeight({ type: 'resize.embed', data: 812 }), 812); // Reddit
  assert.equal(
    extractEmbedHeight({
      'twttr.embed': [{ method: 'twttr.private.resize', params: [{ height: 500 }] }],
    }),
    500,
  );
  assert.equal(extractEmbedHeight({ height: 300 }), 300); // generic fallback
  assert.equal(extractEmbedHeight({ type: 'other' }), undefined);
  assert.equal(extractEmbedHeight('not-an-object'), undefined);
});

test('mobile Shorts (m.youtube.com) → portrait', () => {
  assert.equal(parseMediaEmbed('https://m.youtube.com/shorts/abc123', 'h')?.kind, 'portrait');
});

test('TikTok: canonical /video/<id> only', () => {
  assert.equal(
    getTikTokVideoId('https://www.tiktok.com/@user/video/7234567890123456789'),
    '7234567890123456789',
  );
  assert.equal(getTikTokVideoId('https://vm.tiktok.com/ZMabc/'), null); // short link → oEmbed
  assert.equal(getTikTokVideoId('https://www.tiktok.com/@user'), null);
});

test('isTikTokLink: canonical + short + vm/vt', () => {
  assert.equal(isTikTokLink('https://www.tiktok.com/@user/video/123'), true);
  assert.equal(isTikTokLink('https://www.tiktok.com/t/ZTSHuuXWq/'), true);
  assert.equal(isTikTokLink('https://vm.tiktok.com/ZMabc/'), true);
  assert.equal(isTikTokLink('https://www.tiktok.com/@user'), false); // profile, not a video
  assert.equal(isTikTokLink('https://youtube.com/watch?v=x'), false);
  assert.equal(parseMediaEmbed('https://www.tiktok.com/@u/video/123', 'h'), null); // handled by its own card
});

test('tiktokIdFromOembed + player url', () => {
  assert.equal(
    tiktokIdFromOembed({ embed_product_id: '7659555276823006478' }),
    '7659555276823006478',
  );
  assert.equal(tiktokIdFromOembed({ html: '<blockquote data-video-id="123456">' }), '123456');
  assert.equal(tiktokIdFromOembed({}), null);
  assert.equal(
    tiktokPlayerEmbedUrl('999'),
    'https://www.tiktok.com/player/v1/999?autoplay=1&rel=0',
  );
});

test('Dailymotion + Streamable', () => {
  assert.equal(getDailymotionId('https://www.dailymotion.com/video/x8abcde'), 'x8abcde');
  assert.equal(getDailymotionId('https://dai.ly/x8abcde'), 'x8abcde');
  assert.equal(getStreamableId('https://streamable.com/abc12'), 'abc12');
  assert.equal(getStreamableId('https://streamable.com/e/abc12'), null); // already an embed path
  assert.equal(getStreamableId('https://streamable.com/login'), null); // reserved page
});

test('Twitch: channel / video / clip', () => {
  assert.deepEqual(getTwitchTarget('https://www.twitch.tv/somestreamer'), {
    type: 'channel',
    value: 'somestreamer',
  });
  assert.deepEqual(getTwitchTarget('https://www.twitch.tv/videos/123456789'), {
    type: 'video',
    value: '123456789',
  });
  assert.deepEqual(getTwitchTarget('https://clips.twitch.tv/FunnyClipSlug'), {
    type: 'clip',
    value: 'FunnyClipSlug',
  });
  assert.deepEqual(getTwitchTarget('https://www.twitch.tv/streamer/clip/CoolSlug'), {
    type: 'clip',
    value: 'CoolSlug',
  });
  // reserved utility pages are not channels
  assert.equal(getTwitchTarget('https://twitch.tv/directory'), null);
  assert.equal(getTwitchTarget('https://twitch.tv/settings'), null);
  assert.equal(getTwitchTarget('https://twitch.tv/videos'), null); // bare /videos, not a channel
});

test('Spotify target + height', () => {
  assert.deepEqual(getSpotifyEmbedTarget('https://open.spotify.com/track/4cOdK2wGLETKBW3PvgPWqT'), {
    type: 'track',
    id: '4cOdK2wGLETKBW3PvgPWqT',
  });
  assert.deepEqual(getSpotifyEmbedTarget('https://open.spotify.com/intl-de/album/xyz'), {
    type: 'album',
    id: 'xyz',
  });
  assert.equal(getSpotifyEmbedTarget('https://open.spotify.com/'), null);
  assert.equal(spotifyEmbedHeight('track'), 152);
  assert.equal(spotifyEmbedHeight('album'), 352);
});

test('SoundCloud track detection', () => {
  assert.equal(isSoundCloudTrack('https://soundcloud.com/artist/some-track'), true);
  assert.equal(isSoundCloudTrack('https://soundcloud.com/artist'), false); // bare profile
  // on.soundcloud.com short links intentionally not handled (need oEmbed resolve)
  assert.equal(isSoundCloudTrack('https://on.soundcloud.com/abc123'), false);
  assert.equal(isSoundCloudTrack('https://soundcloud.com/discover/xyz'), false); // site section
  assert.equal(isSoundCloudTrack('https://soundcloud.com/artist/sets'), false); // profile-tab listing
  assert.equal(isSoundCloudTrack('https://soundcloud.com/artist/sets/my-set'), true); // a real set
});

test('buildVideoEmbedUrl: cookie-less YouTube + Vimeo', () => {
  assert.equal(
    buildVideoEmbedUrl('youtube', 'dQw4w9WgXcQ'),
    'https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ?autoplay=1&rel=0&playsinline=1',
  );
  assert.equal(
    buildVideoEmbedUrl('vimeo', '42'),
    'https://player.vimeo.com/video/42?autoplay=1&dnt=1',
  );
  assert.equal(
    buildVideoEmbedUrl('vimeo', '42', 'h4sh'),
    'https://player.vimeo.com/video/42?autoplay=1&dnt=1&h=h4sh',
  );
});

test('parseMediaEmbed: routes provider + kind, builds embed URLs', () => {
  assert.deepEqual(parseMediaEmbed('https://youtube.com/shorts/abc', HOST), {
    provider: 'youtube',
    kind: 'portrait',
    embedUrl: 'https://www.youtube-nocookie.com/embed/abc?autoplay=1&rel=0&playsinline=1',
  });
  assert.equal(parseMediaEmbed('https://www.youtube.com/watch?v=xyz', HOST)?.kind, 'landscape');
  assert.equal(parseMediaEmbed('https://streamable.com/abc', HOST)?.provider, 'streamable');
  const spotify = parseMediaEmbed('https://open.spotify.com/track/abc', HOST);
  assert.equal(spotify?.kind, 'audio');
  assert.equal(spotify?.height, 152);
  assert.equal(parseMediaEmbed('https://soundcloud.com/a/b', HOST)?.provider, 'soundcloud');
  assert.equal(parseMediaEmbed('https://example.com/x', HOST), null);
});

test('Apple Music: album vs single song height, embed host swap', () => {
  const album = getAppleMusicEmbed('https://music.apple.com/us/album/some-album/123456');
  assert.equal(album?.embedUrl, 'https://embed.music.apple.com/us/album/some-album/123456');
  assert.equal(album?.height, 450);
  const song = getAppleMusicEmbed('https://music.apple.com/us/album/some-album/123456?i=789');
  assert.equal(song?.height, 175);
  assert.ok(song?.embedUrl.includes('?i=789'));
  assert.equal(getAppleMusicEmbed('https://music.apple.com/us/browse'), null);
  assert.equal(getAppleMusicEmbed('https://example.com/album/x/1'), null);
});

test('Mixcloud: cloudcast feed vs profile/section', () => {
  assert.equal(
    getMixcloudFeed('https://www.mixcloud.com/NTSRadio/some-show-2024/'),
    'https://www.mixcloud.com/NTSRadio/some-show-2024/',
  );
  assert.equal(getMixcloudFeed('https://www.mixcloud.com/NTSRadio/'), null); // bare profile
  assert.equal(getMixcloudFeed('https://www.mixcloud.com/NTSRadio/uploads/'), null); // profile tab
  assert.equal(getMixcloudFeed('https://www.mixcloud.com/discover/house/'), null); // site section
  assert.equal(getMixcloudFeed('https://example.com/a/b/'), null);
  assert.ok(
    parseMediaEmbed('https://www.mixcloud.com/NTSRadio/some-show/', HOST)?.embedUrl.startsWith(
      'https://www.mixcloud.com/widget/iframe/?feed=',
    ),
  );
});

test('Deezer: track / album / playlist (+ locale prefix)', () => {
  assert.deepEqual(getDeezerEmbed('https://www.deezer.com/track/3135556'), {
    type: 'track',
    id: '3135556',
  });
  assert.deepEqual(getDeezerEmbed('https://deezer.com/en/album/302127'), {
    type: 'album',
    id: '302127',
  });
  assert.deepEqual(getDeezerEmbed('https://www.deezer.com/us/playlist/1479458365?utm=x'), {
    type: 'playlist',
    id: '1479458365',
  });
  // Podcasts live at /show/<id>; /podcast/<id> is not a real Deezer path.
  assert.deepEqual(getDeezerEmbed('https://www.deezer.com/us/show/1002330852'), {
    type: 'show',
    id: '1002330852',
  });
  assert.deepEqual(getDeezerEmbed('https://www.deezer.com/us/episode/897651701'), {
    type: 'episode',
    id: '897651701',
  });
  assert.equal(getDeezerEmbed('https://www.deezer.com/us/podcast/1002330852'), null);
  assert.equal(getDeezerEmbed('https://www.deezer.com/'), null);
  assert.equal(getDeezerEmbed('https://www.deezer.com/track/notanid'), null);
  assert.equal(deezerEmbedHeight('track'), 152);
  assert.equal(deezerEmbedHeight('episode'), 152);
  assert.equal(deezerEmbedHeight('show'), 352);
  assert.equal(deezerEmbedHeight('album'), 352);
  assert.ok(
    parseMediaEmbed('https://www.deezer.com/track/3135556', HOST)?.embedUrl.startsWith(
      'https://widget.deezer.com/widget/dark/track/3135556',
    ),
  );
});

test('getSteamTarget: app / news / bundle / non-content', () => {
  assert.deepEqual(getSteamTarget('https://store.steampowered.com/app/739630/Phasmophobia/'), {
    kind: 'app',
    appId: '739630',
  });
  assert.deepEqual(
    getSteamTarget(
      'https://store.steampowered.com/news/app/739630/view/668371152183232404?l=english',
    ),
    { kind: 'news', appId: '739630', gid: '668371152183232404' },
  );
  assert.deepEqual(getSteamTarget('https://store.steampowered.com/bundle/232/'), {
    kind: 'store',
    label: 'bundle',
  });
  assert.deepEqual(getSteamTarget('https://store.steampowered.com/sub/12345/'), {
    kind: 'store',
    label: 'sub',
  });
  // non-content store pages and other hosts are not embedded
  assert.equal(getSteamTarget('https://store.steampowered.com/'), null);
  assert.equal(getSteamTarget('https://store.steampowered.com/search/?term=horror'), null);
  assert.equal(getSteamTarget('https://steamcommunity.com/app/739630'), null);
  assert.equal(getSteamTarget('not a url'), null);
});

test('steamWidgetEmbedUrl', () => {
  assert.equal(steamWidgetEmbedUrl('739630'), 'https://store.steampowered.com/widget/739630/');
});

test('getTweetId', () => {
  assert.equal(getTweetId('https://x.com/user/status/1799999999999999999'), '1799999999999999999');
  assert.equal(getTweetId('https://twitter.com/user/status/12345'), '12345');
  assert.equal(getTweetId('https://x.com/user'), null);
  assert.equal(getTweetId('https://youtube.com/watch?v=x'), null);
});

test('parseMediaEmbed: Apple Music → audio', () => {
  const m = parseMediaEmbed('https://music.apple.com/us/album/x/1?i=2', 'chat.lotusguild.org');
  assert.equal(m?.provider, 'applemusic');
  assert.equal(m?.kind, 'audio');
  assert.equal(m?.height, 175);
});

test('Tidal: track (audio) vs video (landscape)', () => {
  assert.deepEqual(getTidalEmbed('https://tidal.com/browse/track/12345'), {
    kind: 'audio',
    embedUrl: 'https://embed.tidal.com/tracks/12345',
    height: 120,
  });
  assert.equal(
    getTidalEmbed('https://listen.tidal.com/album/999')?.embedUrl,
    'https://embed.tidal.com/albums/999?layout=gridify',
  );
  assert.equal(getTidalEmbed('https://listen.tidal.com/album/999')?.height, 275);
  assert.equal(getTidalEmbed('https://tidal.com/video/555')?.kind, 'landscape');
  assert.equal(getTidalEmbed('https://tidal.com/browse'), null);
});

test('Instagram: p / reel / tv → embed path', () => {
  assert.equal(
    getInstagramEmbed('https://www.instagram.com/p/AbC123_-/'),
    'https://www.instagram.com/p/AbC123_-/embed/',
  );
  assert.equal(
    getInstagramEmbed('https://instagram.com/reel/XyZ/'),
    'https://www.instagram.com/reel/XyZ/embed/',
  );
  assert.equal(
    getInstagramEmbed('https://www.instagram.com/reels/XyZ/'),
    'https://www.instagram.com/reel/XyZ/embed/',
  );
  assert.equal(getInstagramEmbed('https://www.instagram.com/someuser/'), null);
});

test('Reddit post embed → embed.reddit.com', () => {
  assert.equal(
    getRedditPostEmbed('https://www.reddit.com/r/aww/comments/abc123/cute_cat/'),
    'https://embed.reddit.com/r/aww/comments/abc123/?ref_source=embed&ref=share&embed=true&theme=dark',
  );
  assert.equal(
    getRedditPostEmbed('https://old.reddit.com/r/aww/comments/xyz/'),
    'https://embed.reddit.com/r/aww/comments/xyz/?ref_source=embed&ref=share&embed=true&theme=dark',
  );
  assert.equal(getRedditPostEmbed('https://www.reddit.com/r/aww/'), null); // subreddit, not a post
  // redd.it short link / i.redd.it media host can't build the /r/<sub>/comments/<id>
  // path embed.reddit.com requires (a bare /comments/<id> 404s) → null so the caller's
  // og:url fallback resolves the canonical URL first.
  assert.equal(getRedditPostEmbed('https://redd.it/1abc23'), null);
  assert.equal(getRedditPostEmbed('https://i.redd.it/abcd1234.jpg'), null);
});

test('parseMediaEmbed: Instagram/Reddit → rich, Tidal → audio', () => {
  assert.equal(parseMediaEmbed('https://www.instagram.com/p/abc/', 'h')?.kind, 'rich');
  assert.equal(
    parseMediaEmbed('https://www.reddit.com/r/x/comments/y/z/', 'h')?.provider,
    'reddit',
  );
  assert.equal(parseMediaEmbed('https://tidal.com/browse/track/1', 'h')?.provider, 'tidal');
});

test('Bluesky / Loom / Kick', () => {
  assert.equal(
    getBlueskyEmbed('https://bsky.app/profile/alice.bsky.social/post/3kabc'),
    'https://embed.bsky.app/embed/alice.bsky.social/app.bsky.feed.post/3kabc',
  );
  assert.equal(getBlueskyEmbed('https://bsky.app/profile/alice.bsky.social'), null);
  assert.equal(
    parseMediaEmbed('https://bsky.app/profile/a.bsky.social/post/3k', 'h')?.kind,
    'rich',
  );

  assert.equal(getLoomId('https://www.loom.com/share/abc123DEF'), 'abc123DEF');
  assert.equal(getLoomId('https://www.loom.com/embed/abc123DEF'), 'abc123DEF');
  assert.equal(
    parseMediaEmbed('https://www.loom.com/share/xyz', 'h')?.embedUrl,
    'https://www.loom.com/embed/xyz',
  );

  assert.equal(getKickChannel('https://kick.com/somestreamer'), 'somestreamer');
  assert.equal(getKickChannel('https://kick.com/streamer/videos/123'), null); // VOD → no embed
  assert.equal(getKickChannel('https://kick.com/browse'), null); // nav page, not a channel
  assert.equal(getKickChannel('https://kick.com/following'), null);
  assert.ok(
    parseMediaEmbed('https://kick.com/streamer', 'h')?.embedUrl.includes(
      'player.kick.com/streamer?autoplay=true',
    ),
  );
});

test('parseMediaEmbed: Twitch embed carries the parent host', () => {
  const chan = parseMediaEmbed('https://twitch.tv/streamer', HOST);
  assert.equal(chan?.provider, 'twitch');
  assert.ok(chan?.embedUrl.includes('channel=streamer'));
  assert.ok(chan?.embedUrl.includes(`parent=${HOST}`));
  const clip = parseMediaEmbed('https://clips.twitch.tv/Slug', HOST);
  assert.ok(clip?.embedUrl.startsWith('https://clips.twitch.tv/embed?clip=Slug'));
});
