import { test, expect } from '@playwright/test';
import { loginThroughAdminUi, navigateInBlazor } from './helpers/admin-auth';
import { captureEvidence } from './helpers/evidence';

test('production: verify all admin pages load correctly', async ({ page }) => {
  const baseUrl = (process.env.E2E_BASE_URL || 'https://www.taxbaik.com').replace(/\/$/, '');

  await loginThroughAdminUi(page, baseUrl, 'test_admin', 'TestAdmin@123456');

  const pageHero = page.locator('.admin-page-hero').first();
  const loadingOverlay = page.locator('#blazor-loading');

  const pages = [
    { name: '📊 Dashboard', url: `${baseUrl}/admin/dashboard`, hasData: false },
    { name: '👥 Clients', url: `${baseUrl}/admin/clients`, hasData: true },
    { name: '📅 Tax Filings', url: `${baseUrl}/admin/tax-filings`, hasData: true },
    { name: '📢 Announcements', url: `${baseUrl}/admin/announcements`, hasData: false },
    { name: '❓ FAQs', url: `${baseUrl}/admin/faqs`, hasData: true },
    { name: '📝 Blog', url: `${baseUrl}/admin/blog`, hasData: true },
    { name: '🎭 Season Simulator', url: `${baseUrl}/admin/season-simulator`, hasData: false },
    { name: '❔ Inquiries', url: `${baseUrl}/admin/inquiries`, hasData: true },
    { name: '⚙️ Settings', url: `${baseUrl}/admin/settings`, hasData: false },
  ];

  for (const pageInfo of pages) {
    console.log(`Testing: ${pageInfo.name}`);
    console.log(`URL: ${pageInfo.url}`);

    const startTime = Date.now();

    try {
      await navigateInBlazor(page, pageInfo.url);

      try {
        await pageHero.waitFor({ state: 'visible', timeout: 3000 });
      } catch {}

      const pageContent = page.locator('body').first();
      await pageContent.waitFor({ state: 'visible', timeout: 5000 });

      if (pageInfo.hasData) {
        try {
          await page.waitForSelector('tbody tr', { timeout: 8000 });
          const rowCount = await page.locator('tbody tr').count();
          if (rowCount > 0) {
            console.log(`  ✓ Data loaded: ${rowCount} rows`);
          }
        } catch {
          console.log(`  ℹ️  No table data`);
        }
      }

      const overlayShown = await loadingOverlay.evaluate((el: HTMLElement) =>
        el.classList.contains('show')
      ).catch(() => false);

      if (!overlayShown) {
      }

      const totalTime = Date.now() - startTime;
      console.log(`  ⏱️  Load time: ${totalTime}ms`);
      await captureEvidence(page, test.info(), pageInfo.name.replace(/[^a-zA-Z0-9]+/g, '_').toLowerCase());
    } catch (error) {
      const totalTime = Date.now() - startTime;
      console.log(`  ❌ FAILED: ${error}`);
      console.log(`  ⏱️  Time: ${totalTime}ms`);
      throw error;
    }
  }
});
