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

test.describe('Navigation and Routing', () => {
  test('homepage loads and has navigation links', async ({ page }) => {
    await page.goto('/');

    await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
    // Header navigation should have links
    const nav = page.locator('header nav, header');
    await expect(nav.first()).toBeVisible();
  });

  test('navigates from homepage to search', async ({ page }) => {
    await page.goto('/');

    // Click on search-related link or button
    const searchLink = page.getByRole('link', { name: /Tim kiem|Tìm kiếm|Search/i }).first();
    if (await searchLink.isVisible()) {
      await searchLink.click();
      await expect(page).toHaveURL(/\/search/);
    }
  });

  test('navigates from homepage to login', async ({ page }) => {
    await page.goto('/');

    const loginLink = page.getByRole('link', { name: /Dang nhap|Đăng nhập|Login/i }).first();
    if (await loginLink.isVisible()) {
      await loginLink.click();
      await expect(page).toHaveURL(/\/login/);
    }
  });

  test('navigates from homepage to register', async ({ page }) => {
    await page.goto('/');

    const registerLink = page.getByRole('link', { name: /Dang ky|Đăng ký|Register/i }).first();
    if (await registerLink.isVisible()) {
      await registerLink.click();
      await expect(page).toHaveURL(/\/register/);
    }
  });

  test('login page links to register and vice versa', async ({ page }) => {
    await page.goto('/login');
    await page.getByRole('link', { name: 'Đăng ký' }).click();
    await expect(page).toHaveURL(/\/register/);

    await page.getByRole('link', { name: 'Đăng nhập' }).click();
    await expect(page).toHaveURL(/\/login/);
  });

  test('404 page does not crash', async ({ page }) => {
    const response = await page.goto('/nonexistent-page-xyz');
    // Page should load (even if 404)
    await expect(page.locator('body')).toBeVisible();
    // Should either show 404 or redirect
    expect(response?.status()).toBeLessThan(500);
  });

  test('search page with query params loads correctly', async ({ page }) => {
    await page.route('**/listings**', (route) =>
      route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({ data: [], total: 0, page: 1, limit: 12, totalPages: 0 }),
      }),
    );

    await page.goto('/search?transactionType=SALE&city=Ho+Chi+Minh');
    await expect(page.getByRole('heading', { name: 'Tìm kiếm bất động sản' })).toBeVisible();
  });
});
