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

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

test('rolling a skill from the sheet shows the roll tray', async ({ page }) => {
  await page.getByRole('button', { name: '+ New campaign' }).first().click();
  await page.locator('input[data-autofocus]').fill('Dice Camp');
  await page.getByRole('button', { name: 'Create' }).click();
  await page.getByRole('link', { name: 'Characters' }).click();
  await createCharacter(page, 'Roller');

  // Click the Acrobatics modifier to roll it
  await page.getByTitle('Roll Acrobatics (DEX)').click();
  // The shared roll tray appears (unique dismiss control) showing the roll
  await expect(page.getByRole('button', { name: 'Dismiss roll' })).toBeVisible();
  await expect(page.locator('text=/= \\d+/').first()).toBeVisible();
});

test('advantage toggle applies to any die, not just d20', async ({ page }) => {
  await page.getByRole('link', { name: 'Dice' }).click();
  await page.getByRole('button', { name: 'Advantage', exact: true }).click();
  await page.getByRole('button', { name: 'd4', exact: true }).click();
  // The rolled expression became 2d4kh1 (advantage on a d4)
  await expect(page.getByText(/Rolled 2d4kh1/)).toBeVisible();
});

test('dice page: save and use a macro', async ({ page }) => {
  await page.getByRole('link', { name: 'Dice' }).click();
  await page.getByLabel('Dice expression').fill('2d6+3');
  await page.getByRole('button', { name: /Save/ }).click();
  // Macro chip appears and rolls when clicked
  const chip = page.getByRole('button', { name: '2d6+3', exact: true });
  await expect(chip).toBeVisible();
  await chip.click();
  await expect(page.locator('text=/= \\d+/').first()).toBeVisible();
});
