import { test, expect } from '@playwright/test';

test.describe('Pricing Page Console Errors', () => {
  test('should not have console errors on pricing page', async ({ page }) => {
    const consoleMessages: string[] = [];
    const consoleErrors: string[] = [];
    const consoleWarnings: string[] = [];

    // Listen to console events
    page.on('console', msg => {
      const text = msg.text();
      const type = msg.type();

      consoleMessages.push(`[${type.toUpperCase()}] ${text}`);

      if (type === 'error') {
        consoleErrors.push(text);
      } else if (type === 'warning') {
        consoleWarnings.push(text);
      }
    });

    // Listen to page errors
    page.on('pageerror', error => {
      consoleErrors.push(`Page Error: ${error.message}`);
    });

    // Navigate to pricing page
    await page.goto('http://localhost:9000/en/pricing');

    // Wait for page to fully load
    await page.waitForLoadState('networkidle');

    // Wait a bit for any async operations
    await page.waitForTimeout(2000);

    // Check if page loaded successfully
    const title = await page.title();
    console.log('Page Title:', title);

    // Check for key elements
    const hasTrialBanner = await page.locator('text=Free 7-Day Trial').isVisible();
    const hasTiers = await page.locator('text=Starter').isVisible();
    const hasCurrencySelector = await page.locator('select').first().isVisible();
    const hasBillingToggle = await page.locator('text=Monthly').isVisible();

    console.log('\n=== PAGE ELEMENTS ===');
    console.log('Trial Banner:', hasTrialBanner);
    console.log('Tiers Visible:', hasTiers);
    console.log('Currency Selector:', hasCurrencySelector);
    console.log('Billing Toggle:', hasBillingToggle);

    // Print all console messages
    console.log('\n=== ALL CONSOLE MESSAGES ===');
    consoleMessages.forEach(msg => console.log(msg));

    // Print warnings
    if (consoleWarnings.length > 0) {
      console.log('\n=== WARNINGS ===');
      consoleWarnings.forEach(warning => console.log(warning));
    }

    // Print errors
    if (consoleErrors.length > 0) {
      console.log('\n=== ERRORS ===');
      consoleErrors.forEach(error => console.log(error));
    }

    // Take screenshot
    await page.screenshot({ path: 'pricing-page-test.png', fullPage: true });
    console.log('\nScreenshot saved to: pricing-page-test.png');

    // Assertions
    expect(hasTrialBanner).toBeTruthy();
    expect(hasTiers).toBeTruthy();
    expect(hasCurrencySelector).toBeTruthy();
    expect(hasBillingToggle).toBeTruthy();

    // Check for critical errors (excluding React DevTools and known warnings)
    const criticalErrors = consoleErrors.filter(error =>
      !error.includes('React DevTools') &&
      !error.includes('Download the React DevTools') &&
      error.includes('Error') || error.includes('TypeError')
    );

    if (criticalErrors.length > 0) {
      console.log('\n=== CRITICAL ERRORS FOUND ===');
      criticalErrors.forEach(error => console.log(error));
    }

    // Fail test if critical errors exist
    expect(criticalErrors.length).toBe(0);
  });

  test('should toggle between monthly and yearly billing', async ({ page }) => {
    await page.goto('http://localhost:9000/en/pricing');
    await page.waitForLoadState('networkidle');

    // Click yearly button
    await page.locator('text=Yearly').click();
    await page.waitForTimeout(500);

    // Check for "Save 7%" badge
    const saveBadge = await page.locator('text=Save 7%').isVisible();
    expect(saveBadge).toBeTruthy();

    // Check for "Billed annually" text
    const billedAnnually = await page.locator('text=Billed annually').first().isVisible();
    expect(billedAnnually).toBeTruthy();

    // Click monthly button
    await page.locator('text=Monthly').click();
    await page.waitForTimeout(500);

    // "Billed annually" should be hidden
    const billedAnnuallyAfter = await page.locator('text=Billed annually').first().isVisible().catch(() => false);
    expect(billedAnnuallyAfter).toBeFalsy();
  });

  test('should change currency', async ({ page }) => {
    await page.goto('http://localhost:9000/en/pricing');
    await page.waitForLoadState('networkidle');

    // Get initial price
    const initialPrice = await page.locator('.text-4xl').first().textContent();
    console.log('Initial Price:', initialPrice);

    // Change to USD
    await page.locator('select').first().selectOption('USD');
    await page.waitForTimeout(500);

    // Get new price
    const newPrice = await page.locator('.text-4xl').first().textContent();
    console.log('New Price (USD):', newPrice);

    // Prices should be different
    expect(initialPrice).not.toBe(newPrice);
    expect(newPrice).toContain('$');
  });
});
