import { test, expect } from '@playwright/test';
import {
    BASE_URL, ADMIN, SUPER_ADMIN, loginAs, registerAndLogin, ensureMinesEnabled, playMinesRound,
    readWalletBalance, manila, windowAroundNow, createPaymentDetail, requestDeposit, approveNewestDepositOf,
} from '../helpers';

// Campaigns ▸ Overview (ROLE_SUPER_ADMIN): every campaign active in a period,
// with what it paid (wallet credits in the period) and whom it reached.

/** The first peso amount in a text, e.g. "1 player · ₱0.30" → 0.30. */
const money = (s: string | null) => Number(((s ?? '').match(/₱([\d,]+\.\d{2})/)?.[1] ?? 'NaN').replace(/,/g, ''));

test.describe('WFBO Campaigns Overview', () => {
    test.setTimeout(180_000);

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

    test('lists the deposit promo and cashback campaigns active today with what they paid', async ({ page }, testInfo) => {
        const today = manila().date;
        const stamp = Date.now();
        const player = await registerAndLogin(page);

        // A deposit promo covering now; the player's ₱200 deposit earns ₱20.
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        const account = await createPaymentDetail(page, `Overview Bank ${stamp}`);
        await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);
        const win = windowAroundNow();
        await page.goto(`${BASE_URL}/wfbo/deposit-campaigns/new`);
        await page.fill('[data-testid="input-dc-name"]', `Overview Promo ${stamp}`);
        await page.fill('[data-testid="input-dc-start-date"]', today);
        await page.fill('[data-testid="input-dc-end-date"]', today);
        await page.fill('[data-testid="input-dc-window-start"]', win.start);
        await page.fill('[data-testid="input-dc-window-end"]', win.end);
        await page.click('[data-testid="btn-submit-deposit-campaign"]');
        const dRow = page.locator('[data-testid^="deposit-campaign-row-"]', { hasText: `Overview Promo ${stamp}` });
        const depositId = ((await dRow.getAttribute('data-testid')) ?? '').replace('deposit-campaign-row-', '');

        await loginAs(page, player.mobile, player.password);
        await requestDeposit(page, account, '200');
        expect(await approveNewestDepositOf(page, player.mobile)).toContain(`Promo bonus ₱20.00 credited (Overview Promo ${stamp})`);

        // Disable it straight away so it can't pay other specs' deposits (it
        // stays in the Overview: it ran today and paid in the period).
        await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/deposit-campaigns`);
        await page.click(`[data-testid="btn-toggle-deposit-campaign-${depositId}"]`);
        await expect(page.locator(`[data-testid="deposit-campaign-status-${depositId}"]`)).toHaveText(/disabled/i);

        // A Mines cashback campaign; the player loses, then a release pays 10%.
        await ensureMinesEnabled(page);
        await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/cashback-campaigns/new`);
        await page.fill('[data-testid="input-cb-name"]', `Overview Cash ${stamp}`);
        await page.fill('[data-testid="input-cb-start-date"]', today);
        await page.fill('[data-testid="input-cb-end-date"]', today);
        await page.click('[data-testid="cb-games-none"]');
        await page.check('[data-testid="input-cb-game-mines"]');
        await page.fill('[data-testid="input-cb-percentage"]', '10');
        await page.click('[data-testid="btn-submit-cashback-campaign"]');
        const cRow = page.locator('[data-testid^="cashback-campaign-row-"]', { hasText: `Overview Cash ${stamp}` });
        const cashbackId = ((await cRow.getAttribute('data-testid')) ?? '').replace('cashback-campaign-row-', '');

        await loginAs(page, player.mobile, player.password);
        await page.goto(`${BASE_URL}/`);
        const start = await readWalletBalance(page);
        let balance = start;
        for (let i = 0; i < 15 && balance >= start; i++) {
            expect(await playMinesRound(page)).toBe(true);
            await page.goto(`${BASE_URL}/`);
            balance = await readWalletBalance(page);
        }
        expect(balance).toBeLessThan(start);

        await loginAs(page, SUPER_ADMIN.mobile, SUPER_ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo/cashback-campaigns/${cashbackId}/payout`);
        await page.click('[data-testid="btn-pay-out-cashback"]');
        await expect(page.locator('[data-testid="cashback-release-1"]')).toBeVisible();
        const cashbackPaid = money(await page.locator('[data-testid="cashback-release-1-total"]').textContent());
        expect(cashbackPaid).toBeGreaterThan(0);

        // Campaigns ▸ Overview, Today.
        await page.goto(`${BASE_URL}/wfbo`);
        await page.click('[data-testid="wfbo-nav-campaigns-group"]');
        await page.click('[data-testid="wfbo-nav-campaigns-report"]');
        await expect(page).toHaveURL(/\/wfbo\/campaigns\/report/);
        await page.click('[data-testid="cr-period-today"]');
        await expect(page.locator('[data-testid="cr-period-label"]')).toContainText('Today');

        await expect(page.locator(`[data-testid="cr-row-deposit-${depositId}"]`)).toBeVisible();
        await expect(page.locator(`[data-testid="cr-paid-deposit-${depositId}"]`)).toContainText('₱20.00');
        await expect(page.locator(`[data-testid="cr-row-cashback-${cashbackId}"]`)).toBeVisible();
        expect(money(await page.locator(`[data-testid="cr-paid-cashback-${cashbackId}"]`).textContent())).toBeCloseTo(cashbackPaid, 2);
        await expect(page.locator(`[data-testid="cr-link-deposit-${depositId}"]`)).toHaveAttribute('href', `/wfbo/deposit-campaigns/${depositId}/report`);

        // The headline total is the sum of the type totals.
        const total    = money(await page.locator('[data-testid="cr-total"]').textContent());
        const deposit  = money(await page.locator('[data-testid="cr-total-deposit"]').textContent());
        const cashback = money(await page.locator('[data-testid="cr-total-cashback"]').textContent());
        const bonus    = money(await page.locator('[data-testid="cr-total-bonus"]').textContent());
        expect(total).toBeCloseTo(deposit + cashback + bonus, 2);
        expect(deposit).toBeGreaterThanOrEqual(20);
        await expect(page.locator('[data-testid="cr-chart"] canvas')).toBeVisible();
        await page.waitForTimeout(1200);
        await page.screenshot({ path: testInfo.outputPath('campaigns-overview.png'), fullPage: true });

        // A custom range in the past lists neither.
        await page.fill('[data-testid="cr-from"]', '2026-01-01');
        await page.fill('[data-testid="cr-to"]', '2026-01-31');
        await page.click('[data-testid="cr-range-submit"]');
        await expect(page.locator('[data-testid="cr-period-label"]')).toContainText('Jan 1 – Jan 31, 2026');
        await expect(page.locator(`[data-testid="cr-row-deposit-${depositId}"]`)).toHaveCount(0);
        await expect(page.locator(`[data-testid="cr-row-cashback-${cashbackId}"]`)).toHaveCount(0);
    });

    test('a plain ADMIN has no Overview link and gets 403', async ({ page }) => {
        await loginAs(page, ADMIN.mobile, ADMIN.password);
        await page.goto(`${BASE_URL}/wfbo`);
        await expect(page.locator('[data-testid="wfbo-nav-campaigns-report"]')).toHaveCount(0);
        const res = await page.goto(`${BASE_URL}/wfbo/campaigns/report`);
        expect(res?.status()).toBe(403);
    });
});
