import { test, expect } from '@playwright/test';
import {
    BASE_URL,
    USER,
    ADMIN,
    loginAs,
    ensureLiveRacingEnabled,
    createArena,
    createEventShowUrl,
    addRace,
    addHorses,
    offerSingleBetTypes,
    publishEvent,
} from '../helpers';

// A Live Racing event's video can be a Kick stream as well as YouTube. Admins
// paste a kick.com/{channel} link or Kick's whole <iframe> embed code; it is
// saved as https://player.kick.com/{channel} (Event::setVideoUrl → KickUrl).

const KICK_EMBED_CODE = '<iframe src="https://player.kick.com/kick-djs" height="720" width="1280" frameborder="0" scrolling="no" allowfullscreen="true"></iframe>';
const KICK_EMBED_URL = 'https://player.kick.com/kick-djs';

test.describe('Live Racing — Kick and YouTube video links', () => {
    test.setTimeout(120_000);

    test('a pasted Kick embed code plays the Kick stream for players and on the WFBO monitor', async ({ page }, testInfo) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await ensureLiveRacingEnabled(page);
        const arena = await createArena(page, 'LRKick', { win: '10' });
        const { eventUrl, eventId } = await createEventShowUrl(page, arena);
        const race = await addRace(page, eventUrl, 1);
        await addHorses(page, race.raceUrl, 4);
        await offerSingleBetTypes(page, eventUrl, [{ key: 'win', raceId: race.raceId }]);

        // Kick's embed snippet, exactly as their Share ▸ Embed gives it.
        await page.goto(`${BASE_URL}/wfbo/events/${eventId}/edit`);
        await expect(page.locator('[data-testid="event-form"]')).toContainText('Kick channel link');
        await page.fill('[data-testid="input-event-video-url"]', KICK_EMBED_CODE);
        await page.click('[data-testid="btn-submit"]');
        await expect(page).toHaveURL(`${BASE_URL}/wfbo/events`);
        await page.goto(`${BASE_URL}/wfbo/events/${eventId}/edit`);
        await expect(page.locator('[data-testid="input-event-video-url"]')).toHaveValue(KICK_EMBED_URL);

        // A plain kick.com channel link is saved the same way.
        await page.fill('[data-testid="input-event-video-url"]', 'https://kick.com/kick-djs');
        await page.click('[data-testid="btn-submit"]');
        await expect(page).toHaveURL(`${BASE_URL}/wfbo/events`);
        await page.goto(`${BASE_URL}/wfbo/events/${eventId}/edit`);
        await expect(page.locator('[data-testid="input-event-video-url"]')).toHaveValue(KICK_EMBED_URL);

        await publishEvent(page, eventUrl);

        // WFBO monitor: the same Kick player as the players get, with Kick's autoplay params.
        await page.goto(`${BASE_URL}/wfbo/live-racing/monitor?event=${eventId}`);
        const monitorVideo = page.locator('[data-testid="lr-monitor-video"] [data-testid="live-racing-kick-video"]');
        await expect(monitorVideo).toBeVisible();
        expect(await monitorVideo.getAttribute('src')).toBe(`${KICK_EMBED_URL}?autoplay=true&muted=false`);

        // Player page: the Kick iframe in the video slot - no YouTube player, no banner slider.
        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/play/live-racing/${eventId}`);
        const kick = page.locator('[data-testid="live-racing-kick-video"]');
        await expect(kick).toBeVisible();
        expect(await kick.getAttribute('src')).toBe(`${KICK_EMBED_URL}?autoplay=true&muted=false`);
        expect(await kick.getAttribute('allow')).toContain('autoplay');
        await expect(page.locator('script[src*="youtube.com/iframe_api"]')).toHaveCount(0);
        await expect(page.locator('[data-testid="live-racing-banner-slider"]')).toHaveCount(0);
        // Players can click the Kick player itself (unmute / fullscreen) - unlike the locked YouTube one.
        await expect(kick).toHaveCSS('pointer-events', 'auto');
        await page.waitForTimeout(3000);
        await page.screenshot({ path: testInfo.outputPath('lr-kick-player-page.png') });

        await page.setViewportSize({ width: 390, height: 844 });
        await page.waitForTimeout(1500);
        await page.screenshot({ path: testInfo.outputPath('lr-kick-player-page-phone.png') });
    });

    test('a YouTube live share link is saved as the embed link and plays on the player page', async ({ page }, testInfo) => {
        const shareLink = 'https://www.youtube.com/live/ZGylNaQtilE?si=lp6bX1D-tNQmtPTv';
        const embedUrl = 'https://www.youtube.com/embed/ZGylNaQtilE';

        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await ensureLiveRacingEnabled(page);
        const arena = await createArena(page, 'LRYoutube', { win: '10' });
        const { eventUrl, eventId } = await createEventShowUrl(page, arena);
        const race = await addRace(page, eventUrl, 1);
        await addHorses(page, race.raceUrl, 4);
        await offerSingleBetTypes(page, eventUrl, [{ key: 'win', raceId: race.raceId }]);

        await page.goto(`${BASE_URL}/wfbo/events/${eventId}/edit`);
        await page.fill('[data-testid="input-event-video-url"]', shareLink);
        await page.click('[data-testid="btn-submit"]');
        await expect(page).toHaveURL(`${BASE_URL}/wfbo/events`);
        await page.goto(`${BASE_URL}/wfbo/events/${eventId}/edit`);
        await expect(page.locator('[data-testid="input-event-video-url"]')).toHaveValue(embedUrl);
        await page.screenshot({ path: testInfo.outputPath('lr-youtube-saved-link.png') });

        await publishEvent(page, eventUrl);

        // WFBO monitor plays it in the same player as the players get (no YouTube controls).
        await page.goto(`${BASE_URL}/wfbo/live-racing/monitor?event=${eventId}`);
        const monitorPlayer = page.locator('[data-testid="lr-monitor-video"] iframe#yt-player');
        await expect(monitorPlayer).toBeAttached({ timeout: 20_000 });
        expect(await monitorPlayer.getAttribute('src')).toContain('youtube.com/embed/ZGylNaQtilE');
        expect(await monitorPlayer.getAttribute('src')).toContain('controls=0');

        // Player page: the YouTube IFrame API player for that video - not the Kick iframe.
        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/play/live-racing/${eventId}`);
        const player = page.locator('iframe#yt-player');
        await expect(player).toBeAttached({ timeout: 20_000 });
        expect(await player.getAttribute('src')).toContain('youtube.com/embed/ZGylNaQtilE');
        await expect(page.locator('[data-testid="live-racing-kick-video"]')).toHaveCount(0);
        await page.waitForTimeout(4000);
        await page.screenshot({ path: testInfo.outputPath('lr-youtube-player-page.png') });

        await page.setViewportSize({ width: 390, height: 844 });
        await page.waitForTimeout(2000);
        await page.screenshot({ path: testInfo.outputPath('lr-youtube-player-page-phone.png') });
    });
});
