import { test, expect, type Page } from '@playwright/test';
import { BASE_URL, USER, loginAs, createYoutubeVideoEvent } from '../helpers';

// Two videos per Live Racing event, switched on the WFBO Live Racing monitor:
// which one players see (Main) and whether the other plays hidden as
// background music (Sound = BGM, main muted). An open player page picks the
// change up on its 5s race-status poll - no reload.
// The launch flag allows autoplay with sound, so the result doesn't depend on
// the headless default (see live_racing_video_controls.spec.ts).

test.use({ launchOptions: { args: ['--autoplay-policy=no-user-gesture-required'] } });

const VIDEO_2 = 'https://www.youtube.com/watch?v=M7lc1UVf-VE';
const KICK_2 = 'https://kick.com/kick-djs';

test.describe('WFBO Live Racing monitor — two videos and BGM', () => {
    test.setTimeout(240_000);

    test('monitor picks the main video and plays the other as BGM; open player pages follow live', async ({ page, browser }, testInfo) => {
        const eventId = await createYoutubeVideoEvent(page, 'LRTwoVideos');
        const monitorUrl = `${BASE_URL}/wfbo/live-racing/monitor?event=${eventId}`;

        // Admin adds Video 2 from the monitor itself.
        await page.goto(monitorUrl);
        const controls = page.locator('[data-testid="lr-monitor-video-controls"]');
        await expect(controls).toBeVisible();
        await expect(page.locator('[data-testid="lr-monitor-main-2"]')).toBeDisabled();
        await expect(page.locator('[data-testid="lr-monitor-sound-bgm"]')).toBeDisabled();
        await page.click('[data-testid="lr-monitor-video-links-toggle"]');
        await expect(page.locator('[data-testid="lr-monitor-video-links-popup"]')).toBeVisible();
        await page.fill('[data-testid="lr-monitor-video-url-2"]', VIDEO_2);
        await page.screenshot({ path: testInfo.outputPath('monitor-links-popup.png') });
        await page.click('[data-testid="lr-monitor-video-links-save"]');
        await expect(page).toHaveURL(monitorUrl);
        await expect(page.locator('[data-testid="lr-monitor-main-1"]')).toHaveClass(/is-on/);
        await expect(page.locator('[data-testid="lr-monitor-main-2"]')).toBeEnabled();
        await expect(page.locator('[data-testid="lr-monitor-sound-main"]')).toHaveClass(/is-on/);

        // A player has the race open the whole time.
        const playerContext = await browser.newContext({ viewport: { width: 1280, height: 900 } });
        const player = await playerContext.newPage();
        await loginAs(player, USER.mobile, USER.password);
        await player.goto(`${BASE_URL}/play/live-racing/${eventId}`);
        const container = player.locator('#yt-player-container');
        const mainVideo = player.locator('iframe#yt-player');
        const bgm = player.locator('[data-testid="lr-video-bgm-player"]');
        await expect(container).toHaveAttribute('data-player-ready', 'true', { timeout: 30_000 });
        expect(await mainVideo.getAttribute('src')).toContain('ZGylNaQtilE');
        await expect(bgm).toHaveCount(0);
        await player.evaluate(() => { (window as unknown as { noReload: number }).noReload = 1; });
        await player.screenshot({ path: testInfo.outputPath('player-video-1.png') });

        // Main → Video 2.
        await page.click('[data-testid="lr-monitor-main-2"]');
        await expect(page.locator('[data-testid="lr-monitor-main-2"]')).toHaveClass(/is-on/);
        await expect.poll(async () => page.locator('[data-testid="lr-monitor-video"] iframe#yt-player').getAttribute('src'), { timeout: 20_000 }).toContain('M7lc1UVf-VE');
        await expect(page.locator('[data-testid="lr-monitor-sound-bgm"]')).toHaveText('Video 1 as BGM');
        await page.screenshot({ path: testInfo.outputPath('monitor-main-video-2.png') });

        await expect.poll(async () => mainVideo.getAttribute('src'), { timeout: 20_000 }).toContain('M7lc1UVf-VE');
        await expect(container).toHaveAttribute('data-player-ready', 'true', { timeout: 30_000 });
        await player.waitForTimeout(2000);
        await player.screenshot({ path: testInfo.outputPath('player-video-2.png') });

        // Sound → Video 1 as BGM: main muted, Video 1 plays hidden with sound.
        await page.click('[data-testid="lr-monitor-sound-bgm"]');
        await expect(page.locator('[data-testid="lr-monitor-sound-bgm"]')).toHaveClass(/is-on/);
        await page.screenshot({ path: testInfo.outputPath('monitor-video-1-as-bgm.png') });

        await expect(container).toHaveAttribute('data-bgm', 'youtube', { timeout: 20_000 });
        await expect(bgm).toBeAttached({ timeout: 30_000 });
        expect(await bgm.getAttribute('src')).toContain('ZGylNaQtilE');
        expect(await mainVideo.getAttribute('src')).toContain('M7lc1UVf-VE');
        expect(await mainVideo.getAttribute('src')).toContain('mute=1');
        await expect(container).toHaveAttribute('data-muted', 'false');
        await expect(player.locator('[data-testid="lr-video-sound-toggle"]')).toBeVisible();
        await player.waitForTimeout(2000);
        await player.screenshot({ path: testInfo.outputPath('player-video-2-with-bgm.png') });

        // The player's sound button mutes / unmutes the BGM.
        await player.click('[data-testid="lr-video-sound-toggle"]');
        await expect(container).toHaveAttribute('data-muted', 'true');
        await player.click('[data-testid="lr-video-sound-toggle"]');
        await expect(container).toHaveAttribute('data-muted', 'false');

        // A Kick channel as Video 2 still works as the main video with BGM: the
        // Kick player is muted through its src, the YouTube BGM keeps the sound.
        await setLinks(page, null, KICK_2);
        const kick = player.locator('[data-testid="live-racing-kick-video"]');
        await expect.poll(async () => kick.getAttribute('src'), { timeout: 20_000 }).toBe('https://player.kick.com/kick-djs?autoplay=true&muted=true');
        await expect(bgm).toBeAttached({ timeout: 30_000 });
        expect(await bgm.getAttribute('src')).toContain('ZGylNaQtilE');
        await player.waitForTimeout(2000);
        await player.screenshot({ path: testInfo.outputPath('player-kick-main-with-bgm.png') });

        // Main → Video 1: now Kick is the BGM (sound through its src).
        await page.click('[data-testid="lr-monitor-main-1"]');
        await expect.poll(async () => mainVideo.getAttribute('src'), { timeout: 20_000 }).toContain('ZGylNaQtilE');
        await expect(container).toHaveAttribute('data-bgm', 'kick', { timeout: 20_000 });
        expect(await bgm.getAttribute('src')).toBe('https://player.kick.com/kick-djs?autoplay=true&muted=false');
        await player.click('[data-testid="lr-video-sound-toggle"]');
        await expect(container).toHaveAttribute('data-muted', 'true');
        expect(await bgm.getAttribute('src')).toBe('https://player.kick.com/kick-djs?autoplay=true&muted=true');
        await player.click('[data-testid="lr-video-sound-toggle"]');

        // Sound → Main video: the BGM is gone.
        await page.click('[data-testid="lr-monitor-sound-main"]');
        await expect(page.locator('[data-testid="lr-monitor-sound-main"]')).toHaveClass(/is-on/);
        await expect(bgm).toHaveCount(0, { timeout: 20_000 });
        await expect(container).not.toHaveAttribute('data-bgm', /.+/);
        expect(await mainVideo.getAttribute('src')).toContain('ZGylNaQtilE');

        // All of it without reloading the player's page.
        expect(await player.evaluate(() => (window as unknown as { noReload?: number }).noReload)).toBe(1);
        await player.screenshot({ path: testInfo.outputPath('player-back-to-video-1.png') });
        await playerContext.close();
    });

    test('Links opens a popup that closes on Cancel, the X, Esc or the backdrop without saving', async ({ page }, testInfo) => {
        const eventId = await createYoutubeVideoEvent(page, 'LRLinksPopup');
        await page.goto(`${BASE_URL}/wfbo/live-racing/monitor?event=${eventId}`);
        const popup = page.locator('[data-testid="lr-monitor-video-links-popup"]');
        const open = async () => {
            await page.click('[data-testid="lr-monitor-video-links-toggle"]');
            await expect(popup).toBeVisible();
        };
        await expect(popup).toBeHidden();

        await open();
        // A real modal: centred on the screen, not tucked under the video.
        const box = await popup.boundingBox();
        const view = page.viewportSize()!;
        expect(Math.abs(box!.x + box!.width / 2 - view.width / 2)).toBeLessThan(4);
        await expect(page.locator('[data-testid="lr-monitor-video-url-1"]')).toHaveValue(/ZGylNaQtilE/);
        await page.fill('[data-testid="lr-monitor-video-url-2"]', VIDEO_2);
        await page.screenshot({ path: testInfo.outputPath('monitor-links-popup-open.png') });
        await page.click('[data-testid="lr-monitor-video-links-cancel"]');
        await expect(popup).toBeHidden();

        await open();
        await page.click('[data-testid="lr-monitor-video-links-close"]');
        await expect(popup).toBeHidden();

        await open();
        await page.keyboard.press('Escape');
        await expect(popup).toBeHidden();

        await open();
        await page.mouse.click(5, 5); // the backdrop
        await expect(popup).toBeHidden();

        // Nothing was saved.
        await page.reload();
        await expect(page.locator('[data-testid="lr-monitor-main-2"]')).toBeDisabled();
    });

    test('the event form takes a Video 2 link too', async ({ page }) => {
        const eventId = await createYoutubeVideoEvent(page, 'LRVideo2Form');
        await page.goto(`${BASE_URL}/wfbo/events/${eventId}/edit`);
        await page.fill('[data-testid="input-event-video-url-2"]', 'https://youtu.be/M7lc1UVf-VE?si=abc');
        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-2"]')).toHaveValue('https://www.youtube.com/embed/M7lc1UVf-VE');
    });
});

/** Monitor ▸ Links: set Video 1 and/or Video 2 (null keeps the current one) and save. */
async function setLinks(page: Page, video1: string | null, video2: string | null): Promise<void> {
    await page.click('[data-testid="lr-monitor-video-links-toggle"]');
    if (video1 !== null) await page.fill('[data-testid="lr-monitor-video-url-1"]', video1);
    if (video2 !== null) await page.fill('[data-testid="lr-monitor-video-url-2"]', video2);
    await page.click('[data-testid="lr-monitor-video-links-save"]');
    await expect(page.locator('[data-testid="lr-monitor-video-controls"]')).toBeVisible();
}
