import { test, expect, Page } from '@playwright/test';
import path from 'path';
import { ADMIN, BASE_URL, SUPER_ADMIN, loginAs, manilaLocal, registerAndLogin } from '../helpers';

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

/** Creates a popup banner through the WFBO form (page logged in as super admin); returns its id. */
async function createPopupBanner(page: Page, title: string, opts: { startsAt?: string; endsAt?: string } = {}): Promise<string> {
    await page.goto(`${BASE_URL}/wfbo/popup-banners/new`);
    await page.fill('[data-testid="input-title"]', title);
    await page.setInputFiles('[data-testid="input-image"]', TEST_IMAGE);
    if (opts.startsAt) await page.fill('[data-testid="input-starts-at"]', opts.startsAt);
    if (opts.endsAt) await page.fill('[data-testid="input-ends-at"]', opts.endsAt);
    await page.click('[data-testid="btn-submit"]');

    await expect(page).toHaveURL(/\/wfbo\/popup-banners$/);
    const row = page.locator('[data-testid^="popup-banner-row-"]', { hasText: title }).first();
    await expect(row).toBeVisible();
    return ((await row.getAttribute('data-testid')) ?? '').replace('popup-banner-row-', '');
}

/** Deletes every popup banner so later home-page specs are never blocked by the modal. */
async function deleteAllPopupBanners(page: Page): Promise<void> {
    await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);
    page.on('dialog', (d) => d.accept().catch(() => {}));
    await page.goto(`${BASE_URL}/wfbo/popup-banners`);
    const deletes = page.locator('[data-testid^="btn-delete-"]');
    while (await deletes.count() > 0) {
        await deletes.first().click();
        await page.waitForLoadState('load');
    }
}

test.describe('WFBO Popup Banners', () => {

    test.afterEach(async ({ browser }) => {
        const page = await (await browser.newContext()).newPage();
        await deleteAllPopupBanners(page);
        await page.context().close();
    });

    test('one random banner of the active ones pops up, comes back 1 hour after closing, and stops when disabled', async ({ page, browser }) => {
        await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo`);
        await page.locator('button[aria-controls="campaigns-group-body"]').click();
        await page.locator('#campaigns-group-body [data-testid="wfbo-nav-popup-banners"]').click();
        await expect(page).toHaveURL(/\/wfbo\/popup-banners/);

        const first  = await createPopupBanner(page, `Always on ${Date.now()}`);
        await expect(page.locator(`[data-testid="popup-banner-duration-${first}"]`)).toHaveText('Always on');
        await expect(page.locator(`[data-testid="popup-banner-status-${first}"]`)).toHaveText(/active/i);
        const second = await createPopupBanner(page, `Dated ${Date.now()}`, { startsAt: manilaLocal(-60), endsAt: manilaLocal(24 * 60) });
        await expect(page.locator(`[data-testid="popup-banner-status-${second}"]`)).toHaveText(/active/i);

        // Player: popup shows on the home page with ONE of the two banners, no carousel.
        const playerContext = await browser.newContext();
        const player = await playerContext.newPage();
        await registerAndLogin(player);   // logging in lands on the home page = first visit
        const modal = player.locator('[data-testid="popup-banner"]');
        await expect(modal).toBeVisible();
        const slides = player.locator('[data-testid^="popup-banner-slide-"]');
        await expect(slides).toHaveCount(1);
        const shownId = ((await slides.getAttribute('data-testid')) ?? '').replace('popup-banner-slide-', '');
        expect([first, second]).toContain(shownId);
        await expect(player.locator('[data-testid="popup-banner-next"]')).toHaveCount(0);
        await expect(player.locator('[data-testid^="popup-banner-dot-"]')).toHaveCount(0);

        // It's random: over fresh visits (no snooze) both banners turn up.
        const seen = new Set([shownId]);
        for (let i = 0; i < 20 && seen.size < 2; i++) {
            await player.evaluate(() => localStorage.removeItem('popupBanners.closed'));
            await player.reload();
            await expect(modal).toBeVisible();
            seen.add(((await slides.getAttribute('data-testid')) ?? '').replace('popup-banner-slide-', ''));
        }
        expect([...seen].sort()).toEqual([first, second].sort());

        // Closing it snoozes ALL of them for an hour: refreshes (which could roll
        // the other banner) and new tabs stay quiet.
        await player.click('[data-testid="popup-banner-close"]');
        await expect(modal).toBeHidden();
        await player.reload();
        await expect(player.locator('[data-testid="wallet-bar"]')).toBeVisible();
        await player.waitForTimeout(800);
        await expect(modal).toBeHidden();
        const tab = await playerContext.newPage();
        await tab.goto(`${BASE_URL}/`);
        await expect(tab.locator('[data-testid="wallet-bar"]')).toBeVisible();
        await tab.waitForTimeout(800);
        await expect(tab.locator('[data-testid="popup-banner"]')).toBeHidden();
        await tab.close();

        // An hour after closing it pops up again.
        await player.evaluate(() => {
            const saved = JSON.parse(localStorage.getItem('popupBanners.closed') ?? '{}');
            localStorage.setItem('popupBanners.closed', JSON.stringify({ ...saved, at: Date.now() - 61 * 60_000 }));
        });
        await player.reload();
        await expect(modal).toBeVisible();
        await player.click('[data-testid="popup-banner-close"]');
        await expect(modal).toBeHidden();

        // Disabling a banner changes the set → it shows again with the remaining one.
        page.once('dialog', (d) => d.accept());
        await page.click(`[data-testid="btn-toggle-${second}"]`);
        await expect(page.locator(`[data-testid="popup-banner-status-${second}"]`)).toHaveText(/disabled/i);
        await player.goto(`${BASE_URL}/`);
        await expect(modal).toBeVisible();
        await expect(slides).toHaveCount(1);
        await expect(player.locator('[data-testid="popup-banner-next"]')).toHaveCount(0);
        await player.click('[data-testid="popup-banner-close"]');

        // A new visit (fresh browser session) shows it again.
        const freshContext = await browser.newContext();
        const fresh = await freshContext.newPage();
        await registerAndLogin(fresh);
        await expect(fresh.locator('[data-testid="popup-banner"]')).toBeVisible();

        await playerContext.close();
        await freshContext.close();
    });

    test('ended and scheduled banners do not pop up; bad dates are rejected', async ({ page, browser }) => {
        await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);
        const ended = await createPopupBanner(page, `Ended ${Date.now()}`, { startsAt: manilaLocal(-120), endsAt: manilaLocal(-60) });
        await expect(page.locator(`[data-testid="popup-banner-status-${ended}"]`)).toHaveText(/ended/i);
        const later = await createPopupBanner(page, `Later ${Date.now()}`, { startsAt: manilaLocal(60) });
        await expect(page.locator(`[data-testid="popup-banner-status-${later}"]`)).toHaveText(/scheduled/i);
        await expect(page.locator(`[data-testid="popup-banner-duration-${later}"]`)).toContainText('From');

        await page.goto(`${BASE_URL}/wfbo/popup-banners/new`);
        await page.fill('[data-testid="input-title"]', 'Backwards');
        await page.fill('[data-testid="input-starts-at"]', manilaLocal(60));
        await page.fill('[data-testid="input-ends-at"]', manilaLocal(0));
        await page.click('[data-testid="btn-submit"]');
        const errors = page.locator('[data-testid="flash-error"]');
        await expect(errors.filter({ hasText: 'End must be after Start' })).toHaveCount(1);
        await expect(errors.filter({ hasText: 'Banner image is required' })).toHaveCount(1);

        const playerContext = await browser.newContext();
        const player = await playerContext.newPage();
        await registerAndLogin(player);
        await player.goto(`${BASE_URL}/`);
        await expect(player.locator('[data-testid="wallet-bar"]')).toBeVisible();
        await expect(player.locator('[data-testid="popup-banner"]')).toHaveCount(0);
        await playerContext.close();
    });

    test('a regular admin cannot see or open popup banners', async ({ page }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo`);
        await expect(page.locator('[data-testid="wfbo-nav-popup-banners"]')).toHaveCount(0);

        const response = await page.goto(`${BASE_URL}/wfbo/popup-banners`);
        expect(response?.status()).toBe(403);
    });

});
