const { test, expect } = require('@playwright/test');

const TEST_EMAIL    = process.env.TEST_EMAIL    || 'lars@stommer.com';
const TEST_PASSWORD = process.env.TEST_PASSWORD || '5112';

async function login(page) {
  await page.goto('/');
  await page.waitForLoadState('networkidle');
  await page.fill('input[type="email"]', TEST_EMAIL);
  await page.fill('input[type="password"]', TEST_PASSWORD);
  await page.click('button:has-text("Anmelden")');
  await page.waitForLoadState('networkidle');
}

test('1. Login funktioniert', async ({ page }) => {
  await page.goto('/');
  await page.fill('input[type="email"]', TEST_EMAIL);
  await page.fill('input[type="password"]', TEST_PASSWORD);
  await page.click('button:has-text("Anmelden")');
  await page.waitForLoadState('networkidle');
  const loginButton = page.locator('button:has-text("Anmelden")');
  await expect(loginButton).toHaveCount(0, { timeout: 10000 });
  await page.screenshot({ path: 'screenshots/01-nach-login.png' });
  console.log('Login erfolgreich');
});

test('2. Dashboard laedt ohne Fehler', async ({ page }) => {
  await login(page);
  await expect(page.locator('.spinner')).toHaveCount(0, { timeout: 10000 });
  await page.screenshot({ path: 'screenshots/02-dashboard.png' });
  console.log('Dashboard OK');
});

test('3. Erfassung erreichbar', async ({ page }) => {
  await login(page);
  await page.click('text=Erfassung');
  await page.waitForLoadState('networkidle');
  await page.screenshot({ path: 'screenshots/03-erfassung.png' });
  console.log('Erfassung OK');
});

test('4. Analyse erreichbar', async ({ page }) => {
  await login(page);
  await page.click('text=Analyse');
  await page.waitForLoadState('networkidle');
  await page.screenshot({ path: 'screenshots/04-analyse.png' });
  console.log('Analyse OK');
});

test('5. Keine kritischen Console-Fehler', async ({ page }) => {
  const errors = [];
  page.on('console', msg => {
    if (msg.type() === 'error') errors.push(msg.text());
  });
  await login(page);
  await page.waitForLoadState('networkidle');
  const kritisch = errors.filter(e =>
    !e.includes('favicon') && !e.includes('sourceMap') && !e.includes('404')
  );
  if (kritisch.length > 0) {
    console.log('Console-Fehler:', kritisch.join(', '));
  } else {
    console.log('Keine kritischen Console-Fehler');
  }
});