import { test } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';

test.describe('Detailed Color Contrast Analysis', () => {
  test('identify specific elements with contrast issues', async ({ page }) => {
    const pages = [
      { url: 'http://localhost:9000/en/login', name: 'Login (EN)' },
      { url: 'http://localhost:9000/en/signup', name: 'Signup (EN)' },
    ];

    for (const pageInfo of pages) {
      console.log(`\n${'='.repeat(60)}`);
      console.log(`Analyzing: ${pageInfo.name}`);
      console.log('='.repeat(60));

      await page.goto(pageInfo.url);

      const results = await new AxeBuilder({ page })
        .withTags(['wcag2aa'])
        .analyze();

      const contrastViolations = results.violations.filter(
        (v) => v.id === 'color-contrast'
      );

      if (contrastViolations.length > 0) {
        console.log(`\nFound ${contrastViolations.length} contrast violation(s):\n`);

        for (const violation of contrastViolations) {
          console.log(`Violation: ${violation.help}`);
          console.log(`Impact: ${violation.impact}\n`);

          for (let i = 0; i < violation.nodes.length; i++) {
            const node = violation.nodes[i];
            console.log(`Element ${i + 1}:`);
            console.log(`  HTML: ${node.html}`);
            console.log(`  Target: ${JSON.stringify(node.target)}`);

            if (node.any && node.any.length > 0) {
              node.any.forEach((check: any) => {
                console.log(`  Issue: ${check.message}`);
                if (check.data) {
                  console.log(`  Details:`, JSON.stringify(check.data, null, 2));
                }
              });
            }

            // Get computed styles for the element
            const elementStyles = await page.evaluate((selector) => {
              const el = document.querySelector(selector);
              if (!el) return null;

              const styles = window.getComputedStyle(el);
              return {
                color: styles.color,
                backgroundColor: styles.backgroundColor,
                fontSize: styles.fontSize,
                fontWeight: styles.fontWeight,
              };
            }, node.target[0]);

            if (elementStyles) {
              console.log(`  Computed Styles:`, elementStyles);
            }

            console.log('');
          }
        }
      } else {
        console.log('✅ No color contrast violations found!');
      }
    }
  });
});
