import { test, expect } from '@playwright/test';

/**
 * Homepage Test Suite for SAWIS Business Intelligence Dashboard
 * Tests the main landing page functionality and layout
 */
test.describe('SAWIS Homepage', () => {
  
  test.beforeEach(async ({ page }) => {
    // Navigate to the homepage before each test
    await page.goto('/');
    // Wait for the page to load completely with longer timeout
    await page.waitForLoadState('domcontentloaded');
    // Additional wait for dynamic content
    await page.waitForTimeout(5000);
  });

  test('should load homepage successfully', async ({ page }) => {
    // Verify page title
    await expect(page).toHaveTitle(/SAWIS Report/);
    
    // Verify URL
    await expect(page).toHaveURL('https://bi.sawisonline.co.za/');
    
    // Verify main elements are present
    await expect(page.locator('img[alt="Banner"]')).toBeVisible();
    await expect(page.locator('img[alt="SAWIS"]')).toBeVisible();
  });

  test('should display navigation elements', async ({ page }) => {
    // Check login button
    await expect(page.getByRole('button', { name: 'Login' })).toBeVisible();
    
    // Check contact link
    await expect(page.getByRole('link', { name: 'Contact' })).toBeVisible();
    await expect(page.getByRole('link', { name: 'Contact' })).toHaveAttribute('href', 'mailto:bi@sawis.co.za');
    
    // Check main navigation tabs
    await expect(page.getByRole('button', { name: 'Overview' })).toBeVisible();
    await expect(page.getByRole('button', { name: 'Volume' })).toBeVisible();
    await expect(page.getByRole('button', { name: 'Value' })).toBeVisible();
    await expect(page.getByRole('button', { name: 'Price Range' })).toBeVisible();
  });

  test('should display key metrics', async ({ page }) => {
    // Wait for metrics to load
    await page.waitForTimeout(2000);
    
    // Check for key metric sections
    await expect(page.getByText('Total Export (l)')).toBeVisible();
    await expect(page.getByText('Packaged (l)')).toBeVisible();
    await expect(page.getByText('Bulk (l)')).toBeVisible();
    
    // Verify metrics have values (not just "0")
    const totalExport = page.locator('text=Total Export (l)').locator('..').locator('text=/\\d+/').first();
    await expect(totalExport).toBeVisible();
  });

  test('should display chart sections', async ({ page }) => {
    // Wait for charts to load
    await page.waitForTimeout(3000);
    
    // Check for chart headings
    await expect(page.getByText('Export market per product type')).toBeVisible();
    await expect(page.getByText('Exports (L)')).toBeVisible();
    await expect(page.getByText('Cultivar / Type Exported')).toBeVisible();
    await expect(page.getByText('Export market volume by product type')).toBeVisible();
    await expect(page.getByText('Top Export Countries')).toBeVisible();
  });

  test('should have functional filter sidebar', async ({ page }) => {
    // Check filter sections
    await expect(page.getByText('Year')).toBeVisible();
    await expect(page.getByText('Ending Month')).toBeVisible();
    await expect(page.getByText('Reporting Period (Months)')).toBeVisible();
    await expect(page.getByText('Product Type')).toBeVisible();
    await expect(page.getByText('Country')).toBeVisible();
    await expect(page.getByText('Package Type')).toBeVisible();
    await expect(page.getByText('Cultivar/Type')).toBeVisible();
    
    // Check filter buttons
    await expect(page.getByRole('button', { name: 'Apply' })).toBeVisible();
    await expect(page.getByRole('button', { name: 'Clear' })).toBeVisible();
  });

  test('should display footer information', async ({ page }) => {
    // Check footer content
    await expect(page.getByText('Source: Department of Agriculture')).toBeVisible();
    await expect(page.getByRole('link', { name: 'Wine Online' })).toBeVisible();
    await expect(page.getByRole('link', { name: 'Silicon Overdrive' })).toBeVisible();
    
    // Verify footer links
    await expect(page.getByRole('link', { name: 'Wine Online' })).toHaveAttribute('href', 'https://www.dawineonline.co.za/');
    await expect(page.getByRole('link', { name: 'Silicon Overdrive' })).toHaveAttribute('href', 'https://www.overdrive.co.za/');
  });

  test('should handle responsive design', async ({ page }) => {
    // Test mobile viewport
    await page.setViewportSize({ width: 375, height: 667 });
    await page.waitForTimeout(1000);
    
    // Verify elements are still accessible
    await expect(page.getByRole('button', { name: 'Login' })).toBeVisible();
    await expect(page.getByRole('button', { name: 'Overview' })).toBeVisible();
    
    // Test tablet viewport
    await page.setViewportSize({ width: 768, height: 1024 });
    await page.waitForTimeout(1000);
    
    // Verify layout adapts
    await expect(page.getByRole('button', { name: 'Login' })).toBeVisible();
  });

  test('should have proper accessibility elements', async ({ page }) => {
    // Check for proper heading structure
    await expect(page.locator('h4')).toHaveCount(5); // Main chart headings
    
    // Check for alt text on images
    await expect(page.locator('img[alt="Banner"]')).toBeVisible();
    await expect(page.locator('img[alt="SAWIS"]')).toBeVisible();
    
    // Check for proper button roles
    await expect(page.getByRole('button', { name: 'Login' })).toBeVisible();
    await expect(page.getByRole('button', { name: 'Apply' })).toBeVisible();
  });

  test('should load without critical errors', async ({ page }) => {
    // Listen for console errors
    const errors: string[] = [];
    page.on('console', msg => {
      if (msg.type() === 'error') {
        errors.push(msg.text());
      }
    });
    
    // Wait for page to fully load
    await page.waitForTimeout(5000);
    
    // Filter out expected errors (like 404 for manifest.json)
    const criticalErrors = errors.filter(error => 
      !error.includes('manifest.json') && 
      !error.includes('gtag') &&
      !error.includes('GA4React')
    );
    
    // Log errors for debugging
    if (criticalErrors.length > 0) {
      console.log('Console errors found:', criticalErrors);
    }
    
    // Verify no critical errors (allowing for known non-critical issues)
    expect(criticalErrors.length).toBeLessThan(5);
  });
}); 