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

// A sound switch from the WFBO monitor never jumps on the player: the current
// sound fades out, then the new one (the BGM) fades in from silence over ~3s.
// The page mirrors the ramp on #yt-player-container (data-volume,
// data-sound-fade=out|in), which this test records.

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

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

type Sample = { t: number; fade: string | null; volume: number | null };

test.describe('WFBO Live Racing monitor — BGM fades in', () => {
    test.setTimeout(180_000);

    test('switching the sound fades the old one out and the BGM in, then back again', async ({ page, browser }, testInfo) => {
        const eventId = await createYoutubeVideoEvent(page, 'LRBgmFade');
        await page.goto(`${BASE_URL}/wfbo/live-racing/monitor?event=${eventId}`);
        await page.click('[data-testid="lr-monitor-video-links-toggle"]');
        await page.fill('[data-testid="lr-monitor-video-url-2"]', VIDEO_2);
        await page.click('[data-testid="lr-monitor-video-links-save"]');
        await expect(page.locator('[data-testid="lr-monitor-sound-bgm"]')).toBeEnabled();

        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');
        await expect(container).toHaveAttribute('data-player-ready', 'true', { timeout: 30_000 });
        await player.waitForTimeout(3000); // past the blocked-autoplay check
        await expect(container).toHaveAttribute('data-muted', 'false');
        // On page load there is no fade: sound starts as before.
        await expect(container).not.toHaveAttribute('data-sound-fade', /.+/);

        // Record every volume step from here on.
        const record = () => player.evaluate(() => {
            const el = document.getElementById('yt-player-container')!;
            const log: Sample[] = [];
            (window as unknown as { fadeLog: Sample[] }).fadeLog = log;
            const t0 = performance.now();
            new MutationObserver(() => log.push({
                t: Math.round(performance.now() - t0),
                fade: el.getAttribute('data-sound-fade'),
                volume: el.hasAttribute('data-volume') ? Number(el.getAttribute('data-volume')) : null,
            })).observe(el, { attributes: true, attributeFilter: ['data-volume', 'data-sound-fade'] });
        });
        const samples = async () => player.evaluate(() => (window as unknown as { fadeLog: Sample[] }).fadeLog);

        // Sound → Video 2 as BGM.
        await record();
        await page.click('[data-testid="lr-monitor-sound-bgm"]');
        await expect(container).toHaveAttribute('data-sound-fade', 'out', { timeout: 20_000 });
        await expect(container).toHaveAttribute('data-sound-fade', 'in', { timeout: 30_000 });
        await player.waitForTimeout(1200);
        await player.screenshot({ path: testInfo.outputPath('player-bgm-fading-in.png') });
        await expect(container).not.toHaveAttribute('data-sound-fade', /.+/, { timeout: 10_000 });
        await expect(container).toHaveAttribute('data-volume', '100');
        await expect(container).toHaveAttribute('data-bgm', 'youtube');
        await expect(container).toHaveAttribute('data-muted', 'false');
        checkRamp(await samples());

        // Sound → Main video: same the other way round.
        await record();
        await page.click('[data-testid="lr-monitor-sound-main"]');
        await expect(container).toHaveAttribute('data-sound-fade', 'out', { timeout: 20_000 });
        await expect(container).toHaveAttribute('data-sound-fade', 'in', { timeout: 30_000 });
        await expect(container).not.toHaveAttribute('data-sound-fade', /.+/, { timeout: 10_000 });
        await expect(container).toHaveAttribute('data-volume', '100');
        await expect(container).not.toHaveAttribute('data-bgm', /.+/);
        checkRamp(await samples());
        await player.screenshot({ path: testInfo.outputPath('player-main-sound-back.png') });

        await playerContext.close();
    });
});

/** Out: the volume only goes down to 0. In: from near silence only up to 100, over ~3s. */
function checkRamp(log: Sample[]): void {
    const out = log.filter((s) => s.fade === 'out' && s.volume !== null).map((s) => s.volume!);
    const fadeIn = log.filter((s) => s.fade === 'in' && s.volume !== null);
    const vols = fadeIn.map((s) => s.volume!);

    expect(out.length).toBeGreaterThan(2);
    expect(out[out.length - 1]).toBeLessThanOrEqual(15);
    out.slice(1).forEach((v, i) => expect(v).toBeLessThanOrEqual(out[i]));

    expect(vols.length).toBeGreaterThan(10);
    expect(vols[0]).toBeLessThanOrEqual(10);
    vols.slice(1).forEach((v, i) => expect(v).toBeGreaterThanOrEqual(vols[i]));
    expect(fadeIn[fadeIn.length - 1].t - fadeIn[0].t).toBeGreaterThanOrEqual(2500);
}
