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('character depth: inventory, spellcasting, attacks, resources + rest', async ({ page }) => {
  // Campaign + character
  await page.getByRole('button', { name: '+ New campaign' }).first().click();
  await page.locator('input[data-autofocus]').fill('Phandelver');
  await page.getByRole('button', { name: 'Create' }).click();
  await page.getByRole('link', { name: 'Characters' }).click();
  await page.getByRole('button', { name: '+ New character' }).first().click();
  await page.locator('input[data-autofocus]').fill('Gandalf');
  await page.getByRole('button', { name: 'Create' }).click();
  await page.getByRole('link', { name: /Gandalf/ }).click();

  // Set INT high so spell DC is computable
  await page.getByLabel('INT score').fill('18');

  // Inventory — add an item via Enter
  await page.getByPlaceholder('Longsword', { exact: true }).fill('Staff of Power');
  await page.getByPlaceholder('Longsword', { exact: true }).press('Enter');
  await expect(page.locator('input[aria-label="Item name"]')).toHaveValue('Staff of Power');

  // Spellcasting — choose ability, expect a derived DC to appear
  await page.getByLabel('Casting ability').selectOption('int');
  await expect(page.getByText('Spell DC')).toBeVisible();

  // Attacks — add one, expect a computed to-hit
  await page.getByPlaceholder('Longsword, Shortbow…').fill('Quarterstaff');
  await page.getByPlaceholder('Longsword, Shortbow…').press('Enter');
  await expect(page.getByText('to hit')).toBeVisible();

  // Resources — add one, spend it, long rest restores it
  await page.getByPlaceholder('Ki Points, Rage, Focus…').fill('Sorcery Points');
  await page.getByPlaceholder('Ki Points, Rage, Focus…').press('Enter');
  // Only one resource exists, so the controls are unambiguous.
  await page.getByRole('button', { name: 'Spend' }).click();
  await expect(page.getByText('0/1')).toBeVisible();
  await page.getByRole('button', { name: 'Long Rest' }).click();
  await expect(page.getByText('1/1')).toBeVisible();

  // Reload — persistence survived (autosave). Wait for the debounce + beforeunload flush.
  await page.waitForTimeout(500);
  await page.reload();
  await expect(page.locator('input[aria-label="Item name"]')).toHaveValue('Staff of Power');
});
