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

// Use internal Docker network hostname for frontend
const FRONTEND_URL = 'http://sf_public_frontend:5173';
// Test user credentials (should be a valid test user in the dev database)
const TEST_EMAIL = 'superadmin@profibot.hu';
const TEST_PASSWORD = 'anypassword';

test.describe('Frontend UI E2E Flow', () => {
  test('should login, select profile mode, and load dashboard', async ({ page }) => {
    // Step 1: Open login page
    await page.goto(`${FRONTEND_URL}/login`);
    await expect(page).toHaveURL(/\/login/);
    await expect(page.getByRole('heading', { name: /login/i })).toBeVisible();

    // Step 2: Fill credentials and submit
    await page.getByLabel(/email/i).fill(TEST_EMAIL);
    await page.getByLabel(/password/i).fill(TEST_PASSWORD);
    await page.getByRole('button', { name: /sign in|login/i }).click();

    // Step 3: Wait for redirect to profile selection (since no UI mode selected)
    await expect(page).toHaveURL(/\/profile-select/);
    await expect(page.getByRole('heading', { name: /welcome to service finder/i })).toBeVisible();

    // Step 4: Select Private Garage mode
    await page.getByText(/private garage/i).click();
    await expect(page.locator('.selected').filter({ hasText: /private garage/i })).toBeVisible();

    // Step 5: Click Continue to Dashboard
    await page.getByRole('button', { name: /continue to dashboard/i }).click();

    // Step 6: Verify dashboard loads
    await expect(page).toHaveURL(/\//);
    await expect(page.getByRole('heading').filter({ hasText: /dashboard/i }).first()).toBeVisible();

    // Step 7: Verify gamification trophies are present
    await expect(page.getByText(/trophies|achievements/i).first()).toBeVisible();

    // Step 8: Verify "Add Expense" link is present and clickable
    const addExpenseLink = page.getByRole('link', { name: /add expense/i });
    await expect(addExpenseLink).toBeVisible();
    await addExpenseLink.click();
    // Should navigate to add expense page
    await expect(page.getByRole('heading', { name: /add expense/i })).toBeVisible();
  });

  test('should handle corporate fleet selection', async ({ page }) => {
    await page.goto(`${FRONTEND_URL}/login`);
    await page.getByLabel(/email/i).fill(TEST_EMAIL);
    await page.getByLabel(/password/i).fill(TEST_PASSWORD);
    await page.getByRole('button', { name: /sign in|login/i }).click();

    await expect(page).toHaveURL(/\/profile-select/);
    await page.getByText(/corporate fleet/i).click();
    await page.getByRole('button', { name: /continue to dashboard/i }).click();

    await expect(page).toHaveURL(/\//);
    // Fleet dashboard may have different elements, but at least dashboard title
    await expect(page.getByRole('heading').filter({ hasText: /dashboard/i }).first()).toBeVisible();
  });
});