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

test.describe('🔥 Smoke Tests - Critical Paths', () => {
  test.describe.configure({ mode: 'serial' });

  // Test 1: Homepage - English
  test('01. ✅ Homepage loads successfully (English)', async ({ page }) => {
    const response = await page.goto('http://localhost:9000/en');
    expect(response?.status()).toBe(200);

    // Check key elements
    await expect(page.locator('h1')).toBeVisible({ timeout: 10000 });
    await expect(page.locator('nav')).toBeVisible();
    await expect(page.locator('footer')).toBeVisible();

    // Check for console errors
    const errors: string[] = [];
    page.on('console', msg => {
      if (msg.type() === 'error') errors.push(msg.text());
    });

    await page.waitForTimeout(1000);
    console.log(`Console errors on homepage (EN): ${errors.length}`);
  });

  // Test 2: Homepage - Arabic (RTL)
  test('02. ✅ Homepage loads successfully (Arabic RTL)', async ({ page }) => {
    const response = await page.goto('http://localhost:9000/ar');
    expect(response?.status()).toBe(200);

    // Verify RTL direction
    const dir = await page.locator('html').getAttribute('dir');
    expect(dir).toBe('rtl');

    await expect(page.locator('h1')).toBeVisible({ timeout: 10000 });
    await expect(page.locator('nav')).toBeVisible();
  });

  // Test 3: Demo Booking Form
  test('03. 📅 Demo booking form accessible', async ({ page }) => {
    await page.goto('http://localhost:9000/en/demo');

    // Check form fields
    await expect(page.locator('[name="name"]')).toBeVisible({ timeout: 10000 });
    await expect(page.locator('[name="email"]')).toBeVisible();
    await expect(page.locator('[name="phone"]')).toBeVisible();

    // Check calendar exists
    const calendarExists = await page.locator('[data-testid="calendar"], .calendar, [class*="calendar"]').count() > 0;
    console.log(`Calendar component found: ${calendarExists}`);
  });

  // Test 4: Demo Booking - Arabic
  test('04. 📅 Demo booking form accessible (Arabic)', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/demo');

    const dir = await page.locator('html').getAttribute('dir');
    expect(dir).toBe('rtl');

    await expect(page.locator('[name="name"]')).toBeVisible({ timeout: 10000 });
  });

  // Test 5: Signup Page
  test('05. 🔐 Signup form accessible', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup');

    // Check form fields
    await expect(page.locator('[name="email"]')).toBeVisible({ timeout: 10000 });
    await expect(page.locator('[name="password"]')).toBeVisible();
    await expect(page.locator('[name="fullName"]')).toBeVisible();
    await expect(page.locator('[type="submit"]')).toBeVisible();
  });

  // Test 6: Signup Validation
  test('06. 🔐 Signup validation works', async ({ page }) => {
    await page.goto('http://localhost:9000/en/signup');

    // Try to submit empty form
    await page.click('[type="submit"]');

    // Should show validation errors
    await page.waitForTimeout(1000);
    const hasErrors = await page.locator('[role="alert"], .error, [class*="error"]').count() > 0;
    console.log(`Validation errors shown: ${hasErrors}`);
  });

  // Test 7: Login Page
  test('07. 🔑 Login form accessible', async ({ page }) => {
    await page.goto('http://localhost:9000/en/login');

    await expect(page.locator('[name="email"]')).toBeVisible({ timeout: 10000 });
    await expect(page.locator('[name="password"]')).toBeVisible();
    await expect(page.locator('[type="submit"]')).toBeVisible();
  });

  // Test 8: Password Reset
  test('08. 🔄 Password reset page accessible', async ({ page }) => {
    await page.goto('http://localhost:9000/en/forgot-password');

    await expect(page.locator('[name="email"]')).toBeVisible({ timeout: 10000 });
    await expect(page.locator('[type="submit"]')).toBeVisible();
  });

  // Test 9: Pricing Page
  test('09. 💰 Pricing page loads and displays tiers', async ({ page }) => {
    await page.goto('http://localhost:9000/en/pricing');

    // Check for pricing tiers (should have at least 3)
    const pricingCards = await page.locator('[class*="tier"], [class*="pricing"], [class*="plan"]').count();
    console.log(`Pricing tiers found: ${pricingCards}`);

    // Check for prices
    const priceElements = await page.locator('[class*="price"], [class*="amount"]').count();
    console.log(`Price elements found: ${priceElements}`);
  });

  // Test 10: Pricing Page - Arabic
  test('10. 💰 Pricing page loads (Arabic)', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/pricing');

    const dir = await page.locator('html').getAttribute('dir');
    expect(dir).toBe('rtl');
  });

  // Test 11: Language Switching
  test('11. 🌐 Language switching works', async ({ page }) => {
    await page.goto('http://localhost:9000/en');

    // Look for language switcher
    const langSwitcher = page.locator('[data-testid="lang-switcher"], [class*="lang"], a[href*="/ar"]').first();

    if (await langSwitcher.isVisible()) {
      await langSwitcher.click();
      await page.waitForTimeout(1000);

      // Verify switched to Arabic
      const currentUrl = page.url();
      console.log(`URL after language switch: ${currentUrl}`);
      expect(currentUrl).toContain('/ar');
    } else {
      console.log('Language switcher not found - checking navigation links');
    }
  });

  // Test 12-16: Dynamic Service × Location Pages
  test('12. 🏥 Service page: Qatar - WhatsApp Appointments', async ({ page }) => {
    await page.goto('http://localhost:9000/en/qatar/whatsapp-appointment-booking');
    const response = await page.waitForLoadState('networkidle');

    // Check page loaded
    await expect(page.locator('h1, h2')).toBeVisible({ timeout: 10000 });
  });

  test('13. 🏥 Service page: Dubai - WhatsApp Appointments (Arabic)', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/dubai/whatsapp-appointment-booking');

    const dir = await page.locator('html').getAttribute('dir');
    expect(dir).toBe('rtl');
    await expect(page.locator('h1, h2')).toBeVisible({ timeout: 10000 });
  });

  test('14. 🏥 Service page: Riyadh - Patient Management', async ({ page }) => {
    await page.goto('http://localhost:9000/en/riyadh/patient-management-system');
    await expect(page.locator('h1, h2')).toBeVisible({ timeout: 10000 });
  });

  test('15. 🏥 Service page: Kuwait - Queue Management', async ({ page }) => {
    await page.goto('http://localhost:9000/en/kuwait-city/queue-management');
    await expect(page.locator('h1, h2')).toBeVisible({ timeout: 10000 });
  });

  test('16. 🏥 Service page: Manama - Reminders', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/manama/automated-reminders');

    const dir = await page.locator('html').getAttribute('dir');
    expect(dir).toBe('rtl');
    await expect(page.locator('h1, h2')).toBeVisible({ timeout: 10000 });
  });

  // Test 17: Blog Listing
  test('17. 📝 Blog page loads with posts', async ({ page }) => {
    await page.goto('http://localhost:9000/en/blog');

    // Check for blog posts
    const posts = await page.locator('article, [class*="post"], [class*="card"]').count();
    console.log(`Blog posts found: ${posts}`);

    // Check pagination (if exists)
    const pagination = await page.locator('[class*="pagination"]').count();
    console.log(`Pagination found: ${pagination > 0}`);
  });

  // Test 18: Blog - Arabic
  test('18. 📝 Blog page loads (Arabic)', async ({ page }) => {
    await page.goto('http://localhost:9000/ar/blog');

    const dir = await page.locator('html').getAttribute('dir');
    expect(dir).toBe('rtl');
  });

  // Test 19: Blog Individual Post
  test('19. 📄 Individual blog post loads', async ({ page }) => {
    // First get the blog page to find a post
    await page.goto('http://localhost:9000/en/blog');

    // Find first blog post link
    const firstPostLink = page.locator('a[href*="/blog/"]').first();

    if (await firstPostLink.isVisible({ timeout: 5000 }).catch(() => false)) {
      await firstPostLink.click();
      await page.waitForLoadState('networkidle');

      // Verify post loaded
      await expect(page.locator('h1, article')).toBeVisible({ timeout: 10000 });
      console.log('Blog post loaded successfully');
    } else {
      console.log('No blog posts found to test');
    }
  });

  // Test 20: Dashboard (Protected Route)
  test('20. 🔒 Dashboard redirects unauthenticated users', async ({ page }) => {
    await page.goto('http://localhost:9000/en/dashboard');

    // Should redirect to login
    await page.waitForTimeout(2000);
    const currentUrl = page.url();
    console.log(`Dashboard redirect URL: ${currentUrl}`);

    const isLoginPage = currentUrl.includes('/login') || currentUrl.includes('/signin');
    console.log(`Redirected to login: ${isLoginPage}`);
  });

  // Test 21: API Health Check
  test('21. ⚕️ API health endpoint responds', async ({ request }) => {
    const response = await request.get('http://localhost:9000/api/health');
    expect(response.ok()).toBeTruthy();

    const body = await response.json();
    console.log('API Health:', body);
  });

  // Test 22: Static Assets
  test('22. 🖼️ Static assets load correctly', async ({ page }) => {
    await page.goto('http://localhost:9000/en');

    // Check images load (first 3)
    const images = await page.locator('img').all();
    let imageCount = 0;

    for (const img of images.slice(0, 3)) {
      const src = await img.getAttribute('src');
      if (src && !src.startsWith('data:')) {
        imageCount++;
      }
    }

    console.log(`Images found: ${imageCount}`);
  });

  // Test 23: Navigation Links
  test('23. 🧭 Navigation links work', async ({ page }) => {
    await page.goto('http://localhost:9000/en');

    // Find and click pricing link
    const pricingLink = page.locator('nav a[href*="/pricing"], a[href*="/pricing"]').first();

    if (await pricingLink.isVisible({ timeout: 5000 }).catch(() => false)) {
      await pricingLink.click();
      await page.waitForTimeout(1000);

      const url = page.url();
      expect(url).toContain('pricing');
      console.log('Navigation to pricing works');
    }
  });

  // Test 24: Contact Page
  test('24. 📧 Contact page loads', async ({ page }) => {
    const response = await page.goto('http://localhost:9000/en/contact');

    if (response?.status() === 200) {
      await expect(page.locator('h1, h2, form')).toBeVisible({ timeout: 10000 });
      console.log('Contact page loaded');
    } else {
      console.log(`Contact page status: ${response?.status() || 'N/A'}`);
    }
  });

  // Test 25: About Page
  test('25. ℹ️ About page loads', async ({ page }) => {
    const response = await page.goto('http://localhost:9000/en/about');

    if (response?.status() === 200) {
      await expect(page.locator('h1, h2')).toBeVisible({ timeout: 10000 });
      console.log('About page loaded');
    } else {
      console.log(`About page status: ${response?.status() || 'N/A'}`);
    }
  });

  // Test 26: Features Page
  test('26. ⭐ Features page loads', async ({ page }) => {
    const response = await page.goto('http://localhost:9000/en/features');

    if (response?.status() === 200) {
      await expect(page.locator('h1, h2')).toBeVisible({ timeout: 10000 });
      console.log('Features page loaded');
    } else {
      console.log(`Features page status: ${response?.status() || 'N/A'}`);
    }
  });

  // Test 27: Console Errors Check
  test('27. 🐛 Check for console errors across pages', async ({ page }) => {
    const errors: string[] = [];

    page.on('console', msg => {
      if (msg.type() === 'error') {
        errors.push(msg.text());
      }
    });

    // Visit multiple pages
    await page.goto('http://localhost:9000/en');
    await page.waitForTimeout(1000);

    await page.goto('http://localhost:9000/en/pricing');
    await page.waitForTimeout(1000);

    await page.goto('http://localhost:9000/ar/demo');
    await page.waitForTimeout(1000);

    console.log(`Total console errors: ${errors.length}`);
    if (errors.length > 0) {
      console.log('Console errors:', errors.slice(0, 5));
    }
  });
});
