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

test.beforeEach(async ({ page }) => {
  await page.goto('/');
  await page.evaluate(async () => {
    indexedDB.deleteDatabase('ttrpg-manager');
    localStorage.clear();
  });
  await page.reload();
});

test('combat depth: timed condition auto-expires, log records events, roll-all works', async ({ page }) => {
  await page.getByRole('button', { name: '+ New campaign' }).first().click();
  await page.locator('input[data-autofocus]').fill('Depth');
  await page.getByRole('button', { name: 'Create' }).click();

  await page.getByRole('link', { name: 'Combat' }).click();
  await page.getByRole('button', { name: '+ New encounter' }).first().click();
  await page.locator('input[data-autofocus]').fill('Brawl');
  await page.getByRole('button', { name: 'Create' }).click();

  await page.getByLabel('Name').fill('Goblin');
  await page.getByRole('button', { name: 'Add', exact: true }).click();

  const row = page.locator('li', { hasText: 'Goblin' });

  // Add Prone with a 1-round duration
  await row.getByLabel('Condition duration in rounds').fill('1');
  await row.getByLabel('Add condition').selectOption('Prone');
  await expect(row.getByRole('button', { name: /Prone \(1r\)/ })).toBeVisible();

  // Roll-all initiative
  await page.getByRole('button', { name: /Roll all/ }).click();

  // Start combat, then advance a turn — Prone should expire on Goblin's next turn
  await page.getByRole('button', { name: 'Start combat' }).click();
  await expect(page.getByRole('button', { name: 'End' })).toBeVisible(); // combat is active
  await page.getByRole('button', { name: /Next turn/ }).click();
  await expect(row.getByRole('button', { name: /Prone/ })).toHaveCount(0);

  // Combat log captured the events
  await expect(page.getByText('Combat Log')).toBeVisible();
  await expect(page.getByText(/Prone wore off/)).toBeVisible();
});
