import { test, expect } from '@playwright/test';
import {
    BASE_URL,
    USER,
    ADMIN,
    loginAs,
    ensureLiveRacingEnabled,
    createArena,
    createEventShowUrl,
    addRace,
    addHorses,
    offerSingleBetTypes,
    publishEvent,
} from '../helpers';

// A Live Racing event's video can be a Facebook video too. Admins paste the
// page's Share ▸ Embed code (or a plain facebook.com video link); Event::
// setVideoUrl normalises it to the plugin embed URL (FacebookUrl).
const FACEBOOK_IFRAME = '<iframe src="https://www.facebook.com/plugins/video.php?height=314&href=https%3A%2F%2Fwww.facebook.com%2Fmmtciracing%2Fvideos%2F1131658679514126%2F&show_text=false&width=560&t=0" width="560" height="314" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowfullscreen="true" allow="autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share" allowFullScreen="true"></iframe>';
const FACEBOOK_EMBED_URL = 'https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2Fmmtciracing%2Fvideos%2F1131658679514126%2F&show_text=false&width=560';

test.describe('Live Racing — Facebook video', () => {
    test.setTimeout(120_000);

    test('a pasted Facebook embed code plays on the WFBO monitor and the player page', async ({ page }, testInfo) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await ensureLiveRacingEnabled(page);
        const arena = await createArena(page, 'LRFacebook', { win: '10' });
        const { eventUrl, eventId } = await createEventShowUrl(page, arena);
        const race = await addRace(page, eventUrl, 1);
        await addHorses(page, race.raceUrl, 4);
        await offerSingleBetTypes(page, eventUrl, [{ key: 'win', raceId: race.raceId }]);

        // The embed snippet from the user's Facebook post is accepted as-is.
        await page.goto(`${BASE_URL}/wfbo/events/${eventId}/edit`);
        await expect(page.locator('[data-testid="event-form"]')).toContainText('Facebook video link');
        await page.fill('[data-testid="input-event-video-url"]', FACEBOOK_IFRAME);
        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"]')).toHaveValue(FACEBOOK_EMBED_URL);
        await page.screenshot({ path: testInfo.outputPath('lr-facebook-saved-embed.png') });

        // A plain page video link is saved the same way.
        await page.fill('[data-testid="input-event-video-url"]', 'https://www.facebook.com/mmtciracing/videos/1131658679514126/');
        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"]')).toHaveValue(FACEBOOK_EMBED_URL);

        await publishEvent(page, eventUrl);

        // Facebook's plugin is third-party: stub it so the test never waits on it.
        await page.route('https://www.facebook.com/plugins/video.php**', (route) => route.fulfill({
            status: 200,
            contentType: 'text/html',
            body: '<!doctype html><title>Facebook video</title>',
        }));

        // WFBO monitor: the Facebook iframe in the video slot.
        await page.goto(`${BASE_URL}/wfbo/live-racing/monitor?event=${eventId}`);
        const monitorVideo = page.locator('[data-testid="lr-monitor-video"] [data-testid="live-racing-facebook-video"]');
        await expect(monitorVideo).toBeAttached({ timeout: 20_000 });
        expect(await monitorVideo.getAttribute('src')).toBe(`${FACEBOOK_EMBED_URL}&autoplay=true&mute=0`);
        expect(await monitorVideo.getAttribute('data-facebook')).toBe('1');

        // Player page: the same Facebook iframe - no YouTube player, no banner slider.
        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/play/live-racing/${eventId}`);
        const player = page.locator('[data-testid="live-racing-facebook-video"]');
        await expect(player).toBeVisible({ timeout: 20_000 });
        expect(await player.getAttribute('src')).toBe(`${FACEBOOK_EMBED_URL}&autoplay=true&mute=0`);
        expect(await player.getAttribute('allow')).toContain('autoplay');
        await expect(page.locator('script[src*="youtube.com/iframe_api"]')).toHaveCount(0);
        await expect(page.locator('[data-testid="live-racing-banner-slider"]')).toHaveCount(0);
        // Players can click the Facebook player itself (unmute / fullscreen).
        await expect(player).toHaveCSS('pointer-events', 'auto');
        await page.waitForTimeout(1500);
        await page.screenshot({ path: testInfo.outputPath('lr-facebook-player-page.png') });

        await page.setViewportSize({ width: 390, height: 844 });
        await page.waitForTimeout(1000);
        await page.screenshot({ path: testInfo.outputPath('lr-facebook-player-page-phone.png') });
    });
});
