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

// A browser that blocks autoplay with sound: the race video falls back to muted
// play with "Tap for sound", and a tap turns the sound on.
//
// The block is simulated inside YouTube's frame - an unmuted play() is rejected
// with NotAllowedError, as a real browser does on a first visit - for the first
// seconds after load, so the result doesn't depend on the headless default.

test.describe('Live Racing — video sound blocked by the browser', () => {
    test.setTimeout(150_000);

    test('falls back to muted play with "Tap for sound", and a tap turns sound on', async ({ page }, testInfo) => {
        const eventId = await createYoutubeVideoEvent(page, 'LRVideoBlocked');
        await loginAs(page, USER.mobile, USER.password);
        await page.addInitScript(() => {
            if (!/youtube/.test(location.host)) return;
            const play = HTMLMediaElement.prototype.play;
            HTMLMediaElement.prototype.play = function (this: HTMLMediaElement) {
                if (!this.muted && performance.now() < 8000) {
                    return Promise.reject(new DOMException('play() with sound needs a user gesture', 'NotAllowedError'));
                }
                return play.call(this);
            };
        });
        await page.setViewportSize({ width: 390, height: 844 });
        await page.goto(`${BASE_URL}/play/live-racing/${eventId}`);

        const container = page.locator('#yt-player-container');
        await expect(container).toHaveAttribute('data-player-ready', 'true', { timeout: 30_000 });
        await expect(container).toHaveAttribute('data-muted', 'true', { timeout: 10_000 });
        await expect(page.locator('[data-testid="lr-video-sound-hint"]')).toBeVisible();
        await page.waitForTimeout(1500);
        await page.screenshot({ path: testInfo.outputPath('lr-video-blocked-muted-phone.png') });

        await page.waitForTimeout(6000); // past the simulated block
        await page.locator('[data-testid="lr-video-shield"]').click();
        await expect(container).toHaveAttribute('data-muted', 'false');
        await page.waitForTimeout(1000);
        await page.screenshot({ path: testInfo.outputPath('lr-video-blocked-then-tapped-phone.png') });
        await expect(page.locator('[data-testid="lr-video-sound-hint"]')).toBeHidden();
    });
});
