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

// When a Live Racing event has no stream video URL, the video slot shows a
// carousel: the banners managed in WFBO ▸ Administration ▸ Live Racing
// Banners, or - with none enabled - the built-in assets/images/live-racing-banner/*.
// See event.html.twig + PlayController::liveRacingBanners().

const TEST_IMAGE = path.join(__dirname, '..', 'fixtures', 'test-banner.png');

test.describe('Live Racing event — banner carousel when there is no video', () => {
    test.setTimeout(120_000);

    test('shows the banner slider (and not the YouTube player) on a video-less event', async ({ page }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await ensureLiveRacingEnabled(page);
        const arena = await createArena(page, 'LRBanner', { 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 }]);
        await publishEvent(page, eventUrl); // createEventShowUrl sets no videoUrl

        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/play/live-racing/${eventId}`);

        const slider = page.locator('[data-testid="live-racing-banner-slider"]');
        await expect(slider).toBeVisible();
        await expect(page.locator('#yt-player')).toHaveCount(0);

        // One slide per file in the folder (>= 1).
        const slides = page.locator('[data-testid^="live-racing-banner-slide-"]');
        const count = await slides.count();
        expect(count).toBeGreaterThanOrEqual(1);
        await expect(slides.first()).toBeVisible();

        // Arrows/dots only when there is more than one banner (desktop viewport).
        if (count > 1) {
            await expect(page.locator('[data-testid="live-racing-banner-dot-0"]')).toHaveClass(/is-active/);

            // Auto-advances on its own (no interaction).
            await expect(page.locator('[data-testid="live-racing-banner-dot-1"]'))
                .toHaveClass(/is-active/, { timeout: 12_000 });

            // Loops: from the last banner it wraps back to the first.
            await page.click(`[data-testid="live-racing-banner-dot-${count - 1}"]`);
            await expect(page.locator(`[data-testid="live-racing-banner-dot-${count - 1}"]`)).toHaveClass(/is-active/);
            await expect(page.locator('[data-testid="live-racing-banner-dot-0"]'))
                .toHaveClass(/is-active/, { timeout: 12_000 });
        } else {
            await expect(page.locator('[data-testid="live-racing-banner-dots"]')).toHaveCount(0);
        }

        // Mobile: the slider is full-bleed (spans the viewport, wider than the
        // padded page container) and doesn't cause a horizontal page scroll.
        await page.setViewportSize({ width: 390, height: 844 });
        const metrics = await page.evaluate(() => {
            const el = document.querySelector('[data-testid="live-racing-banner-slider"]')!;
            return {
                sliderWidth: Math.round(el.getBoundingClientRect().width),
                viewport: document.documentElement.clientWidth,
                pageScrollable: document.documentElement.scrollWidth > document.documentElement.clientWidth + 1,
            };
        });
        expect(metrics.sliderWidth).toBe(metrics.viewport);
        expect(metrics.pageScrollable).toBe(false);
    });

    test('managed Live Racing banners replace the built-in ones, and the built-ins return when hidden', async ({ page }) => {
        const title = `LR Promo ${Date.now()}`;

        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await ensureLiveRacingEnabled(page);
        const arena = await createArena(page, 'LRManagedBanner', { 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 }]);
        await publishEvent(page, eventUrl);

        // Add an enabled, linked Live Racing banner.
        await page.goto(`${BASE_URL}/wfbo/lr-banners/new`);
        await page.fill('[data-testid="input-title"]', title);
        await page.setInputFiles('[data-testid="input-image"]', TEST_IMAGE);
        await page.fill('[data-testid="input-link-url"]', 'https://example.com/lr-promo');
        await page.click('[data-testid="btn-submit"]');
        const row = page.locator('[data-testid^="site-banner-row-"]', { hasText: title });
        const bannerId = ((await row.getAttribute('data-testid')) ?? '').replace('site-banner-row-', '');

        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/play/live-racing/${eventId}`);

        const slides = page.locator('[data-testid^="live-racing-banner-slide-"]');
        await expect(page.locator('[data-testid="live-racing-banner-slider"]')).toBeVisible();
        await expect(slides).toHaveCount(1);
        await expect(slides.first()).toHaveAttribute('alt', title);
        await expect(slides.first()).toHaveAttribute('src', /live-racing-banners\//);
        const link = page.locator('[data-testid="live-racing-banner-link-0"]');
        await expect(link).toHaveAttribute('href', 'https://example.com/lr-promo');
        await expect(link).toHaveAttribute('target', '_blank');

        // Hide it: the built-in banners come back.
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/lr-banners`);
        page.once('dialog', (d) => d.accept());
        await page.click(`[data-testid="btn-toggle-${bannerId}"]`);
        await expect(page.locator(`[data-testid="badge-status-${bannerId}"]`)).toHaveText('Disabled');

        await loginAs(page, USER.mobile, USER.password);
        await page.goto(`${BASE_URL}/play/live-racing/${eventId}`);
        await expect(slides.first()).toHaveAttribute('src', /live-racing-banner\/banner-1/);
        await expect(page.locator('[data-testid="live-racing-banner-link-0"]')).toHaveCount(0);

        // Clean up so the built-in-carousel test above stays deterministic.
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/lr-banners`);
        page.once('dialog', (d) => d.accept());
        await page.click(`[data-testid="btn-delete-${bannerId}"]`);
        await expect(page.locator(`[data-testid="site-banner-row-${bannerId}"]`)).toHaveCount(0);
    });
});
