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

// On a phone the race video autoplays on load - muted, because iOS/Android
// never autoplay with sound - with "Tap for sound"; a tap turns sound on.

const { defaultBrowserType: _ignored, ...iPhone } = devices['iPhone 13'];
test.use(iPhone);

test.describe('Live Racing — video on a phone', () => {
    test.setTimeout(150_000);

    test('autoplays muted on load with Tap for sound, and a tap turns sound on', async ({ page }, testInfo) => {
        const eventId = await createYoutubeVideoEvent(page, 'LRVideoPhone');
        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/play/live-racing/${eventId}`);

        const container = page.locator('#yt-player-container');
        await expect(container).toHaveAttribute('data-muted', 'true');
        await expect(page.locator('[data-testid="lr-video-sound-hint"]')).toBeVisible();

        // Muted in the embed itself, and playing on its own (YT.PlayerState.PLAYING = 1).
        const iframe = page.locator('iframe#yt-player');
        await expect(iframe).toBeAttached({ timeout: 30_000 });
        expect(await iframe.getAttribute('src')).toContain('mute=1');
        await expect(container).toHaveAttribute('data-player-state', '1', { timeout: 30_000 });
        await page.waitForTimeout(1500);
        await page.screenshot({ path: testInfo.outputPath('lr-video-phone-autoplay-muted.png') });

        // One tap on the video: sound on, still playing.
        await page.locator('[data-testid="lr-video-shield"]').tap();
        await expect(container).toHaveAttribute('data-muted', 'false');
        await expect(page.locator('[data-testid="lr-video-sound-hint"]')).toBeHidden();
        await expect(container).toHaveAttribute('data-player-state', '1');
        await page.screenshot({ path: testInfo.outputPath('lr-video-phone-tapped-sound-on.png') });
    });
});
