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

// A live race stays live: when the YouTube stream falls behind the live point
// (buffering, a background tab, a locked phone) the race video jumps back to it,
// on the players' page and on the WFBO monitor (same player). A real live stream
// doesn't play reliably headless, so the YouTube IFrame API is replaced by a fake
// whose stream we can put behind live on purpose. A real stream also plays some
// seconds behind its newest point by itself (fakeYTDelay): that counts as live,
// and the video must not keep jumping (each jump re-buffers = the video glitches).

const FAKE_YT_API = `
(function () {
    var players = [];
    window.fakeYT = { players: players, live: window.fakeYTLive !== false };
    var S = { UNSTARTED: -1, ENDED: 0, PLAYING: 1, PAUSED: 2, BUFFERING: 3, CUED: 5 };
    function Player(el, opts) {
        var self = this;
        var f = document.createElement('iframe');
        f.id = typeof el === 'string' ? el : el.id;
        f.src = 'about:blank';
        f.setAttribute('data-video-id', opts.videoId);
        (typeof el === 'string' ? document.getElementById(el) : el).replaceWith(f);
        var t0 = Date.now();
        var anchorPos = 1000 - (window.fakeYTDelay || 0), anchorAt = t0;
        self.seeks = [];
        self.isLiveStream = window.fakeYT.live;
        self.state = S.PLAYING;
        self.muted = !!(opts.playerVars && opts.playerVars.mute);
        self.vol = 100;
        var now = function () { return (Date.now() - t0) / 1000; };
        self.getDuration = function () { return self.isLiveStream ? 1000 + now() : 600; };
        self.getCurrentTime = function () {
            return self.state === S.PLAYING ? anchorPos + (Date.now() - anchorAt) / 1000 : anchorPos;
        };
        self.setBehind = function (secs) { anchorPos = self.getDuration() - secs; anchorAt = Date.now(); };
        self.seekTo = function (t) { self.seeks.push(t); anchorPos = t; anchorAt = Date.now(); };
        self.getVideoData = function () { return { video_id: opts.videoId, isLive: self.isLiveStream }; };
        self.getPlayerState = function () { return self.state; };
        self.playVideo = function () {
            if (self.state !== S.PLAYING) { anchorPos = self.getCurrentTime(); anchorAt = Date.now(); }
            self.state = S.PLAYING;
        };
        self.pauseVideo = function () { anchorPos = self.getCurrentTime(); self.state = S.PAUSED; };
        self.mute = function () { self.muted = true; };
        self.unMute = function () { self.muted = false; };
        self.isMuted = function () { return self.muted; };
        self.setVolume = function (v) { self.vol = v; };
        self.getVolume = function () { return self.vol; };
        // Draw the fake stream so the evidence shows it: how far behind live it is.
        var draw = setInterval(function () {
            var d = f.contentDocument;
            if (!d || !d.body) return;
            var lag = Math.max(0, Math.round(self.getDuration() - self.getCurrentTime()));
            var atLive = !self.isLiveStream || lag <= (window.fakeYTDelay || 0) + 15;
            d.body.style.cssText = 'margin:0;height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;'
                + 'font:700 6vw system-ui,sans-serif;color:#fff;background:' + (atLive ? '#0f5132' : '#842029');
            d.body.innerHTML = '<div style="font-size:3vw;opacity:.8">Test stream ' + (self.isLiveStream ? '(live)' : '(recorded)') + '</div>'
                + '<div>' + (self.isLiveStream ? (atLive ? 'AT LIVE (' + lag + 's stream delay)' : lag + 's BEHIND LIVE') : 'position ' + Math.round(self.getCurrentTime()) + 's') + '</div>'
                + '<div style="font-size:3vw;opacity:.8">' + (self.state === S.PAUSED ? 'paused' : 'playing') + ' · jumps to live: ' + self.seeks.length + '</div>';
        }, 200);
        self.destroy = function () { clearInterval(draw); f.remove(); };
        players.push(self);
        setTimeout(function () { opts.events.onReady({ target: self }); }, 300);
    }
    window.YT = { Player: Player, PlayerState: S };
    if (window.onYouTubeIframeAPIReady) window.onYouTubeIframeAPIReady();
})();
`;

type Fake = { seeks: number[]; lag: number };

async function useFakeYouTube(page: Page, live = true, delay = 0): Promise<void> {
    await page.addInitScript(([isLive, d]) => {
        Object.assign(window, { fakeYTLive: isLive, fakeYTDelay: d });
    }, [live, delay] as const);
    await page.route('https://www.youtube.com/iframe_api', (route) => route.fulfill({
        contentType: 'text/javascript', body: FAKE_YT_API,
    }));
}

/** The main video's fake player: how far behind live it is and where it was sought to. */
async function mainPlayer(page: Page): Promise<Fake> {
    return page.evaluate(() => {
        const p = (window as unknown as { fakeYT: { players: Array<{ seeks: number[]; getDuration(): number; getCurrentTime(): number }> } }).fakeYT.players[0];
        return { seeks: p.seeks.slice(), lag: p.getDuration() - p.getCurrentTime() };
    });
}

async function putBehind(page: Page, secs: number): Promise<void> {
    await page.evaluate((s) => {
        (window as unknown as { fakeYT: { players: Array<{ setBehind(n: number): void }> } }).fakeYT.players[0].setBehind(s);
    }, secs);
}

async function expectCatchesUp(page: Page, container: ReturnType<Page['locator']>): Promise<void> {
    const before = Number((await container.getAttribute('data-live-syncs')) ?? '0');
    await putBehind(page, 40);
    await page.waitForTimeout(800); // visible "40s BEHIND LIVE" in the evidence video
    await expect(container).toHaveAttribute('data-live-syncs', String(before + 1), { timeout: 8_000 });
    const p = await mainPlayer(page);
    expect(p.lag).toBeLessThan(3);
}

test.describe('Live Racing — the race video always stays live', () => {
    test.setTimeout(150_000);

    test('players: a live stream that fell behind jumps back to live, a small delay is left alone', async ({ page, browser }, testInfo) => {
        const eventId = await createYoutubeVideoEvent(page, 'LRStayLive');
        const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });
        const player = await ctx.newPage();
        await useFakeYouTube(player);
        await loginAs(player, USER.mobile, USER.password);
        await player.goto(`${BASE_URL}/play/live-racing/${eventId}`);
        const container = player.locator('#yt-player-container');
        await expect(container).toHaveAttribute('data-player-ready', 'true', { timeout: 30_000 });
        await expect(container).toHaveAttribute('data-live', '1', { timeout: 8_000 });
        await expect(container).toHaveAttribute('data-live-mode', 'player');

        // A few seconds behind is normal live delay: no jump.
        await putBehind(player, 5);
        await player.waitForTimeout(6_000);
        expect((await mainPlayer(player)).seeks).toHaveLength(0);
        expect(Number(await container.getAttribute('data-live-lag'))).toBeLessThanOrEqual(15);

        // 40s behind (a stall): back at the live point within one check.
        await expectCatchesUp(player, container);
        await player.screenshot({ path: testInfo.outputPath('player-caught-up-to-live.png') });

        // Back from a background tab / locked phone: catches up straight away,
        // and a paused stream plays again.
        await putBehind(player, 120);
        await player.evaluate(() => {
            const p = (window as unknown as { fakeYT: { players: Array<{ pauseVideo(): void }> } }).fakeYT.players[0];
            p.pauseVideo();
        });
        await player.waitForTimeout(1500);
        await player.screenshot({ path: testInfo.outputPath('player-behind-and-paused.png') });
        await player.evaluate(() => document.dispatchEvent(new Event('visibilitychange')));
        await expect(container).toHaveAttribute('data-live-syncs', '2', { timeout: 2_000 });
        const back = await mainPlayer(player);
        expect(back.lag).toBeLessThan(3);
        expect(await player.evaluate(() => (window as unknown as { fakeYT: { players: Array<{ state: number }> } }).fakeYT.players[0].state)).toBe(1);
        await player.screenshot({ path: testInfo.outputPath('player-back-from-background.png') });
        await ctx.close();
    });

    test('a recorded (not live) video is never moved', async ({ page, browser }) => {
        const eventId = await createYoutubeVideoEvent(page, 'LRStayVod');
        const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });
        const player = await ctx.newPage();
        await useFakeYouTube(player, false);
        await loginAs(player, USER.mobile, USER.password);
        await player.goto(`${BASE_URL}/play/live-racing/${eventId}`);
        const container = player.locator('#yt-player-container');
        await expect(container).toHaveAttribute('data-player-ready', 'true', { timeout: 30_000 });
        await putBehind(player, 300);
        await player.waitForTimeout(11_000);
        expect((await mainPlayer(player)).seeks).toHaveLength(0);
        await expect(container).not.toHaveAttribute('data-live', /.+/);
        await ctx.close();
    });

    test('WFBO monitor: same player, kept tighter to live (5s)', async ({ page }, testInfo) => {
        const eventId = await createYoutubeVideoEvent(page, 'LRStayLiveMon');
        await useFakeYouTube(page);
        await page.setViewportSize({ width: 1600, height: 900 });
        await page.goto(`${BASE_URL}/wfbo/live-racing/monitor?event=${eventId}`);
        const container = page.locator('[data-testid="lr-monitor-video"] #yt-player-container');
        await expect(container).toHaveAttribute('data-player-ready', 'true', { timeout: 30_000 });
        await expect(container).toHaveAttribute('data-live', '1', { timeout: 8_000 });
        await expect(container).toHaveAttribute('data-live-mode', 'monitor');

        // 8s behind: left alone on a player's phone, but the wall display jumps back to live.
        const before = Number((await container.getAttribute('data-live-syncs')) ?? '0');
        await putBehind(page, 8);
        await page.waitForTimeout(800); // visible "8s BEHIND LIVE" in the evidence video
        await expect(container).toHaveAttribute('data-live-syncs', String(before + 1), { timeout: 4_000 });
        expect((await mainPlayer(page)).lag).toBeLessThan(3);
        await page.screenshot({ path: testInfo.outputPath('monitor-8s-behind-caught-up.png') });
    });

    test('players: a stream that normally runs 25s behind is left alone, and never jumps back-to-back', async ({ page, browser }, testInfo) => {
        const eventId = await createYoutubeVideoEvent(page, 'LRStayDelay');
        const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });
        const player = await ctx.newPage();
        await useFakeYouTube(player, true, 25);
        await loginAs(player, USER.mobile, USER.password);
        await player.goto(`${BASE_URL}/play/live-racing/${eventId}`);
        const container = player.locator('#yt-player-container');
        await expect(container).toHaveAttribute('data-player-ready', 'true', { timeout: 30_000 });
        await expect(container).toHaveAttribute('data-live', '1', { timeout: 8_000 });

        // 25s is this stream's own delay: no jumping (this used to jump every 5s).
        await player.waitForTimeout(12_000);
        expect((await mainPlayer(player)).seeks).toHaveLength(0);
        await expect(container).toHaveAttribute('data-live-base-lag', /^2[4-6]$/);

        // Fell 40s further behind: one jump, back to the stream's own delay (not the edge).
        await putBehind(player, 65);
        await expect(container).toHaveAttribute('data-live-syncs', '1', { timeout: 8_000 });
        const after = await mainPlayer(player);
        expect(after.lag).toBeGreaterThan(20);
        expect(after.lag).toBeLessThan(30);

        // Right behind again (a stream that can't hold the live point): no second
        // jump inside the cooldown, so the video doesn't keep re-buffering.
        await putBehind(player, 65);
        await player.waitForTimeout(12_000);
        expect((await mainPlayer(player)).seeks).toHaveLength(1);
        await player.screenshot({ path: testInfo.outputPath('player-no-jump-loop.png') });
        await ctx.close();
    });
});
