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

// Regression: picking an advance event after the current one has closed used to
// bounce the wizard back into the previous event's "Betting is closed" state a
// few seconds later. The race-status poll (every 5s) of the previous event was
// never stopped on Turbo navigation, so its "every race is closed" answer kept
// hiding the new event's wizard and showing the closed notice.
// See templates/play/live-racing/event.html.twig (stopRaceStatusPoll()).

/** Creates a published-able event on the given date; returns its id and show URL. */
async function createEventOnDate(page: Page, arenaName: string, dateStr: string): Promise<{ eventUrl: string; eventId: string }> {
    await page.goto(`${BASE_URL}/wfbo/events/new`);
    await page.selectOption('[data-testid="select-event-management"]', { label: arenaName });
    await page.fill('[data-testid="input-event-date"]', dateStr);
    await page.click('[data-testid="btn-submit"]');

    // The list is paginated newest-first, so a new event lands on the page that
    // holds its row (see WfboController::redirectToEventsPage()).
    await expect(page).toHaveURL(/\/wfbo\/events(\?page=\d+)?$/);

    const row  = page.locator('[data-testid^="event-row-"]').filter({ hasText: dateStr });
    const href = await row.locator('[data-testid^="btn-view-"]').getAttribute('href');
    const eventUrl = href ?? '';
    return { eventUrl, eventId: eventUrl.split('/').pop() ?? '' };
}

/** Shifts a YYYY-MM-DD string by whole days (UTC, no TZ drift). */
function shiftDays(dateStr: string, days: number): string {
    const d = new Date(`${dateStr}T00:00:00Z`);
    d.setUTCDate(d.getUTCDate() + days);
    return d.toISOString().slice(0, 10);
}

/** "Wednesday, December 25, 2030" for a YYYY-MM-DD string. */
function longDate(dateStr: string): string {
    return new Intl.DateTimeFormat('en-US', {
        timeZone: 'UTC', weekday: 'long', month: 'long', day: 'numeric', year: 'numeric',
    }).format(new Date(`${dateStr}T12:00:00Z`));
}

/** One event with a single race, two horses, a Win bet type - published. */
async function publishSimpleEvent(page: Page, arenaName: string, dateStr: string): Promise<{ eventUrl: string; eventId: string; raceUrl: string; raceId: string }> {
    const { eventUrl, eventId } = await createEventOnDate(page, arenaName, dateStr);
    const race = await addRace(page, eventUrl, 1);
    await addHorses(page, race.raceUrl, 2);
    await offerSingleBetTypes(page, eventUrl, [{ key: 'win', raceId: race.raceId }]);
    await publishEvent(page, eventUrl);

    return { eventUrl, eventId, raceUrl: race.raceUrl, raceId: race.raceId };
}

test.describe('Live Racing — advance event after the current one closed', () => {
    test.setTimeout(240_000);

    test('picking the next event keeps its wizard open instead of reverting to the closed event', async ({ page }) => {
        // Two consecutive dates, unique per run so a re-run never collides.
        const nextDate   = uniqueFutureDate();
        const closedDate = shiftDays(nextDate, -1);

        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await ensureLiveRacingEnabled(page);
        const arena = await createArena(page, 'LRAfterClose', { win: '10' });

        // The event the player is on: every race closed, so the page shows
        // "Betting is closed" and its poller answers "all closed".
        const closed = await publishSimpleEvent(page, arena, closedDate);
        await closeBetting(page, closed.raceUrl);

        // The advance event picked next - races open.
        const next = await publishSimpleEvent(page, arena, nextDate);

        await loginAs(page, USER.mobile, USER.password);

        // Only the current event's poller should run once the page is swapped.
        const statusCalls: string[] = [];
        page.on('request', (r) => {
            if (r.url().includes('/race-statuses')) statusCalls.push(r.url());
        });

        await page.goto(`${BASE_URL}/play/live-racing/${closed.eventId}`, { waitUntil: 'domcontentloaded' });
        await expect(page.locator('[data-testid="live-racing-event-date"]')).toHaveText(longDate(closedDate));
        await expect(page.locator('[data-testid="betting-closed-notice"]')).toBeVisible();
        await expect(page.locator('[data-testid="betting-wizard-card"]')).toBeHidden();

        // Its poller runs at once (and every 5s) - let one tick through.
        await expect.poll(() => statusCalls.filter((u) => u.includes(`/live-racing/${closed.eventId}/race-statuses`)).length)
            .toBeGreaterThan(0);

        // Pick the advance event from the closed notice's tabs.
        await page.click(`[data-testid="wizard-event-tabs-closed"] [data-testid="tab-event-${next.eventId}"]`);
        await expect(page).toHaveURL(new RegExp(`/play/live-racing/${next.eventId}$`));

        // The page is the next event, with its betting wizard open.
        await expect(page.locator('[data-testid="live-racing-event-date"]')).toHaveText(longDate(nextDate));
        await expect(page.locator('[data-testid="betting-wizard-card"]')).toBeVisible();
        await expect(page.locator('[data-testid="betting-closed-notice"]')).toBeHidden();

        // The regression: the previous event's poll keeps firing every 5s. Wait
        // past several ticks and the wizard must still be there.
        statusCalls.length = 0;
        await page.waitForTimeout(7000);

        await expect(page.locator('[data-testid="betting-wizard-card"]')).toBeVisible();
        await expect(page.locator('[data-testid="betting-closed-notice"]')).toBeHidden();
        await expect(page.locator('[data-testid="live-racing-event-date"]')).toHaveText(longDate(nextDate));

        // ...and it must poll the event on screen, not the one we left.
        expect(statusCalls.filter((u) => u.includes(`/live-racing/${next.eventId}/race-statuses`)).length).toBeGreaterThan(0);
        expect(statusCalls.filter((u) => u.includes(`/live-racing/${closed.eventId}/race-statuses`))).toEqual([]);
    });
});
