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

test.describe('Create Listing Page (Multi-step Form)', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/listings/new');
  });

  test('renders step 1 - basic info form', async ({ page }) => {
    // Step indicators should be visible
    await expect(page.getByText('Thông tin')).toBeVisible();
    await expect(page.getByText('Vị trí')).toBeVisible();
    await expect(page.getByText('Chi tiết')).toBeVisible();
    await expect(page.getByText('Giá cả')).toBeVisible();
    await expect(page.getByText('Hình ảnh')).toBeVisible();
  });

  test('shows validation errors when advancing without filling required fields', async ({ page }) => {
    // Try to go to next step without filling anything
    const nextButton = page.getByRole('button', { name: /Tiep|Next|Tiếp/i });
    if (await nextButton.isVisible()) {
      await nextButton.click();
      // Should show validation errors
      const alerts = page.locator('[role="alert"], .text-destructive');
      await expect(alerts.first()).toBeVisible({ timeout: 5000 });
    }
  });

  test('has back button disabled on first step', async ({ page }) => {
    const backButton = page.getByRole('button', { name: /Quay lai|Back|Quay lại/i });
    if (await backButton.isVisible()) {
      await expect(backButton).toBeDisabled();
    }
  });

  test('shows error alert on submission failure', async ({ page }) => {
    await page.route('**/listings', (route) => {
      if (route.request().method() === 'POST') {
        return route.fulfill({
          status: 400,
          contentType: 'application/json',
          body: JSON.stringify({ message: 'Validation failed' }),
        });
      }
      return route.continue();
    });

    // Page should render without errors
    await expect(page.getByText('Thông tin')).toBeVisible();
  });
});
