import { test, expect, Page, TestInfo } from '@playwright/test';
import {
    BASE_URL, ADMIN, SUPER_ADMIN, loginAs, readWalletBalance,
    manilaDate, disableAllBonusCampaigns, createBonusCampaign,
} from '../helpers';

// Campaigns ▸ Registration Bonus (ROLE_SUPER_ADMIN): dated signup bonus
// campaigns. A player who signs up on /register on an enabled campaign's dates
// gets its fixed ₱ bonus right away, into the main wallet or the mini-games
// bonus wallet. Enabled campaigns can't overlap.

const AGENT_REFERRAL_CODE = 'ABCDEF01';

/** Signs a new player up and returns the login-page toast, then logs them in. */
async function registerPlayer(page: Page, testInfo?: TestInfo, snapName?: string): Promise<{ mobile: string; password: string; toast: string }> {
    const mobile   = `+639${Date.now().toString().slice(-9)}`;
    const password = 'TestPass1!';

    await page.context().clearCookies();
    await page.goto(`${BASE_URL}/register`, { waitUntil: 'domcontentloaded', timeout: 60000 });
    if (testInfo && snapName) await snap(page, testInfo, snapName);
    await page.fill('[data-testid="input-first-name"]', 'Signup');
    await page.fill('[data-testid="input-last-name"]', 'Bonus');
    await page.fill('[data-testid="input-mobile-number"]', mobile);
    await page.fill('[data-testid="input-referral-code"]', AGENT_REFERRAL_CODE);
    await page.fill('[data-testid="input-password"]', password);
    await page.fill('[data-testid="input-password-confirm"]', password);
    await page.click('[data-testid="btn-register"]');
    await page.waitForURL(`${BASE_URL}/login`, { timeout: 30000 });
    const toast = (await page.locator('.toast').first().textContent()) ?? '';

    await loginAs(page, mobile, password);
    return { mobile, password, toast };
}

async function snap(page: Page, testInfo: TestInfo, name: string): Promise<void> {
    const viewport = page.viewportSize();
    await page.setViewportSize({ width: 390, height: 844 });   // a player's phone
    await page.addStyleTag({ content: '.sf-toolbar, .sf-minitoolbar, .sf-toolbarreset { display: none !important; }' });
    await page.waitForTimeout(900);
    await page.screenshot({ path: testInfo.outputPath(`player-${name}.png`) });
    if (viewport) await page.setViewportSize(viewport);
}

test.describe.serial('WFBO Registration Bonus campaigns', () => {
    test.setTimeout(180_000);

    test.beforeEach(async ({ page }) => {
        page.on('dialog', (d) => { d.accept().catch(() => {}); });
    });

    test.beforeAll(async ({ browser }) => {
        const page = await browser.newPage();
        await disableAllBonusCampaigns(page, 'rb');
        await page.close();
    });

    test.afterAll(async ({ browser }) => {
        // Leave them all off so other specs' sign-ups start at ₱0.
        const page = await browser.newPage();
        await disableAllBonusCampaigns(page, 'rb');
        await page.close();
    });

    test('campaigns have dates, cannot overlap, and can be scheduled ahead', async ({ page }) => {
        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('[data-testid="wfbo-nav-registration-bonus"]').click();
        await expect(page).toHaveURL(/\/wfbo\/registration-bonus$/);
        await expect(page.locator('[data-testid="wfbo-page-title"]')).toContainText('Registration Bonus');

        const zero = await createBonusCampaign(page, 'rb', { amount: '0' });
        expect(zero.id).toBe(0);
        await expect(page.locator('[data-testid="flash-error"]')).toContainText('Bonus amount must be greater than zero.');

        const now = await createBonusCampaign(page, 'rb', { name: `RB This Week ${Date.now()}`, start: manilaDate(), end: manilaDate(6) });
        expect(now.id).toBeGreaterThan(0);
        await expect(page.locator(`[data-testid="rb-campaign-status-${now.id}"]`)).toHaveText('active');

        const clash = await createBonusCampaign(page, 'rb', { start: manilaDate(-2), end: manilaDate() });
        expect(clash.id).toBe(0);
        await expect(page.locator('[data-testid="flash-error"]')).toContainText(`The dates overlap with "${now.name}"`);

        const next = await createBonusCampaign(page, 'rb', { name: `RB Next Week ${Date.now()}`, start: manilaDate(7), end: manilaDate(13) });
        expect(next.id).toBeGreaterThan(0);
        await expect(page.locator(`[data-testid="rb-campaign-status-${next.id}"]`)).toHaveText('scheduled');

        // A disabled campaign can share dates; turning it on while they clash is refused.
        await page.click(`[data-testid="btn-toggle-rb-campaign-${next.id}"]`);
        await expect(page.locator(`[data-testid="rb-campaign-status-${next.id}"]`)).toHaveText('disabled');
        await page.click(`[data-testid="btn-edit-rb-campaign-${next.id}"]`);
        await page.fill('[data-testid="input-rb-start-date"]', manilaDate(3));
        await page.click('[data-testid="btn-submit-rb-campaign"]');
        await expect(page.locator('[data-testid="flash-success"]')).toContainText('updated');
        await page.click(`[data-testid="btn-toggle-rb-campaign-${next.id}"]`);
        await expect(page.locator('[data-testid="flash-error"]')).toContainText(`The dates overlap with "${now.name}"`);
        await expect(page.locator(`[data-testid="rb-campaign-status-${next.id}"]`)).toHaveText('disabled');
    });

    test('admin (non super admin) cannot open the page', async ({ page }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        const response = await page.goto(`${BASE_URL}/wfbo/registration-bonus`);
        expect(response?.status()).toBe(403);
    });

    test('no campaign running today: no offer on /register and new players start at ₱0', async ({ page }) => {
        await disableAllBonusCampaigns(page, 'rb');
        await createBonusCampaign(page, 'rb', { amount: '50', start: manilaDate(2), end: manilaDate(5) });   // scheduled only

        await page.context().clearCookies();
        await page.goto(`${BASE_URL}/register`);
        await expect(page.locator('[data-testid="registration-form"]')).toBeVisible();
        await expect(page.locator('[data-testid="register-bonus-notice"]')).toHaveCount(0);

        const player = await registerPlayer(page);
        expect(player.toast).not.toContain('You get');
        expect(await readWalletBalance(page)).toBe(0);
    });

    test('main wallet: new player gets ₱50 they can see on the wallet bar', async ({ page }, testInfo) => {
        await disableAllBonusCampaigns(page, 'rb');
        const campaign = await createBonusCampaign(page, 'rb', { amount: '50', creditTo: 'main' });

        await page.context().clearCookies();
        await page.goto(`${BASE_URL}/register`);
        await expect(page.locator('[data-testid="register-bonus-notice"]')).toContainText('FREE when you sign up!');
        await expect(page.locator('[data-testid="register-bonus-amount"]')).toHaveText('₱50');
        await expect(page.locator('[data-testid="register-bonus-note"]')).toHaveCount(0);

        const player = await registerPlayer(page, testInfo, '1-register-offer-main');
        expect(player.toast).toContain('Registration successful! You get ₱50.00. Please log in.');
        expect(await readWalletBalance(page)).toBe(50);
        await expect(page.locator('[data-testid="wallet-bar-bonus"]')).toBeHidden();
        await snap(page, testInfo, '2-home-main-50');

        // Paid count on the list, the award on Bonuses Paid, and the player's ledger.
        await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/registration-bonus`);
        await expect(page.locator(`[data-testid="rb-campaign-paid-${campaign.id}"]`)).toHaveText('1 · ₱50.00');
        await page.goto(`${BASE_URL}/wfbo/registration-bonus/${campaign.id}/awards`);
        const row = page.locator('[data-testid="rb-awards-table"] tbody tr', { hasText: player.mobile });
        await expect(row).toContainText('₱50.00');

        // Effectiveness report: verdict, bonus cost, the player, the chart.
        await page.click('[data-testid="link-rb-campaign-report"]');
        await expect(page).toHaveURL(new RegExp(`/wfbo/registration-bonus/${campaign.id}/report$`));
        await expect(page.locator('[data-testid="bcr-verdict-badge"]')).toBeVisible();
        await expect(page.locator('[data-testid="bcr-verdict-reasons"]')).toContainText('Sign-ups per day');
        await expect(page.locator('[data-testid="bcr-bonus-cost"]')).toHaveText('₱50.00');
        await expect(page.locator('[data-testid="bcr-depositors"]')).toHaveText('0 / 1');
        const reportRow = page.locator('[data-testid^="bcr-player-"]', { hasText: player.mobile });
        await expect(reportRow).toContainText('No deposit yet');
        await expect(reportRow).toContainText('-₱50.00');
        await expect(page.locator('[data-testid="bcr-signups"]')).toBeVisible();
        await expect(page.locator('[data-testid="bcr-chart"] canvas')).toBeVisible();
        await page.addStyleTag({ content: '.sf-toolbar, .sf-minitoolbar, .sf-toolbarreset { display: none !important; }' });
        await page.waitForTimeout(1500);
        await page.screenshot({ path: testInfo.outputPath('wfbo-signup-campaign-report.png'), fullPage: true });

        // The list has a Report button too.
        await page.goto(`${BASE_URL}/wfbo/registration-bonus`);
        await page.click(`[data-testid="btn-report-rb-campaign-${campaign.id}"]`);
        await expect(page.locator('[data-testid="bcr-verdict"]')).toBeVisible();

        await page.goto(`${BASE_URL}/wfbo/registration-bonus/${campaign.id}/awards`);
        await page.locator('[data-testid="rb-awards-table"] tbody tr', { hasText: player.mobile }).locator('a').first().click();
        await expect(page.getByText('Registration Bonus').first()).toBeVisible();
    });

    test('bonus wallet: new player gets ₱30 in the bonus wallet, main stays ₱0', async ({ page }, testInfo) => {
        await disableAllBonusCampaigns(page, 'rb');
        const campaign = await createBonusCampaign(page, 'rb', { amount: '30', creditTo: 'bonus' });

        await page.context().clearCookies();
        await page.goto(`${BASE_URL}/register`);
        await expect(page.locator('[data-testid="register-bonus-amount"]')).toHaveText('₱30');
        await expect(page.locator('[data-testid="register-bonus-note"]')).toHaveText('🎮 Use it on any mini game');

        const player = await registerPlayer(page, testInfo, '3-register-offer-bonus');
        expect(player.toast).toContain('Registration successful! You get ₱30.00 to use on any mini game. Please log in.');
        expect(await readWalletBalance(page)).toBe(0);
        await expect(page.locator('[data-testid="wallet-bar-bonus-amount"]')).toHaveText('₱30.00');
        await snap(page, testInfo, '4-home-bonus-30');

        await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/registration-bonus/${campaign.id}/awards`);
        await expect(page.locator('[data-testid="rb-awards-table"] tbody tr', { hasText: player.mobile })).toContainText('₱30.00');
    });
});
